Skip to content

Open source, composable payments platform | PCI compliant | SaaS and Self-host options | Enables connectivity to multiple payment, payout, fraud, vault and tokenization providers | Uplifts authorization with intelligent routing and revenue recovery | Reduce payment processing costs with cost observability | Reduces payment ops with reconciliation

feat(loadtest): add loadtest via CLI and performance console (#15215)

Kashif4050f0d7963d
diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md
index f74bd82944..cf0a02aad5 100644
--- a/.github/PULL_REQUEST_TEMPLATE.md
+++ b/.github/PULL_REQUEST_TEMPLATE.md
@@ -25,7 +25,7 @@ Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
-3. `loadtest/config`
+3. `loadtest/loadtest.config.example.json` (load-test console)
-->
diff --git a/.gitignore b/.gitignore
index 59b4cc3cf0..cc15b08f2b 100644
--- a/.gitignore
+++ b/.gitignore
@@ -255,7 +255,6 @@ logs/
monitoring/*.tmp/
config/sandbox.toml
config/production.toml
-!loadtest/.env
loadtest/*.tmp/
# Nix output
diff --git a/README.md b/README.md
index bd2f985a30..e2a6486edf 100644
--- a/README.md
+++ b/README.md
@@ -47,6 +47,7 @@
- [Hosted Sandbox (No Setup Required)](#hosted-sandbox-no-setup-required)
- [Why Hyperswitch?](#-why-hyperswitch)
- [Architectural Overview](#architectural-overview)
+- [Load Testing](loadtest/README.md)
- [Our Vision](#our-vision)
- [Community & Contributions](#community--contributions)
- [Feature Requests & Bugs](#feature-requests--bugs)
diff --git a/loadtest/.gitignore b/loadtest/.gitignore
new file mode 100644
index 0000000000..28e647ec19
--- /dev/null
+++ b/loadtest/.gitignore
@@ -0,0 +1,2 @@
+/artifacts/
+/loadtest.config.json
diff --git a/loadtest/Dockerfile b/loadtest/Dockerfile
deleted file mode 100644
index ebea439eb8..0000000000
--- a/loadtest/Dockerfile
+++ /dev/null
@@ -1,11 +0,0 @@
-FROM rust:latest AS builder
-
-WORKDIR /app
-COPY . .
-RUN cargo install diesel_cli && cargo build --bin router --release
-
-FROM rust:latest AS runtime
-WORKDIR /app
-COPY --from=builder /app/migrations migrations
-COPY --from=builder /app/target/release/router router
-COPY --from=builder /usr/local/cargo/bin/diesel diesel
diff --git a/loadtest/README.md b/loadtest/README.md
index 6f768a55c8..d90880168d 100644
--- a/loadtest/README.md
+++ b/loadtest/README.md
@@ -1,79 +1,53 @@
-## Performance Benchmarking Setup
+# Load testing
-The setup uses docker compose to get the required components up and running. It also handles running database migration
-and starts [K6 load testing](https://k6.io/docs/) script at the end. The metrics are visible in the console as well as
-through Grafana dashboard.
+Docker bundles Node, the UI and the compiled Go/k6 recorder; no host toolchain is
+needed. Run Hyperswitch and its required services separately. For services on your
+Mac, use `host.docker.internal` rather than `127.0.0.1` in connection settings.
-We have added a callback at the end of the script to compare result with existing baseline values. The env variable
-`LOADTEST_RUN_NAME` can be used to change the name of the run which will be used to create json, result summary and diff
-benchmark files. The default value is "baseline", and diff will be created by comparing new results against baseline.
-See 'How to run' section.
+## Loadtesting using CLI
-### Structure/Files
+From the repository root, build the shared image and mount a local artifact directory:
-`config`: contains router toml file to change settings. Also setting files for other components like Tempo etc.
+```sh
+docker build -t hyperswitch-loadtest -f loadtest/console/Dockerfile .
+mkdir -p loadtest/artifacts
-`grafana`: data source and dashboard files
+# Run the engine inside the image; /data persists on the host.
+loadtest_cli() {
+ docker run --rm -i --user "$(id -u):$(id -g)" \
+ -v "$PWD/loadtest/artifacts:/data" hyperswitch-loadtest \
+ node /app/loadtest/k6/scenario-mix/run.mjs "$@"
+}
-`k6`: K6 load testing tool scripts. The `setup.js` contain common functions like creating merchant api key etc.
- Each js files will contain load testing scenario of each APIs. Currently, we have `health.js` and `payment-confirm.js`.
-
-`.env`: It provide default value to docker compose file. Developer can specify which js script they want to run using env
- variable called `LOADTEST_K6_SCRIPT`. The default script is `health.js`. See 'How to run' section.
-
-### How to run
-
-Build image of checked out branch.
-```bash
-docker compose build
-```
-
-Run default (`health.js`) script. It will generate baseline result.
-```bash
-bash loadtest.sh
+loadtest_cli fixtures --config /data/provision.json --output /data/fixtures/local
+loadtest_cli load --config /data/load.json --fixtures /data/fixtures/local \
+ --output /data/runs/test-1 --k6 /usr/local/bin/k6-sqlite
+loadtest_cli reconcile --db /data/runs/test-1/results.sqlite \
+ --csv /data/payments.csv --output /data/reconciliation.csv
```
-The `loadtest.sh` script takes following flags,
-
-`-c`: _compare_ with baseline results [without argument]
- auto assign run name based on current commit number
-
-`-r`: takes _run name_ as argument (default: baseline)
-
-`-s`: _script name_ exists in `k6` directory without the file extension as argument (default: health)
+Before running, place your provisioning and load configurations in
+`loadtest/artifacts/`, using the settings in
+[`loadtest.config.example.json`](loadtest.config.example.json). Configure concrete
+credentials or explicitly pass the required environment variables to `docker run`.
+Use a fresh output directory for each run. CLI reconciliation uses a payment CSV.
+For native execution and tests, see the [engine guide](k6/scenario-mix/README.md).
-`-a`: run loadtest for _all scripts_ existing in `k6` directory [without argument]
+## Loadtesting using console
-For example, to run the baseline for `payment-confirm.js` script.
-```bash
-bash loadtest.sh -s payment-confirm
+```sh
+cd loadtest/console
+cp .env.example .env
+# Set the admin password hash and service credentials; see the setup guide.
+docker compose up -d --build
```
-The run name could be anything. It will be used to prefix benchmarking files, stored at `./k6/benchmark`. For example,
-```bash
-bash loadtest.sh -r made_calls_asyns -s payment-confirm
-```
-
-A preferred way to compare new changes with the baseline is using the `-c` flag. It automatically assigns commit numbers to
-easily match different results.
-```bash
-bash loadtest.sh -c -s payment-confirm
-```
-
-Assuming there is baseline files for all the script, following command will compare them with new changes,
-```bash
-bash loadtest.sh -ca
-```
-It uses `-c` compare flag and `-a` run loadtest using all the scripts.
-
-Developer can observe live metrics using [K6 Load Testing Dashboard](http://localhost:3002/d/k6/k6-load-testing-results?orgId=1&refresh=5s&from=now-1m&to=now) in Grafana.
-The [Tempo datasource](http://localhost:3002/explore?orgId=1&left=%7B%22datasource%22:%22P214B5B846CF3925F%22,%22queries%22:%5B%7B%22refId%22:%22A%22,%22queryType%22:%22nativeSearch%22%7D%5D,%22range%22:%7B%22from%22:%22now-1m%22,%22to%22:%22now%22%7D%7D)
-is available to inspect tracing of individual requests.
-
-### Notes
+Open http://127.0.0.1:4174. Configure **Settings**, create a **Scenario**, provision
+**Fixtures**, start load in **Performance**, and inspect **Results**. The console
+also manages faults, pause/resume, distributed workers and PostgreSQL reconciliation.
+Grafana embeds use a separate listener on port 4176; see the deployment guide for HTTPS setup.
-1. The script will first "down" the already running docker compose to run loadtest on freshly created database.
-2. Make sure that the Rust compiler is happy with your changes before you start running a performance test. This will save a lot of your time.
-3. If the project image is available locally then `docker compose up` won't take your new changes into account.
- Either first do `docker compose build` or `docker compose up --build k6`.
-4. For baseline, make sure you in the right branch and have build the image before running the loadtest script.
+See the [setup guide](console/README.md) for configuration and native development
+(Node 24.19+, Go 1.24.4 and a C compiler) and the
+[deployment guide](console/DEPLOYMENT.md). Keep credentials, generated fixtures,
+recordings and binaries out of version control.
diff --git a/loadtest/config/development.toml b/loadtest/config/development.toml
deleted file mode 100644
index 19a53120cd..0000000000
--- a/loadtest/config/development.toml
+++ /dev/null
@@ -1,1030 +0,0 @@
-[log.file]
-enabled = false
-
-[log.console]
-enabled = false
-
-[log.telemetry]
-traces_enabled = true
-metrics_enabled = true
-ignore_errors = false
-
-[key_manager]
-url = "http://localhost:5000"
-use_legacy_key_store_decryption = false
-
-[master_database]
-username = "postgres"
-password = "postgres"
-host = "db"
-port = 5432
-dbname = "loadtest_router"
-max_pool_size = 20
-connection_timeout = 10
-min_idle_pool_size = 2
-idle_timeout = 300
-max_lifetime = 1800
-
-[accounts_database]
-username = "postgres"
-password = "postgres"
-host = "db"
-port = 5432
-dbname = "loadtest_router"
-max_pool_size = 20
-connection_timeout = 10
-min_idle_pool_size = 2
-idle_timeout = 300
-max_lifetime = 1800
-
-[global_database]
-username = "postgres"
-password = "postgres"
-host = "db"
-port = 5432
-dbname = "loadtest_router"
-max_pool_size = 20
-connection_timeout = 10
-min_idle_pool_size = 2
-idle_timeout = 300
-max_lifetime = 1800
-
-[server]
-host = "0.0.0.0"
-
-[redis]
-host = "redis-queue"
-
-[secrets]
-admin_api_key = "test_admin"
-jwt_secret = "secret"
-
-[user]
-password_validity_in_days = 90
-two_factor_auth_expiry_in_secs = 300
-totp_issuer_name = "Hyperswitch"
-force_two_factor_auth = false
-force_cookies = false
-
-[oidc.key.k1]
-kid = "" # Key ID used to identify the signing key in JWKS and JWT headers (Generate using: openssl rand -hex 16)
-private_key = "" # RSA private key used for signing ID tokens (Generate using: openssl genrsa -out private.key 4096)
-
-[oidc.key.k2]
-kid = "" # Key ID used to identify the signing key in JWKS and JWT headers (Generate using: openssl rand -hex 16)
-private_key = "" # RSA private key used for signing ID tokens (Generate using: openssl genrsa -out private2.key 4096)
-
-[oidc.client.c1]
-client_id = "" # OIDC client identifier for the relying party (Generate using: openssl rand -hex 8)
-client_secret = "" # Client secret used to authenticate the client (Generate using: openssl rand -hex 32)
-redirect_uri = "" # Redirect URI registered for the OIDC client
-
-[locker]
-host = ""
-mock_locker = true
-locker_enabled = true
-ttl_for_storage_in_secs = 220752000
-create_entity_on_merchant_create = false
-
-[forex_api]
-api_key = ""
-fallback_api_key = ""
-data_expiration_delay_in_seconds = 21600
-redis_lock_timeout_in_seconds = 100
-redis_ttl_in_seconds = 172800
-
-[eph_key]
-validity = 1
-
-[refund]
-max_attempts = 10
-max_age = 365
-
-[jwekey]
-vault_encryption_key = ""
-vault_private_key = ""
-
-[webhooks]
-outgoing_enabled = true
-redis_lock_expiry_seconds = 180
-
-[api_keys]
-hash_key = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"
-
-[connectors]
-absa_sanlam.base_url = "dev"
-aci.base_url = "https://eu-test.oppwa.com/"
-adyen.base_url = "https://checkout-test.adyen.com/"
-adyenplatform.base_url = "https://balanceplatform-api-test.adyen.com/"
-affirm.base_url = "https://sandbox.affirm.com/api"
-adyen.payout_base_url = "https://pal-test.adyen.com/"
-adyen.dispute_base_url = "https://ca-test.adyen.com/"
-adyen.management_base_url = "https://management-test.adyen.com/"
-airwallex.base_url = "https://api-demo.airwallex.com/"
-amazonpay.base_url = "https://pay-api.amazon.com/sandbox/v2"
-applepay.base_url = "https://apple-pay-gateway-cert.apple.com/"
-archipel.base_url = "https://{{merchant_endpoint_prefix}}/ArchiPEL/Transaction/v1"
-authipay.base_url = "https://prod.emea.api.fiservapps.com/sandbox/ipp/payments-gateway/v2/"
-authorizedotnet.base_url = "https://apitest.authorize.net/xml/v1/request.api"
-bambora.base_url = "https://api.na.bambora.com"
-bamboraapac.base_url = "https://demo.ippayments.com.au/interface/api"
-bankofamerica.base_url = "https://apitest.merchant-services.bankofamerica.com/"
-barclaycard.base_url = "https://api.smartpayfuse-test.barclaycard/"
-billwerk.base_url = "https://api.reepay.com/"
-billwerk.secondary_base_url = "https://card.reepay.com/"
-bitpay.base_url = "https://test.bitpay.com"
-blackhawknetwork.base_url = "https://api-sandbox.blackhawknetwork.com/"
-calida.base_url = "https://dev.eorder.reloadhero.com/"
-bluesnap.base_url = "https://sandbox.bluesnap.com/"
-bluesnap.secondary_base_url = "https://sandpay.bluesnap.com/"
-boku.base_url = "https://country-api4-stage.boku.com"
-braintree.base_url = "https://payments.sandbox.braintree-api.com/graphql"
-breadpay.base_url = "https://api-sandbox.getbread.com"
-cashtocode.base_url = "https://cluster05.api-test.cashtocode.com"
-celero.base_url = "https://sandbox.gotnpgateway.com"
-chargebee.base_url = "https://$.chargebee.com/api/"
-checkbook.base_url = "https://api.sandbox.checkbook.io"
-checkout.base_url = "https://api.sandbox.checkout.com/"
-citigate.base_url = "https://gw-test.cgate.tech"
-coinbase.base_url = "https://api.commerce.coinbase.com"
-coingate.base_url = "https://api-sandbox.coingate.com"
-cryptopay.base_url = "https://business-sandbox.cryptopay.me"
-cybersource.base_url = "https://apitest.cybersource.com/"
-cybersourcedecisionmanager.base_url = "https://apitest.cybersource.com/"
-d24.base_url = "https://api-stg.directa24.com"
-datatrans.base_url = "https://api.sandbox.datatrans.com/"
-datatrans.secondary_base_url = "https://pay.sandbox.datatrans.com/"
-deutschebank.base_url = "https://testmerch.directpos.de/rest-api"
-digitalvirgo.base_url = "https://dcb-integration-service-sandbox-external.staging.digitalvirgo.pl"
-dlocal.base_url = "https://sandbox.dlocal.com/"
-dummyconnector.base_url = "http://localhost:8080/dummy-connector"
-dwolla.base_url = "https://api-sandbox.dwolla.com"
-ebanx.base_url = "https://sandbox.ebanxpay.com/"
-ecommpay.base_url = "https://api.ecommpay.com/"
-elavon.base_url = "https://api.demo.convergepay.com/VirtualMerchantDemo/"
-# Elavon Payment Gateway (EPG), Elavon's JSON REST gateway. Distinct from the
-# `elavon` entry above, which is Elavon Converge (an XML API).
-elavon_pg.base_url = "https://api.sandbox.elavonpayments.com"
-envoy.base_url = "https://test.envoytx.com/"
-etisalat.base_url = "https://demo-ipg.ctdev.comtrust.ae:2443"
-facilitapay.base_url = "https://sandbox-api.facilitapay.com/api/v1"
-finix.base_url = "https://finix.sandbox-payments-api.com"
-fiserv.base_url = "https://cert.api.fiservapps.com/"
-fiservcommercehub.base_url = "https://connect-cert.fiservapis.com/ch/"
-fiservemea.base_url = "https://prod.emea.api.fiservapps.com/sandbox"
-fiuu.base_url = "https://sandbox.merchant.razer.com/"
-flexiti.base_url = "https://onlineapi.flexiti.fi/flexiti/online-api/"
-fiuu.secondary_base_url = "https://sandbox.merchant.razer.com/"
-forte.base_url = "https://sandbox.forte.net/api/v3"
-getnet.base_url = "https://api-test.getneteurope.com/engine/rest"
-gigadat.base_url = "https://interac.express-connect.com/"
-givepayments.base_url = "https://api-sandbox.givepayments.com"
-globalpay.base_url = "https://apis.sandbox.globalpay.com/ucp/"
-globalpayments_heartland.base_url = "https://cert.api2.heartlandportico.com/Hps.Exchange.PosGateway/PosGatewayService.asmx"
-globalpayments_realex.base_url = "https://api.sandbox.realexpayments.com/"
-globepay.base_url = "https://pay.globepay.co/"
-gocardless.base_url = "https://api-sandbox.gocardless.com"
-gotyme_sanlam.base_url = "dev"
-gpayments.base_url = "https://{{merchant_endpoint_prefix}}-test.api.as1.gpayments.net"
-helcim.base_url = "https://api.helcim.com/"
-hipay.base_url = "https://stage-secure-gateway.hipay-tpp.com/rest/"
-hyperpg.base_url = "https://sandbox.hyperpg.in"
-hyperswitch_vault.base_url = "http://localhost:8080"
-hyperwallet.base_url = "https://uat-api.paylution.com"
-hipay.secondary_base_url = "https://stage-secure2-vault.hipay-tpp.com/rest/"
-hipay.third_base_url = "https://stage-api-gateway.hipay.com/"
-iatapay.base_url = "https://sandbox.iata-pay.iata.org/api/v1"
-ilixium.base_url = "https://prprocessing.ilixium.com/platform/ili"
-imerchantsolutions.base_url = "https://imerchantsolutions.com/api"
-inespay.base_url = "https://apiflow.inespay.com/san/v21"
-interpayments.base_url = "https://api-test.interpayments.com/v1"
-itaubank.base_url = "https://sandbox.devportal.itau.com.br/"
-jpmorgan.base_url = "https://api-mock.payments.jpmorgan.com/api/v2"
-juspaythreedsserver.base_url = "http://localhost:8000"
-katapult.base_url = "https://sandbox.katapult.com/api/v3"
-jpmorgan.secondary_base_url = "https://id.payments.jpmorgan.com"
-# JP Morgan Orbital (Chase Paymentech Orbital Gateway JSON API v4). Distinct from the
-# `jpmorgan` entry above, which is the JPMorgan Payments API v2.
-jpmorgan_orbital.base_url = "https://orbitalvar1.chasepaymentech.com/gwapi/v4/gateway"
-klarna.base_url = "https://api{{klarna_region}}.playground.klarna.com/"
-loonio.base_url = "https://integration.loonio.ca/"
-merchante.base_url = "https://cert.merchante-solutions.com/mes-api/tridentApi"
-mifinity.base_url = "https://demo.mifinity.com/"
-mollie.base_url = "https://api.mollie.com/v2/"
-moneris.base_url = "https://api.sb.moneris.io"
-mpgs.base_url = "https://test-gateway.mastercard.com"
-mollie.secondary_base_url = "https://api.cc.mollie.com/v1/"
-multisafepay.base_url = "https://testapi.multisafepay.com/"
-netcetera.base_url = "https://api.prev.euc1.acquiring.cloud.netcetera.com/3ds-server"
-nexinets.base_url = "https://apitest.payengine.de/v1"
-nexixpay.base_url = "https://xpaysandbox.nexigroup.com/api/phoenix-0.0/psp/api/v1"
-payconex.base_url = "https://cert.payconex.net"
-paydotcom.base_url = "https://api.pay.com/"
-nmi.base_url = "https://secure.nmi.com/"
-nomupay.base_url = "https://payout-api.sandbox.nomupay.com"
-noon.base_url = "https://api-test{{region}}.noonpayments.com/"
-nordea.base_url = "https://api.nordeaopenbanking.com"
-noon.key_mode = "Test"
-novalnet.base_url = "https://payport.novalnet.de/v2"
-nsure.base_url = "https://sandbox.nsureapi.com"
-nuvei.base_url = "https://ppp-test.nuvei.com/"
-opayo.base_url = "https://pi-test.sagepay.com/"
-opennode.base_url = "https://dev-api.opennode.com"
-paybox.base_url = "https://preprod-ppps.paybox.com/PPPS.php"
-paybox.secondary_base_url = "https://preprod-tpeweb.paybox.com/"
-payeezy.base_url = "https://api-cert.payeezy.com/"
-payhound.base_url = "https://sandbox-api.payhound.com"
-payjustnow.base_url = "https://sandbox-checkout.payjustnow.io/v2"
-payjustnowinstore.base_url = "https://sandbox.payjustnow.com/api"
-payload.base_url = "https://api.payload.com"
-payme.base_url = "https://sandbox.payme.io/"
-paynearme.base_url = "https://api.paynearme-sandbox.com/json-api"
-payone.base_url = "https://payment.preprod.payone.com/"
-paypal.base_url = "https://api-m.sandbox.paypal.com/"
-paysafe.base_url = "https://api.test.paysafe.com/paymenthub/"
-paystack.base_url = "https://api.paystack.co"
-paytm.base_url = "https://securegw-stage.paytm.in/"
-payu.base_url = "https://secure.snd.payu.com/"
-peachpayments.base_url = "https://apitest.bankint.ppay.io/v/1"
-phonepe.base_url = "https://api.phonepe.com/apis/hermes/"
-placetopay.base_url = "https://test.placetopay.com/rest/gateway"
-plaid.base_url = "https://sandbox.plaid.com"
-powertranz.base_url = "https://staging.ptranz.com/api/"
-prophetpay.base_url = "https://ccm-thirdparty.cps.golf/"
-rapyd.base_url = "https://sandboxapi.rapyd.net"
-razorpay.base_url = "https://api.razorpay.com/"
-recurly.base_url = "https://v3.recurly.com"
-redsys.base_url = "https://sis-t.redsys.es:25443"
-revolv3.base_url = "https://api-sandbox.revolv3.com"
-riskified.base_url = "https://sandbox.riskified.com/api"
-saferpay.base_url = "https://test.saferpay.com/api"
-santander.base_url = "https://trust-pix-h.santander.com.br/"
-santander.secondary_base_url = "https://trust-open-h.api.santander.com.br/"
-shift4.base_url = "https://api.shift4.com/"
-sift.base_url = "https://api.sift.com/v205"
-silverflow.base_url = "https://api-sbx.silverflow.co/v1"
-signifyd.base_url = "https://api.signifyd.com/"
-square.base_url = "https://connect.squareupsandbox.com/"
-square.secondary_base_url = "https://pci-connect.squareupsandbox.com/"
-stax.base_url = "https://apiprod.fattlabs.com/"
-stripe.base_url = "https://api.stripe.com/"
-stripebilling.base_url = "https://api.stripe.com/"
-taxjar.base_url = "https://api.sandbox.taxjar.com/v2/"
-tesouro.base_url = "https://api.sandbox.tesouro.com"
-threedsecureio.base_url = "https://service.sandbox.3dsecure.io"
-thunes.base_url = "https://api.limonetikqualif.com/"
-tokenex.base_url = "https://test-api.tokenex.com"
-tokenio.base_url = "https://api.sandbox.token.io"
-truelayer.base_url = "https://api.truelayer-sandbox.com"
-trustly.base_url = "https://test.trustly.com/api/1"
-truelayer.secondary_base_url = "https://auth.truelayer-sandbox.com"
-stripe.base_url_file_upload = "https://files.stripe.com/"
-trustpay.base_url = "https://test-tpgw.trustpay.eu/"
-trustpayments.base_url = "https://webservices.securetrading.net/"
-trustpay.base_url_bank_redirects = "https://aapi.trustpay.eu/"
-tsys.base_url = "https://stagegw.transnox.com/"
-unified_authentication_service.base_url = "http://localhost:8000"
-vgs.base_url = "https://api.sandbox.verygoodvault.com/"
-volt.base_url = "https://gateway.sandbox.volt.io"
-volt.secondary_base_url = "https://api.sandbox.volt.io"
-wellsfargo.base_url = "https://apitest.cybersource.com/"
-wellsfargopayout.base_url = "https://api-sandbox.wellsfargo.com/"
-worldline.base_url = "https://eu.sandbox.api-ingenico.com/"
-worldpay.base_url = "https://try.access.worldpay.com/"
-worldpaymodular.base_url = "https://try.access.worldpay.com/"
-worldpayraft.base_url = "https://ws-cert.vantiv.com/merchant/servicing/apitransactions/NativeRaftApi/v1"
-worldpayvantiv.base_url = "https://transact.vantivprelive.com/vap/communicator/online"
-worldpayvantiv.secondary_base_url = "https://onlinessr.vantivprelive.com"
-worldpayvantiv.third_base_url = "https://services.vantivprelive.com"
-worldpayxml.base_url = "https://secure-test.worldpay.com/jsp/merchant/xml/paymentService.jsp"
-worldpayxml.secondary_base_url = "https://centinelapistag.cardinalcommerce.com"
-xendit.base_url = "https://api.xendit.co"
-zift.base_url = "https://sandbox-secure.zift.io/"
-wise.base_url = "https://api.wise-sandbox.com/"
-zen.base_url = "https://api.zen-test.com/"
-zen.secondary_base_url = "https://secure.zen-test.com/"
-zsl.base_url = "https://api.sitoffalb.net/"
-
-[pm_filters.default]
-apple_pay = { country = "AU,CN,HK,JP,MO,MY,NZ,SG,TW,AM,AT,AZ,BY,BE,BG,HR,CY,CZ,DK,EE,FO,FI,FR,GE,DE,GR,GL,GG,HU,IS,IE,IM,IT,KZ,JE,LV,LI,LT,LU,MT,MD,MC,ME,NL,NO,PL,PT,RO,SM,RS,SK,SI,ES,SE,CH,UA,GB,AR,CO,CR,BR,MX,PE,BH,IL,JO,KW,PS,QA,SA,AE,CA,UM,US,KR,VN,MA,ZA,VA,CL,SV,GT,HN,PA", currency = "AED,AUD,CHF,CAD,EUR,GBP,HKD,SGD,USD" }
-
-[connectors.supported]
-wallets = ["klarna", "mifinity", "braintree", "applepay","finix", "worldpayxml"]
-rewards = ["cashtocode", "zen"]
-cards = [
- "aci",
- "adyen",
- "adyenplatform",
- "airwallex",
- "amazonpay",
- "archipel",
- "authipay",
- "authorizedotnet",
- "bambora",
- "bamboraapac",
- "bankofamerica",
- "barclaycard",
- "billwerk",
- "bitpay",
- "bluesnap",
- "boku",
- "braintree",
- "celero",
- "checkbook",
- "checkout",
- "coinbase",
- "coingate",
- "cryptopay",
- "ctp_visa",
- "custombilling",
- "cybersource",
- "datatrans",
- "deutschebank",
- "digitalvirgo",
- "dlocal",
- "dummyconnector",
- "dwolla",
- "ebanx",
- "elavon",
- "facilitapay",
- "fiserv",
- "fiservemea",
- "fiuu",
- "forte",
- "getnet",
- "globalpay",
- "globepay",
- "gocardless",
- "gpayments",
- "helcim",
- "hipay",
- "hyperswitch_vault",
- "iatapay",
- "inespay",
- "itaubank",
- "jpmorgan",
- "juspaythreedsserver",
- "mollie",
- "moneris",
- "multisafepay",
- "netcetera",
- "nexinets",
- "nexixpay",
- "nmi",
- "noon",
- "nordea",
- "novalnet",
- "nuvei",
- "opayo",
- "opennode",
- "paybox",
- "paydotcom",
- "payeezy",
- "payload",
- "payme",
- "payone",
- "paypal",
- "paystack",
- "payu",
- "placetopay",
- "plaid",
- "powertranz",
- "prophetpay",
- "redsys",
- "santander",
- "shift4",
- "silverflow",
- "square",
- "stax",
- "stripe",
- "stripebilling",
- "taxjar",
- "threedsecureio",
- "thunes",
- "tokenio",
- "trustpay",
- "tsys",
- "unified_authentication_service",
- "vgs",
- "volt",
- "wellsfargo",
- "wellsfargopayout",
- "wise",
- "worldline",
- "worldpay",
- "worldpayvantiv",
- "worldpayxml",
- "xendit",
- "zen",
- "zsl",
-]
-
-[pm_filters.checkout]
-debit = { country = "AT,BE,BG,HR,CY,CZ,DK,EE,FI,FR,DE,GR,HU,IS,IE,IT,LV,LI,LT,LU,MT,NL,NO,PL,PT,RO,SK,SI,ES,SE,CH,GB,US,AU,HK,SG,SA,AE,BH,MX,AR,CL,CO,PE", currency = "AED,AFN,ALL,AMD,ANG,AOA,AUD,AWG,AZN,BAM,BBD,BDT,BGN,BHD,BIF,BMD,BND,BOB,BRL,BSD,BTN,BWP,BYN,BZD,CAD,CDF,CHF,CLP,CNY,COP,CRC,CUP,CVE,CZK,DJF,DKK,DOP,DZD,EGP,ERN,ETB,EUR,FJD,FKP,GBP,GEL,GHS,GIP,GMD,GNF,GTQ,GYD,HKD,HNL,HRK,HTG,HUF,IDR,ILS,INR,IQD,IRR,ISK,JMD,JOD,JPY,KES,KGS,KHR,KMF,KRW,KWD,KYD,KZT,LAK,LBP,LKR,LRD,LSL,LYD,MAD,MDL,MGA,MKD,MMK,MNT,MOP,MRU,MUR,MVR,MWK,MXN,MYR,MZN,NAD,NGN,NIO,NOK,NPR,NZD,OMR,PAB,PEN,PGK,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,RWF,SAR,SBD,SCR,SDG,SEK,SGD,SHP,SLE,SLL,SOS,SRD,SSP,STN,SYP,SZL,THB,TJS,TMT,TND,TOP,TRY,TTD,TWD,TZS,UAH,UGX,USD,UYU,UZS,VES,VND,VUV,WST,XAF,XCD,XOF,XPF,YER,ZAR,ZMW,ZWL" }
-credit = { country = "AT,BE,BG,HR,CY,CZ,DK,EE,FI,FR,DE,GR,HU,IS,IE,IT,LV,LI,LT,LU,MT,NL,NO,PL,PT,RO,SK,SI,ES,SE,CH,GB,US,AU,HK,SG,SA,AE,BH,MX,AR,CL,CO,PE", currency = "AED,AFN,ALL,AMD,ANG,AOA,AUD,AWG,AZN,BAM,BBD,BDT,BGN,BHD,BIF,BMD,BND,BOB,BRL,BSD,BTN,BWP,BYN,BZD,CAD,CDF,CHF,CLP,CNY,COP,CRC,CUP,CVE,CZK,DJF,DKK,DOP,DZD,EGP,ERN,ETB,EUR,FJD,FKP,GBP,GEL,GHS,GIP,GMD,GNF,GTQ,GYD,HKD,HNL,HRK,HTG,HUF,IDR,ILS,INR,IQD,IRR,ISK,JMD,JOD,JPY,KES,KGS,KHR,KMF,KRW,KWD,KYD,KZT,LAK,LBP,LKR,LRD,LSL,LYD,MAD,MDL,MGA,MKD,MMK,MNT,MOP,MRU,MUR,MVR,MWK,MXN,MYR,MZN,NAD,NGN,NIO,NOK,NPR,NZD,OMR,PAB,PEN,PGK,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,RWF,SAR,SBD,SCR,SDG,SEK,SGD,SHP,SLE,SLL,SOS,SRD,SSP,STN,SYP,SZL,THB,TJS,TMT,TND,TOP,TRY,TTD,TWD,TZS,UAH,UGX,USD,UYU,UZS,VES,VND,VUV,WST,XAF,XCD,XOF,XPF,YER,ZAR,ZMW,ZWL" }
-google_pay = { country = "AL, DZ, AS, AO, AG, AR, AU, AT, AZ, BH, BY, BE, BR, CA, BG, CL, CO, HR, DK, DO, EE, EG, FI, FR, DE, GR, HK, HU, IN, ID, IE, IL, IT, JP, JO, KZ, KE, KW, LV, LB, LT, LU, MY, MX, NL, NZ, NO, OM, PK, PA, PE, PH, PL, PT, QA, RO, SA, SG, SK, ZA, ES, LK, SE, CH, TH, TW, TR, UA, AE, US, UY, VN", currency = "AED, ALL, AOA, AUD, AZN, BGN, BHD, BRL, CAD, CHF, CLP, COP, CZK, DKK, DOP, DZD, EGP, EUR, GBP, HKD, HUF, IDR, ILS, INR, JPY, KES, KWD, KZT, LKR, MXN, MYR, NOK, NZD, OMR, PAB, PEN, PHP, PKR, PLN, QAR, RON, SAR, SEK, SGD, THB, TRY, TWD, UAH, USD, UYU, VND, XCD, ZAR" }
-apple_pay = { country = "AM, AT, AZ, BY, BE, BG, HR, CY, DK, EE, FO, FI, FR, GE, DE, GR, GL, GG, HU, IS, IE, IM, IT, KZ, JE, LV, LI, LT, LU, MT, MD, MC, ME, NL, NO, PL, PT, RO, SM, RS, SK, SI, ES, SE, CH, UA, GB, VA, AU , HK, JP , MY , MN, NZ, SG, TW, VN, EG , MA, ZA, AR, BR, CL, CO, CR, DO, EC, SV, GT, HN, MX, PA, PY, PE, UY, BH, IL, JO, KW, OM,QA, SA, AE, CA", currency = "EGP, MAD, ZAR, AUD, CNY, HKD, JPY, MOP, MYR, MNT, NZD, SGD, KRW, TWD, VND, AMD, EUR, BGN, CZK, DKK, GEL, GBP, HUF, ISK, KZT, CHF, MDL, NOK, PLN, RON, RSD, SEK, UAH, BRL, COP, CRC, DOP, GTQ, HNL, MXN, PAB, PYG, PEN, BSD, UYU, BHD, ILS, JOD, KWD, OMR, QAR, SAR, AED, CAD, USD" }
-
-[pm_filters.cybersource]
-credit = { currency = "USD,GBP,EUR,PLN,SEK,XOF,CAD,KWD,QAR" }
-debit = { currency = "USD,GBP,EUR,PLN,SEK,XOF,CAD,KWD,QAR" }
-apple_pay = { currency = "ARS, CAD, CLP, COP, CNY, EUR, HKD, KWD, MYR, MXN, NZD, PEN, QAR, SAR, SGD, ZAR, UAH, GBP, AED, USD, PLN, SEK" }
-google_pay = { currency = "ARS, AUD, CAD, CLP, COP, EUR, HKD, INR, KWD, MYR, MXN, NZD, PEN, QAR, SAR, SGD, ZAR, UAH, AED, GBP, USD, PLN, SEK" }
-samsung_pay = { currency = "USD,GBP,EUR,SEK" }
-paze = { currency = "USD,SEK" }
-
-[pm_filters.mollie]
-eps = { country = "AT", currency = "EUR" }
-ideal = { country = "NL", currency = "EUR" }
-przelewy24 = { country = "PL", currency = "PLN,EUR" }
-klarna = { country = "DE,AT,NL,BE,FR,GB,IT,ES,PT,SE,DK,FI,NO,CH,IR,CZ,PL,GR,SK", currency = "EUR,GBP,DKK,SEK,NOK,CHF,PLN,CZK" }
-
-[pm_filters.mifinity]
-mifinity = { not_available_flows = { capture_method = "manual" }, country = "BR,CN,SG,MY,DE,CH,DK,GB,ES,AD,GI,FI,FR,GR,HR,IT,JP,MX,AR,CO,CL,PE,VE,UY,PY,BO,EC,GT,HN,SV,NI,CR,PA,DO,CU,PR,NL,NO,PL,PT,SE,RU,TR,TW,HK,MO,AX,AL,DZ,AS,AO,AI,AG,AM,AW,AU,AT,AZ,BS,BH,BD,BB,BE,BZ,BJ,BM,BT,BQ,BA,BW,IO,BN,BG,BF,BI,KH,CM,CA,CV,KY,CF,TD,CX,CC,KM,CG,CK,CI,CW,CY,CZ,DJ,DM,EG,GQ,ER,EE,ET,FK,FO,FJ,GF,PF,TF,GA,GM,GE,GH,GL,GD,GP,GU,GG,GN,GW,GY,HT,HM,VA,IS,IN,ID,IE,IM,IL,JE,JO,KZ,KE,KI,KW,KG,LA,LV,LB,LS,LI,LT,LU,MK,MG,MW,MV,ML,MT,MH,MQ,MR,MU,YT,FM,MD,MC,MN,ME,MS,MA,MZ,NA,NR,NP,NC,NZ,NE,NG,NU,NF,MP,OM,PK,PW,PS,PG,PH,PN,QA,RE,RO,RW,BL,SH,KN,LC,MF,PM,VC,WS,SM,ST,SA,SN,RS,SC,SL,SX,SK,SI,SB,SO,ZA,GS,KR,LK,SR,SJ,SZ,TH,TL,TG,TK,TO,TT,TN,TM,TC,TV,UG,UA,AE,UZ,VU,VN,VG,VI,WF,EH,ZM", currency = "AUD,CAD,CHF,CNY,CZK,DKK,EUR,GBP,INR,JPY,NOK,NZD,PLN,RUB,SEK,ZAR,USD,EGP,UYU,UZS" }
-
-[pm_filters.globepay]
-ali_pay = { country = "GB", currency = "GBP,CNY" }
-we_chat_pay = { country = "GB", currency = "GBP,CNY" }
-
-
-[pm_filters.itaubank]
-pix = { country = "BR", currency = "BRL" }
-
-[pm_filters.nexinets]
-credit = { country = "DE", currency = "EUR" }
-debit = { country = "DE", currency = "EUR" }
-ideal = { country = "DE", currency = "EUR" }
-giropay = { country = "DE", currency = "EUR" }
-sofort = { country = "DE", currency = "EUR" }
-eps = { country = "DE", currency = "EUR" }
-apple_pay = { country = "DE", currency = "EUR" }
-paypal = { country = "DE", currency = "EUR" }
-
-[pm_filters.nuvei]
-credit = { country = "AF,AX,AL,DZ,AS,AD,AO,AI,AQ,AG,AR,AM,AW,AU,AT,AZ,BS,BH,BD,BB,BY,BE,BZ,BJ,BM,BT,BO,BQ,BA,BW,BV,BR,IO,BN,BG,BF,BI,KH,CM,CA,CV,KY,CF,TD,CL,CN,CX,CC,CO,KM,CG,CD,CK,CR,CI,HR,CU,CW,CY,CZ,DK,DJ,DM,DO,EC,EG,SV,GQ,ER,EE,ET,FK,FO,FJ,FI,FR,GF,PF,TF,GA,GM,GE,DE,GH,GI,GR,GL,GD,GP,GU,GT,GG,GN,GW,GY,HT,HM,VA,HN,HK,HU,IS,IN,ID,IR,IQ,IE,IM,IL,IT,JM,JP,JE,JO,KZ,KE,KI,KP,KR,KW,KG,LA,LV,LB,LS,LR,LY,LI,LT,LU,MO,MK,MG,MW,MY,MV,ML,MT,MH,MQ,MR,MU,YT,MX,FM,MD,MC,MN,ME,MS,MA,MZ,MM,NA,NR,NP,NL,NC,NZ,NI,NE,NG,NU,NF,MP,NO,OM,PK,PW,PS,PA,PG,PY,PE,PH,PN,PL,PT,PR,QA,RE,RO,RU,RW,BL,SH,KN,LC,MF,PM,VC,WS,SM,ST,SA,SN,RS,SC,SL,SG,SX,SK,SI,SB,SO,ZA,GS,SS,ES,LK,SD,SR,SJ,SZ,SE,CH,SY,TW,TJ,TZ,TH,TL,TG,TK,TO,TT,TN,TR,TM,TC,TV,UG,UA,AE,GB,UM,UY,UZ,VU,VE,VN,VG,VI,WF,EH,YE,ZM,ZW,US",currency = "AED,ALL,AMD,ARS,AUD,AZN,BAM,BDT,BGN,BHD,BMD,BND,BRL,BYN,CAD,CHF,CLP,CNY,COP,CRC,CZK,DKK,DOP,DZD,EGP,EUR,GBP,GEL,GHS,GTQ,HKD,HUF,IDR,INR,IQD,ISK,JOD,JPY,KES,KGS,KRW,KWD,KYD,KZT,LBP,LKR,MAD,MDL,MKD,MMK,MNT,MUR,MWK,MXN,MYR,MZN,NAD,NGN,NOK,NZD,OMR,PEN,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,SAR,SEK,SGD,SOS,THB,TND,TOP,TRY,TTD,TWD,UAH,UGX,USD,UYU,UZS,VND,XAF,XOF,YER,ZAR" }
-debit = { country = "AF,AX,AL,DZ,AS,AD,AO,AI,AQ,AG,AR,AM,AW,AU,AT,AZ,BS,BH,BD,BB,BY,BE,BZ,BJ,BM,BT,BO,BQ,BA,BW,BV,BR,IO,BN,BG,BF,BI,KH,CM,CA,CV,KY,CF,TD,CL,CN,CX,CC,CO,KM,CG,CD,CK,CR,CI,HR,CU,CW,CY,CZ,DK,DJ,DM,DO,EC,EG,SV,GQ,ER,EE,ET,FK,FO,FJ,FI,FR,GF,PF,TF,GA,GM,GE,DE,GH,GI,GR,GL,GD,GP,GU,GT,GG,GN,GW,GY,HT,HM,VA,HN,HK,HU,IS,IN,ID,IR,IQ,IE,IM,IL,IT,JM,JP,JE,JO,KZ,KE,KI,KP,KR,KW,KG,LA,LV,LB,LS,LR,LY,LI,LT,LU,MO,MK,MG,MW,MY,MV,ML,MT,MH,MQ,MR,MU,YT,MX,FM,MD,MC,MN,ME,MS,MA,MZ,MM,NA,NR,NP,NL,NC,NZ,NI,NE,NG,NU,NF,MP,NO,OM,PK,PW,PS,PA,PG,PY,PE,PH,PN,PL,PT,PR,QA,RE,RO,RU,RW,BL,SH,KN,LC,MF,PM,VC,WS,SM,ST,SA,SN,RS,SC,SL,SG,SX,SK,SI,SB,SO,ZA,GS,SS,ES,LK,SD,SR,SJ,SZ,SE,CH,SY,TW,TJ,TZ,TH,TL,TG,TK,TO,TT,TN,TR,TM,TC,TV,UG,UA,AE,GB,UM,UY,UZ,VU,VE,VN,VG,VI,WF,EH,YE,ZM,ZW,US",currency = "AED,ALL,AMD,ARS,AUD,AZN,BAM,BDT,BGN,BHD,BMD,BND,BRL,BYN,CAD,CHF,CLP,CNY,COP,CRC,CZK,DKK,DOP,DZD,EGP,EUR,GBP,GEL,GHS,GTQ,HKD,HUF,IDR,INR,IQD,ISK,JOD,JPY,KES,KGS,KRW,KWD,KYD,KZT,LBP,LKR,MAD,MDL,MKD,MMK,MNT,MUR,MWK,MXN,MYR,MZN,NAD,NGN,NOK,NZD,OMR,PEN,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,SAR,SEK,SGD,SOS,THB,TND,TOP,TRY,TTD,TWD,UAH,UGX,USD,UYU,UZS,VND,XAF,XOF,YER,ZAR" }
-klarna = { country = "AU,CA,GB,IN,JP,NZ,PH,SG,TH,US",currency = "AED,ALL,AMD,ARS,AUD,AZN,BAM,BDT,BGN,BHD,BMD,BND,BRL,BYN,CAD,CHF,CLP,CNY,COP,CRC,CZK,DKK,DOP,DZD,EGP,EUR,GBP,GEL,GHS,GTQ,HKD,HUF,IDR,INR,IQD,ISK,JOD,JPY,KES,KGS,KRW,KWD,KYD,KZT,LBP,LKR,MAD,MDL,MKD,MMK,MNT,MUR,MWK,MXN,MYR,MZN,NAD,NGN,NOK,NZD,OMR,PEN,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,SAR,SEK,SGD,SOS,THB,TND,TOP,TRY,TTD,TWD,UAH,UGX,USD,UYU,UZS,VND,XAF,XOF,YER,ZAR" }
-afterpay_clearpay = { country = "AU,CA,GB,IN,JP,NZ,PH,SG,TH,US",currency = "AED,ALL,AMD,ARS,AUD,AZN,BAM,BDT,BGN,BHD,BMD,BND,BRL,BYN,CAD,CHF,CLP,CNY,COP,CRC,CZK,DKK,DOP,DZD,EGP,EUR,GBP,GEL,GHS,GTQ,HKD,HUF,IDR,INR,IQD,ISK,JOD,JPY,KES,KGS,KRW,KWD,KYD,KZT,LBP,LKR,MAD,MDL,MKD,MMK,MNT,MUR,MWK,MXN,MYR,MZN,NAD,NGN,NOK,NZD,OMR,PEN,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,SAR,SEK,SGD,SOS,THB,TND,TOP,TRY,TTD,TWD,UAH,UGX,USD,UYU,UZS,VND,XAF,XOF,YER,ZAR" }
-giropay = { currency = "EUR" }
-ideal = { currency = "EUR" }
-sofort = { country = "AU,CA,GB,IN,JP,NZ,PH,SG,TH,US",currency = "AED,ALL,AMD,ARS,AUD,AZN,BAM,BDT,BGN,BHD,BMD,BND,BRL,BYN,CAD,CHF,CLP,CNY,COP,CRC,CZK,DKK,DOP,DZD,EGP,EUR,GBP,GEL,GHS,GTQ,HKD,HUF,IDR,INR,IQD,ISK,JOD,JPY,KES,KGS,KRW,KWD,KYD,KZT,LBP,LKR,MAD,MDL,MKD,MMK,MNT,MUR,MWK,MXN,MYR,MZN,NAD,NGN,NOK,NZD,OMR,PEN,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,SAR,SEK,SGD,SOS,THB,TND,TOP,TRY,TTD,TWD,UAH,UGX,USD,UYU,UZS,VND,XAF,XOF,YER,ZAR" }
-eps = { country = "AU,CA,GB,IN,JP,NZ,PH,SG,TH,US",currency = "AED,ALL,AMD,ARS,AUD,AZN,BAM,BDT,BGN,BHD,BMD,BND,BRL,BYN,CAD,CHF,CLP,CNY,COP,CRC,CZK,DKK,DOP,DZD,EGP,EUR,GBP,GEL,GHS,GTQ,HKD,HUF,IDR,INR,IQD,ISK,JOD,JPY,KES,KGS,KRW,KWD,KYD,KZT,LBP,LKR,MAD,MDL,MKD,MMK,MNT,MUR,MWK,MXN,MYR,MZN,NAD,NGN,NOK,NZD,OMR,PEN,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,SAR,SEK,SGD,SOS,THB,TND,TOP,TRY,TTD,TWD,UAH,UGX,USD,UYU,UZS,VND,XAF,XOF,YER,ZAR" }
-apple_pay = { country = "AU,AT,BY,BE,BR,BG,CA,CN,HR,CY,CZ,DK,EE,FO,FI,FR,GE,DE,GR,GL,GG,HK,HU,IS,IE,IM,IL,IT,JP,JE,KZ,LV,LI,LT,LU,MO,MT,MC,NL,NZ,NO,PL,PT,RO,RU,SM,SA,SG,SK,SI,ES,SE,CH,TW,UA,AE,GB,US,VA",currency = "AED,ALL,AMD,ARS,AUD,AZN,BAM,BDT,BGN,BHD,BMD,BND,BRL,BYN,CAD,CHF,CLP,CNY,COP,CRC,CZK,DKK,DOP,DZD,EGP,EUR,GBP,GEL,GHS,GTQ,HKD,HUF,IDR,INR,IQD,ISK,JOD,JPY,KES,KGS,KRW,KWD,KYD,KZT,LBP,LKR,MAD,MDL,MKD,MMK,MNT,MUR,MWK,MXN,MYR,MZN,NAD,NGN,NOK,NZD,OMR,PEN,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,SAR,SEK,SGD,SOS,THB,TND,TOP,TRY,TTD,TWD,UAH,UGX,USD,UYU,UZS,VND,XAF,XOF,YER,ZAR" }
-google_pay = { country = "AF,AX,AL,DZ,AD,AO,AI,AQ,AG,AR,AM,AW,AU,AT,AZ,BS,BH,BD,BB,BY,BE,BZ,BJ,BM,BT,BO,BQ,BA,BW,BV,BR,IO,BN,BG,BF,KH,CM,CA,CV,KY,CF,TD,CL,CN,TW,CX,CC,CO,KM,CG,CK,CR,CI,HR,CW,CY,CZ,DK,DJ,DM,DO,EC,EG,SV,GQ,ER,EE,ET,FK,FO,FJ,FI,FR,GF,PF,TF,GA,GM,GE,DE,GH,GI,GR,GL,GD,GP,GU,GT,GG,GN,GW,GY,HT,HM,HN,HK,HU,IS,IN,ID,IQ,IE,IM,IL,IT,JM,JP,JE,JO,KZ,KE,KI,KW,KG,LA,LV,LB,LS,LR,LY,LI,LT,LU,MO,MK,MG,MW,MY,MV,ML,MT,MH,MQ,MR,MU,YT,MX,FM,MD,MC,MN,ME,MS,MA,MZ,MM,NA,NR,NP,NL,NC,NZ,NI,NE,NG,NU,NF,MP,NO,OM,PK,PW,PS,PA,PG,PY,PE,PH,PN,PL,PT,PR,QA,RE,RO,RU,RW,BL,SH,KN,LC,MF,PM,VI,VC,WS,SM,ST,SA,SN,RS,SC,SL,SG,SK,SI,SB,SO,ZA,GS,KR,ES,LK,SR,SJ,SZ,SE,CH,TW,TJ,TZ,TH,TL,TG,TK,TO,TT,TN,TR,TM,TC,TV,UG,UA,AE,GB,UY,UZ,VU,VA,VE,VN,VI,WF,EH,YE,ZM,ZW",currency = "AED,ALL,AMD,ARS,AUD,AZN,BAM,BDT,BGN,BHD,BMD,BND,BRL,BYN,CAD,CHF,CLP,CNY,COP,CRC,CZK,DKK,DOP,DZD,EGP,EUR,GBP,GEL,GHS,GTQ,HKD,HUF,IDR,INR,IQD,ISK,JOD,JPY,KES,KGS,KRW,KWD,KYD,KZT,LBP,LKR,MAD,MDL,MKD,MMK,MNT,MUR,MWK,MXN,MYR,MZN,NAD,NGN,NOK,NZD,OMR,PEN,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,SAR,SEK,SGD,SOS,THB,TND,TOP,TRY,TTD,TWD,UAH,UGX,USD,UYU,UZS,VND,XAF,XOF,YER,ZAR" }
-paypal = { country = "AU,CA,GB,IN,JP,NZ,PH,SG,TH,US",currency = "AED,ALL,AMD,ARS,AUD,AZN,BAM,BDT,BGN,BHD,BMD,BND,BRL,BYN,CAD,CHF,CLP,CNY,COP,CRC,CZK,DKK,DOP,DZD,EGP,EUR,GBP,GEL,GHS,GTQ,HKD,HUF,IDR,INR,IQD,ISK,JOD,JPY,KES,KGS,KRW,KWD,KYD,KZT,LBP,LKR,MAD,MDL,MKD,MMK,MNT,MUR,MWK,MXN,MYR,MZN,NAD,NGN,NOK,NZD,OMR,PEN,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,SAR,SEK,SGD,SOS,THB,TND,TOP,TRY,TTD,TWD,UAH,UGX,USD,UYU,UZS,VND,XAF,XOF,YER,ZAR" }
-
-[pm_filters.payload]
-debit = { currency = "USD,CAD" }
-credit = { currency = "USD,CAD" }
-
-[pm_filters.prophetpay]
-card_redirect = { country = "US", currency = "USD" }
-
-[pm_filters.volt]
-open_banking = { country = "DE,GB,AT,BE,CY,EE,ES,FI,FR,GR,HR,IE,IT,LT,LU,LV,MT,NL,PT,SI,SK,BG,CZ,DK,HU,NO,PL,RO,SE,AU,BR", currency = "GBP,EUR,DKK,NOK,PLN,SEK" }
-open_banking_uk = { country = "DE,GB,AT,BE,CY,EE,ES,FI,FR,GR,HR,IE,IT,LT,LU,LV,MT,NL,PT,SI,SK,BG,CZ,DK,HU,NO,PL,RO,SE,AU,BR", currency = "GBP" }
-
-[pm_filters.trustpay]
-instant_bank_transfer = { country = "CZ,SK,GB,AT,DE,IT", currency = "CZK, EUR, GBP" }
-instant_bank_transfer_poland = { country = "PL", currency = "PLN" }
-instant_bank_transfer_finland = { country = "FI", currency = "EUR" }
-sepa = { country = "ES,SK,AT,NL,DE,BE,FR,FI,PT,IE,EE,LT,LV,IT,GB", currency = "EUR" }
-
-[pm_filters.razorpay]
-upi_collect = { country = "IN", currency = "INR" }
-
-[pm_filters.phonepe]
-upi_collect = { country = "IN", currency = "INR" }
-upi_intent = { country = "IN", currency = "INR" }
-
-[pm_filters.paytm]
-upi_collect = { country = "IN", currency = "INR" }
-upi_intent = { country = "IN", currency = "INR" }
-
-[pm_filters.hyperpg]
-credit = { currency = "INR,USD,GBP,EUR" }
-debit = { currency = "INR,USD,GBP,EUR" }
-
-[pm_filters.truelayer]
-open_banking = { currency = "GBP,EUR" }
-
-[payout_method_filters.truelayer]
-open_banking = { currency = "GBP,EUR,PLN" }
-
-[payout_method_filters.trustly]
-trustly = { currency = "BGN,GBP,EUR,PLN,CZK,DKK,HRK,HUF,NOK,PLN,RON,SEK" }
-
-[pm_filters.trustly]
-trustly = { currency = "BGN,GBP,EUR,PLN,CZK,DKK,HRK,HUF,NOK,PLN,RON,SEK" }
-
-[pm_filters.adyen]
-boleto = { country = "BR", currency = "BRL" }
-sofort = { country = "AT,BE,DE,ES,CH,NL", currency = "CHF,EUR" }
-paypal = { country = "AU,NZ,CN,JP,HK,MY,TH,KR,PH,ID,AE,KW,BR,ES,GB,SE,NO,SK,AT,NL,DE,HU,CY,LU,CH,BE,FR,DK,FI,RO,HR,UA,MT,SI,GI,PT,IE,CZ,EE,LT,LV,IT,PL,IS,CA,US", currency = "AUD,BRL,CAD,CZK,DKK,EUR,HKD,HUF,INR,JPY,MYR,MXN,NZD,NOK,PHP,PLN,RUB,GBP,SGD,SEK,CHF,THB,USD" }
-klarna = { country = "AU,AT,BE,CA,CZ,DK,FI,FR,DE,GR,IE,IT,NO,PL,PT,RO,ES,SE,CH,NL,GB,US", currency = "AUD,EUR,CAD,CZK,DKK,NOK,PLN,RON,SEK,CHF,GBP,USD" }
-ideal = { country = "NL", currency = "EUR" }
-
-[pm_filters.affirm]
-affirm = { currency = "USD" }
-
-[pm_filters.amazonpay]
-amazon_pay = { country = "US", currency = "USD" }
-
-[pm_filters.bambora]
-credit = { country = "US,CA", currency = "USD" }
-debit = { country = "US,CA", currency = "USD" }
-
-[pm_filters.barclaycard]
-credit = { currency = "USD,GBP,EUR,PLN,SEK" }
-debit = { currency = "USD,GBP,EUR,PLN,SEK" }
-google_pay = { currency = "ARS, AUD, CAD, CLP, COP, EUR, HKD, INR, KWD, MYR, MXN, NZD, PEN, QAR, SAR, SGD, ZAR, UAH, AED, GBP, USD, PLN, SEK" }
-
-[pm_filters.nexixpay]
-credit = { country = "AT,BE,CY,EE,FI,FR,DE,GR,IE,IT,LV,LT,LU,MT,NL,PT,SK,SI,ES,BG,HR,DK,GB,NO,PL,CZ,RO,SE,CH,HU,AU,BR,US", currency = "ARS,AUD,BHD,CAD,CLP,CNY,COP,HRK,CZK,DKK,HKD,HUF,INR,JPY,KZT,JOD,KRW,KWD,MYR,MXN,NGN,NOK,PHP,QAR,RUB,SAR,SGD,VND,ZAR,SEK,CHF,THB,AED,EGP,GBP,USD,TWD,BYN,RSD,AZN,RON,TRY,AOA,BGN,EUR,UAH,PLN,BRL" }
-debit = { country = "AT,BE,CY,EE,FI,FR,DE,GR,IE,IT,LV,LT,LU,MT,NL,PT,SK,SI,ES,BG,HR,DK,GB,NO,PL,CZ,RO,SE,CH,HU,AU,BR,US", currency = "ARS,AUD,BHD,CAD,CLP,CNY,COP,HRK,CZK,DKK,HKD,HUF,INR,JPY,KZT,JOD,KRW,KWD,MYR,MXN,NGN,NOK,PHP,QAR,RUB,SAR,SGD,VND,ZAR,SEK,CHF,THB,AED,EGP,GBP,USD,TWD,BYN,RSD,AZN,RON,TRY,AOA,BGN,EUR,UAH,PLN,BRL" }
-
-[pm_filters.square]
-credit = { country = "AU,CA,FR,IE,JP,ES,GB,US", currency = "AED,AFN,ALL,AMD,ANG,AOA,ARS,AUD,AWG,AZN,BAM,BBD,BDT,BGN,BHD,BIF,BMD,BND,BOB,BRL,BSD,BTN,BWP,BZD,CAD,CDF,CHF,CLP,CNY,COP,CRC,CUP,CVE,CZK,DJF,DKK,DOP,DZD,EGP,ERN,ETB,EUR,FJD,FKP,GBP,GEL,GHS,GIP,GMD,GNF,GTQ,GYD,HKD,HNL,HRK,HTG,HUF,IDR,ILS,INR,IQD,IRR,ISK,JMD,JOD,JPY,KES,KGS,KHR,KMF,KPW,KRW,KWD,KYD,KZT,LAK,LBP,LKR,LRD,LSL,LYD,MAD,MDL,MGA,MKD,MMK,MNT,MOP,MUR,MVR,MWK,MXN,MYR,MZN,NAD,NGN,NIO,NOK,NPR,NZD,OMR,PAB,PEN,PGK,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,RWF,SAR,SBD,SCR,SDG,SEK,SGD,SHP,SLE,SLL,SOS,SRD,SSP,SVC,SYP,SZL,THB,TJS,TMT,TND,TOP,TRY,TTD,TWD,TZS,UAH,UGX,USD,UYU,UZS,VND,VUV,WST,XAF,XCD,XOF,XPF,YER,ZAR,ZMW" }
-debit = { country = "AU,CA,FR,IE,JP,ES,GB,US", currency = "AED,AFN,ALL,AMD,ANG,AOA,ARS,AUD,AWG,AZN,BAM,BBD,BDT,BGN,BHD,BIF,BMD,BND,BOB,BRL,BSD,BTN,BWP,BZD,CAD,CDF,CHF,CLP,CNY,COP,CRC,CUP,CVE,CZK,DJF,DKK,DOP,DZD,EGP,ERN,ETB,EUR,FJD,FKP,GBP,GEL,GHS,GIP,GMD,GNF,GTQ,GYD,HKD,HNL,HRK,HTG,HUF,IDR,ILS,INR,IQD,IRR,ISK,JMD,JOD,JPY,KES,KGS,KHR,KMF,KPW,KRW,KWD,KYD,KZT,LAK,LBP,LKR,LRD,LSL,LYD,MAD,MDL,MGA,MKD,MMK,MNT,MOP,MUR,MVR,MWK,MXN,MYR,MZN,NAD,NGN,NIO,NOK,NPR,NZD,OMR,PAB,PEN,PGK,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,RWF,SAR,SBD,SCR,SDG,SEK,SGD,SHP,SLE,SLL,SOS,SRD,SSP,SVC,SYP,SZL,THB,TJS,TMT,TND,TOP,TRY,TTD,TWD,TZS,UAH,UGX,USD,UYU,UZS,VND,VUV,WST,XAF,XCD,XOF,XPF,YER,ZAR,ZMW" }
-
-[pm_filters.iatapay]
-upi_collect = { country = "IN", currency = "INR" }
-upi_intent = { country = "IN", currency = "INR" }
-ideal = { country = "NL", currency = "EUR" }
-local_bank_redirect = { country = "AT,BE,EE,FI,FR,DE,IE,IT,LV,LT,LU,NL,PT,ES,GB,IN,HK,SG,TH,BR,MX,GH,VN,MY,PH,JO,AU,CO", currency = "EUR,GBP,INR,HKD,SGD,THB,BRL,MXN,GHS,VND,MYR,PHP,JOD,AUD,COP" }
-duit_now = { country = "MY", currency = "MYR" }
-fps = { country = "GB", currency = "GBP" }
-prompt_pay = { country = "TH", currency = "THB" }
-viet_qr = { country = "VN", currency = "VND" }
-
-[pm_filters.coinbase]
-crypto_currency = { country = "ZA,US,BR,CA,TR,SG,VN,GB,DE,FR,ES,PT,IT,NL,AU" }
-
-[pm_filters.zen]
-credit = { not_available_flows = { capture_method = "manual" } }
-debit = { not_available_flows = { capture_method = "manual" } }
-boleto = { country = "BR", currency = "BRL" }
-efecty = { country = "CO", currency = "COP" }
-multibanco = { country = "PT", currency = "EUR" }
-pago_efectivo = { country = "PE", currency = "PEN" }
-pse = { country = "CO", currency = "COP" }
-pix = { country = "BR", currency = "BRL" }
-red_compra = { country = "CL", currency = "CLP" }
-red_pagos = { country = "UY", currency = "UYU" }
-
-[pm_filters.facilitapay]
-pix = { country = "BR", currency = "BRL" }
-
-[pm_filters.globalpay]
-credit = { country = "AF,AX,AL,DZ,AS,AD,AO,AI,AQ,AG,AR,AM,AW,AU,AT,AZ,BS,BH,BD,BB,BY,BE,BZ,BJ,BM,BT,BO,BQ,BA,BW,BV,BR,IO,BN,BG,BF,BI,KH,CM,CA,CV,KY,CF,TD,CL,CN,CX,CC,CO,KM,CG,CD,CK,CR,CI,HR,CU,CW,CY,CZ,DK,DJ,DM,DO,EC,EG,SV,GQ,ER,EE,SZ,ET,FK,FO,FJ,FI,FR,GF,PF,TF,GA,GM,GE,DE,GH,GI,GR,GL,GD,GP,GU,GT,GG,GN,GW,GY,HT,HM,VA,HN,HK,HU,IS,IN,ID,IR,IQ,IE,IM,IL,IT,JM,JP,JE,JO,KZ,KE,KI,KP,KR,KW,KG,LA,LV,LB,LS,LR,LY,LI,LT,LU,MO,MK,MG,MW,MY,MV,ML,MT,MH,MQ,MR,MU,YT,MX,FM,MD,MC,MN,ME,MS,MA,MZ,MM,NA,NR,NP,NL,NC,NZ,NI,NE,NG,NU,NF,MP,NO,OM,PK,PW,PS,PA,PG,PY,PE,PH,PN,PL,PT,PR,QA,RE,RO,RU,RW,BL,SH,KN,LC,MF,PM,VC,WS,SM,ST,SA,SN,RS,SC,SL,SG,SX,SK,SI,SB,SO,ZA,GS,SS,ES,LK,SD,SR,SJ,SE,CH,SY,TW,TJ,TZ,TH,TL,TG,TK,TO,TT,TN,TR,TM,TC,TV,UG,UA,AE,GB,US,UM,UY,UZ,VU,VE,VN,VG,VI,WF,EH,YE,ZM,ZW", currency = "AFN,DZD,ARS,AMD,AWG,AUD,AZN,BSD,BHD,THB,PAB,BBD,BYN,BZD,BMD,BOB,BRL,BND,BGN,BIF,CVE,CAD,CLP,COP,KMF,CDF,NIO,CRC,CUP,CZK,GMD,DKK,MKD,DJF,DOP,VND,XCD,EGP,SVC,ETB,EUR,FKP,FJD,HUF,GHS,GIP,HTG,PYG,GNF,GYD,HKD,UAH,ISK,INR,IRR,IQD,JMD,JOD,KES,PGK,HRK,KWD,AOA,MMK,LAK,GEL,LBP,ALL,HNL,SLL,LRD,LYD,SZL,LSL,MGA,MWK,MYR,MUR,MXN,MDL,MAD,MZN,NGN,ERN,NAD,NPR,ANG,ILS,TWD,NZD,BTN,KPW,NOK,TOP,PKR,MOP,UYU,PHP,GBP,BWP,QAR,GTQ,ZAR,OMR,KHR,RON,MVR,IDR,RUB,RWF,SHP,SAR,RSD,SCR,SGD,PEN,SBD,KGS,SOS,TJS,SSP,LKR,SDG,SRD,SEK,CHF,SYP,BDT,WST,TZS,KZT,TTD,MNT,TND,TRY,TMT,AED,UGX,USD,UZS,VUV,KRW,YER,JPY,CNY,ZMW,ZWL,PLN,CLF,STD,CUC" }
-debit = { country = "AF,AX,AL,DZ,AS,AD,AO,AI,AQ,AG,AR,AM,AW,AU,AT,AZ,BS,BH,BD,BB,BY,BE,BZ,BJ,BM,BT,BO,BQ,BA,BW,BV,BR,IO,BN,BG,BF,BI,KH,CM,CA,CV,KY,CF,TD,CL,CN,CX,CC,CO,KM,CG,CD,CK,CR,CI,HR,CU,CW,CY,CZ,DK,DJ,DM,DO,EC,EG,SV,GQ,ER,EE,SZ,ET,FK,FO,FJ,FI,FR,GF,PF,TF,GA,GM,GE,DE,GH,GI,GR,GL,GD,GP,GU,GT,GG,GN,GW,GY,HT,HM,VA,HN,HK,HU,IS,IN,ID,IR,IQ,IE,IM,IL,IT,JM,JP,JE,JO,KZ,KE,KI,KP,KR,KW,KG,LA,LV,LB,LS,LR,LY,LI,LT,LU,MO,MK,MG,MW,MY,MV,ML,MT,MH,MQ,MR,MU,YT,MX,FM,MD,MC,MN,ME,MS,MA,MZ,MM,NA,NR,NP,NL,NC,NZ,NI,NE,NG,NU,NF,MP,NO,OM,PK,PW,PS,PA,PG,PY,PE,PH,PN,PL,PT,PR,QA,RE,RO,RU,RW,BL,SH,KN,LC,MF,PM,VC,WS,SM,ST,SA,SN,RS,SC,SL,SG,SX,SK,SI,SB,SO,ZA,GS,SS,ES,LK,SD,SR,SJ,SE,CH,SY,TW,TJ,TZ,TH,TL,TG,TK,TO,TT,TN,TR,TM,TC,TV,UG,UA,AE,GB,US,UM,UY,UZ,VU,VE,VN,VG,VI,WF,EH,YE,ZM,ZW", currency = "AFN,DZD,ARS,AMD,AWG,AUD,AZN,BSD,BHD,THB,PAB,BBD,BYN,BZD,BMD,BOB,BRL,BND,BGN,BIF,CVE,CAD,CLP,COP,KMF,CDF,NIO,CRC,CUP,CZK,GMD,DKK,MKD,DJF,DOP,VND,XCD,EGP,SVC,ETB,EUR,FKP,FJD,HUF,GHS,GIP,HTG,PYG,GNF,GYD,HKD,UAH,ISK,INR,IRR,IQD,JMD,JOD,KES,PGK,HRK,KWD,AOA,MMK,LAK,GEL,LBP,ALL,HNL,SLL,LRD,LYD,SZL,LSL,MGA,MWK,MYR,MUR,MXN,MDL,MAD,MZN,NGN,ERN,NAD,NPR,ANG,ILS,TWD,NZD,BTN,KPW,NOK,TOP,PKR,MOP,UYU,PHP,GBP,BWP,QAR,GTQ,ZAR,OMR,KHR,RON,MVR,IDR,RUB,RWF,SHP,SAR,RSD,SCR,SGD,PEN,SBD,KGS,SOS,TJS,SSP,LKR,SDG,SRD,SEK,CHF,SYP,BDT,WST,TZS,KZT,TTD,MNT,TND,TRY,TMT,AED,UGX,USD,UZS,VUV,KRW,YER,JPY,CNY,ZMW,ZWL,PLN,CLF,STD,CUC" }
-eps = { country = "AT", currency = "EUR" }
-giropay = { country = "DE", currency = "EUR" }
-ideal = { country = "NL", currency = "EUR" }
-sofort = { country = "AT,BE,DE,ES,IT,NL", currency = "EUR" }
-
-[pm_filters.rapyd]
-apple_pay = { country = "BR, CA, CL, CO, DO, SV, MX, PE, PT, US, AT, BE, BG, HR, CY, CZ, DO, DK, EE, FI, FR, GE, DE, GR, GL, HU, IS, IE, IL, IT, LV, LI, LT, LU, MT, MD, MC, ME, NL, NO, PL, RO, SM, SK, SI, ZA, ES, SE, CH, GB, VA, AU, HK, JP, MY, NZ, SG, KR, TW, VN", currency = "AMD, AUD, BGN, BRL, BYN, CAD, CHF, CLP, CNY, COP, CRC, CZK, DKK, DOP, EUR, GBP, GEL, GTQ, HUF, ISK, JPY, KRW, MDL, MXN, MYR, NOK, PAB, PEN, PLN, PYG, RON, RSD, SEK, SGD, TWD, UAH, USD, UYU, VND, ZAR" }
-google_pay = { country = "BR, CA, CL, CO, DO, MX, PE, PT, US, AT, BE, BG, HR, CZ, DK, EE, FI, FR, DE, GR, HU, IE, IL, IT, LV, LT, LU, NZ, NO, GB, PL, RO, RU, SK, ZA, ES, SE, CH, TR, AU, HK, IN, ID, JP, MY, PH, SG, TW, TH, VN", currency = "AUD, BGN, BRL, BYN, CAD, CHF, CLP, COP, CZK, DKK, DOP, EUR, GBP, HUF, IDR, JPY, KES, MXN, MYR, NOK, PAB, PEN, PHP, PLN, RON, RUB, SEK, SGD, THB, TRY, TWD, UAH, USD, UYU, VND, ZAR" }
-credit = { country = "AE,AF,AG,AI,AL,AM,AO,AQ,AR,AS,AT,AU,AW,AX,AZ,BA,BB,BD,BE,BF,BG,BH,BI,BJ,BL,BM,BN,BO,BQ,BR,BS,BT,BV,BW,BY,BZ,CA,CC,CD,CF,CG,CH,CI,CK,CL,CM,CN,CO,CR,CU,CV,CW,CX,CY,CZ,DE,DJ,DK,DM,DO,DZ,EC,EE,EG,EH,ER,ES,ET,FI,FJ,FK,FM,FO,FR,GA,GB,GD,GE,GF,GG,GH,GI,GL,GM,GN,GP,GQ,GR,GT,GU,GW,GY,HK,HM,HN,HR,HT,HU,ID,IE,IL,IM,IN,IO,IQ,IR,IS,IT,JE,JM,JO,JP,KE,KG,KH,KI,KM,KN,KP,KR,KW,KY,KZ,LA,LB,LC,LI,LK,LR,LS,LT,LU,LV,LY,MA,MC,MD,ME,MF,MG,MH,MK,ML,MM,MN,MO,MP,MQ,MR,MS,MT,MU,MV,MW,MX,MY,MZ,NA,NC,NE,NF,NG,NI,NL,NO,NP,NR,NU,NZ,OM,PA,PE,PF,PG,PH,PK,PL,PM,PN,PR,PS,PT,PW,PY,QA,RE,RO,RS,RU,RW,SA,SB,SC,SD,SE,SG,SH,SI,SJ,SK,SL,SM,SN,SO,SR,SS,ST,SV,SX,SY,SZ,TC,TD,TF,TG,TH,TJ,TL,TM,TN,TO,TR,TT,TV,TW,TZ,UA,UG,UM,US,UY,UZ,VA,VC,VE,VG,VI,VN,VU,WF,WS,YE,YT,ZA,ZM,ZW", currency = "AED,AUD,BDT,BGN,BND,BOB,BRL,BWP,CAD,CHF,CNY,COP,CZK,DKK,EGP,EUR,FJD,GBP,GEL,GHS,HKD,HRK,HUF,IDR,ILS,INR,IQD,IRR,ISK,JPY,KES,KRW,KWD,KZT,LAK,LKR,MAD,MDL,MMK,MOP,MXN,MYR,MZN,NAD,NGN,NOK,NPR,NZD,PEN,PHP,PKR,PLN,QAR,RON,RSD,RUB,RWF,SAR,SCR,SEK,SGD,SLL,THB,TRY,TWD,TZS,UAH,UGX,USD,UYU,VND,XAF,XOF,ZAR,ZMW,MWK" }
-debit = { country = "AE,AF,AG,AI,AL,AM,AO,AQ,AR,AS,AT,AU,AW,AX,AZ,BA,BB,BD,BE,BF,BG,BH,BI,BJ,BL,BM,BN,BO,BQ,BR,BS,BT,BV,BW,BY,BZ,CA,CC,CD,CF,CG,CH,CI,CK,CL,CM,CN,CO,CR,CU,CV,CW,CX,CY,CZ,DE,DJ,DK,DM,DO,DZ,EC,EE,EG,EH,ER,ES,ET,FI,FJ,FK,FM,FO,FR,GA,GB,GD,GE,GF,GG,GH,GI,GL,GM,GN,GP,GQ,GR,GT,GU,GW,GY,HK,HM,HN,HR,HT,HU,ID,IE,IL,IM,IN,IO,IQ,IR,IS,IT,JE,JM,JO,JP,KE,KG,KH,KI,KM,KN,KP,KR,KW,KY,KZ,LA,LB,LC,LI,LK,LR,LS,LT,LU,LV,LY,MA,MC,MD,ME,MF,MG,MH,MK,ML,MM,MN,MO,MP,MQ,MR,MS,MT,MU,MV,MW,MX,MY,MZ,NA,NC,NE,NF,NG,NI,NL,NO,NP,NR,NU,NZ,OM,PA,PE,PF,PG,PH,PK,PL,PM,PN,PR,PS,PT,PW,PY,QA,RE,RO,RS,RU,RW,SA,SB,SC,SD,SE,SG,SH,SI,SJ,SK,SL,SM,SN,SO,SR,SS,ST,SV,SX,SY,SZ,TC,TD,TF,TG,TH,TJ,TL,TM,TN,TO,TR,TT,TV,TW,TZ,UA,UG,UM,US,UY,UZ,VA,VC,VE,VG,VI,VN,VU,WF,WS,YE,YT,ZA,ZM,ZW", currency = "AED,AUD,BDT,BGN,BND,BOB,BRL,BWP,CAD,CHF,CNY,COP,CZK,DKK,EGP,EUR,FJD,GBP,GEL,GHS,HKD,HRK,HUF,IDR,ILS,INR,IQD,IRR,ISK,JPY,KES,KRW,KWD,KZT,LAK,LKR,MAD,MDL,MMK,MOP,MXN,MYR,MZN,NAD,NGN,NOK,NPR,NZD,PEN,PHP,PKR,PLN,QAR,RON,RSD,RUB,RWF,SAR,SCR,SEK,SGD,SLL,THB,TRY,TWD,TZS,UAH,UGX,USD,UYU,VND,XAF,XOF,ZAR,ZMW,MWK" }
-
-[pm_filters.bamboraapac]
-credit = { country = "AD,AE,AG,AL,AM,AO,AR,AT,AU,AZ,BA,BB,BD,BE,BG,BH,BI,BJ,BN,BO,BR,BS,BT,BW,BY,BZ,CA,CD,CF,CG,CH,CI,CL,CM,CN,CO,CR,CV,CY,CZ,DE,DK,DJ,DM,DO,DZ,EC,EE,EG,ER,ES,ET,FI,FJ,FM,FR,GA,GB,GD,GE,GG,GH,GM,GN,GQ,GR,GT,GW,GY,HN,HR,HT,HU,ID,IE,IL,IN,IS,IT,JM,JP,JO,KE,KG,KH,KI,KM,KN,KR,KW,KZ,LA,LB,LC,LI,LK,LR,LS,LT,LU,LV,MA,MC,MD,ME,MG,MH,MK,ML,MM,MN,MR,MT,MU,MV,MW,MX,MY,MZ,NA,NE,NG,NI,NL,NO,NP,NR,NZ,OM,PA,PE,PG,PH,PK,PL,PS,PT,PW,PY,QA,RO,RS,RW,SA,SB,SC,SE,SG,SI,SK,SL,SM,SN,SO,SR,SS,ST,SV,SZ,TD,TG,TH,TJ,TL,TM,TN,TO,TR,TT,TV,TZ,UA,UG,US,UY,UZ,VA,VC,VE,VN,VU,WS,ZA,ZM,ZW", currency = "AED,AUD,BDT,BGN,BND,BOB,BRL,BWP,CAD,CHF,CNY,COP,CZK,DKK,EGP,EUR,FJD,GBP,GEL,GHS,HKD,HRK,HUF,IDR,ILS,INR,IQD,IRR,ISK,JPY,KES,KRW,KWD,KZT,LAK,LKR,MAD,MDL,MMK,MOP,MXN,MYR,MZN,NAD,NGN,NOK,NPR,NZD,PEN,PHP,PKR,PLN,QAR,RON,RSD,RUB,RWF,SAR,SCR,SEK,SGD,SLL,THB,TRY,TWD,TZS,UAH,UGX,USD,UYU,VND,XAF,XOF,ZAR,ZMW,MWK" }
-debit = { country = "AD,AE,AG,AL,AM,AO,AR,AT,AU,AZ,BA,BB,BD,BE,BG,BH,BI,BJ,BN,BO,BR,BS,BT,BW,BY,BZ,CA,CD,CF,CG,CH,CI,CL,CM,CN,CO,CR,CV,CY,CZ,DE,DK,DJ,DM,DO,DZ,EC,EE,EG,ER,ES,ET,FI,FJ,FM,FR,GA,GB,GD,GE,GG,GH,GM,GN,GQ,GR,GT,GW,GY,HN,HR,HT,HU,ID,IE,IL,IN,IS,IT,JM,JP,JO,KE,KG,KH,KI,KM,KN,KR,KW,KZ,LA,LB,LC,LI,LK,LR,LS,LT,LU,LV,MA,MC,MD,ME,MG,MH,MK,ML,MM,MN,MR,MT,MU,MV,MW,MX,MY,MZ,NA,NE,NG,NI,NL,NO,NP,NR,NZ,OM,PA,PE,PG,PH,PK,PL,PS,PT,PW,PY,QA,RO,RS,RW,SA,SB,SC,SE,SG,SI,SK,SL,SM,SN,SO,SR,SS,ST,SV,SZ,TD,TG,TH,TJ,TL,TM,TN,TO,TR,TT,TV,TZ,UA,UG,US,UY,UZ,VA,VC,VE,VN,VU,WS,ZA,ZM,ZW", currency = "AED,AUD,BDT,BGN,BND,BOB,BRL,BWP,CAD,CHF,CNY,COP,CZK,DKK,EGP,EUR,FJD,GBP,GEL,GHS,HKD,HRK,HUF,IDR,ILS,INR,IQD,IRR,ISK,JPY,KES,KRW,KWD,KZT,LAK,LKR,MAD,MDL,MMK,MOP,MXN,MYR,MZN,NAD,NGN,NOK,NPR,NZD,PEN,PHP,PKR,PLN,QAR,RON,RSD,RUB,RWF,SAR,SCR,SEK,SGD,SLL,THB,TRY,TWD,TZS,UAH,UGX,USD,UYU,VND,XAF,XOF,ZAR,ZMW,MWK" }
-
-[pm_filters.gocardless]
-ach = { country = "US", currency = "USD" }
-becs = { country = "AU", currency = "AUD" }
-sepa = { country = "AU,AT,BE,BG,CA,HR,CY,CZ,DK,FI,FR,DE,HU,IT,LU,MT,NL,NZ,NO,PL,PT,IE,RO,SK,SI,ZA,ES,SE,CH,GB", currency = "GBP,EUR,SEK,DKK,AUD,NZD,CAD" }
-
-[pm_filters.powertranz]
-credit = { country = "AE,AF,AG,AI,AL,AM,AO,AQ,AR,AS,AT,AU,AW,AX,AZ,BA,BB,BD,BE,BF,BG,BH,BI,BJ,BL,BM,BN,BO,BQ,BR,BS,BT,BV,BW,BY,BZ,CA,CC,CD,CF,CG,CH,CI,CK,CL,CM,CN,CO,CR,CU,CV,CW,CX,CY,CZ,DE,DJ,DK,DM,DO,DZ,EC,EE,EG,EH,ER,ES,ET,FI,FJ,FK,FM,FO,FR,GA,GB,GD,GE,GF,GG,GH,GI,GL,GM,GN,GP,GQ,GR,GT,GU,GW,GY,HK,HM,HN,HR,HT,HU,ID,IE,IL,IM,IN,IO,IQ,IR,IS,IT,JE,JM,JO,JP,KE,KG,KH,KI,KM,KN,KP,KR,KW,KY,KZ,LA,LB,LC,LI,LK,LR,LS,LT,LU,LV,LY,MA,MC,MD,ME,MF,MG,MH,MK,ML,MM,MN,MO,MP,MQ,MR,MS,MT,MU,MV,MW,MX,MY,MZ,NA,NC,NE,NF,NG,NI,NL,NO,NP,NR,NU,NZ,OM,PA,PE,PF,PG,PH,PK,PL,PM,PN,PR,PS,PT,PW,PY,QA,RE,RO,RS,RU,RW,SA,SB,SC,SD,SE,SG,SH,SI,SJ,SK,SL,SM,SN,SO,SR,SS,ST,SV,SX,SY,SZ,TC,TD,TF,TG,TH,TJ,TL,TM,TN,TO,TR,TT,TV,TW,TZ,UA,UG,UM,US,UY,UZ,VA,VC,VE,VG,VI,VN,VU,WF,WS,YE,YT,ZA,ZM,ZW", currency = "BBD,BMD,BSD,CRC,GTQ,HNL,JMD,KYD,TTD,USD" }
-debit = { country = "AE,AF,AG,AI,AL,AM,AO,AQ,AR,AS,AT,AU,AW,AX,AZ,BA,BB,BD,BE,BF,BG,BH,BI,BJ,BL,BM,BN,BO,BQ,BR,BS,BT,BV,BW,BY,BZ,CA,CC,CD,CF,CG,CH,CI,CK,CL,CM,CN,CO,CR,CU,CV,CW,CX,CY,CZ,DE,DJ,DK,DM,DO,DZ,EC,EE,EG,EH,ER,ES,ET,FI,FJ,FK,FM,FO,FR,GA,GB,GD,GE,GF,GG,GH,GI,GL,GM,GN,GP,GQ,GR,GT,GU,GW,GY,HK,HM,HN,HR,HT,HU,ID,IE,IL,IM,IN,IO,IQ,IR,IS,IT,JE,JM,JO,JP,KE,KG,KH,KI,KM,KN,KP,KR,KW,KY,KZ,LA,LB,LC,LI,LK,LR,LS,LT,LU,LV,LY,MA,MC,MD,ME,MF,MG,MH,MK,ML,MM,MN,MO,MP,MQ,MR,MS,MT,MU,MV,MW,MX,MY,MZ,NA,NC,NE,NF,NG,NI,NL,NO,NP,NR,NU,NZ,OM,PA,PE,PF,PG,PH,PK,PL,PM,PN,PR,PS,PT,PW,PY,QA,RE,RO,RS,RU,RW,SA,SB,SC,SD,SE,SG,SH,SI,SJ,SK,SL,SM,SN,SO,SR,SS,ST,SV,SX,SY,SZ,TC,TD,TF,TG,TH,TJ,TL,TM,TN,TO,TR,TT,TV,TW,TZ,UA,UG,UM,US,UY,UZ,VA,VC,VE,VG,VI,VN,VU,WF,WS,YE,YT,ZA,ZM,ZW", currency = "BBD,BMD,BSD,CRC,GTQ,HNL,JMD,KYD,TTD,USD" }
-
-[pm_filters.worldline]
-giropay = { country = "DE", currency = "EUR" }
-ideal = { country = "NL", currency = "EUR" }
-credit = { country = "AD,AE,AF,AG,AI,AL,AM,AO,AQ,AR,AS,AT,AU,AW,AX,AZ,BA,BB,BD,BE,BF,BG,BH,BI,BJ,BL,BM,BN,BO,BQ,BR,BS,BT,BV,BW,BY,BZ,CA,CC,CD,CF,CG,CH,CI,CK,CL,CM,CN,CO,CR,CU,CV,CW,CX,CY,CZ,DE,DJ,DK,DM,DO,DZ,EC,EE,EG,EH,ER,ES,ET,FI,FJ,FK,FM,FO,FR,GA,GB,GD,GE,GF,GG,GH,GI,GL,GM,GN,GP,GQ,GR,GT,GU,GW,GY,HK,HM,HN,HR,HT,HU,ID,IE,IL,IM,IN,IO,IQ,IR,IS,IT,JE,JM,JO,JP,KE,KG,KH,KI,KM,KN,KP,KR,KW,KY,KZ,LA,LB,LC,LI,LK,LR,LS,LT,LU,LV,LY,MA,MC,MD,ME,MF,MG,MH,MK,ML,MM,MN,MO,MP,MQ,MR,MS,MT,MU,MV,MW,MX,MY,MZ,NA,NC,NE,NF,NG,NI,NL,NO,NP,NR,NU,NZ,OM,PA,PE,PF,PG,PH,PK,PL,PM,PN,PR,PS,PT,PW,PY,QA,RE,RO,RS,RU,RW,SA,SB,SC,SD,SE,SG,SH,SI,SJ,SK,SL,SM,SN,SO,SR,SS,ST,SV,SX,SY,SZ,TC,TD,TF,TG,TH,TJ,TL,TM,TN,TO,TR,TT,TV,TW,TZ,UA,UG,UM,US,UY,UZ,VA,VC,VE,VG,VI,VN,VU,WF,WS,YE,YT,ZA,ZM,ZW", currency = "AED,AFN,ALL,AMD,ANG,AOA,ARS,AUD,AWG,AZN,BAM,BBD,BDT,BGN,BHD,BIF,BMD,BND,BOB,BRL,BSD,BTN,BWP,BYN,BZD,CAD,CDF,CHF,CLP,CNY,COP,CRC,CUP,CVE,CZK,DJF,DKK,DOP,DZD,EGP,ERN,ETB,EUR,FJD,FKP,GBP,GEL,GHS,GIP,GMD,GNF,GTQ,GYD,HKD,HNL,HRK,HTG,HUF,IDR,ILS,INR,IQD,IRR,ISK,JMD,JOD,JPY,KES,KGS,KHR,KMF,KPW,KRW,KWD,KYD,KZT,LAK,LBP,LKR,LRD,LSL,LYD,MAD,MDL,MGA,MKD,MMK,MNT,MOP,MRU,MUR,MVR,MWK,MXN,MYR,MZN,NAD,NGN,NIO,NOK,NPR,NZD,OMR,PAB,PEN,PGK,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,RWF,SAR,SBD,SCR,SDG,SEK,SGD,SHP,SLL,SOS,SRD,SSP,SVC,SYP,SZL,THB,TJS,TMT,TND,TOP,TRY,TTD,TWD,TZS,UAH,UGX,USD,UYU,UZS,VND,VUV,WST,XAF,XCD,XOF,XPF,YER,ZAR,ZMW,ZWL" }
-debit = { country = "AD,AE,AF,AG,AI,AL,AM,AO,AQ,AR,AS,AT,AU,AW,AX,AZ,BA,BB,BD,BE,BF,BG,BH,BI,BJ,BL,BM,BN,BO,BQ,BR,BS,BT,BV,BW,BY,BZ,CA,CC,CD,CF,CG,CH,CI,CK,CL,CM,CN,CO,CR,CU,CV,CW,CX,CY,CZ,DE,DJ,DK,DM,DO,DZ,EC,EE,EG,EH,ER,ES,ET,FI,FJ,FK,FM,FO,FR,GA,GB,GD,GE,GF,GG,GH,GI,GL,GM,GN,GP,GQ,GR,GT,GU,GW,GY,HK,HM,HN,HR,HT,HU,ID,IE,IL,IM,IN,IO,IQ,IR,IS,IT,JE,JM,JO,JP,KE,KG,KH,KI,KM,KN,KP,KR,KW,KY,KZ,LA,LB,LC,LI,LK,LR,LS,LT,LU,LV,LY,MA,MC,MD,ME,MF,MG,MH,MK,ML,MM,MN,MO,MP,MQ,MR,MS,MT,MU,MV,MW,MX,MY,MZ,NA,NC,NE,NF,NG,NI,NL,NO,NP,NR,NU,NZ,OM,PA,PE,PF,PG,PH,PK,PL,PM,PN,PR,PS,PT,PW,PY,QA,RE,RO,RS,RU,RW,SA,SB,SC,SD,SE,SG,SH,SI,SJ,SK,SL,SM,SN,SO,SR,SS,ST,SV,SX,SY,SZ,TC,TD,TF,TG,TH,TJ,TL,TM,TN,TO,TR,TT,TV,TW,TZ,UA,UG,UM,US,UY,UZ,VA,VC,VE,VG,VI,VN,VU,WF,WS,YE,YT,ZA,ZM,ZW", currency = "AED,AFN,ALL,AMD,ANG,AOA,ARS,AUD,AWG,AZN,BAM,BBD,BDT,BGN,BHD,BIF,BMD,BND,BOB,BRL,BSD,BTN,BWP,BYN,BZD,CAD,CDF,CHF,CLP,CNY,COP,CRC,CUP,CVE,CZK,DJF,DKK,DOP,DZD,EGP,ERN,ETB,EUR,FJD,FKP,GBP,GEL,GHS,GIP,GMD,GNF,GTQ,GYD,HKD,HNL,HRK,HTG,HUF,IDR,ILS,INR,IQD,IRR,ISK,JMD,JOD,JPY,KES,KGS,KHR,KMF,KPW,KRW,KWD,KYD,KZT,LAK,LBP,LKR,LRD,LSL,LYD,MAD,MDL,MGA,MKD,MMK,MNT,MOP,MRU,MUR,MVR,MWK,MXN,MYR,MZN,NAD,NGN,NIO,NOK,NPR,NZD,OMR,PAB,PEN,PGK,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,RWF,SAR,SBD,SCR,SDG,SEK,SGD,SHP,SLL,SOS,SRD,SSP,SVC,SYP,SZL,THB,TJS,TMT,TND,TOP,TRY,TTD,TWD,TZS,UAH,UGX,USD,UYU,UZS,VND,VUV,WST,XAF,XCD,XOF,XPF,YER,ZAR,ZMW,ZWL" }
-
-[pm_filters.worldpayvantiv]
-debit = { country = "AF,DZ,AW,AU,AZ,BS,BH,BD,BB,BZ,BM,BT,BO,BA,BW,BR,BN,BG,BI,KH,CA,CV,KY,CL,CO,KM,CD,CR,CZ,DK,DJ,ST,DO,EC,EG,SV,ER,ET,FK,FJ,GM,GE,GH,GI,GT,GN,GY,HT,HN,HK,HU,IS,IN,ID,IR,IQ,IE,IL,IT,JM,JP,JO,KZ,KE,KW,LA,LB,LS,LR,LY,LT,MO,MK,MG,MW,MY,MV,MR,MU,MX,MD,MN,MA,MZ,MM,NA,NZ,NI,NG,KP,NO,AR,PK,PG,PY,PE,UY,PH,PL,GB,QA,OM,RO,RU,RW,WS,SG,ST,ZA,KR,LK,SH,SD,SR,SZ,SE,CH,SY,TW,TJ,TZ,TH,TT,TN,TR,UG,UA,US,UZ,VU,VE,VN,ZM,ZW", currency = "AFN,DZD,ANG,AWG,AUD,AZN,BSD,BHD,BDT,BBD,BZD,BMD,BTN,BOB,BAM,BWP,BRL,BND,BGN,BIF,KHR,CAD,CVE,KYD,XOF,XAF,XPF,CLP,COP,KMF,CDF,CRC,EUR,CZK,DKK,DJF,DOP,XCD,EGP,SVC,ERN,ETB,EUR,FKP,FJD,GMD,GEL,GHS,GIP,GTQ,GNF,GYD,HTG,HNL,HKD,HUF,ISK,INR,IDR,IRR,IQD,ILS,JMD,JPY,JOD,KZT,KES,KWD,LAK,LBP,LSL,LRD,LYD,MOP,MKD,MGA,MWK,MYR,MVR,MRU,MUR,MXN,MDL,MNT,MAD,MZN,MMK,NAD,NPR,NZD,NIO,NGN,KPW,NOK,ARS,PKR,PAB,PGK,PYG,PEN,UYU,PHP,PLN,GBP,QAR,OMR,RON,RUB,RWF,WST,SAR,RSD,SCR,SLL,SGD,STN,SBD,SOS,ZAR,KRW,LKR,SHP,SDG,SRD,SZL,SEK,CHF,SYP,TWD,TJS,TZS,THB,TOP,TTD,TND,TRY,TMT,AED,UGX,UAH,USD,UZS,VUV,VND,YER,CNY,ZMW,ZWL" }
-credit = { country = "AF,DZ,AW,AU,AZ,BS,BH,BD,BB,BZ,BM,BT,BO,BA,BW,BR,BN,BG,BI,KH,CA,CV,KY,CL,CO,KM,CD,CR,CZ,DK,DJ,ST,DO,EC,EG,SV,ER,ET,FK,FJ,GM,GE,GH,GI,GT,GN,GY,HT,HN,HK,HU,IS,IN,ID,IR,IQ,IE,IL,IT,JM,JP,JO,KZ,KE,KW,LA,LB,LS,LR,LY,LT,MO,MK,MG,MW,MY,MV,MR,MU,MX,MD,MN,MA,MZ,MM,NA,NZ,NI,NG,KP,NO,AR,PK,PG,PY,PE,UY,PH,PL,GB,QA,OM,RO,RU,RW,WS,SG,ST,ZA,KR,LK,SH,SD,SR,SZ,SE,CH,SY,TW,TJ,TZ,TH,TT,TN,TR,UG,UA,US,UZ,VU,VE,VN,ZM,ZW", currency = "AFN,DZD,ANG,AWG,AUD,AZN,BSD,BHD,BDT,BBD,BZD,BMD,BTN,BOB,BAM,BWP,BRL,BND,BGN,BIF,KHR,CAD,CVE,KYD,XOF,XAF,XPF,CLP,COP,KMF,CDF,CRC,EUR,CZK,DKK,DJF,DOP,XCD,EGP,SVC,ERN,ETB,EUR,FKP,FJD,GMD,GEL,GHS,GIP,GTQ,GNF,GYD,HTG,HNL,HKD,HUF,ISK,INR,IDR,IRR,IQD,ILS,JMD,JPY,JOD,KZT,KES,KWD,LAK,LBP,LSL,LRD,LYD,MOP,MKD,MGA,MWK,MYR,MVR,MRU,MUR,MXN,MDL,MNT,MAD,MZN,MMK,NAD,NPR,NZD,NIO,NGN,KPW,NOK,ARS,PKR,PAB,PGK,PYG,PEN,UYU,PHP,PLN,GBP,QAR,OMR,RON,RUB,RWF,WST,SAR,RSD,SCR,SLL,SGD,STN,SBD,SOS,ZAR,KRW,LKR,SHP,SDG,SRD,SZL,SEK,CHF,SYP,TWD,TJS,TZS,THB,TOP,TTD,TND,TRY,TMT,AED,UGX,UAH,USD,UZS,VUV,VND,YER,CNY,ZMW,ZWL" }
-
-[pm_filters.shift4]
-eps = { country = "AT", currency = "EUR" }
-giropay = { country = "DE", currency = "EUR" }
-ideal = { country = "NL", currency = "EUR" }
-sofort = { country = "AT,BE,CH,DE,ES,FI,FR,GB,IT,NL,PL,SE", currency = "CHF,EUR" }
-credit = { country = "AD,AE,AF,AG,AI,AL,AM,AO,AQ,AR,AS,AT,AU,AW,AX,AZ,BA,BB,BD,BE,BF,BG,BH,BI,BJ,BL,BM,BN,BO,BQ,BR,BS,BT,BV,BW,BY,BZ,CA,CC,CD,CF,CG,CH,CI,CK,CL,CM,CN,CO,CR,CU,CV,CW,CX,CY,CZ,DE,DJ,DK,DM,DO,DZ,EC,EE,EG,EH,ER,ES,ET,FI,FJ,FK,FM,FO,FR,GA,GB,GD,GE,GF,GG,GH,GI,GL,GM,GN,GP,GQ,GR,GT,GU,GW,GY,HK,HM,HN,HR,HT,HU,ID,IE,IL,IM,IN,IO,IQ,IR,IS,IT,JE,JM,JO,JP,KE,KG,KH,KI,KM,KN,KP,KR,KW,KY,KZ,LA,LB,LC,LI,LK,LR,LS,LT,LU,LV,LY,MA,MC,MD,ME,MF,MG,MH,MK,ML,MM,MN,MO,MP,MQ,MR,MS,MT,MU,MV,MW,MX,MY,MZ,NA,NC,NE,NF,NG,NI,NL,NO,NP,NR,NU,NZ,OM,PA,PE,PF,PG,PH,PK,PL,PM,PN,PR,PS,PT,PW,PY,QA,RE,RO,RS,RU,RW,SA,SB,SC,SD,SE,SG,SH,SI,SJ,SK,SL,SM,SN,SO,SR,SS,ST,SV,SX,SY,SZ,TC,TD,TF,TG,TH,TJ,TL,TM,TN,TO,TR,TT,TV,TW,TZ,UA,UG,UM,US,UY,UZ,VA,VC,VE,VG,VI,VN,VU,WF,WS,YE,YT,ZA,ZM,ZW", currency = "AED,AFN,ALL,AMD,ANG,AOA,ARS,AUD,AWG,AZN,BAM,BBD,BDT,BGN,BHD,BIF,BMD,BND,BOB,BRL,BSD,BTN,BWP,BYN,BZD,CAD,CDF,CHF,CLP,CNY,COP,CRC,CUP,CVE,CZK,DJF,DKK,DOP,DZD,EGP,ERN,ETB,EUR,FJD,FKP,GBP,GEL,GHS,GIP,GMD,GNF,GTQ,GYD,HKD,HNL,HRK,HTG,HUF,IDR,ILS,INR,IQD,IRR,ISK,JMD,JOD,JPY,KES,KGS,KHR,KMF,KPW,KRW,KWD,KYD,KZT,LAK,LBP,LKR,LRD,LSL,LYD,MAD,MDL,MGA,MKD,MMK,MNT,MOP,MRU,MUR,MVR,MWK,MXN,MYR,MZN,NAD,NGN,NIO,NOK,NPR,NZD,OMR,PAB,PEN,PGK,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,RWF,SAR,SBD,SCR,SDG,SEK,SGD,SHP,SLL,SOS,SRD,SSP,SVC,SYP,SZL,THB,TJS,TMT,TND,TOP,TRY,TTD,TWD,TZS,UAH,UGX,USD,UYU,UZS,VND,VUV,WST,XAF,XCD,XOF,XPF,YER,ZAR,ZMW,ZWL" }
-debit = { country = "AD,AE,AF,AG,AI,AL,AM,AO,AQ,AR,AS,AT,AU,AW,AX,AZ,BA,BB,BD,BE,BF,BG,BH,BI,BJ,BL,BM,BN,BO,BQ,BR,BS,BT,BV,BW,BY,BZ,CA,CC,CD,CF,CG,CH,CI,CK,CL,CM,CN,CO,CR,CU,CV,CW,CX,CY,CZ,DE,DJ,DK,DM,DO,DZ,EC,EE,EG,EH,ER,ES,ET,FI,FJ,FK,FM,FO,FR,GA,GB,GD,GE,GF,GG,GH,GI,GL,GM,GN,GP,GQ,GR,GT,GU,GW,GY,HK,HM,HN,HR,HT,HU,ID,IE,IL,IM,IN,IO,IQ,IR,IS,IT,JE,JM,JO,JP,KE,KG,KH,KI,KM,KN,KP,KR,KW,KY,KZ,LA,LB,LC,LI,LK,LR,LS,LT,LU,LV,LY,MA,MC,MD,ME,MF,MG,MH,MK,ML,MM,MN,MO,MP,MQ,MR,MS,MT,MU,MV,MW,MX,MY,MZ,NA,NC,NE,NF,NG,NI,NL,NO,NP,NR,NU,NZ,OM,PA,PE,PF,PG,PH,PK,PL,PM,PN,PR,PS,PT,PW,PY,QA,RE,RO,RS,RU,RW,SA,SB,SC,SD,SE,SG,SH,SI,SJ,SK,SL,SM,SN,SO,SR,SS,ST,SV,SX,SY,SZ,TC,TD,TF,TG,TH,TJ,TL,TM,TN,TO,TR,TT,TV,TW,TZ,UA,UG,UM,US,UY,UZ,VA,VC,VE,VG,VI,VN,VU,WF,WS,YE,YT,ZA,ZM,ZW", currency = "AED,AFN,ALL,AMD,ANG,AOA,ARS,AUD,AWG,AZN,BAM,BBD,BDT,BGN,BHD,BIF,BMD,BND,BOB,BRL,BSD,BTN,BWP,BYN,BZD,CAD,CDF,CHF,CLP,CNY,COP,CRC,CUP,CVE,CZK,DJF,DKK,DOP,DZD,EGP,ERN,ETB,EUR,FJD,FKP,GBP,GEL,GHS,GIP,GMD,GNF,GTQ,GYD,HKD,HNL,HRK,HTG,HUF,IDR,ILS,INR,IQD,IRR,ISK,JMD,JOD,JPY,KES,KGS,KHR,KMF,KPW,KRW,KWD,KYD,KZT,LAK,LBP,LKR,LRD,LSL,LYD,MAD,MDL,MGA,MKD,MMK,MNT,MOP,MRU,MUR,MVR,MWK,MXN,MYR,MZN,NAD,NGN,NIO,NOK,NPR,NZD,OMR,PAB,PEN,PGK,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,RWF,SAR,SBD,SCR,SDG,SEK,SGD,SHP,SLL,SOS,SRD,SSP,SVC,SYP,SZL,THB,TJS,TMT,TND,TOP,TRY,TTD,TWD,TZS,UAH,UGX,USD,UYU,UZS,VND,VUV,WST,XAF,XCD,XOF,XPF,YER,ZAR,ZMW,ZWL" }
-boleto = { country = "BR", currency = "BRL" }
-trustly = { currency = "CZK,DKK,EUR,GBP,NOK,SEK" }
-ali_pay = { country = "CN", currency = "CNY" }
-we_chat_pay = { country = "CN", currency = "CNY" }
-klarna = { currency = "EUR,GBP,CHF,SEK" }
-blik = { country = "PL", currency = "PLN" }
-crypto_currency = { currency = "USD,GBP,AED" }
-paysera = { currency = "EUR" }
-skrill = { currency = "USD" }
-
-[pm_filters.getnet]
-credit = { country = "AR, BR, CL, MX, UY, ES, PT, DE, IT, FR, NL, BE, AT, PL, CH, GB, IE, LU, DK, SE, NO, FI, IN, AE", currency = "ARS, BRL, CLP, MXN, UYU, EUR, PLN, CHF, GBP, DKK, SEK, NOK, INR, AED" }
-
-[pm_filters.hipay]
-credit = { country = "GB, CH, SE, DK, NO, PL, CZ, US, CA, JP, HK, AU, ZA", currency = "EUR, GBP, CHF, SEK, DKK, NOK, PLN, CZK, USD, CAD, JPY, HKD, AUD, ZAR" }
-debit = { country = "GB, CH, SE, DK, NO, PL, CZ, US, CA, JP, HK, AU, ZA", currency = "EUR, GBP, CHF, SEK, DKK, NOK, PLN, CZK, USD, CAD, JPY, HKD, AUD, ZAR" }
-
-[pm_filters.moneris]
-credit = { country = "AE, AF, AL, AO, AR, AT, AU, AW, AZ, BA, BB, BD, BE, BG, BH, BI, BM, BN, BO, BR, BT, BY, BZ, CA, CH, CL, CN, CO, CR, CU, CV, CY, CZ, DE, DJ, DK, DO, DZ, EE, EG, ES, FI, FJ, FR, GB, GE, GI, GM, GN, GR, GT, GY, HK, HN, HR, HT, HU, ID, IE, IL, IN, IS, IT, JM, JO, JP, KE, KM, KR, KW, KY, KZ, LA, LK, LR, LS, LV, LT, LU, MA, MD, MG, MK, MO, MR, MT, MU, MV, MW, MX, MY, MZ, NA, NG, NI, NL, NO, NP, NZ, OM, PE, PG, PK, PL, PT, PY, QA, RO, RS, RU, RW, SA, SB, SC, SE, SG, SH, SI, SK, SL, SR, SV, SZ, TH, TJ, TM, TN, TR, TT, TW, TZ, UG, US, UY, UZ, VN, VU, WS, ZA, ZM", currency = "AED, AFN, ALL, ANG, AOA, ARS, AUD, AWG, AZN, BAM, BBD, BDT, BGN, BHD, BIF, BMD, BND, BOB, BRL, BTN, BYN, BZD, CAD, CHF, CLP, CNY, COP, CRC, CUP, CVE, CZK, DJF, DKK, DOP, DZD, EGP, EUR, FJD, GBP, GEL, GIP, GMD, GNF, GTQ, GYD, HKD, HNL, HRK, HTG, HUF, IDR, ILS, INR, ISK, JMD, JOD, JPY, KES, KMF, KRW, KWD, KYD, KZT, LAK, LKR, LRD, LSL, MAD, MDL, MGA, MKD, MOP, MRU, MUR, MVR, MWK, MXN, MYR, MZN, NAD, NGN, NIO, NOK, NPR, NZD, OMR, PEN, PGK, PHP, PKR, PLN, PYG, QAR, RON, RSD, RUB, RWF, SAR, SBD, SCR, SEK, SGD, SHP, SLL, SRD, SVC, SZL, THB, TJS, TMT, TND, TRY, TTD, TWD, TZS, UGX, USD, UYU, UZS, VND, VUV, WST, XCD, XOF, XPF, ZAR, ZMW" }
-debit = { country = "AE, AF, AL, AO, AR, AT, AU, AW, AZ, BA, BB, BD, BE, BG, BH, BI, BM, BN, BO, BR, BT, BY, BZ, CA, CH, CL, CN, CO, CR, CU, CV, CY, CZ, DE, DJ, DK, DO, DZ, EE, EG, ES, FI, FJ, FR, GB, GE, GI, GM, GN, GR, GT, GY, HK, HN, HR, HT, HU, ID, IE, IL, IN, IS, IT, JM, JO, JP, KE, KM, KR, KW, KY, KZ, LA, LK, LR, LS, LV, LT, LU, MA, MD, MG, MK, MO, MR, MT, MU, MV, MW, MX, MY, MZ, NA, NG, NI, NL, NO, NP, NZ, OM, PE, PG, PK, PL, PT, PY, QA, RO, RS, RU, RW, SA, SB, SC, SE, SG, SH, SI, SK, SL, SR, SV, SZ, TH, TJ, TM, TN, TR, TT, TW, TZ, UG, US, UY, UZ, VN, VU, WS, ZA, ZM", currency = "AED, AFN, ALL, ANG, AOA, ARS, AUD, AWG, AZN, BAM, BBD, BDT, BGN, BHD, BIF, BMD, BND, BOB, BRL, BTN, BYN, BZD, CAD, CHF, CLP, CNY, COP, CRC, CUP, CVE, CZK, DJF, DKK, DOP, DZD, EGP, EUR, FJD, GBP, GEL, GIP, GMD, GNF, GTQ, GYD, HKD, HNL, HRK, HTG, HUF, IDR, ILS, INR, ISK, JMD, JOD, JPY, KES, KMF, KRW, KWD, KYD, KZT, LAK, LKR, LRD, LSL, MAD, MDL, MGA, MKD, MOP, MRU, MUR, MVR, MWK, MXN, MYR, MZN, NAD, NGN, NIO, NOK, NPR, NZD, OMR, PEN, PGK, PHP, PKR, PLN, PYG, QAR, RON, RSD, RUB, RWF, SAR, SBD, SCR, SEK, SGD, SHP, SLL, SRD, SVC, SZL, THB, TJS, TMT, TND, TRY, TTD, TWD, TZS, UGX, USD, UYU, UZS, VND, VUV, WST, XCD, XOF, XPF, ZAR, ZMW" }
-apple_pay = { country = "AE, AF, AL, AO, AR, AT, AU, AW, AZ, BA, BB, BD, BE, BG, BH, BI, BM, BN, BO, BR, BT, BY, BZ, CA, CH, CL, CN, CO, CR, CU, CV, CY, CZ, DE, DJ, DK, DO, DZ, EE, EG, ES, FI, FJ, FR, GB, GE, GI, GM, GN, GR, GT, GY, HK, HN, HR, HT, HU, ID, IE, IL, IN, IS, IT, JM, JO, JP, KE, KM, KR, KW, KY, KZ, LA, LK, LR, LS, LV, LT, LU, MA, MD, MG, MK, MO, MR, MT, MU, MV, MW, MX, MY, MZ, NA, NG, NI, NL, NO, NP, NZ, OM, PE, PG, PK, PL, PT, PY, QA, RO, RS, RU, RW, SA, SB, SC, SE, SG, SH, SI, SK, SL, SR, SV, SZ, TH, TJ, TM, TN, TR, TT, TW, TZ, UG, US, UY, UZ, VN, VU, WS, ZA, ZM", currency = "AED, AFN, ALL, ANG, AOA, ARS, AUD, AWG, AZN, BAM, BBD, BDT, BGN, BHD, BIF, BMD, BND, BOB, BRL, BTN, BYN, BZD, CAD, CHF, CLP, CNY, COP, CRC, CUP, CVE, CZK, DJF, DKK, DOP, DZD, EGP, EUR, FJD, GBP, GEL, GIP, GMD, GNF, GTQ, GYD, HKD, HNL, HRK, HTG, HUF, IDR, ILS, INR, ISK, JMD, JOD, JPY, KES, KMF, KRW, KWD, KYD, KZT, LAK, LKR, LRD, LSL, MAD, MDL, MGA, MKD, MOP, MRU, MUR, MVR, MWK, MXN, MYR, MZN, NAD, NGN, NIO, NOK, NPR, NZD, OMR, PEN, PGK, PHP, PKR, PLN, PYG, QAR, RON, RSD, RUB, RWF, SAR, SBD, SCR, SEK, SGD, SHP, SLL, SRD, SVC, SZL, THB, TJS, TMT, TND, TRY, TTD, TWD, TZS, UGX, USD, UYU, UZS, VND, VUV, WST, XCD, XOF, XPF, ZAR, ZMW" }
-google_pay = { country = "AE, AF, AL, AO, AR, AT, AU, AW, AZ, BA, BB, BD, BE, BG, BH, BI, BM, BN, BO, BR, BT, BY, BZ, CA, CH, CL, CN, CO, CR, CU, CV, CY, CZ, DE, DJ, DK, DO, DZ, EE, EG, ES, FI, FJ, FR, GB, GE, GI, GM, GN, GR, GT, GY, HK, HN, HR, HT, HU, ID, IE, IL, IN, IS, IT, JM, JO, JP, KE, KM, KR, KW, KY, KZ, LA, LK, LR, LS, LV, LT, LU, MA, MD, MG, MK, MO, MR, MT, MU, MV, MW, MX, MY, MZ, NA, NG, NI, NL, NO, NP, NZ, OM, PE, PG, PK, PL, PT, PY, QA, RO, RS, RU, RW, SA, SB, SC, SE, SG, SH, SI, SK, SL, SR, SV, SZ, TH, TJ, TM, TN, TR, TT, TW, TZ, UG, US, UY, UZ, VN, VU, WS, ZA, ZM", currency = "AED, AFN, ALL, ANG, AOA, ARS, AUD, AWG, AZN, BAM, BBD, BDT, BGN, BHD, BIF, BMD, BND, BOB, BRL, BTN, BYN, BZD, CAD, CHF, CLP, CNY, COP, CRC, CUP, CVE, CZK, DJF, DKK, DOP, DZD, EGP, EUR, FJD, GBP, GEL, GIP, GMD, GNF, GTQ, GYD, HKD, HNL, HRK, HTG, HUF, IDR, ILS, INR, ISK, JMD, JOD, JPY, KES, KMF, KRW, KWD, KYD, KZT, LAK, LKR, LRD, LSL, MAD, MDL, MGA, MKD, MOP, MRU, MUR, MVR, MWK, MXN, MYR, MZN, NAD, NGN, NIO, NOK, NPR, NZD, OMR, PEN, PGK, PHP, PKR, PLN, PYG, QAR, RON, RSD, RUB, RWF, SAR, SBD, SCR, SEK, SGD, SHP, SLL, SRD, SVC, SZL, THB, TJS, TMT, TND, TRY, TTD, TWD, TZS, UGX, USD, UYU, UZS, VND, VUV, WST, XCD, XOF, XPF, ZAR, ZMW" }
-
-[pm_filters.fiservcommercehub]
-apple_pay = { country = "AE, AF, AL, AO, AR, AT, AU, AW, AZ, BA, BB, BD, BE, BG, BH, BI, BM, BN, BO, BR, BT, BY, BZ, CH, CL, CN, CO, CR, CU, CV, CY, CZ, DE, DJ, DK, DO, DZ, EE, EG, ES, FI, FJ, FR, GB, GE, GI, GM, GN, GR, GT, GY, HK, HN, HR, HT, HU, ID, IE, IL, IN, IS, IT, JM, JO, JP, KE, KM, KR, KW, KY, KZ, LA, LK, LR, LS, LV, LT, LU, MA, MD, MG, MK, MO, MR, MT, MU, MV, MW, MX, MY, MZ, NA, NG, NI, NL, NO, NP, NZ, OM, PE, PG, PK, PL, PT, PY, QA, RO, RS, RU, RW, SA, SB, SC, SE, SG, SH, SI, SK, SL, SR, SV, SZ, TH, TJ, TM, TN, TR, TT, TW, TZ, UG, US, UY, UZ, VN, VU, WS, ZA, ZM", currency = "AED, AFN, ALL, ANG, AOA, ARS, AUD, AWG, AZN, BAM, BBD, BDT, BGN, BHD, BIF, BMD, BND, BOB, BRL, BTN, BYN, BZD, CHF, CLP, CNY, COP, CRC, CUP, CVE, CZK, DJF, DKK, DOP, DZD, EGP, EUR, FJD, GBP, GEL, GIP, GMD, GNF, GTQ, GYD, HKD, HNL, HRK, HTG, HUF, IDR, ILS, INR, ISK, JMD, JOD, JPY, KES, KMF, KRW, KWD, KYD, KZT, LAK, LKR, LRD, LSL, MAD, MDL, MGA, MKD, MOP, MRU, MUR, MVR, MWK, MXN, MYR, MZN, NAD, NGN, NIO, NOK, NPR, NZD, OMR, PEN, PGK, PHP, PKR, PLN, PYG, QAR, RON, RSD, RUB, RWF, SAR, SBD, SCR, SEK, SGD, SHP, SLL, SRD, SVC, SZL, THB, TJS, TMT, TND, TRY, TTD, TWD, TZS, UGX, USD, UYU, UZS, VND, VUV, WST, XCD, XOF, XPF, ZAR, ZMW" }
-google_pay = { country = "AE, AF, AL, AO, AR, AT, AU, AW, AZ, BA, BB, BD, BE, BG, BH, BI, BM, BN, BO, BR, BT, BY, BZ, CH, CL, CN, CO, CR, CU, CV, CY, CZ, DE, DJ, DK, DO, DZ, EE, EG, ES, FI, FJ, FR, GB, GE, GI, GM, GN, GR, GT, GY, HK, HN, HR, HT, HU, ID, IE, IL, IN, IS, IT, JM, JO, JP, KE, KM, KR, KW, KY, KZ, LA, LK, LR, LS, LV, LT, LU, MA, MD, MG, MK, MO, MR, MT, MU, MV, MW, MX, MY, MZ, NA, NG, NI, NL, NO, NP, NZ, OM, PE, PG, PK, PL, PT, PY, QA, RO, RS, RU, RW, SA, SB, SC, SE, SG, SH, SI, SK, SL, SR, SV, SZ, TH, TJ, TM, TN, TR, TT, TW, TZ, UG, US, UY, UZ, VN, VU, WS, ZA, ZM", currency = "AED, AFN, ALL, ANG, AOA, ARS, AUD, AWG, AZN, BAM, BBD, BDT, BGN, BHD, BIF, BMD, BND, BOB, BRL, BTN, BYN, BZD, CHF, CLP, CNY, COP, CRC, CUP, CVE, CZK, DJF, DKK, DOP, DZD, EGP, EUR, FJD, GBP, GEL, GIP, GMD, GNF, GTQ, GYD, HKD, HNL, HRK, HTG, HUF, IDR, ILS, INR, ISK, JMD, JOD, JPY, KES, KMF, KRW, KWD, KYD, KZT, LAK, LKR, LRD, LSL, MAD, MDL, MGA, MKD, MOP, MRU, MUR, MVR, MWK, MXN, MYR, MZN, NAD, NGN, NIO, NOK, NPR, NZD, OMR, PEN, PGK, PHP, PKR, PLN, PYG, QAR, RON, RSD, RUB, RWF, SAR, SBD, SCR, SEK, SGD, SHP, SLL, SRD, SVC, SZL, THB, TJS, TMT, TND, TRY, TTD, TWD, TZS, UGX, USD, UYU, UZS, VND, VUV, WST, XCD, XOF, XPF, ZAR, ZMW" }
-
-[pm_filters.opennode]
-crypto_currency = { country = "US, CA, GB, AU, BR, MX, SG, PH, NZ, ZA, JP, AT, BE, HR, CY, EE, FI, FR, DE, GR, IE, IT, LV, LT, LU, MT, NL, PT, SK, SI, ES", currency = "USD, CAD, GBP, AUD, BRL, MXN, SGD, PHP, NZD, ZAR, JPY, EUR" }
-
-[pm_filters.klarna]
-klarna = { country = "AU,AT,BE,CA,CZ,DK,FI,FR,DE,GR,IE,IT,NL,NZ,NO,PL,PT,ES,SE,CH,GB,US", currency = "CHF,DKK,EUR,GBP,NOK,PLN,SEK,USD,AUD,NZD,CAD" }
-
-[pm_filters.flexiti]
-flexiti = { country = "CA", currency = "CAD" }
-
-[pm_filters.bluesnap]
-credit = { country = "AD,AE,AG,AL,AM,AO,AR,AT,AU,AZ,BA,BB,BD,BE,BG,BH,BI,BJ,BN,BO,BR,BS,BT,BW,BY,BZ,CA,CD,CF,CG,CH,CI,CL,CM,CN,CO,CR,CV,CY,CZ,DE,DK,DJ,DM,DO,DZ,EC,EE,EG,ER,ES,ET,FI,FJ,FM,FR,GA,GB,GD,GE,GG,GH,GM,GN,GQ,GR,GT,GW,GY,HN,HR,HT,HU,ID,IE,IL,IN,IS,IT,JM,JP,JO,KE,KG,KH,KI,KM,KN,KR,KW,KZ,LA,LB,LC,LI,LK,LR,LS,LT,LU,LV,MA,MC,MD,ME,MG,MH,MK,ML,MM,MN,MR,MT,MU,MV,MW,MX,MY,MZ,NA,NE,NG,NI,NL,NO,NP,NR,NZ,OM,PA,PE,PG,PH,PK,PL,PS,PT,PW,PY,QA,RO,RS,RW,SA,SB,SC,SE,SG,SI,SK,SL,SM,SN,SO,SR,SS,ST,SV,SZ,TD,TG,TH,TJ,TL,TM,TN,TO,TR,TT,TV,TZ,UA,UG,US,UY,UZ,VA,VC,VE,VN,VU,WS,ZA,ZM,ZW", currency = "AED,AFN,ALL,AMD,ANG,ARS,AUD,AWG,BAM,BBD,BGN,BHD,BMD,BND,BOB,BRL,BSD,BWP,CAD,CHF,CLP,CNY,COP,CRC,CZK,DKK,DOP,DZD,EGP,EUR,FJD,GBP,GEL,GIP,GTQ,HKD,HUF,IDR,ILS,INR,ISK,JMD,JPY,KES,KHR,KRW,KWD,KYD,KZT,LBP,LKR,MAD,MDL,MKD,MUR,MWK,MXN,MYR,NAD,NGN,NOK,NPR,NZD,OMR,PAB,PEN,PGK,PHP,PLN,PKR,QAR,RON,RSD,RUB,SAR,SCR,SDG,SEK,SGD,THB,TND,TRY,TTD,TWD,TZS,UAH,USD,UYU,UZS,VND,XAF,XCD,XOF,ZAR"}
-google_pay = { country = "AL, DZ, AS, AO, AG, AR, AU, AT, AZ, BH, BY, BE, BR, BG, CL, CO, HR, CZ, DK, DO, EG, EE, FI, FR, DE, GR, HK, HU, IN, ID, IE, IL, IT, JP, JO, KZ, KE, KW, LV, LB, LT, LU, MY, MX, NL, NZ, NO, OM, PK, PA, PE, PH, PL, PT, QA, RO, RU, SA, SG, SK, ZA, ES, LK, SE, CH, TW, TH, TR, UA, AE, GB, US, UY, VN", currency = "ALL, DZD, USD, XCD, ARS, AUD, EUR, BHD, BRL, BGN, CAD, CLP, COP, CZK, DKK, DOP, EGP, HKD, HUF, INR, IDR, ILS, JPY, KZT, KES, KWD, LBP, MYR, MXN, NZD, NOK, OMR, PKR, PAB, PEN, PHP, PLN, QAR, RON, RUB, SAR, SGD, ZAR, LKR, SEK, CHF, TWD, THB, TRY, UAH, AED, GBP, UYU, VND"}
-apple_pay = { country = "EG, MA, ZA, AU, HK, JP, MO, MY, MN, NZ, SG, KR, TW, VN, AM, AT, AZ, BY, BE, BG, HR, CY, DK, EE, FO, FI, FR, GE, DE, GR, GL, GG, HU, IS, IE, IM, IT , KZ, JE, LV, LI, LT, LU, MT, MD, MC, ME, NL, NO, PL, PT, RO, SM, RS, SI, ES, SE, CH, UA, GB, VA, AR, BR, CL, CO, CR, DO, EC, SV, GT, HN, MX, PA, PY, PE, BS, UY, BH, IL, JO, KW, OM, PS, QA, SA, AE, CA, US", currency = "EGP, MAD, ZAR, AUD, CNY, HKD, JPY, MYR, NZD, SGD, KRW, TWD, VND, AMD, EUR, BGN, CZK, DKK, GEL, GBP, HUF, ISK, KZT, CHF, MDL, NOK, PLN, RON, RSD, SEK, UAH, GBP, ARS, BRL, CLP, COP, CRC, DOP, USD, GTQ, MXN, PAB, PEN, BSD, UYU, BHD, ILS, KWD, OMR, QAR, SAR, AED, CAD"}
-
-[pm_filters.inespay]
-sepa = { country = "ES", currency = "EUR" }
-
-[pm_filters.tesouro]
-credit = { country = "AF,AL,DZ,AD,AO,AI,AG,AR,AM,AW,AU,AT,AZ,BS,BH,BD,BB,BY,BE,BZ,BJ,BM,BT,BO,BA,BW,BN,BG,BF,BI,KH,CM,CA,CV,KY,CF,TD,CL,CN,CO,KM,CD,CG,CK,CR,HR,CU,CW,CY,CZ,DK,DJ,DM,DO,EC,SV,GQ,ER,EE,ET,FK,FO,FJ,FI,FR,GF,PF,TF,GA,GM,GE,DE,GH,GI,GR,GL,GD,GP,GU,GT,GG,GN,GW,GY,HT,HM,VA,HN,HK,HU,IS,ID,IR,IQ,IE,IM,IL,IT,JM,JP,JE,JO,KZ,KE,KI,KR,KW,KG,LA,LV,LB,LS,LR,LY,LI,LT,LU,MO,MG,MW,MY,MV,ML,MT,MH,MR,MU,MX,FM,MD,MC,MN,ME,MS,MA,MZ,MM,NA,NR,NP,NL,NC,NZ,NI,NE,NG,NU,NO,OM,PK,PW,PS,PA,PG,PY,PE,PH,PL,PT,PR,QA,CG,RO,RW,KN,LC,VC,WS,SM,ST,SA,SN,RS,SC,SL,SG,SX,SK,SI,SO,ZA,GS,ES,LK,SR,SJ,SZ,SE,CH,TW,TJ,TZ,TH,TL,TG,TO,TT,TN,TR,TM,TC,TV,UG,UA,AE,GB,US,UY,UZ,VU,VE,VN,VG,WF,YE,ZM,ZW", currency = "AED,AFN,ALL,AMD,ANG,AOA,ARS,AUD,AWG,AZN,BAM,BBD,BDT,BGN,BHD,BIF,BMD,BND,BOB,BRL,BSD,BTN,BWP,BYN,BZD,CAD,CDF,CHF,CLF,CLP,CNY,COP,CRC,CUC,CUP,CVE,CZK,DJF,DKK,DOP,DZD,EGP,ERN,ETB,EUR,FJD,FKP,GBP,GEL,GHS,GIP,GMD,GNF,GTQ,GYD,HKD,HNL,HRK,HTG,HUF,IDR,ILS,INR,IQD,IRR,ISK,JMD,JOD,JPY,KES,KGS,KHR,KMF,KPW,KRW,KWD,KYD,KZT,LAK,LBP,LKR,LRD,LSL,LYD,MAD,MDL,MGA,MKD,MMK,MNT,MOP,MRU,MUR,MVR,MWK,MXN,MYR,MZN,NAD,NGN,NIO,NOK,NPR,NZD,OMR,PAB,PEN,PGK,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,RWF,SAR,SBD,SCR,SDG,SEK,SGD,SHP,SLE,SLL,SOS,SRD,SSP,STD,STN,SVC,SYP,SZL,THB,TJS,TMT,TND,TOP,TRY,TTD,TWD,TZS,UAH,UGX,USD,UYU,UZS,VES,VND,VUV,WST,XAF,XCD,XOF,XPF,YER,ZAR,ZMW,ZWL" }
-debit = { country = "AF,AL,DZ,AD,AO,AI,AG,AR,AM,AW,AU,AT,AZ,BS,BH,BD,BB,BY,BE,BZ,BJ,BM,BT,BO,BA,BW,BN,BG,BF,BI,KH,CM,CA,CV,KY,CF,TD,CL,CN,CO,KM,CD,CG,CK,CR,HR,CU,CW,CY,CZ,DK,DJ,DM,DO,EC,SV,GQ,ER,EE,ET,FK,FO,FJ,FI,FR,GF,PF,TF,GA,GM,GE,DE,GH,GI,GR,GL,GD,GP,GU,GT,GG,GN,GW,GY,HT,HM,VA,HN,HK,HU,IS,ID,IR,IQ,IE,IM,IL,IT,JM,JP,JE,JO,KZ,KE,KI,KR,KW,KG,LA,LV,LB,LS,LR,LY,LI,LT,LU,MO,MG,MW,MY,MV,ML,MT,MH,MR,MU,MX,FM,MD,MC,MN,ME,MS,MA,MZ,MM,NA,NR,NP,NL,NC,NZ,NI,NE,NG,NU,NO,OM,PK,PW,PS,PA,PG,PY,PE,PH,PL,PT,PR,QA,CG,RO,RW,KN,LC,VC,WS,SM,ST,SA,SN,RS,SC,SL,SG,SX,SK,SI,SO,ZA,GS,ES,LK,SR,SJ,SZ,SE,CH,TW,TJ,TZ,TH,TL,TG,TO,TT,TN,TR,TM,TC,TV,UG,UA,AE,GB,US,UY,UZ,VU,VE,VN,VG,WF,YE,ZM,ZW", currency = "AED,AFN,ALL,AMD,ANG,AOA,ARS,AUD,AWG,AZN,BAM,BBD,BDT,BGN,BHD,BIF,BMD,BND,BOB,BRL,BSD,BTN,BWP,BYN,BZD,CAD,CDF,CHF,CLF,CLP,CNY,COP,CRC,CUC,CUP,CVE,CZK,DJF,DKK,DOP,DZD,EGP,ERN,ETB,EUR,FJD,FKP,GBP,GEL,GHS,GIP,GMD,GNF,GTQ,GYD,HKD,HNL,HRK,HTG,HUF,IDR,ILS,INR,IQD,IRR,ISK,JMD,JOD,JPY,KES,KGS,KHR,KMF,KPW,KRW,KWD,KYD,KZT,LAK,LBP,LKR,LRD,LSL,LYD,MAD,MDL,MGA,MKD,MMK,MNT,MOP,MRU,MUR,MVR,MWK,MXN,MYR,MZN,NAD,NGN,NIO,NOK,NPR,NZD,OMR,PAB,PEN,PGK,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,RWF,SAR,SBD,SCR,SDG,SEK,SGD,SHP,SLE,SLL,SOS,SRD,SSP,STD,STN,SVC,SYP,SZL,THB,TJS,TMT,TND,TOP,TRY,TTD,TWD,TZS,UAH,UGX,USD,UYU,UZS,VES,VND,VUV,WST,XAF,XCD,XOF,XPF,YER,ZAR,ZMW,ZWL" }
-apple_pay = { currency = "USD" }
-google_pay = { currency = "USD" }
-
-[pm_filters.fiserv]
-credit = { country = "AU,NZ,CN,HK,IN,LK,KR,MY,SG,GB,BE,FR,DE,IT,ME,NL,PL,ES,ZA,AR,BR,CO,MX,PA,UY,US,CA", currency = "AFN,ALL,DZD,AOA,ARS,AMD,AWG,AUD,AZN,BSD,BHD,BDT,BBD,BYN,BZD,BMD,BTN,BOB,VES,BAM,BWP,BRL,BND,BGN,BIF,KHR,CAD,CVE,KYD,XAF,CLP,CNY,COP,KMF,CDF,CRC,HRK,CUP,CZK,DKK,DJF,DOP,XCD,EGP,ERN,ETB,EUR,FKP,FJD,XPF,GMD,GEL,GHS,GIP,GTQ,GNF,GYD,HTG,HNL,HKD,HUF,ISK,INR,IDR,IRR,IQD,ILS,JMD,JPY,JOD,KZT,KES,KGS,KWD,LAK,LBP,LSL,LRD,LYD,MOP,MKD,MGA,MWK,MYR,MVR,MRU,MUR,MXN,MDL,MNT,MAD,MZN,MMK,NAD,NPR,ANG,NZD,NIO,NGN,VUV,KPW,NOK,OMR,PKR,PAB,PGK,PYG,PEN,PHP,PLN,GBP,QAR,RON,RUB,RWF,SHP,SVC,WST,STN,SAR,RSD,SCR,SLL,SGD,SBD,SOS,ZAR,KRW,SSP,LKR,SDG,SRD,SZL,SEK,CHF,SYP,TWD,TJS,TZS,THB,TOP,TTD,TND,TRY,TMT,UGX,UAH,AED,USD,UYU,UZS,VND,XOF,YER,ZMW,ZWL" }
-debit = { country = "AU,NZ,CN,HK,IN,LK,KR,MY,SG,GB,BE,FR,DE,IT,ME,NL,PL,ES,ZA,AR,BR,CO,MX,PA,UY,US,CA", currency = "AFN,ALL,DZD,AOA,ARS,AMD,AWG,AUD,AZN,BSD,BHD,BDT,BBD,BYN,BZD,BMD,BTN,BOB,VES,BAM,BWP,BRL,BND,BGN,BIF,KHR,CAD,CVE,KYD,XAF,CLP,CNY,COP,KMF,CDF,CRC,HRK,CUP,CZK,DKK,DJF,DOP,XCD,EGP,ERN,ETB,EUR,FKP,FJD,XPF,GMD,GEL,GHS,GIP,GTQ,GNF,GYD,HTG,HNL,HKD,HUF,ISK,INR,IDR,IRR,IQD,ILS,JMD,JPY,JOD,KZT,KES,KGS,KWD,LAK,LBP,LSL,LRD,LYD,MOP,MKD,MGA,MWK,MYR,MVR,MRU,MUR,MXN,MDL,MNT,MAD,MZN,MMK,NAD,NPR,ANG,NZD,NIO,NGN,VUV,KPW,NOK,OMR,PKR,PAB,PGK,PYG,PEN,PHP,PLN,GBP,QAR,RON,RUB,RWF,SHP,SVC,WST,STN,SAR,RSD,SCR,SLL,SGD,SBD,SOS,ZAR,KRW,SSP,LKR,SDG,SRD,SZL,SEK,CHF,SYP,TWD,TJS,TZS,THB,TOP,TTD,TND,TRY,TMT,UGX,UAH,AED,USD,UYU,UZS,VND,XOF,YER,ZMW,ZWL" }
-paypal = { currency = "AUD,EUR,BRL,CAD,CNY,EUR,EUR,EUR,GBP,HKD,INR,EUR,JPY,MYR,EUR,NZD,PHP,PLN,SGD,USD", country = "AU, BE, BR, CA, CN, DE, ES, FR, GB, HK, IN, IT, JP, MY, NL, NZ, PH, PL, SG, US" }
-google_pay = { country = "AU,AT,BE,BR,CA,CN,HK,MY,NZ,SG,US", currency = "AUD,EUR,EUR,BRL,CAD,CNY,HKD,MYR,NZD,SGD,USD" }
-
-[pm_filters.stax]
-credit = { country = "US", currency = "USD" }
-debit = { country = "US", currency = "USD" }
-ach = { country = "US", currency = "USD" }
-
-[pm_filters.braintree]
-credit = { country = "AD,AT,AU,BE,BG,CA,CH,CY,CZ,DE,DK,EE,ES,FI,FR,GB,GG,GI,GR,HK,HR,HU,IE,IM,IT,JE,LI,LT,LU,LV,MT,MC,MY,NL,NO,NZ,PL,PT,RO,SE,SG,SI,SK,SM,US", currency = "AED,AMD,AOA,ARS,AUD,AWG,AZN,BAM,BBD,BDT,BGN,BIF,BMD,BND,BOB,BRL,BSD,BWP,BYN,BZD,CAD,CHF,CLP,CNY,COP,CRC,CVE,CZK,DJF,DKK,DOP,DZD,EGP,ETB,EUR,FJD,FKP,GBP,GEL,GHS,GIP,GMD,GNF,GTQ,GYD,HKD,HNL,HRK,HTG,HUF,IDR,ILS,INR,ISK,JMD,JPY,KES,KGS,KHR,KMF,KRW,KYD,KZT,LAK,LBP,LKR,LRD,LSL,MAD,MDL,MKD,MNT,MOP,MUR,MVR,MWK,MXN,MYR,MZN,NAD,NGN,NIO,NOK,NPR,NZD,PAB,PEN,PGK,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,RWF,SAR,SBD,SCR,SEK,SGD,SHP,SLL,SOS,SRD,STD,SVC,SYP,SZL,THB,TJS,TOP,TRY,TTD,TWD,TZS,UAH,UGX,USD,UYU,UZS,VES,VND,VUV,WST,XAF,XCD,XOF,XPF,YER,ZAR,ZMW,ZWL" }
-debit = { country = "AD,AT,AU,BE,BG,CA,CH,CY,CZ,DE,DK,EE,ES,FI,FR,GB,GG,GI,GR,HK,HR,HU,IE,IM,IT,JE,LI,LT,LU,LV,MT,MC,MY,NL,NO,NZ,PL,PT,RO,SE,SG,SI,SK,SM,US", currency = "AED,AMD,AOA,ARS,AUD,AWG,AZN,BAM,BBD,BDT,BGN,BIF,BMD,BND,BOB,BRL,BSD,BWP,BYN,BZD,CAD,CHF,CLP,CNY,COP,CRC,CVE,CZK,DJF,DKK,DOP,DZD,EGP,ETB,EUR,FJD,FKP,GBP,GEL,GHS,GIP,GMD,GNF,GTQ,GYD,HKD,HNL,HRK,HTG,HUF,IDR,ILS,INR,ISK,JMD,JPY,KES,KGS,KHR,KMF,KRW,KYD,KZT,LAK,LBP,LKR,LRD,LSL,MAD,MDL,MKD,MNT,MOP,MUR,MVR,MWK,MXN,MYR,MZN,NAD,NGN,NIO,NOK,NPR,NZD,PAB,PEN,PGK,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,RWF,SAR,SBD,SCR,SEK,SGD,SHP,SLL,SOS,SRD,STD,SVC,SYP,SZL,THB,TJS,TOP,TRY,TTD,TWD,TZS,UAH,UGX,USD,UYU,UZS,VES,VND,VUV,WST,XAF,XCD,XOF,XPF,YER,ZAR,ZMW,ZWL" }
-
-[pm_filters.aci]
-credit = { country = "AD,AE,AT,BE,BG,CH,CN,CO,CR,CY,CZ,DE,DK,DO,EE,EG,ES,ET,FI,FR,GB,GH,GI,GR,GT,HN,HK,HR,HU,ID,IE,IS,IT,JP,KH,LA,LI,LT,LU,LY,MK,MM,MX,MY,MZ,NG,NZ,OM,PA,PE,PK,PL,PT,QA,RO,SA,SN,SE,SI,SK,SV,TH,UA,US,UY,VN,ZM", currency = "AED,ALL,ARS,BGN,CHF,CLP,CNY,COP,CRC,CZK,DKK,DOP,EGP,EUR,GBP,GHS,HKD,HNL,HRK,HUF,IDR,ILS,ISK,JPY,KHR,KPW,LAK,LKR,MAD,MKD,MMK,MXN,MYR,MZN,NGN,NOK,NZD,OMR,PAB,PEN,PHP,PKR,PLN,QAR,RON,RSD,SAR,SEK,SGD,THB,TRY,TWD,UAH,USD,UYU,VND,ZAR,ZMW" }
-debit = { country = "AD,AE,AT,BE,BG,CH,CN,CO,CR,CY,CZ,DE,DK,DO,EE,EG,ES,ET,FI,FR,GB,GH,GI,GR,GT,HN,HK,HR,HU,ID,IE,IS,IT,JP,KH,LA,LI,LT,LU,LY,MK,MM,MX,MY,MZ,NG,NZ,OM,PA,PE,PK,PL,PT,QA,RO,SA,SN,SE,SI,SK,SV,TH,UA,US,UY,VN,ZM", currency = "AED,ALL,ARS,BGN,CHF,CLP,CNY,COP,CRC,CZK,DKK,DOP,EGP,EUR,GBP,GHS,HKD,HNL,HRK,HUF,IDR,ILS,ISK,JPY,KHR,KPW,LAK,LKR,MAD,MKD,MMK,MXN,MYR,MZN,NGN,NOK,NZD,OMR,PAB,PEN,PHP,PKR,PLN,QAR,RON,RSD,SAR,SEK,SGD,THB,TRY,TWD,UAH,USD,UYU,VND,ZAR,ZMW" }
-mb_way = { country = "EE,ES,PT", currency = "EUR" }
-ali_pay = { country = "CN", currency = "CNY" }
-eps = { country = "AT", currency = "EUR" }
-ideal = { country = "NL", currency = "EUR" }
-giropay = { country = "DE", currency = "EUR" }
-sofort = { country = "AT,BE,CH,DE,ES,GB,IT,NL,PL", currency = "CHF,EUR,GBP,HUF,PLN" }
-interac = { country = "CA", currency = "CAD,USD" }
-przelewy24 = { country = "PL", currency = "CZK,EUR,GBP,PLN" }
-trustly = { country = "ES,GB,SE,NO,AT,NL,DE,DK,FI,EE,LT,LV", currency = "CZK,DKK,EUR,GBP,NOK,SEK" }
-klarna = { country = "AU,AT,BE,CA,CZ,DK,FI,FR,DE,GR,IE,IT,NL,NZ,NO,PL,PT,ES,SE,CH,GB,US", currency = "CHF,DKK,EUR,GBP,NOK,PLN,SEK,USD,AUD,NZD,CAD" }
-apple_pay = { country = "AU,CN,HK,JP,MO,MY,NZ,SG,TW,AM,AT,AZ,BY,BE,BG,HR,CY,CZ,DK,EE,FO,FI,FR,GE,DE,GR,GL,GG,HU,IS,IE,IM,IT,KZ,JE,LV,LI,LT,LU,MT,MD,MC,ME,NL,NO,PL,PT,RO,SM,RS,SK,SI,ES,SE,CH,UA,GB,AR,CO,CR,BR,MX,PE,BH,IL,JO,KW,PS,QA,SA,AE,CA,US,KR,VN,MA,ZA", currency = "AED,AUD,CAD,CHF,EUR,GBP,HKD,SGD,USD" }
-google_pay = { country = "AL,DZ,AS,AO,AG,AR,AU,AT,AZ,BH,BY,BE,BR,BG,CA,CL,CO,HR,CZ,DK,DO,EG,EE,FI,FR,DE,GR,HK,HU,IN,ID,IE,IL,IT,JP,JO,KZ,KE,KW,LV,LB,LT,LU,MY,MX,NL,NZ,NO,OM,PK,PA,PE,PH,PL,PT,QA,RO,SA,SG,SK,ZA,ES,LK,SE,CH,TW,TH,TR,UA,AE,GB,US,UY,VN" }
-samsung_pay = { country = "AU,BH,BR,CA,CN,DK,FI,FR,DE,HK,IN,IT,JP,KZ,KR,KW,MY,NZ,NO,OM,QA,SA,SG,ZA,ES,SE,CH,TW,AE,GB,US", currency = "AED,AUD,CAD,CHF,EUR,GBP,HKD,SGD,USD" }
-
-[pm_filters.gigadat]
-interac = { currency = "CAD"}
-
-[pm_filters.loonio]
-interac = { currency = "CAD"}
-
-[pm_filters.dlocal]
-oxxo = { currency = "MXN" }
-
-[pm_filters.authorizedotnet]
-credit = { currency = "CAD,USD" }
-debit = { currency = "CAD,USD" }
-google_pay = { currency = "CHF,DKK,EUR,GBP,NOK,PLN,SEK,USD,AUD,NZD,CAD" }
-apple_pay = { currency = "EUR,GBP,ISK,USD,AUD,CAD,BRL,CLP,COP,CRC,CZK,DKK,EGP,GEL,GHS,GTQ,HNL,HKD,HUF,ILS,INR,JPY,KZT,KRW,KWD,MAD,MXN,MYR,NOK,NZD,PEN,PLN,PYG,QAR,RON,SAR,SEK,SGD,THB,TWD,UAH,AED,VND,ZAR" }
-paypal = { currency = "AUD,BRL,CAD,CHF,CNY,CZK,DKK,EUR,GBP,HKD,HUF,ILS,JPY,MXN,MYR,NOK,NZD,PHP,PLN,SEK,SGD,THB,TWD,USD" }
-
-[pm_filters.dwolla]
-ach = { country = "US", currency = "USD" }
-
-[pm_filters.forte]
-credit = { country = "US, CA", currency = "CAD,USD" }
-debit = { country = "US, CA", currency = "CAD,USD" }
-
-[pm_filters.nordea]
-sepa = { country = "DK,FI,NO,SE", currency = "DKK,EUR,NOK,SEK" }
-
-[pm_filters.fiuu]
-duit_now = { country = "MY", currency = "MYR" }
-apple_pay = { country = "MY", currency = "MYR" }
-google_pay = { country = "MY", currency = "MYR" }
-online_banking_fpx = { country = "MY", currency = "MYR" }
-credit = { country = "CN,HK,ID,MY,PH,SG,TH,TW,VN", currency = "CNY,HKD,IDR,MYR,PHP,SGD,THB,TWD,VND" }
-debit = { country = "CN,HK,ID,MY,PH,SG,TH,TW,VN", currency = "CNY,HKD,IDR,MYR,PHP,SGD,THB,TWD,VND" }
-
-[pm_filters.placetopay]
-credit = { country = "BE,CH,CO,CR,EC,HN,MX,PA,PR,UY", currency = "CLP,COP,USD" }
-debit = { country = "BE,CH,CO,CR,EC,HN,MX,PA,PR,UY", currency = "CLP,COP,USD" }
-
-[pm_filters.coingate]
-crypto_currency = { country = "AL, AD, AT, BE, BA, BG, HR, CZ, DK, EE, FI, FR, DE, GR, HU, IS, IE, IT, LV, LT, LU, MT, MD, NL, NO, PL, PT, RO, RS, SK, SI, ES, SE, CH, UA, GB, AR, BR, CL, CO, CR, DO, SV, GD, MX, PE, LC, AU, NZ, CY, HK, IN, IL, JP, KR, QA, SA, SG, EG", currency = "EUR, USD, GBP" }
-
-[pm_filters.paystack]
-eft = { country = "NG, ZA, GH, KE, CI", currency = "NGN, GHS, ZAR, KES, USD" }
-
-[pm_filters.santander]
-pix_qr = { country = "BR", currency = "BRL" }
-boleto = { country = "BR", currency = "BRL" }
-pix_automatico_qr = { country = "BR", currency = "BRL" }
-pix_automatico_push = { country = "BR", currency = "BRL" }
-
-[pm_filters.calida]
-bluecode = { country = "AT,BE,BG,HR,CY,CZ,DK,EE,FI,FR,DE,GR,HU,IE,IT,LV,LT,LU,MT,NL,PL,PT,RO,SK,SI,ES,SE,IS,LI,NO", currency = "EUR" }
-
-[pm_filters.airwallex]
-credit = { country = "AU,HK,SG,NZ,US", currency = "AED,AFN,ALL,AMD,ANG,AOA,ARS,AUD,AWG,AZN,BAM,BBD,BDT,BGN,BHD,BIF,BMD,BND,BOB,BRL,BSD,BTN,BWP,BYN,BZD,CAD,CDF,CHF,CLP,CNY,COP,CRC,CUP,CVE,CZK,DJF,DKK,DOP,DZD,EGP,ERN,ETB,EUR,FJD,FKP,GBP,GEL,GHS,GIP,GMD,GNF,GTQ,GYD,HKD,HNL,HRK,HTG,HUF,IDR,ILS,INR,IQD,IRR,ISK,JMD,JOD,JPY,KES,KGS,KHR,KMF,KPW,KRW,KWD,KYD,KZT,LAK,LBP,LKR,LRD,LSL,LYD,MAD,MDL,MGA,MKD,MMK,MNT,MOP,MRU,MUR,MVR,MWK,MXN,MYR,MZN,NAD,NGN,NIO,NOK,NPR,NZD,OMR,PAB,PEN,PGK,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,RWF,SAR,SBD,SCR,SDG,SEK,SGD,SHP,SLE,SLL,SOS,SRD,SSP,STN,SVC,SYP,SZL,THB,TJS,TMT,TND,TOP,TRY,TTD,TWD,TZS,UAH,UGX,USD,UYU,UZS,VES,VND,VUV,WST,XAF,XCD,XOF,XPF,YER,ZAR,ZMW,ZWL" }
-debit = { country = "AU,HK,SG,NZ,US", currency = "AED,AFN,ALL,AMD,ANG,AOA,ARS,AUD,AWG,AZN,BAM,BBD,BDT,BGN,BHD,BIF,BMD,BND,BOB,BRL,BSD,BTN,BWP,BYN,BZD,CAD,CDF,CHF,CLP,CNY,COP,CRC,CUP,CVE,CZK,DJF,DKK,DOP,DZD,EGP,ERN,ETB,EUR,FJD,FKP,GBP,GEL,GHS,GIP,GMD,GNF,GTQ,GYD,HKD,HNL,HRK,HTG,HUF,IDR,ILS,INR,IQD,IRR,ISK,JMD,JOD,JPY,KES,KGS,KHR,KMF,KPW,KRW,KWD,KYD,KZT,LAK,LBP,LKR,LRD,LSL,LYD,MAD,MDL,MGA,MKD,MMK,MNT,MOP,MRU,MUR,MVR,MWK,MXN,MYR,MZN,NAD,NGN,NIO,NOK,NPR,NZD,OMR,PAB,PEN,PGK,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,RWF,SAR,SBD,SCR,SDG,SEK,SGD,SHP,SLE,SLL,SOS,SRD,SSP,STN,SVC,SYP,SZL,THB,TJS,TMT,TND,TOP,TRY,TTD,TWD,TZS,UAH,UGX,USD,UYU,UZS,VES,VND,VUV,WST,XAF,XCD,XOF,XPF,YER,ZAR,ZMW,ZWL" }
-google_pay = { country = "AL, DZ, AS, AO, AG, AR, AU, AZ, BH, BR, BG, CA, CL, CO, CZ, DK, DO, EG, HK, HU, ID, IL, JP, JO, KZ, KE, KW, LB, MY, MX, OM, PK, PA, PE, PH, PL, QA, RO, SA, SG, ZA, LK, SE, TW, TH, TR, UA, AE, UY, VN, AT, BE, HR, EE, FI, FR, DE, GR, IE, IT, LV, LT, LU, NL, PL, PT, SK, ES, SE, RO, BG", currency = "ALL, DZD, USD, AOA, XCD, ARS, AUD, EUR, AZN, BHD, BRL, BGN, CAD, CLP, COP, CZK, DKK, DOP, EGP, HKD, HUF, INR, IDR, ILS, JPY, JOD, KZT, KES, KWD, LBP, MYR, MXN, NZD, NOK, OMR, PKR, PAB, PEN, PHP, PLN, QAR, RON, SAR, SGD, ZAR, LKR, SEK, CHF, TWD, THB, TRY, UAH, AED, GBP, UYU, VND" }
-paypal = { currency = "AUD,BRL,CAD,CZK,DKK,EUR,HKD,HUF,JPY,MYR,MXN,NOK,NZD,PHP,PLN,GBP,RUB,SGD,SEK,CHF,THB,USD" }
-klarna = { currency = "EUR, DKK, NOK, PLN, SEK, CHF, GBP, USD, CZK" }
-trustly = {currency="DKK, EUR, GBP, NOK, PLN, SEK" }
-blik = { country="PL" , currency = "PLN" }
-atome = { country = "SG, MY" , currency = "SGD, MYR" }
-
-[pm_filters.boku]
-dana = { country = "ID", currency = "IDR" }
-gcash = { country = "PH", currency = "PHP" }
-go_pay = { country = "ID", currency = "IDR" }
-kakao_pay = { country = "KR", currency = "KRW" }
-momo = { country = "VN", currency = "VND" }
-
-[pm_filters.nmi]
-credit = { country = "EG,ZA,BH,CY,HK,IN,ID,IL,JP,JO,KW,MY,PK,PH,SA,SG,KR,TW,TH,TR,AE,VN,AL,AD,AM,AT,AZ,BY,BE,BA,BG,HR,CZ,DK,EE,FI,FR,GE,DE,GR,HU,IS,IE,IT,KZ,LV,LI,LT,LU,MT,MD,MC,ME,NL,MK,NO,PL,PT,RO,SM,RS,SK,SI,ES,SE,CH,TR,GB,VA,AG,BS,BB,BZ,CA,SV,GT,HN,MX,PA,KN,LC,TT,US,AU,NZ,AR,BO,BR,CL,CO,EC,GY,PY,PE,SR,UY,VE", currency = "AED,AFN,ALL,AMD,ANG,AOA,ARS,AUD,AWG,AZN,BAM,BBD,BDT,BGN,BHD,BIF,BMD,BND,BOB,BRL,BSD,BTN,BWP,BYN,BZD,CAD,CDF,CHF,CLF,CLP,CNY,COP,CRC,CUC,CUP,CVE,CZK,DJF,DKK,DOP,DZD,EGP,ERN,ETB,EUR,FJD,FKP,GBP,GEL,GHS,GIP,GMD,GNF,GTQ,GYD,HKD,HNL,HRK,HTG,HUF,IDR,ILS,INR,IQD,IRR,ISK,JMD,JOD,JPY,KES,KGS,KHR,KMF,KPW,KRW,KWD,KYD,KZT,LAK,LBP,LKR,LRD,LSL,LYD,MAD,MDL,MGA,MKD,MMK,MNT,MOP,MRU,MUR,MVR,MWK,MXN,MYR,MZN,NAD,NGN,NIO,NOK,NPR,NZD,OMR,PAB,PEN,PGK,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,RWF,SAR,SBD,SCR,SDG,SEK,SGD,SHP,SLE,SLL,SOS,SRD,SSP,STD,STN,SVC,SYP,SZL,THB,TJS,TMT,TND,TOP,TRY,TTD,TWD,TZS,UAH,UGX,USD,UYU,UZS,VES,VND,VUV,WST,XAF,XCD,XOF,XPF,YER,ZAR,ZMW,ZWL" }
-debit = { country = "EG,ZA,BH,CY,HK,IN,ID,IL,JP,JO,KW,MY,PK,PH,SA,SG,KR,TW,TH,TR,AE,VN,AL,AD,AM,AT,AZ,BY,BE,BA,BG,HR,CZ,DK,EE,FI,FR,GE,DE,GR,HU,IS,IE,IT,KZ,LV,LI,LT,LU,MT,MD,MC,ME,NL,MK,NO,PL,PT,RO,SM,RS,SK,SI,ES,SE,CH,TR,GB,VA,AG,BS,BB,BZ,CA,SV,GT,HN,MX,PA,KN,LC,TT,US,AU,NZ,AR,BO,BR,CL,CO,EC,GY,PY,PE,SR,UY,VE", currency = "AED,AFN,ALL,AMD,ANG,AOA,ARS,AUD,AWG,AZN,BAM,BBD,BDT,BGN,BHD,BIF,BMD,BND,BOB,BRL,BSD,BTN,BWP,BYN,BZD,CAD,CDF,CHF,CLF,CLP,CNY,COP,CRC,CUC,CUP,CVE,CZK,DJF,DKK,DOP,DZD,EGP,ERN,ETB,EUR,FJD,FKP,GBP,GEL,GHS,GIP,GMD,GNF,GTQ,GYD,HKD,HNL,HRK,HTG,HUF,IDR,ILS,INR,IQD,IRR,ISK,JMD,JOD,JPY,KES,KGS,KHR,KMF,KPW,KRW,KWD,KYD,KZT,LAK,LBP,LKR,LRD,LSL,LYD,MAD,MDL,MGA,MKD,MMK,MNT,MOP,MRU,MUR,MVR,MWK,MXN,MYR,MZN,NAD,NGN,NIO,NOK,NPR,NZD,OMR,PAB,PEN,PGK,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,RWF,SAR,SBD,SCR,SDG,SEK,SGD,SHP,SLE,SLL,SOS,SRD,SSP,STD,STN,SVC,SYP,SZL,THB,TJS,TMT,TND,TOP,TRY,TTD,TWD,TZS,UAH,UGX,USD,UYU,UZS,VES,VND,VUV,WST,XAF,XCD,XOF,XPF,YER,ZAR,ZMW,ZWL" }
-apple_pay = { country = "EG,ZA,BH,CY,HK,IN,ID,IL,JP,JO,KW,MY,PK,PH,SA,SG,KR,TW,TH,TR,AE,VN,AL,AD,AM,AT,AZ,BY,BE,BA,BG,HR,CZ,DK,EE,FI,FR,GE,DE,GR,HU,IS,IE,IT,KZ,LV,LI,LT,LU,MT,MD,MC,ME,NL,MK,NO,PL,PT,RO,SM,RS,SK,SI,ES,SE,CH,TR,GB,VA,AG,BS,BB,BZ,CA,SV,GT,HN,MX,PA,KN,LC,TT,US,AU,NZ,AR,BO,BR,CL,CO,EC,GY,PY,PE,SR,UY,VE", currency = "AED,AFN,ALL,AMD,ANG,AOA,ARS,AUD,AWG,AZN,BAM,BBD,BDT,BGN,BHD,BIF,BMD,BND,BOB,BRL,BSD,BTN,BWP,BYN,BZD,CAD,CDF,CHF,CLF,CLP,CNY,COP,CRC,CUC,CUP,CVE,CZK,DJF,DKK,DOP,DZD,EGP,ERN,ETB,EUR,FJD,FKP,GBP,GEL,GHS,GIP,GMD,GNF,GTQ,GYD,HKD,HNL,HRK,HTG,HUF,IDR,ILS,INR,IQD,IRR,ISK,JMD,JOD,JPY,KES,KGS,KHR,KMF,KPW,KRW,KWD,KYD,KZT,LAK,LBP,LKR,LRD,LSL,LYD,MAD,MDL,MGA,MKD,MMK,MNT,MOP,MRU,MUR,MVR,MWK,MXN,MYR,MZN,NAD,NGN,NIO,NOK,NPR,NZD,OMR,PAB,PEN,PGK,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,RWF,SAR,SBD,SCR,SDG,SEK,SGD,SHP,SLE,SLL,SOS,SRD,SSP,STD,STN,SVC,SYP,SZL,THB,TJS,TMT,TND,TOP,TRY,TTD,TWD,TZS,UAH,UGX,USD,UYU,UZS,VES,VND,VUV,WST,XAF,XCD,XOF,XPF,YER,ZAR,ZMW,ZWL" }
-google_pay = { country = "EG,ZA,BH,CY,HK,IN,ID,IL,JP,JO,KW,MY,PK,PH,SA,SG,KR,TW,TH,TR,AE,VN,AL,AD,AM,AT,AZ,BY,BE,BA,BG,HR,CZ,DK,EE,FI,FR,GE,DE,GR,HU,IS,IE,IT,KZ,LV,LI,LT,LU,MT,MD,MC,ME,NL,MK,NO,PL,PT,RO,SM,RS,SK,SI,ES,SE,CH,TR,GB,VA,AG,BS,BB,BZ,CA,SV,GT,HN,MX,PA,KN,LC,TT,US,AU,NZ,AR,BO,BR,CL,CO,EC,GY,PY,PE,SR,UY,VE", currency = "AED,AFN,ALL,AMD,ANG,AOA,ARS,AUD,AWG,AZN,BAM,BBD,BDT,BGN,BHD,BIF,BMD,BND,BOB,BRL,BSD,BTN,BWP,BYN,BZD,CAD,CDF,CHF,CLF,CLP,CNY,COP,CRC,CUC,CUP,CVE,CZK,DJF,DKK,DOP,DZD,EGP,ERN,ETB,EUR,FJD,FKP,GBP,GEL,GHS,GIP,GMD,GNF,GTQ,GYD,HKD,HNL,HRK,HTG,HUF,IDR,ILS,INR,IQD,IRR,ISK,JMD,JOD,JPY,KES,KGS,KHR,KMF,KPW,KRW,KWD,KYD,KZT,LAK,LBP,LKR,LRD,LSL,LYD,MAD,MDL,MGA,MKD,MMK,MNT,MOP,MRU,MUR,MVR,MWK,MXN,MYR,MZN,NAD,NGN,NIO,NOK,NPR,NZD,OMR,PAB,PEN,PGK,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,RWF,SAR,SBD,SCR,SDG,SEK,SGD,SHP,SLE,SLL,SOS,SRD,SSP,STD,STN,SVC,SYP,SZL,THB,TJS,TMT,TND,TOP,TRY,TTD,TWD,TZS,UAH,UGX,USD,UYU,UZS,VES,VND,VUV,WST,XAF,XCD,XOF,XPF,YER,ZAR,ZMW,ZWL" }
-
-[pm_filters.paypal]
-credit = { country = "DZ,AO,BJ,BW,BF,BI,CM,CV,TD,KM,CI,CD,DJ,EG,ER,ET,GA,GM,GN,GW,KE,LS,MG,MW,ML,MR,MU,MA,MZ,NA,NE,NG,CG,RW,SH,ST,SN,SC,SL,SO,ZA,SZ,TZ,TG,TN,UG,ZM,ZW,AI,AG,AR,AW,BS,BB,BZ,BM,BO,BR,VG,CA,KY,CL,CO,CR,DM,DO,EC,SV,FK,GL,GD,GT,GY,HN,JM,MX,MS,NI,PA,PY,PE,KN,LC,PM,VC,SR,TT,TC,US,UY,VE,AM,AU,BH,BT,BN,KH,CN,CK,FJ,PF,HK,IN,ID,IL,JP,JO,KZ,KI,KW,KG,LA,MY,MV,MH,FM,MN,NR,NP,NC,NZ,NU,NF,OM,PW,PG,PH,PN,QA,WS,SA,SG,SB,KR,LK,TW,TJ,TH,TO,TM,TV,AE,VU,VN,WF,YE,AL,AD,AT,AZ,BY,BE,BA,BG,HR,CY,CZ,DK,EE,FO,FI,FR,GE,DE,GR,HU,IS,IE,IT,LV,LI,LT,LU,MK,MT,MD,MC,ME,NL,NO,PL,PT,RO,RU,SM,RS,SK,SI,ES,SJ,SE,CH,UA,GB,VA", currency = "AUD,BRL,CAD,CNY,CZK,DKK,EUR,HKD,HUF,ILS,JPY,MYR,MXN,TWD,NZD,NOK,PHP,PLN,GBP,SGD,SEK,CHF,THB,USD" }
-debit = { country = "DZ,AO,BJ,BW,BF,BI,CM,CV,TD,KM,CI,CD,DJ,EG,ER,ET,GA,GM,GN,GW,KE,LS,MG,MW,ML,MR,MU,MA,MZ,NA,NE,NG,CG,RW,SH,ST,SN,SC,SL,SO,ZA,SZ,TZ,TG,TN,UG,ZM,ZW,AI,AG,AR,AW,BS,BB,BZ,BM,BO,BR,VG,CA,KY,CL,CO,CR,DM,DO,EC,SV,FK,GL,GD,GT,GY,HN,JM,MX,MS,NI,PA,PY,PE,KN,LC,PM,VC,SR,TT,TC,US,UY,VE,AM,AU,BH,BT,BN,KH,CN,CK,FJ,PF,HK,IN,ID,IL,JP,JO,KZ,KI,KW,KG,LA,MY,MV,MH,FM,MN,NR,NP,NC,NZ,NU,NF,OM,PW,PG,PH,PN,QA,WS,SA,SG,SB,KR,LK,TW,TJ,TH,TO,TM,TV,AE,VU,VN,WF,YE,AL,AD,AT,AZ,BY,BE,BA,BG,HR,CY,CZ,DK,EE,FO,FI,FR,GE,DE,GR,HU,IS,IE,IT,LV,LI,LT,LU,MK,MT,MD,MC,ME,NL,NO,PL,PT,RO,RU,SM,RS,SK,SI,ES,SJ,SE,CH,UA,GB,VA", currency = "AUD,BRL,CAD,CNY,CZK,DKK,EUR,HKD,HUF,ILS,JPY,MYR,MXN,TWD,NZD,NOK,PHP,PLN,GBP,SGD,SEK,CHF,THB,USD" }
-paypal = { country = "DZ,AO,BJ,BW,BF,BI,CM,CV,TD,KM,CI,CD,DJ,EG,ER,ET,GA,GM,GN,GW,KE,LS,MG,MW,ML,MR,MU,MA,MZ,NA,NE,NG,CG,RW,SH,ST,SN,SC,SL,SO,ZA,SZ,TZ,TG,TN,UG,ZM,ZW,AI,AG,AR,AW,BS,BB,BZ,BM,BO,BR,VG,CA,KY,CL,CO,CR,DM,DO,EC,SV,FK,GL,GD,GT,GY,HN,JM,MX,MS,NI,PA,PY,PE,KN,LC,PM,VC,SR,TT,TC,US,UY,VE,AM,AU,BH,BT,BN,KH,CN,CK,FJ,PF,HK,IN,ID,IL,JP,JO,KZ,KI,KW,KG,LA,MY,MV,MH,FM,MN,NR,NP,NC,NZ,NU,NF,OM,PW,PG,PH,PN,QA,WS,SA,SG,SB,KR,LK,TW,TJ,TH,TO,TM,TV,AE,VU,VN,WF,YE,AL,AD,AT,AZ,BY,BE,BA,BG,HR,CY,CZ,DK,EE,FO,FI,FR,GE,DE,GR,HU,IS,IE,IT,LV,LI,LT,LU,MK,MT,MD,MC,ME,NL,NO,PL,PT,RO,RU,SM,RS,SK,SI,ES,SJ,SE,CH,UA,GB,VA", currency = "AUD,BRL,CAD,CNY,CZK,DKK,EUR,HKD,HUF,ILS,JPY,MYR,MXN,TWD,NZD,NOK,PHP,PLN,GBP,SGD,SEK,CHF,THB,USD" }
-eps = { country = "DZ,AO,BJ,BW,BF,BI,CM,CV,TD,KM,CI,CD,DJ,EG,ER,ET,GA,GM,GN,GW,KE,LS,MG,MW,ML,MR,MU,MA,MZ,NA,NE,NG,CG,RW,SH,ST,SN,SC,SL,SO,ZA,SZ,TZ,TG,TN,UG,ZM,ZW,AI,AG,AR,AW,BS,BB,BZ,BM,BO,BR,VG,CA,KY,CL,CO,CR,DM,DO,EC,SV,FK,GL,GD,GT,GY,HN,JM,MX,MS,NI,PA,PY,PE,KN,LC,PM,VC,SR,TT,TC,US,UY,VE,AM,AU,BH,BT,BN,KH,CN,CK,FJ,PF,HK,IN,ID,IL,JP,JO,KZ,KI,KW,KG,LA,MY,MV,MH,FM,MN,NR,NP,NC,NZ,NU,NF,OM,PW,PG,PH,PN,QA,WS,SA,SG,SB,KR,LK,TW,TJ,TH,TO,TM,TV,AE,VU,VN,WF,YE,AL,AD,AT,AZ,BY,BE,BA,BG,HR,CY,CZ,DK,EE,FO,FI,FR,GE,DE,GR,HU,IS,IE,IT,LV,LI,LT,LU,MK,MT,MD,MC,ME,NL,NO,PL,PT,RO,RU,SM,RS,SK,SI,ES,SJ,SE,CH,UA,GB,VA", currency = "AUD,BRL,CAD,CNY,CZK,DKK,EUR,HKD,HUF,ILS,JPY,MYR,MXN,TWD,NZD,NOK,PHP,PLN,GBP,SGD,SEK,CHF,THB,USD" }
-giropay = { currency = "EUR" }
-ideal = { currency = "EUR" }
-sofort = { country = "DZ,AO,BJ,BW,BF,BI,CM,CV,TD,KM,CI,CD,DJ,EG,ER,ET,GA,GM,GN,GW,KE,LS,MG,MW,ML,MR,MU,MA,MZ,NA,NE,NG,CG,RW,SH,ST,SN,SC,SL,SO,ZA,SZ,TZ,TG,TN,UG,ZM,ZW,AI,AG,AR,AW,BS,BB,BZ,BM,BO,BR,VG,CA,KY,CL,CO,CR,DM,DO,EC,SV,FK,GL,GD,GT,GY,HN,JM,MX,MS,NI,PA,PY,PE,KN,LC,PM,VC,SR,TT,TC,US,UY,VE,AM,AU,BH,BT,BN,KH,CN,CK,FJ,PF,HK,IN,ID,IL,JP,JO,KZ,KI,KW,KG,LA,MY,MV,MH,FM,MN,NR,NP,NC,NZ,NU,NF,OM,PW,PG,PH,PN,QA,WS,SA,SG,SB,KR,LK,TW,TJ,TH,TO,TM,TV,AE,VU,VN,WF,YE,AL,AD,AT,AZ,BY,BE,BA,BG,HR,CY,CZ,DK,EE,FO,FI,FR,GE,DE,GR,HU,IS,IE,IT,LV,LI,LT,LU,MK,MT,MD,MC,ME,NL,NO,PL,PT,RO,RU,SM,RS,SK,SI,ES,SJ,SE,CH,UA,GB,VA", currency = "AUD,BRL,CAD,CNY,CZK,DKK,EUR,HKD,HUF,ILS,JPY,MYR,MXN,TWD,NZD,NOK,PHP,PLN,GBP,SGD,SEK,CHF,THB,USD" }
-
-[pm_filters.datatrans]
-credit = { }
-debit = { }
-apple_pay = { }
-google_pay = { }
-
-[pm_filters.bankofamerica]
-credit = { country = "AF,AL,DZ,AD,AO,AI,AG,AR,AM,AW,AU,AT,AZ,BS,BH,BD,BB,BY,BE,BZ,BJ,BM,BT,BO,BA,BW,BN,BG,BF,BI,KH,CM,CA,CV,KY,CF,TD,CL,CN,CO,KM,CD,CG,CK,CR,HR,CU,CW,CY,CZ,DK,DJ,DM,DO,EC,SV,GQ,ER,EE,ET,FK,FO,FJ,FI,FR,GF,PF,TF,GA,GM,GE,DE,GH,GI,GR,GL,GD,GP,GU,GT,GG,GN,GW,GY,HT,HM,VA,HN,HK,HU,IS,ID,IR,IQ,IE,IM,IL,IT,JM,JP,JE,JO,KZ,KE,KI,KR,KW,KG,LA,LV,LB,LS,LR,LY,LI,LT,LU,MO,MG,MW,MY,MV,ML,MT,MH,MR,MU,MX,FM,MD,MC,MN,ME,MS,MA,MZ,MM,NA,NR,NP,NL,NC,NZ,NI,NE,NG,NU,NO,OM,PK,PW,PS,PA,PG,PY,PE,PH,PL,PT,PR,QA,CG,RO,RW,KN,LC,VC,WS,SM,ST,SA,SN,RS,SC,SL,SG,SX,SK,SI,SO,ZA,GS,ES,LK,SR,SJ,SZ,SE,CH,TW,TJ,TZ,TH,TL,TG,TO,TT,TN,TR,TM,TC,TV,UG,UA,AE,GB,US,UY,UZ,VU,VE,VN,VG,WF,YE,ZM,ZW", currency = "USD" }
-debit = { country = "AF,AL,DZ,AD,AO,AI,AG,AR,AM,AW,AU,AT,AZ,BS,BH,BD,BB,BY,BE,BZ,BJ,BM,BT,BO,BA,BW,BN,BG,BF,BI,KH,CM,CA,CV,KY,CF,TD,CL,CN,CO,KM,CD,CG,CK,CR,HR,CU,CW,CY,CZ,DK,DJ,DM,DO,EC,SV,GQ,ER,EE,ET,FK,FO,FJ,FI,FR,GF,PF,TF,GA,GM,GE,DE,GH,GI,GR,GL,GD,GP,GU,GT,GG,GN,GW,GY,HT,HM,VA,HN,HK,HU,IS,ID,IR,IQ,IE,IM,IL,IT,JM,JP,JE,JO,KZ,KE,KI,KR,KW,KG,LA,LV,LB,LS,LR,LY,LI,LT,LU,MO,MG,MW,MY,MV,ML,MT,MH,MR,MU,MX,FM,MD,MC,MN,ME,MS,MA,MZ,MM,NA,NR,NP,NL,NC,NZ,NI,NE,NG,NU,NO,OM,PK,PW,PS,PA,PG,PY,PE,PH,PL,PT,PR,QA,CG,RO,RW,KN,LC,VC,WS,SM,ST,SA,SN,RS,SC,SL,SG,SX,SK,SI,SO,ZA,GS,ES,LK,SR,SJ,SZ,SE,CH,TW,TJ,TZ,TH,TL,TG,TO,TT,TN,TR,TM,TC,TV,UG,UA,AE,GB,US,UY,UZ,VU,VE,VN,VG,WF,YE,ZM,ZW", currency = "USD" }
-apple_pay = { country = "AU,AT,BH,BE,BR,BG,CA,CL,CN,CO,CR,HR,CY,CZ,DK,DO,EC,EE,SV,FI,FR,DE,GR,GT,HN,HK,HU,IS,IN,IE,IL,IT,JP,JO,KZ,KW,LV,LI,LT,LU,MY,MT,MX,MC,ME,NL,NZ,NO,OM,PA,PY,PE,PL,PT,QA,RO,SA,SG,SK,SI,ZA,KR,ES,SE,CH,TW,AE,GB,US,UY,VN,VA", currency = "USD" }
-google_pay = { country = "AU,AT,BE,BR,CA,CL,CO,CR,CY,CZ,DK,DO,EC,EE,SV,FI,FR,DE,GR,GT,HN,HK,HU,IS,IN,IE,IL,IT,JP,JO,KZ,KW,LV,LI,LT,LU,MY,MT,MX,NL,NZ,NO,OM,PA,PY,PE,PL,PT,QA,RO,SA,SG,SK,SI,ZA,KR,ES,SE,CH,TW,AE,GB,US,UY,VN,VA", currency = "USD" }
-samsung_pay = { country = "AU,BH,BR,CA,CN,DK,FI,FR,DE,HK,IN,IT,JP,KZ,KR,KW,MY,NZ,NO,OM,QA,SA,SG,ZA,ES,SE,CH,TW,AE,GB,US", currency = "USD" }
-
-[pm_filters.payme]
-credit = { country = "US,CA,IL,GB", currency = "ILS,USD,EUR" }
-debit = { country = "US,CA,IL,GB", currency = "ILS,USD,EUR" }
-apple_pay = { country = "US,CA,IL,GB", currency = "ILS,USD,EUR" }
-
-[pm_filters.paysafe]
-apple_pay = {country = "AF,AX,AL,DZ,AS,AD,AO,AI,AQ,AG,AR,AM,AW,AU,AT,AZ,BS,BH,BD,BB,BY,BE,BZ,BJ,BM,BT,BO,BQ,BA,BW,BV,BR,IO,BN,BG,BF,BI,KH,CM,CA,CV,KY,CF,TD,CL,CN,CX,CC,CO,KM,CG,CD,CK,CR,CI,HR,CU,CW,CY,CZ,DK,DJ,DM,DO,EC,EG,SV,GQ,ER,EE,ET,FK,FO,FJ,FI,FR,GF,PF,TF,GA,GM,GE,DE,GH,GI,GR,GL,GD,GP,GU,GT,GG,GN,GW,GY,HT,HM,HN,HK,HU,IS,IN,ID,IR,IQ,IE,IM,IL,IT,JM,JP,JE,JO,KZ,KE,KI,KP,KR,KW,KG,LA,LV,LB,LS,LR,LY,LI,LT,LU,MO,MK,MG,MW,MY,MV,ML,MT,MH,MQ,MR,MU,YT,MX,FM,MD,MC,MN,ME,MS,MA,MZ,MM,NA,NR,NP,NC,NZ,NI,NE,NG,NU,NF,MP,NO,OM,PK,PW,PS,PA,PG,PY,PE,PH,PN,PL,PT,PR,QA,RE,RO,RU,RW,BL,SH,KN,LC,MF,VC,WS,SM,ST,SA,SN,RS,SC,SL,SG,SX,SK,SI,SB,SO,ZA,GS,SS,ES,LK,PM,SD,SR,SJ,SZ,SE,CH,SY,TW,TJ,TZ,TH,NL,TL,TG,TK,TO,TT,TN,TR,TM,TC,TV,UG,UA,AE,GB,US,UM,UY,UZ,VU,VA,VE,VN,VG,VI,WF,EH,YE,ZM,ZW", currency = "ARS,AUD,AZN,BHD,BOB,BAM,BRL,BGN,CAD,CLP,CNY,COP,CRC,HRK,CZK,DKK,DOP,XCD,EGP,ETB,EUR,FJD,GEL,GTQ,HTG,HNL,HKD,HUF,INR,IDR,JMD,JPY,JOD,KZT,KES,KRW,KWD,LBP,LYD,MWK,MUR,MXN,MDL,MAD,ILS,NZD,NGN,NOK,OMR,PKR,PAB,PYG,PEN,PHP,PLN,GBP,QAR,RON,RUB,RWF,SAR,RSD,SGD,ZAR,LKR,SEK,CHF,SYP,TWD,THB,TTD,TND,TRY,UAH,AED,UYU,USD,VND" }
-google_pay = {country = "AF,AX,AL,DZ,AS,AD,AO,AI,AQ,AG,AR,AM,AW,AU,AT,AZ,BS,BH,BD,BB,BY,BE,BZ,BJ,BM,BT,BO,BQ,BA,BW,BV,BR,IO,BN,BG,BF,BI,KH,CM,CA,CV,KY,CF,TD,CL,CN,CX,CC,CO,KM,CG,CD,CK,CR,CI,HR,CU,CW,CY,CZ,DK,DJ,DM,DO,EC,EG,SV,GQ,ER,EE,ET,FK,FO,FJ,FI,FR,GF,PF,TF,GA,GM,GE,DE,GH,GI,GR,GL,GD,GP,GU,GT,GG,GN,GW,GY,HT,HM,HN,HK,HU,IS,IN,ID,IR,IQ,IE,IM,IL,IT,JM,JP,JE,JO,KZ,KE,KI,KP,KR,KW,KG,LA,LV,LB,LS,LR,LY,LI,LT,LU,MO,MK,MG,MW,MY,MV,ML,MT,MH,MQ,MR,MU,YT,MX,FM,MD,MC,MN,ME,MS,MA,MZ,MM,NA,NR,NP,NC,NZ,NI,NE,NG,NU,NF,MP,NO,OM,PK,PW,PS,PA,PG,PY,PE,PH,PN,PL,PT,PR,QA,RE,RO,RU,RW,BL,SH,KN,LC,MF,VC,WS,SM,ST,SA,SN,RS,SC,SL,SG,SX,SK,SI,SB,SO,ZA,GS,SS,ES,LK,PM,SD,SR,SJ,SZ,SE,CH,SY,TW,TJ,TZ,TH,NL,TL,TG,TK,TO,TT,TN,TR,TM,TC,TV,UG,UA,AE,GB,US,UM,UY,UZ,VU,VA,VE,VN,VG,VI,WF,EH,YE,ZM,ZW", currency = "ARS,AUD,AZN,BHD,BOB,BAM,BRL,BGN,CAD,CLP,CNY,COP,CRC,HRK,CZK,DKK,DOP,XCD,EGP,ETB,EUR,FJD,GEL,GTQ,HTG,HNL,HKD,HUF,INR,IDR,JMD,JPY,JOD,KZT,KES,KRW,KWD,LBP,LYD,MWK,MUR,MXN,MDL,MAD,ILS,NZD,NGN,NOK,OMR,PKR,PAB,PYG,PEN,PHP,PLN,GBP,QAR,RON,RUB,RWF,SAR,RSD,SGD,ZAR,LKR,SEK,CHF,SYP,TWD,THB,TTD,TND,TRY,UAH,AED,UYU,USD,VND" }
-
-[pm_filters.finix]
-google_pay = { country = "AD, AE, AG, AI, AM, AO, AQ, AR, AS, AT, AU, AW, AX, AZ, BA, BB, BD, BE, BF, BG, BH, BI, BJ, BM, BN, BO, BQ, BR, BS, BT, BV, BW, BZ, CA, CC, CG, CH, CI, CK, CL, CM, CN, CO, CR, CV, CW, CX, CY, CZ, DE, DJ, DK, DM, DO, DZ, EC, EE, EG, EH, ER, ES, FI, FJ, FK, FM, FO, FR, GA, GB, GD, GE, GF, GG, GH, GI, GL, GM, GN, GP, GQ, GR, GS, GT, GU, GW, GY, HK, HM, HN, HR, HT, HU, ID, IE, IL, IM, IN, IO, IS, IT, JE, JM, JO, JP, KE, KG, KH, KI, KM, KN, KR, KW, KY, KZ, LA, LC, LI, LK, LR, LS, LT, LU, LV, MA, MC, MD, ME, MF, MG, MH, MK, MN, MO, MP, MQ, MR, MS, MT, MU, MV, MW, MX, MY, MZ, NA, NC, NE, NF, NG, NL, NO, NP, NR, NU, NZ, OM, PA, PE, PF, PG, PH, PK, PL, PM, PN, PR, PT, PW, PY, QA, RE, RO, RS, RW, SA, SB, SC, SE, SG, SH, SI, SJ, SK, SL, SM, SN, SR, ST, SV, SX, SZ, TC, TD, TF, TG, TH, TJ, TK, TL, TM, TN, TO, TT, TV, TZ, UG, UM, UY, UZ, VA, VC, VG, VI, VN, VU, WF, WS, YT, ZA, ZM, US", currency = "USD, CAD" }
-apple_pay = { currency = "USD, CAD" }
-
-[pm_filters.payjustnow]
-payjustnow = { country = "ZA", currency = "ZAR" }
-
-[pm_filters.payjustnowinstore]
-payjustnow = { country = "ZA", currency = "ZAR" }
-
-[pm_filters.worldpayraft]
-credit = { country = "AD,AE,AF,AG,AI,AL,AM,AO,AQ,AR,AS,AT,AU,AW,AX,AZ,BA,BB,BD,BE,BF,BG,BH,BI,BJ,BL,BM,BN,BO,BQ,BR,BS,BT,BV,BW,BY,BZ,CA,CC,CD,CF,CG,CH,CI,CK,CL,CM,CN,CO,CR,CU,CV,CW,CX,CY,CZ,DE,DJ,DK,DM,DO,DZ,EC,EE,EG,EH,ER,ES,ET,FI,FJ,FK,FM,FO,FR,GA,GB,GD,GE,GF,GG,GH,GI,GL,GM,GN,GP,GQ,GR,GS,GT,GU,GW,GY,HK,HM,HN,HR,HT,HU,ID,IE,IL,IM,IN,IO,IQ,IR,IS,IT,JE,JM,JO,JP,KE,KG,KH,KI,KM,KN,KP,KR,KW,KY,KZ,LA,LB,LC,LI,LK,LR,LS,LT,LU,LV,LY,MA,MC,MD,ME,MF,MG,MH,MK,ML,MM,MN,MO,MP,MQ,MR,MS,MT,MU,MV,MW,MX,MY,MZ,NA,NC,NE,NF,NG,NI,NL,NO,NP,NR,NU,NZ,OM,PA,PE,PF,PG,PH,PK,PL,PM,PN,PR,PS,PT,PW,PY,QA,RE,RO,RS,RU,RW,SA,SB,SC,SD,SE,SG,SH,SI,SJ,SK,SL,SM,SN,SO,SR,SS,ST,SV,SX,SY,SZ,TC,TD,TF,TG,TH,TJ,TK,TL,TM,TN,TO,TR,TT,TV,TW,TZ,UA,UG,UM,US,UY,UZ,VA,VC,VE,VG,VI,VN,VU,WF,WS,YE,YT,ZA,ZM,ZW", currency = "AED,AFN,ALL,AMD,ANG,AOA,ARS,AUD,AWG,AZN,BAM,BBD,BDT,BGN,BHD,BIF,BMD,BND,BOB,BRL,BSD,BTN,BWP,BYN,BZD,CAD,CDF,CHF,CLF,CLP,CNY,COP,CRC,CUC,CUP,CVE,CZK,DJF,DKK,DOP,DZD,EGP,ERN,ETB,EUR,FJD,FKP,GBP,GEL,GHS,GIP,GMD,GNF,GTQ,GYD,HKD,HNL,HRK,HTG,HUF,IDR,ILS,INR,IQD,IRR,ISK,JMD,JOD,JPY,KES,KGS,KHR,KMF,KPW,KRW,KWD,KYD,KZT,LAK,LBP,LKR,LRD,LSL,LYD,MAD,MDL,MGA,MKD,MMK,MNT,MOP,MRU,MUR,MVR,MWK,MXN,MYR,MZN,NAD,NGN,NIO,NOK,NPR,NZD,OMR,PAB,PEN,PGK,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,RWF,SAR,SBD,SCR,SDG,SEK,SGD,SHP,SLE,SLL,SOS,SRD,SSP,STD,STN,SVC,SYP,SZL,THB,TJS,TMT,TND,TOP,TRY,TTD,TWD,TZS,UAH,UGX,USD,UYU,UZS,VES,VND,VUV,WST,XAF,XCD,XOF,XPF,YER,ZAR,ZMW,ZWL" }
-debit = { country = "AD,AE,AF,AG,AI,AL,AM,AO,AQ,AR,AS,AT,AU,AW,AX,AZ,BA,BB,BD,BE,BF,BG,BH,BI,BJ,BL,BM,BN,BO,BQ,BR,BS,BT,BV,BW,BY,BZ,CA,CC,CD,CF,CG,CH,CI,CK,CL,CM,CN,CO,CR,CU,CV,CW,CX,CY,CZ,DE,DJ,DK,DM,DO,DZ,EC,EE,EG,EH,ER,ES,ET,FI,FJ,FK,FM,FO,FR,GA,GB,GD,GE,GF,GG,GH,GI,GL,GM,GN,GP,GQ,GR,GS,GT,GU,GW,GY,HK,HM,HN,HR,HT,HU,ID,IE,IL,IM,IN,IO,IQ,IR,IS,IT,JE,JM,JO,JP,KE,KG,KH,KI,KM,KN,KP,KR,KW,KY,KZ,LA,LB,LC,LI,LK,LR,LS,LT,LU,LV,LY,MA,MC,MD,ME,MF,MG,MH,MK,ML,MM,MN,MO,MP,MQ,MR,MS,MT,MU,MV,MW,MX,MY,MZ,NA,NC,NE,NF,NG,NI,NL,NO,NP,NR,NU,NZ,OM,PA,PE,PF,PG,PH,PK,PL,PM,PN,PR,PS,PT,PW,PY,QA,RE,RO,RS,RU,RW,SA,SB,SC,SD,SE,SG,SH,SI,SJ,SK,SL,SM,SN,SO,SR,SS,ST,SV,SX,SY,SZ,TC,TD,TF,TG,TH,TJ,TK,TL,TM,TN,TO,TR,TT,TV,TW,TZ,UA,UG,UM,US,UY,UZ,VA,VC,VE,VG,VI,VN,VU,WF,WS,YE,YT,ZA,ZM,ZW", currency = "AED,AFN,ALL,AMD,ANG,AOA,ARS,AUD,AWG,AZN,BAM,BBD,BDT,BGN,BHD,BIF,BMD,BND,BOB,BRL,BSD,BTN,BWP,BYN,BZD,CAD,CDF,CHF,CLF,CLP,CNY,COP,CRC,CUC,CUP,CVE,CZK,DJF,DKK,DOP,DZD,EGP,ERN,ETB,EUR,FJD,FKP,GBP,GEL,GHS,GIP,GMD,GNF,GTQ,GYD,HKD,HNL,HRK,HTG,HUF,IDR,ILS,INR,IQD,IRR,ISK,JMD,JOD,JPY,KES,KGS,KHR,KMF,KPW,KRW,KWD,KYD,KZT,LAK,LBP,LKR,LRD,LSL,LYD,MAD,MDL,MGA,MKD,MMK,MNT,MOP,MRU,MUR,MVR,MWK,MXN,MYR,MZN,NAD,NGN,NIO,NOK,NPR,NZD,OMR,PAB,PEN,PGK,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,RWF,SAR,SBD,SCR,SDG,SEK,SGD,SHP,SLE,SLL,SOS,SRD,SSP,STD,STN,SVC,SYP,SZL,THB,TJS,TMT,TND,TOP,TRY,TTD,TWD,TZS,UAH,UGX,USD,UYU,UZS,VES,VND,VUV,WST,XAF,XCD,XOF,XPF,YER,ZAR,ZMW,ZWL" }
-apple_pay = { country = "AD,AE,AF,AG,AI,AL,AM,AO,AQ,AR,AS,AT,AU,AW,AX,AZ,BA,BB,BD,BE,BF,BG,BH,BI,BJ,BL,BM,BN,BO,BQ,BR,BS,BT,BV,BW,BY,BZ,CA,CC,CD,CF,CG,CH,CI,CK,CL,CM,CN,CO,CR,CU,CV,CW,CX,CY,CZ,DE,DJ,DK,DM,DO,DZ,EC,EE,EG,EH,ER,ES,ET,FI,FJ,FK,FM,FO,FR,GA,GB,GD,GE,GF,GG,GH,GI,GL,GM,GN,GP,GQ,GR,GS,GT,GU,GW,GY,HK,HM,HN,HR,HT,HU,ID,IE,IL,IM,IN,IO,IQ,IR,IS,IT,JE,JM,JO,JP,KE,KG,KH,KI,KM,KN,KP,KR,KW,KY,KZ,LA,LB,LC,LI,LK,LR,LS,LT,LU,LV,LY,MA,MC,MD,ME,MF,MG,MH,MK,ML,MM,MN,MO,MP,MQ,MR,MS,MT,MU,MV,MW,MX,MY,MZ,NA,NC,NE,NF,NG,NI,NL,NO,NP,NR,NU,NZ,OM,PA,PE,PF,PG,PH,PK,PL,PM,PN,PR,PS,PT,PW,PY,QA,RE,RO,RS,RU,RW,SA,SB,SC,SD,SE,SG,SH,SI,SJ,SK,SL,SM,SN,SO,SR,SS,ST,SV,SX,SY,SZ,TC,TD,TF,TG,TH,TJ,TK,TL,TM,TN,TO,TR,TT,TV,TW,TZ,UA,UG,UM,US,UY,UZ,VA,VC,VE,VG,VI,VN,VU,WF,WS,YE,YT,ZA,ZM,ZW", currency = "AED,AFN,ALL,AMD,ANG,AOA,ARS,AUD,AWG,AZN,BAM,BBD,BDT,BGN,BHD,BIF,BMD,BND,BOB,BRL,BSD,BTN,BWP,BYN,BZD,CAD,CDF,CHF,CLF,CLP,CNY,COP,CRC,CUC,CUP,CVE,CZK,DJF,DKK,DOP,DZD,EGP,ERN,ETB,EUR,FJD,FKP,GBP,GEL,GHS,GIP,GMD,GNF,GTQ,GYD,HKD,HNL,HRK,HTG,HUF,IDR,ILS,INR,IQD,IRR,ISK,JMD,JOD,JPY,KES,KGS,KHR,KMF,KPW,KRW,KWD,KYD,KZT,LAK,LBP,LKR,LRD,LSL,LYD,MAD,MDL,MGA,MKD,MMK,MNT,MOP,MRU,MUR,MVR,MWK,MXN,MYR,MZN,NAD,NGN,NIO,NOK,NPR,NZD,OMR,PAB,PEN,PGK,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,RWF,SAR,SBD,SCR,SDG,SEK,SGD,SHP,SLE,SLL,SOS,SRD,SSP,STD,STN,SVC,SYP,SZL,THB,TJS,TMT,TND,TOP,TRY,TTD,TWD,TZS,UAH,UGX,USD,UYU,UZS,VES,VND,VUV,WST,XAF,XCD,XOF,XPF,YER,ZAR,ZMW,ZWL" }
-google_pay = { country = "AD,AE,AF,AG,AI,AL,AM,AO,AQ,AR,AS,AT,AU,AW,AX,AZ,BA,BB,BD,BE,BF,BG,BH,BI,BJ,BL,BM,BN,BO,BQ,BR,BS,BT,BV,BW,BY,BZ,CA,CC,CD,CF,CG,CH,CI,CK,CL,CM,CN,CO,CR,CU,CV,CW,CX,CY,CZ,DE,DJ,DK,DM,DO,DZ,EC,EE,EG,EH,ER,ES,ET,FI,FJ,FK,FM,FO,FR,GA,GB,GD,GE,GF,GG,GH,GI,GL,GM,GN,GP,GQ,GR,GS,GT,GU,GW,GY,HK,HM,HN,HR,HT,HU,ID,IE,IL,IM,IN,IO,IQ,IR,IS,IT,JE,JM,JO,JP,KE,KG,KH,KI,KM,KN,KP,KR,KW,KY,KZ,LA,LB,LC,LI,LK,LR,LS,LT,LU,LV,LY,MA,MC,MD,ME,MF,MG,MH,MK,ML,MM,MN,MO,MP,MQ,MR,MS,MT,MU,MV,MW,MX,MY,MZ,NA,NC,NE,NF,NG,NI,NL,NO,NP,NR,NU,NZ,OM,PA,PE,PF,PG,PH,PK,PL,PM,PN,PR,PS,PT,PW,PY,QA,RE,RO,RS,RU,RW,SA,SB,SC,SD,SE,SG,SH,SI,SJ,SK,SL,SM,SN,SO,SR,SS,ST,SV,SX,SY,SZ,TC,TD,TF,TG,TH,TJ,TK,TL,TM,TN,TO,TR,TT,TV,TW,TZ,UA,UG,UM,US,UY,UZ,VA,VC,VE,VG,VI,VN,VU,WF,WS,YE,YT,ZA,ZM,ZW", currency = "AED,AFN,ALL,AMD,ANG,AOA,ARS,AUD,AWG,AZN,BAM,BBD,BDT,BGN,BHD,BIF,BMD,BND,BOB,BRL,BSD,BTN,BWP,BYN,BZD,CAD,CDF,CHF,CLF,CLP,CNY,COP,CRC,CUC,CUP,CVE,CZK,DJF,DKK,DOP,DZD,EGP,ERN,ETB,EUR,FJD,FKP,GBP,GEL,GHS,GIP,GMD,GNF,GTQ,GYD,HKD,HNL,HRK,HTG,HUF,IDR,ILS,INR,IQD,IRR,ISK,JMD,JOD,JPY,KES,KGS,KHR,KMF,KPW,KRW,KWD,KYD,KZT,LAK,LBP,LKR,LRD,LSL,LYD,MAD,MDL,MGA,MKD,MMK,MNT,MOP,MRU,MUR,MVR,MWK,MXN,MYR,MZN,NAD,NGN,NIO,NOK,NPR,NZD,OMR,PAB,PEN,PGK,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,RWF,SAR,SBD,SCR,SDG,SEK,SGD,SHP,SLE,SLL,SOS,SRD,SSP,STD,STN,SVC,SYP,SZL,THB,TJS,TMT,TND,TOP,TRY,TTD,TWD,TZS,UAH,UGX,USD,UYU,UZS,VES,VND,VUV,WST,XAF,XCD,XOF,XPF,YER,ZAR,ZMW,ZWL" }
-
-[pm_filters.worldpayxml]
-debit = { currency = "AFN,DZD,ANG,AWG,AUD,AZN,BSD,BHD,BDT,BBD,BZD,BMD,BTN,BOB,BAM,BWP,BRL,BND,BGN,BIF,KHR,CAD,CVE,KYD,XOF,XAF,XPF,CLP,COP,KMF,CDF,CRC,EUR,CZK,DKK,DJF,DOP,XCD,EGP,SVC,ERN,ETB,EUR,FKP,FJD,GMD,GEL,GHS,GIP,GTQ,GNF,GYD,HTG,HNL,HKD,HUF,ISK,INR,IDR,IRR,IQD,ILS,JMD,JPY,JOD,KZT,KES,KWD,LAK,LBP,LSL,LRD,LYD,MOP,MKD,MGA,MWK,MYR,MVR,MRU,MUR,MXN,MDL,MNT,MAD,MZN,MMK,NAD,NPR,NZD,NIO,NGN,KPW,NOK,ARS,PKR,PAB,PGK,PYG,PEN,UYU,PHP,PLN,GBP,QAR,OMR,RON,RUB,RWF,WST,SAR,RSD,SCR,SLL,SGD,STN,SBD,SOS,ZAR,KRW,LKR,SHP,SDG,SRD,SZL,SEK,CHF,SYP,TWD,TJS,TZS,THB,TOP,TTD,TND,TRY,TMT,AED,UGX,UAH,USD,UZS,VUV,VND,YER,CNY,ZMW,ZWL,STD,BYN" }
-credit = { currency = "AFN,DZD,ANG,AWG,AUD,AZN,BSD,BHD,BDT,BBD,BZD,BMD,BTN,BOB,BAM,BWP,BRL,BND,BGN,BIF,KHR,CAD,CVE,KYD,XOF,XAF,XPF,CLP,COP,KMF,CDF,CRC,EUR,CZK,DKK,DJF,DOP,XCD,EGP,SVC,ERN,ETB,EUR,FKP,FJD,GMD,GEL,GHS,GIP,GTQ,GNF,GYD,HTG,HNL,HKD,HUF,ISK,INR,IDR,IRR,IQD,ILS,JMD,JPY,JOD,KZT,KES,KWD,LAK,LBP,LSL,LRD,LYD,MOP,MKD,MGA,MWK,MYR,MVR,MRU,MUR,MXN,MDL,MNT,MAD,MZN,MMK,NAD,NPR,NZD,NIO,NGN,KPW,NOK,ARS,PKR,PAB,PGK,PYG,PEN,UYU,PHP,PLN,GBP,QAR,OMR,RON,RUB,RWF,WST,SAR,RSD,SCR,SLL,SGD,STN,SBD,SOS,ZAR,KRW,LKR,SHP,SDG,SRD,SZL,SEK,CHF,SYP,TWD,TJS,TZS,THB,TOP,TTD,TND,TRY,TMT,AED,UGX,UAH,USD,UZS,VUV,VND,YER,CNY,ZMW,ZWL,STD,BYN" }
-google_pay = { currency = "AFN,DZD,ANG,AWG,AUD,AZN,BSD,BHD,BDT,BBD,BZD,BMD,BTN,BOB,BAM,BWP,BRL,BND,BGN,BIF,KHR,CAD,CVE,KYD,XOF,XAF,XPF,CLP,COP,KMF,CDF,CRC,EUR,CZK,DKK,DJF,DOP,XCD,EGP,SVC,ERN,ETB,EUR,FKP,FJD,GMD,GEL,GHS,GIP,GTQ,GNF,GYD,HTG,HNL,HKD,HUF,ISK,INR,IDR,IRR,IQD,ILS,JMD,JPY,JOD,KZT,KES,KWD,LAK,LBP,LSL,LRD,LYD,MOP,MKD,MGA,MWK,MYR,MVR,MRU,MUR,MXN,MDL,MNT,MAD,MZN,MMK,NAD,NPR,NZD,NIO,NGN,KPW,NOK,ARS,PKR,PAB,PGK,PYG,PEN,UYU,PHP,PLN,GBP,QAR,OMR,RON,RUB,RWF,WST,SAR,RSD,SCR,SLL,SGD,STN,SBD,SOS,ZAR,KRW,LKR,SHP,SDG,SRD,SZL,SEK,CHF,SYP,TWD,TJS,TZS,THB,TOP,TTD,TND,TRY,TMT,AED,UGX,UAH,USD,UZS,VUV,VND,YER,CNY,ZMW,ZWL,STD,BYN" }
-apple_pay = { currency = "AFN,DZD,ANG,AWG,AUD,AZN,BSD,BHD,BDT,BBD,BZD,BMD,BTN,BOB,BAM,BWP,BRL,BND,BGN,BIF,KHR,CAD,CVE,KYD,XOF,XAF,XPF,CLP,COP,KMF,CDF,CRC,EUR,CZK,DKK,DJF,DOP,XCD,EGP,SVC,ERN,ETB,EUR,FKP,FJD,GMD,GEL,GHS,GIP,GTQ,GNF,GYD,HTG,HNL,HKD,HUF,ISK,INR,IDR,IRR,IQD,ILS,JMD,JPY,JOD,KZT,KES,KWD,LAK,LBP,LSL,LRD,LYD,MOP,MKD,MGA,MWK,MYR,MVR,MRU,MUR,MXN,MDL,MNT,MAD,MZN,MMK,NAD,NPR,NZD,NIO,NGN,KPW,NOK,ARS,PKR,PAB,PGK,PYG,PEN,UYU,PHP,PLN,GBP,QAR,OMR,RON,RUB,RWF,WST,SAR,RSD,SCR,SLL,SGD,STN,SBD,SOS,ZAR,KRW,LKR,SHP,SDG,SRD,SZL,SEK,CHF,SYP,TWD,TJS,TZS,THB,TOP,TTD,TND,TRY,TMT,AED,UGX,UAH,USD,UZS,VUV,VND,YER,CNY,ZMW,ZWL,STD,BYN" }
-
-#tokenization configuration which describe token lifetime and payment method for specific connector
-[tokenization]
-stripe = { long_lived_token = false, payment_method = "wallet", payment_method_type = { type = "disable_only", list = "google_pay" } }
-checkout = { long_lived_token = false, payment_method = "wallet", apple_pay_pre_decrypt_flow = "network_tokenization", google_pay_pre_decrypt_flow = "network_tokenization" }
-mollie = { long_lived_token = false, payment_method = "card" }
-braintree = { long_lived_token = false, payment_method = "card" }
-gocardless = { long_lived_token = true, payment_method = "bank_debit" }
-billwerk = { long_lived_token = false, payment_method = "card" }
-globalpay = { long_lived_token = false, payment_method = "card", flow = "mandates" }
-dwolla = { long_lived_token = true, payment_method = "bank_debit" }
-datatrans = { long_lived_token = false, payment_method = "wallet", payment_method_type = { type = "enable_only", list = "google_pay" } }
-elavon_pg = { long_lived_token = false, payment_method = "card", flow = "mandates" }
-
-[connector_customer]
-payout_connector_list = "nomupay,wise"
-
-[payout_method_filters.envoy]
-sepa = { country = "AD, AT, BE, BG, HR, CY, CZ, DK, EE, FI, FR, DE, GR, HU, IS, IE, IT, LV, LI, LT, LU, MT, MC, NL, NO, PL, PT, RO, SM, SK, SI, ES, SE, CH, GB", currency = "EUR, BGN, CZK, DKK, HUF, ISK, CHF, NOK, PLN, RON, SEK, GBP" }
-ach = { country = "AD, AT, BE, BG, HR, CY, CZ, DK, EE, FI, FR, DE, GR, HU, IS, IE, IT, LV, LI, LT, LU, MT, MC, NL, NO, PL, PT, RO, SM, SK, SI, ES, SE, CH, GB", currency = "EUR, BGN, CZK, DKK, HUF, ISK, CHF, NOK, PLN, RON, SEK, GBP" }
-bacs = { country = "AD, AT, BE, BG, HR, CY, CZ, DK, EE, FI, FR, DE, GR, HU, IS, IE, IT, LV, LI, LT, LU, MT, MC, NL, NO, PL, PT, RO, SM, SK, SI, ES, SE, CH, GB", currency = "EUR, BGN, CZK, DKK, HUF, ISK, CHF, NOK, PLN, RON, SEK, GBP" }
-
-[dummy_connector]
-enabled = true
-payment_ttl = 172800
-payment_duration = 1000
-payment_tolerance = 100
-payment_retrieve_duration = 500
-payment_retrieve_tolerance = 100
-payment_complete_duration = 500
-payment_complete_tolerance = 100
-refund_ttl = 172800
-refund_duration = 1000
-refund_tolerance = 100
-refund_retrieve_duration = 500
-refund_retrieve_tolerance = 100
-authorize_ttl = 36000
-assets_base_url = "https://app.hyperswitch.io/assets/TestProcessor/"
-default_return_url = "https://app.hyperswitch.io/"
-slack_invite_url = "https://join.slack.com/t/hyperswitch-io/shared_invite/zt-2awm23agh-p_G5xNpziv6yAiedTkkqLg"
-discord_invite_url = "https://discord.gg/wJZ7DVW8mm"
-
-[payouts]
-payout_eligibility = true
-
-[mandates.supported_payment_methods]
-bank_debit.ach = { connector_list = "gocardless,adyen,stripe" }
-bank_debit.becs = { connector_list = "gocardless,stripe,adyen" }
-bank_debit.bacs = { connector_list = "stripe,gocardless" }
-bank_debit.sepa = { connector_list = "gocardless,adyen,stripe,deutschebank" }
-card.credit.connector_list = "aci,checkout,stripe,adyen,authorizedotnet,cybersource,datatrans,globalpay,worldpay,multisafepay,nmi,nexinets,noon,bankofamerica,braintree,nuvei,payme,wellsfargo,bamboraapac,elavon,fiuu,nexixpay,novalnet,paybox,paypal,xendit,moneris,worldpayvantiv,payload,mollie,airwallex,imerchantsolutions,givepayments,shift4,ecommpay,worldpayraft,elavon_pg"
-card.debit.connector_list = "aci,checkout,stripe,adyen,authorizedotnet,cybersource,datatrans,globalpay,worldpay,multisafepay,nmi,nexinets,noon,bankofamerica,braintree,nuvei,payme,wellsfargo,bamboraapac,elavon,fiuu,nexixpay,novalnet,paybox,paypal,xendit,moneris,worldpayvantiv,payload,mollie,airwallex,imerchantsolutions,givepayments,shift4,ecommpay,worldpayraft,elavon_pg"
-pay_later.klarna.connector_list = "adyen,aci"
-wallet.apple_pay.connector_list = "aci,stripe,adyen,braintree,cybersource,noon,bankofamerica,nexinets,novalnet,authorizedotnet,worldpayxml,imerchantsolutions,datatrans,shift4,fiservcommercehub"
-wallet.samsung_pay.connector_list = "aci,cybersource"
-wallet.google_pay.connector_list = "aci,stripe,adyen,cybersource,bankofamerica,noon,globalpay,multisafepay,novalnet,authorizedotnet,worldpayxml,imerchantsolutions,datatrans,shift4,fiservcommercehub"
-wallet.paypal.connector_list = "adyen,globalpay,nexinets,novalnet,paypal,authorizedotnet"
-wallet.momo.connector_list = "adyen"
-wallet.kakao_pay.connector_list = "adyen"
-wallet.go_pay.connector_list = "adyen"
-wallet.gcash.connector_list = "adyen, dlocal"
-wallet.dana.connector_list = "adyen"
-wallet.twint.connector_list = "adyen"
-wallet.vipps.connector_list = "adyen"
-
-bank_redirect.ideal.connector_list = "stripe,adyen,globalpay,multisafepay,nexinets,aci"
-bank_redirect.sofort.connector_list = "globalpay,aci"
-bank_redirect.giropay.connector_list = "globalpay,multisafepay,nexinets,aci"
-bank_redirect.bancontact_card.connector_list = "adyen,stripe"
-bank_redirect.trustly.connector_list = "adyen,aci"
-bank_redirect.open_banking_uk.connector_list = "adyen"
-bank_redirect.eps.connector_list = "globalpay,nexinets,aci"
-
-[debit_routing_config]
-supported_currencies = "USD"
-supported_connectors = "adyen"
-
-[debit_routing_config.connector_supported_debit_networks]
-adyen = "Star,Pulse,Accel,Nyce"
-
-[cors]
-max_age = 30
-origins = "http://localhost:8080"
-allowed_methods = "GET,POST,PUT,DELETE"
-wildcard_origin = false
-
-[mandates.update_mandate_supported]
-card.credit = { connector_list = "cybersource" }
-card.debit = { connector_list = "cybersource" }
-
-[network_transaction_id_supported_connectors]
-connector_list = "adyen,archipel,checkout,cybersource,novalnet,stripe,worldpay,worldpayvantiv,revolv3,jpmorgan,worldpayraft"
-
-[card_only_mit_supported_connectors]
-connector_list = "peachpayments" # Supported connectors for card only mit
-
-[notify_iframe_exit_and_redirect]
-connector_list = "worldpayxml"
-
-[analytics]
-source = "sqlx"
-
-[analytics.sqlx]
-username = "db_user"
-password = "db_pass"
-host = "localhost"
-port = 5432
-dbname = "hyperswitch_db"
-max_pool_size = 5
-connection_timeout = 10
-min_idle_pool_size = 2
-idle_timeout = 300
-max_lifetime = 1800
-
-[kv_config]
-ttl = 300 # 5 * 60 seconds
-
-[frm]
-enabled = true
-
-[connector_onboarding.paypal]
-client_id = ""
-client_secret = ""
-partner_id = ""
-
-[unmasked_headers]
-keys = "accept-language,user-agent,x-profile-id"
-
-[multitenancy]
-enabled = false
-global_tenant = { tenant_id = "global", schema = "public", redis_key_prefix = "" }
-
-[multitenancy.tenants.public]
-base_url = "http://localhost:8080"
-mtls_base_url = "http://localhost:8080"
-schema = "public"
-accounts_schema = "public"
-redis_key_prefix = ""
-clickhouse_database = "default"
-
-[multitenancy.tenants.public.user]
-control_center_url = "http://localhost:9000"
-
-[email]
-sender_email = "[email protected]"
-aws_region = ""
-allowed_unverified_days = 1
-active_email_client = "NO_EMAIL_CLIENT"
-recon_recipient_email = "[email protected]"
-prod_intent_recipient_email = "[email protected]"
-
-[email.aws_ses]
-email_role_arn = ""
-sts_role_session_name = ""
-
-[temp_locker_enable_config]
-paybox = { payment_method = "card" }
-redsys = { payment_method = "card" }
-barclaycard = { payment_method = "card" }
-globalpayments_realex = { payment_method = "card" }
-worldpayxml = { payment_method = "card" }
-paydotcom = { payment_method = "card" } # Pay.com gateway 3DS settles on CompleteAuthorize; the card must be restorable
-
-[billing_connectors_payment_sync]
-billing_connectors_which_require_payment_sync = "stripebilling, recurly"
-[billing_connectors_invoice_sync]
-billing_connectors_which_requires_invoice_sync_call = "recurly"
-
-[billing_connectors_dispute_record_back]
-billing_connectors_which_requires_dispute_record_back_call = "chargebee"
-
-
-[revenue_recovery.card_config.amex]
-max_retries_per_day = 20
-max_retry_count_for_thirty_day = 20
-
-[revenue_recovery.card_config.mastercard]
-max_retries_per_day = 10
-max_retry_count_for_thirty_day = 35
-
-[revenue_recovery.card_config.visa]
-max_retries_per_day = 20
-max_retry_count_for_thirty_day = 20
-
-[revenue_recovery.card_config.discover]
-max_retries_per_day = 20
-max_retry_count_for_thirty_day = 20
-
-[trace_header]
-header_name = "x-request-id"
-id_reuse_strategy = "ignore_incoming" # Options: "ignore_incoming" (default) or "use_incoming"
-
-# Authentication to communicate between internal services using common_api_key, merchant id and profile id
-[internal_merchant_id_profile_id_auth]
-enabled = false # Enable or disable internal api key, merchant id and profile id based authentication
-primary_internal_api_key = "test_internal_api_key" # API key for internal merchant id and profile id based authentication
-
-[internal_services] # Internal services base urls and configs
-payments_base_url = "http://localhost:8080"
diff --git a/loadtest/config/otel-collector.yaml b/loadtest/config/otel-collector.yaml
deleted file mode 100644
index 7cc459024e..0000000000
--- a/loadtest/config/otel-collector.yaml
+++ /dev/null
@@ -1,16 +0,0 @@
-receivers:
- otlp:
- protocols:
- grpc:
-
-exporters:
- otlp:
- endpoint: tempo:4317
- tls:
- insecure: true
-
-service:
- pipelines:
- traces:
- receivers: [otlp]
- exporters: [otlp]
diff --git a/loadtest/config/tempo.yaml b/loadtest/config/tempo.yaml
deleted file mode 100644
index 135c4bac8d..0000000000
--- a/loadtest/config/tempo.yaml
+++ /dev/null
@@ -1,38 +0,0 @@
-server:
- http_listen_port: 3200
-
-distributor:
- receivers:
- otlp:
- protocols:
- grpc:
-
-ingester:
- trace_idle_period: 10s # the length of time after a trace has not received spans to consider it complete and flush it
- max_block_bytes: 1_000_000 # cut the head block when it hits this size or ...
- max_block_duration: 5m # this much time passes
-
-compactor:
- compaction:
- compaction_window: 1h # blocks in this time window will be compacted together
- max_block_bytes: 100_000_000 # maximum size of compacted blocks
- block_retention: 1h
- compacted_block_retention: 10m
-
-storage:
- trace:
- backend: local # backend configuration to use
- block:
- bloom_filter_false_positive: .05 # bloom filter false positive rate. lower values create larger filters but fewer false positives
- index_downsample_bytes: 1000 # number of bytes per index record
- encoding: zstd # block encoding/compression. options: none, gzip, lz4-64k, lz4-256k, lz4-1M, lz4, snappy, zstd, s2
- wal:
- path: /tmp/tempo/wal # where to store the wal locally
- encoding: snappy # wal encoding/compression. options: none, gzip, lz4-64k, lz4-256k, lz4-1M, lz4, snappy, zstd, s2
- local:
- path: /tmp/tempo/blocks
- pool:
- max_workers: 100 # worker pool determines the number of parallel requests to the object store backend
- queue_depth: 10000
-
-search_enabled: true
diff --git a/loadtest/console/.env.example b/loadtest/console/.env.example
new file mode 100644
index 0000000000..e94b17e8ac
--- /dev/null
+++ b/loadtest/console/.env.example
@@ -0,0 +1,37 @@
+# Supply the real hash and service credentials at runtime. Never commit .env.
+ADMIN_USERNAME=admin
+ADMIN_PASSWORD_HASH=
+ORIGIN=http://127.0.0.1:4174
+ROUTER_ADMIN_API_KEY=
+SUPERPOSITION_TOKEN=
+# Optional. The console also checks the source build and PATH.
+K6_BINARY=
+GRAFANA_URL=http://127.0.0.1:3002
+# Separate origin for active Grafana content. Local default is console port + 2.
+GRAFANA_EMBED_ORIGIN=http://127.0.0.1:4176
+GRAFANA_PROXY_PORT=4176
+# Use a Grafana Viewer identity. Auth proxy mode is needed by some embedded dashboards.
+GRAFANA_TOKEN=
+GRAFANA_USER=
+PGHOST=127.0.0.1
+PGPORT=5432
+PGDATABASE=hyperswitch_db
+# Set an existing account; the console never creates PostgreSQL roles.
+PGUSER=
+PGPASSWORD=
+# Optional private CA for npm run dev:tls / start:tls. Must be an absolute PEM path.
+PGSSLROOTCERT=
+
+# Optional server-only target JSON. Empty means simulation only.
+LOADTEST_FAULT_TARGETS=
+# Remote workers enroll once with this token, then receive a unique credential.
+LOADTEST_WORKER_ENROLLMENT_TOKEN=replace-with-a-long-random-token
+# LOADTEST_CONTROL_PLANE_URL=https://loadtest.example.com
+# LOADTEST_WORKER_NAME=worker-1
+# LOADTEST_WORKER_TPS=250
+# LOADTEST_WORKER_VUS=2500
+# LOADTEST_WORKER_POLL_MS=1000
+
+# Opt in to scheduled shell commands running as the supervisor OS user.
+# Restart the console and its idle worker after changing this value.
+LOADTEST_ALLOW_CUSTOM_COMMANDS=false
diff --git a/loadtest/console/.gitignore b/loadtest/console/.gitignore
new file mode 100644
index 0000000000..57a7ae952e
--- /dev/null
+++ b/loadtest/console/.gitignore
@@ -0,0 +1,14 @@
+node_modules/
+dist/
+.console-state.json
+.data/
+.worker-data/
+.svelte-kit/
+build/
+.env
+# The repository's Nix result* rule also matches these application sources.
+!src/results-limits.mjs
+!src/result-test-cases.mjs
+!test/result-test-cases.test.mjs
+!src/routes/(console)/results/
+!src/routes/(console)/results/**
diff --git a/loadtest/console/DEPLOYMENT.md b/loadtest/console/DEPLOYMENT.md
new file mode 100644
index 0000000000..8335437219
--- /dev/null
+++ b/loadtest/console/DEPLOYMENT.md
@@ -0,0 +1,214 @@
+# EC2 deployment and capacity validation
+
+Use one EC2 instance in the target services' VPC, one container and one admin.
+Start with 16 vCPUs and 32 GiB RAM; choose the final size from generator CPU,
+memory and network measurements. Run the generator on a different host from the
+services under test so they do not compete for compute resources.
+
+## Start
+
+Mount encrypted gp3 EBS at `/srv/loadtest`. Size storage from measured bytes per
+API attempt × attempts/sec × test duration and desired run retention; every
+attempt is recorded, so artifacts are not small at 1,000 flows/sec. Configure
+EBS IOPS/throughput from recorder commit latency and backlog, and keep free-space
+alerts. Ensure `/srv/loadtest` is owned by container UID 1000.
+
+From `loadtest/console`, prepare an ignored `.env` using `.env.example`. Inject
+admin hash and service credentials from AWS Secrets Manager into this runtime
+file or environment using the EC2 instance role. Do not build them into the
+image. Set:
+
+```text
+ORIGIN=https://loadtest.example.com
+CONSOLE_BIND_ADDRESS=0.0.0.0
+CONSOLE_DATA_PATH=/srv/loadtest
+```
+
+Run `docker compose up -d --build`. The image uses the pinned Go/k6 extension and
+Node 24 runtime. Change service endpoints in Settings to the services' private
+DNS names; `127.0.0.1` inside a container refers to the container itself.
+The shared `.env.example` defaults to local development. Set `PGHOST` and
+`GRAFANA_URL` to addresses reachable from the container before deploying it.
+
+Place an HTTPS ALB with an ACM certificate in front of port 4174. Allow inbound
+4174 only from the ALB security group and allow browser ingress only from the
+intended administrator network. Set health checks to `/health`, deregistration
+delay to 75 seconds, and idle timeout to at least 90 seconds. SSE sends a snapshot
+every second and does not depend on the browser remaining open.
+
+Only one console process/container may use the volume. Jobs and sessions persist
+in `/data/console.sqlite`; jobs left active after restart become interrupted.
+New jobs wait until surviving workers have stopped after a restart.
+Cancellation and shutdown allow 60 seconds for k6 to stop and drain. The container
+grace period is 75 seconds. Forced termination leaves incomplete recording.
+
+## Database TLS
+
+Set `PGSSLROOTCERT` to an absolute mounted PEM path when PostgreSQL uses a private
+certificate authority, then launch with `npm run start:tls`. Leave the variable
+empty for a certificate issued by a system-trusted CA. The TLS launcher refuses
+to replace a worker that owns an active job or fault recovery. Container
+deployments can instead save the same CA path in Settings → Database; mount the
+certificate read-only and choose **Verified certificate**. For managed databases
+that require encryption but do not expose a verifiable server CA, choose
+**Required · encrypted**.
+
+## Grafana
+
+Grafana panels run on a separate origin, served on port 4176 by default. Publish
+that port through a separate same-site HTTPS hostname (for example
+`metrics.loadtest.example.com`) and set `GRAFANA_EMBED_ORIGIN` accordingly. Route
+only that hostname to port 4176; keep the console hostname on 4174. Both listeners
+must reach the same console data directory. The normal Compose file exposes both
+ports on loopback for local use. Grafana access uses one-time embed tickets and a
+separate HttpOnly cookie, revoked when its console session ends.
+
+`GRAFANA_URL` binds the server's Grafana identity to its upstream origin. Changing
+the saved base URL to another origin cannot forward that identity; change the
+server configuration explicitly when moving Grafana. Similarly, changing Router,
+Superposition or database destinations requires entering their credentials again.
+
+Workers stop active load if control-plane contact is lost for 30 seconds, with a
+10-second drain before forced termination. Cancellation and worker failures stop
+sibling workers before the coordinator finishes; unverified stops fail explicitly.
+
+The Node adapter permits streamed artifacts up to 2 GB by default. Other API requests and
+login forms retain a streamed 1 MiB limit. Reverse proxies must allow the artifact
+upload size and sufficient upload time on worker routes.
+
+The console automatically detects root-hosted Grafana and rewrites its frontend
+paths under the authenticated `/grafana/` proxy. Existing Grafana deployments
+can stay at `/`; no deployment changes are required for path compatibility.
+Embedding still requires Grafana to permit frames and a server identity that can
+authenticate panel HTML. Grafana Live WebSocket panels are not supported.
+
+For a dedicated Grafana deployment, you can alternatively configure:
+
+```ini
+[server]
+root_url = https://loadtest.example.com/grafana/
+serve_from_sub_path = true
+[security]
+allow_embedding = true
+cookie_secure = true
+```
+
+Supply `GRAFANA_TOKEN` for a Viewer service account. Grafana UI versions that do
+not accept bearer authentication for embeds require auth proxy mode:
+
+```ini
+[auth.proxy]
+enabled = true
+header_name = X-WEBAUTH-USER
+header_property = username
+auto_sign_up = true
+enable_login_token = false
+# Restrict to the console host's private IP; never expose this identity header publicly.
+whitelist = <console-private-IP>
+[users]
+auto_assign_org_role = Viewer
+```
+
+Set `GRAFANA_USER` to that Viewer identity. Supply the private `GRAFANA_URL` as
+the upstream address. The console strips browser cookies/identity headers and
+accepts only the configured upstream. Add panel URLs under `/grafana/d-solo/`.
+The proxy supports read-only dashboard/data-source queries, not Grafana editing
+or live WebSocket panels.
+
+## Acceptance
+
+1. Run 10 flows/sec locally using the three-flow 50/30/20 mix and a Stripe test
+ connector. Check login, SSE progress, cancellation, restart recovery and recon.
+2. On EC2 step through 100, 500 and 1,000 offered flows/sec. Tune VU multipliers
+ from full-flow latency and observed drops, rather than request latency alone.
+3. Sustain 1,000 for 30 minutes in both merchant modes. Require no recording gaps,
+ bounded queue, no dropped iterations due to the generator, and responsive UI.
+ Report successful TPS and downstream failures separately from offered TPS.
+4. Characterize recorder CPU time, memory/network usage, queue depth, commit
+ latency and successful TPS with representative flows before claiming a host's
+ capacity. Use the native mock-backed integration tests for correctness, then
+ measure against your actual environment. AWS provisioning is separate from
+ this image; this console does not create cloud resources.
+
+References: [SvelteKit Node deployment](https://svelte.dev/docs/kit/adapter-node),
+[k6 capacity guidance](https://grafana.com/docs/k6/latest/testing-guides/running-large-tests/),
+and [Grafana auth proxy](https://grafana.com/docs/grafana/latest/setup-grafana/configure-access/configure-authentication/auth-proxy/).
+
+
+## Worker ownership
+
+The container entrypoint runs an SSR server and an independent loopback-only,
+authenticated worker service. `/data/console.sqlite` stores versioned profiles,
+fixture sets, jobs and activity; private worker connection metadata also lives
+under `/data`. Keep this volume on one local EBS filesystem, never share it
+between multiple console containers. Browser disconnects and SSR restarts leave
+workers executing. Container termination signals both services and drains the
+recorder; a worker crash marks unfinished runs incomplete on recovery.
+
+Configure an existing PostgreSQL account with SELECT permission on
+`payment_intent`, then use Settings → Database → Test connection. No role is
+created automatically. Saved connection settings override environment defaults.
+
+## Distributed workers
+
+The console is the control plane. It owns scenarios, synchronized run state,
+fault execution and result merging. Remote workers connect outbound over HTTPS,
+receive a worker-specific fixture/config bundle, run one TPS shard, and stream
+health and progress back. Workers never receive gcloud or kubectl credentials.
+
+Set a long random `LOADTEST_WORKER_ENROLLMENT_TOKEN` on the control plane and
+each new worker. Enrollment exchanges it for a unique credential stored with
+mode `0600` in the worker data directory. Remove the enrollment token from a
+worker after its identity has been created. Put the control plane behind TLS in
+production and restrict the worker API to the private network.
+
+For a local multi-container verification:
+
+```bash
+docker compose -f compose.yaml -f compose.distributed.yaml up --build --scale worker=4
+```
+
+Each worker defaults to 250 TPS and 2,500 VUs. Settings shows heartbeats and
+advertised capacity. Performance enables **Distributed · auto** when at least
+one remote worker is healthy. The scheduler refuses a run unless combined TPS
+and VU capacity satisfy the scenario, then schedules all workers against a
+common future start time. Infrastructure faults remain single control-plane
+events while load continues on every shard.
+
+In cloud deployments use one persistent control-plane data volume, an Auto
+Scaling Group or Kubernetes Deployment for worker containers, and object
+storage for long-term artifact retention. Workers need outbound access to the
+control plane and the tested Hyperswitch endpoints; they need no inbound ports.
+
+Build `Dockerfile.cloud` on top of the published console image for the
+control-plane Deployment. It installs the `gcloud` and `kubectl` binaries used
+by the Cloud fault presets. Authenticate it with workload identity and narrowly
+scoped AlloyDB IAM and Kubernetes RBAC; do not mount either credential into load
+workers. The ordinary console image remains suitable when infrastructure faults
+are disabled.
+
+### Existing fixtures and custom fault execution
+
+Imported credential files use the same private server-side fixture format as
+provisioned fixtures (directories 0700, files 0600). Fixture APIs return verification
+results and identifiers, never keys. Do not commit `.data`, fixture artifacts, or
+credential JSON. Verification performs read-only Hyperswitch inspections; actual
+connector authorization is a separate smoke test. Keep the admin inspection key
+bound to the intended Router endpoint.
+
+Custom fault commands are disabled by default. Setting
+`LOADTEST_ALLOW_CUSTOM_COMMANDS=true` grants authenticated console administrators
+shell execution as the supervisor's OS user. Enable it only on a trusted console;
+use a dedicated OS identity with access limited to the intended test resources.
+The working directory and any scripts must exist on that machine or inside its
+container. Remote hosts require explicit remote commands and credentials managed
+outside command text. Existing GCP/Kubernetes adapters remain the default.
+
+The supervisor snapshots commands into each run and journals recovery before
+triggering. A nonzero exit, timeout, or interrupted trigger still attempts configured
+restoration. Self-recovering faults omit restoration but must pass the healthy check.
+Keep scripts idempotent, checks read-only, and timeouts short enough for stop-time
+recovery. Process groups are killed when a command exceeds its timeout. Command
+stdout/stderr are not recorded; activity and failures identify lifecycle stages.
+Changing the deployment opt-in requires restarting the idle supervisor as well as
+the web process. Never reload it during an active fault.
diff --git a/loadtest/console/Dockerfile b/loadtest/console/Dockerfile
new file mode 100644
index 0000000000..2e0b380447
--- /dev/null
+++ b/loadtest/console/Dockerfile
@@ -0,0 +1,41 @@
+FROM golang:1.24.4-bookworm AS recorder
+WORKDIR /recorder
+COPY loadtest/k6/scenario-mix/recorder/go.mod loadtest/k6/scenario-mix/recorder/go.sum ./
+RUN go mod download
+COPY loadtest/k6/scenario-mix/recorder/ ./
+RUN CGO_ENABLED=1 go build -mod=readonly -trimpath -o /k6-sqlite ./cmd/k6-sqlite
+
+FROM node:24.19.0-bookworm-slim AS web
+WORKDIR /app/loadtest/console
+COPY loadtest/console/package.json loadtest/console/package-lock.json ./
+RUN npm ci
+COPY loadtest/console/src ./src
+COPY loadtest/console/static ./static
+COPY loadtest/console/server ./server
+COPY loadtest/console/vite.config.js loadtest/console/svelte.config.js loadtest/console/jsconfig.json ./
+RUN npm run build && npm prune --omit=dev
+
+FROM node:24.19.0-bookworm-slim
+RUN apt-get update && apt-get install -y --no-install-recommends ca-certificates tini time && rm -rf /var/lib/apt/lists/*
+WORKDIR /app/loadtest/console
+COPY --from=web /app/loadtest/console/build ./build
+COPY --from=web /app/loadtest/console/node_modules ./node_modules
+COPY loadtest/console/package.json loadtest/console/start.mjs ./
+COPY loadtest/console/server ./server
+COPY loadtest/console/src/*.mjs loadtest/console/src/*.json /app/loadtest/console/src/
+COPY loadtest/console/scripts ./scripts
+COPY loadtest/k6/scenario-mix/*.mjs /app/loadtest/k6/scenario-mix/
+COPY loadtest/k6/scenario-mix/scenario-mix.js loadtest/k6/scenario-mix/recording-client.js /app/loadtest/k6/scenario-mix/
+COPY loadtest/k6/scenario-mix/config.example.json /app/loadtest/k6/scenario-mix/
+COPY loadtest/k6/scenario-mix/test/mock-server.mjs /app/loadtest/k6/scenario-mix/test/
+COPY loadtest/k6/scenario-mix/recorder/*.sql /app/loadtest/k6/scenario-mix/recorder/
+COPY loadtest/loadtest.config.example.json /app/loadtest/
+COPY --from=recorder /k6-sqlite /usr/local/bin/k6-sqlite
+RUN mkdir /data && chown node:node /data
+USER node
+ENV NODE_ENV=production HOST=0.0.0.0 PORT=4174 LOADTEST_DATA_DIR=/data LOADTEST_ROOT=/app/loadtest K6_BINARY=/usr/local/bin/k6-sqlite SHUTDOWN_TIMEOUT=70
+EXPOSE 4174 4176
+STOPSIGNAL SIGTERM
+HEALTHCHECK --interval=30s --timeout=5s CMD node -e "fetch('http://127.0.0.1:4174/health').then(r=>process.exit(r.ok?0:1)).catch(()=>process.exit(1))"
+ENTRYPOINT ["/usr/bin/tini","--"]
+CMD ["node","scripts/container.mjs"]
diff --git a/loadtest/console/Dockerfile.cloud b/loadtest/console/Dockerfile.cloud
new file mode 100644
index 0000000000..c9b2ed95ad
--- /dev/null
+++ b/loadtest/console/Dockerfile.cloud
@@ -0,0 +1,13 @@
+ARG CONSOLE_IMAGE=hyperswitch-loadtest-console:latest
+FROM ${CONSOLE_IMAGE}
+
+USER root
+RUN apt-get update \
+ && apt-get install -y --no-install-recommends apt-transport-https ca-certificates curl gnupg \
+ && mkdir -p /etc/apt/keyrings \
+ && curl -fsSL https://packages.cloud.google.com/apt/doc/apt-key.gpg | gpg --dearmor -o /etc/apt/keyrings/cloud.google.gpg \
+ && echo "deb [signed-by=/etc/apt/keyrings/cloud.google.gpg] https://packages.cloud.google.com/apt cloud-sdk main" > /etc/apt/sources.list.d/google-cloud-sdk.list \
+ && apt-get update \
+ && apt-get install -y --no-install-recommends google-cloud-cli kubectl \
+ && rm -rf /var/lib/apt/lists/*
+USER node
diff --git a/loadtest/console/Dockerfile.dockerignore b/loadtest/console/Dockerfile.dockerignore
new file mode 100644
index 0000000000..ce69facafb
--- /dev/null
+++ b/loadtest/console/Dockerfile.dockerignore
@@ -0,0 +1,28 @@
+**
+!loadtest/
+!loadtest/console/
+!loadtest/console/package.json
+!loadtest/console/package-lock.json
+!loadtest/console/start.mjs
+!loadtest/console/vite.config.js
+!loadtest/console/svelte.config.js
+!loadtest/console/jsconfig.json
+!loadtest/console/static/
+!loadtest/console/static/**
+!loadtest/console/src/
+!loadtest/console/src/**
+!loadtest/console/server/
+!loadtest/console/server/**
+!loadtest/console/scripts/
+!loadtest/console/scripts/**
+!loadtest/k6/
+!loadtest/k6/scenario-mix/
+!loadtest/k6/scenario-mix/*.mjs
+!loadtest/k6/scenario-mix/scenario-mix.js
+!loadtest/k6/scenario-mix/recording-client.js
+!loadtest/k6/scenario-mix/config.example.json
+!loadtest/k6/scenario-mix/test/
+!loadtest/k6/scenario-mix/test/mock-server.mjs
+!loadtest/k6/scenario-mix/recorder/
+!loadtest/k6/scenario-mix/recorder/**
+!loadtest/loadtest.config.example.json
diff --git a/loadtest/console/README.md b/loadtest/console/README.md
new file mode 100644
index 0000000000..9b4b2cf686
--- /dev/null
+++ b/loadtest/console/README.md
@@ -0,0 +1,391 @@
+# Load-test console
+
+SvelteKit SSR and authenticated APIs expose the master control plane. It manages
+local or distributed k6 workers, owns infrastructure faults and reconciliation,
+and keeps jobs running independently of browser connections. Load workers call
+Router and PM directly.
+
+```bash
+cd loadtest/console
+npm ci
+cp .env.example .env
+# Generate a password hash without putting the password in shell history:
+read -s "console_password?Admin password: "
+printf '%s' "$console_password" | npm run --silent password
+unset console_password
+# Paste the hash into .env, then configure service credentials.
+npm run dev
+```
+
+Open http://127.0.0.1:4174. For a local production build:
+`npm run build && node --env-file=.env start.mjs`.
+The example uses local PostgreSQL on `127.0.0.1:5432`. Configure a database user
+with SELECT access to `payment_intent` and its password. Saved Settings override
+the initial environment values, so update the saved connection when switching
+between local services and a container deployment.
+
+The first start imports the existing ignored `loadtest.config.json` into `.data`;
+subsequent settings edits affect the console copy. Set `LOADTEST_CONFIG_FILE` to
+import a different configuration and `LOADTEST_DATA_DIR` for durable storage.
+Existing artifact directories remain readable. Settings never return stored
+passwords, API keys or Grafana tokens. Leaving a secret input blank keeps it.
+
+For PostgreSQL servers that require TLS, set the database values in `.env` and
+start the application with the TLS launcher:
+
+```bash
+# PGSSLROOTCERT is optional when the database certificate uses a system-trusted CA.
+export PGSSLROOTCERT=/absolute/path/to/database-ca.pem
+npm run dev:tls
+# Production build: npm run build && npm run start:tls
+```
+
+The launcher enforces certificate verification, validates the optional PEM path,
+and reloads the detached worker so it inherits the TLS configuration. It refuses
+to reload while a job, outage, or recovery is active. The same CA path can be
+entered under Settings → Database; **Test connection** uses the identical TLS
+configuration as reconciliation. `sslmode=disable` behavior remains available by
+using the regular `npm run dev`/`npm start` commands with TLS unchecked.
+
+Use the screens in this order:
+
+1. **Scenarios** — create or edit a named scenario with Single/Tenancy, merchant count,
+ weighted flows, and constant TPS or visual Ramp/Hold stages. Saving creates a
+ new immutable version; existing runs keep their original version.
+2. **Fixtures** — select a scenario and create/recover its infrastructure. Existing
+ ready CLI fixtures are imported automatically. Only compatible ready sets can
+ be selected for execution; merchant identity and provisioning-value changes
+ require new fixtures.
+3. **Performance** — select a saved scenario and ready fixture set. **Smoke test**
+ runs a short, configurable verification without recording responses or adding
+ a Results run. **Start load** launches the recorded scenario independently;
+ it never runs smoke implicitly. “Open Performance” on Scenarios only selects
+ the scenario; it does not launch k6.
+4. **Results** — inspect recordings and Compare with PostgreSQL. Open Settings →
+ Database, enter an existing database account, and Test connection first.
+
+Flow weights must total 100%. TPS means offered payment flows/sec, not API
+requests/sec; a flow may make several requests. The ramp preview uses active test
+time, while live monitoring includes wall time and pauses. Settings → Load
+generator controls preallocated and maximum VUs per TPS. Those limits are copied
+into each run snapshot, so changing them does not alter a run already in progress.
+
+The background worker starts automatically and owns execution. Browser refresh,
+closing a tab, logging out, hot reload, and SSR process restart do not cancel a
+run. Reopening Performance attaches to the active run. Settings edits do not
+change an already captured run or fixture configuration.
+
+```bash
+npm run worker -- status
+# Explicitly stop the worker and drain any active job before changing worker code:
+npm run worker -- stop
+npm run worker -- start
+```
+
+Worker code is loaded when the worker starts; frontend hot reload does not reload
+an executing worker. Container shutdown stops both services, allows recording to
+drain for 60 seconds, and recovers interrupted jobs as incomplete after a crash.
+The container entrypoint supervises both services; `npm start` starts SSR alone,
+so stopping that process intentionally leaves the worker running.
+
+Performance uses five load states:
+
+| State | Available load controls |
+|---|---|
+| Idle | Start |
+| Running | Pause, Stop |
+| Pausing | None; active flows are draining |
+| Paused | Resume, Stop |
+| Completed | None; choose New run to start another |
+
+Pause closes admission to new flows. Already admitted flows finish before Paused.
+The configured load clock freezes during pause and drain; resume does not catch
+up missed arrivals. Waiting VUs remain allocated. The console's Go admission
+controller is used with k6's externally-controlled executor, because k6 1.0.0
+cannot pause a running arrival-rate executor. CLI runs retain their native
+arrival-rate executors. The console searches `K6_BINARY`, the source-tree build,
+its container path and `PATH`. Build the custom binary after a fresh checkout:
+
+```bash
+npm run build:recorder
+```
+
+Cards and the live chart show successful TPS, confirmation p99, HTTP errors and
+pending SQLite writes. Live p99 uses a bounded one-second window (8,192 observations);
+final p99 uses the complete k6 summary. Chart samples use wall time so pauses and
+faults remain visible. The latest 30 minutes are available for replay and flow
+filtering; all samples remain in each run's telemetry.jsonl. Activity is persisted
+in console.sqlite and exported beside the run. k6 output is under Diagnostics.
+Results evaluates the criteria saved in that run's configuration, keeping
+performance acceptance separate from infrastructure recovery verification.
+
+### Environments and payment flows
+
+Settings → Connections selects **Local**, **GCP**, **AWS**, or **Azure**. Service
+connections, database/TLS credentials, and fault targets are saved separately per
+environment. Switching back restores that environment’s saved connections. Saving
+an environment or connection change is blocked while a job or fault recovery is active. Reconciliation of a provider-tagged run requires that provider to be selected. Existing
+run snapshots remain unchanged; provider selection describes the system under test,
+not the location of the load generator.
+
+Local supports the vault launcher and process-compose PostgreSQL/Redis outages.
+GCP supports Kubernetes vault outages and managed AlloyDB/Redis failovers. GCP
+resource identities must be entered explicitly; the editor does not assume a
+project or deployment. Fault target choices, interruption dialogs, activity, and
+new Results summaries identify the provider. Changing providers does not translate
+an outage into a failover: choose a supported action for the selected target.
+
+AWS and Azure retain placeholder connections and resource fields; connection
+checks, fixtures, load generation, and fault execution are unavailable. No fallback
+adapter is invoked. Legacy `cloud` targets migrate to GCP. Unclassified custom
+Kubernetes/Docker targets require provider assignment; ambiguous legacy connection
+sets require an explicit environment selection. Only targets for the selected
+provider participate in health and execution, including server-defined targets.
+
+New scenarios use the payment-method service by default. The flow editor has no
+integration selector or integration badges. Guest, CIT, pay-to-vault and SDK
+checkout flows share this path. Metadata-update, MIT, and saved-card checkout are
+not yet supported on this path and are unavailable for new traffic; an existing
+scenario containing an enabled unsupported flow fails preflight explicitly.
+Historical scenario versions and recorded responses are not rewritten. New fixture
+signatures include provider and execution-model version, so prepare fixtures again
+before running newly migrated scenarios.
+
+## Scenario checks in Results
+
+The run summary groups applicable original test cases under **Load & performance**
+(TC-01, TC-02, TC-03, TC-09) and **Faults & recovery** (TC-04–TC-08, TC-10).
+Each TC has a compact Expected / Observed / Verdict row; expand it to inspect the
+measurements and limits. Steady holds are pooled into one check; repeated
+failovers retain their individual evidence and any failed occurrence. Original
+per-stage observations remain in the cached summary for inspection.
+Normal holds map to steady-load performance. Calibration/burst require explicit
+`load.stages[].intent` (`calibration` / `burst`) or `testCase` (`TC-01` / `TC-03`)
+in the saved run configuration. A ramp alone is shown as observations, never
+claimed as a burst hold. The saved fault-target type identifies the recovery TCs.
+Application-reconnection, restart and merchant-coverage
+claims stay Not measured until the required evidence exists. Card-vault outage
+checks use measured recovery, throughput, latency, and reconciled data-loss
+criteria; additional unattended/unaffected-flow evidence is not required. Explicitly selected
+`load.testCases` without execution evidence stay Not run. The mapping is persisted
+with the summary, without rewriting the saved scenario or raw recording.
+
+The existing evaluator still measures each execution period. Normal stages compare
+successful completions with the integrated offered load, including changing ramp
+rates. Pauses and recovery gates use the sampled active/wall clock recorded in
+`execution.jsonl`; older runs fall back to their uncompressed telemetry. Stage
+boundaries are interpolated between samples, not inferred from the planned wall
+duration. Latency p50/p95/p99 uses successful measured payment confirmations only.
+Steady drift compares median latency in the last third with the first third of
+the combined settled steady periods. The run verdict uses those same pooled
+steady checks shown in the UI.
+
+The latency table uses separate settled periods: baseline after startup settling,
+verified outage after settling until restoration starts, and verified recovery
+after settling until the next fault or run end. A complete flow must fit in a
+settled period, so queued work crossing a transition is excluded. Adjacent clock
+samples form continuous windows; pauses remain gaps. Percentiles use the actual
+successful request samples, with no trimming or capping by latency value. Short
+periods without eligible samples show unavailable values. All raw samples remain
+recorded, and HTTP errors, completed-flow totals and recovery timing retain their
+existing measurement windows.
+
+**Settings → Results limits** defaults to 97% throughput, 0.1% normal-stage HTTP
+errors, 160 ms hold/post-recovery p99, 500 ms ramp p99, 10% latency drift, 60 seconds
+for recovery after restoration starts, 10 seconds of transition settling,
+and zero acknowledged payments lost. Settings apply when the next run starts,
+even for an existing scenario. The effective `resultsLimits` are saved with that
+run; **Reset to defaults** only changes the Settings draft until it is saved.
+
+Intentional fault windows record all failed requests, including vault errors
+hidden from the Performance chart and timeouts returned after recovery. They do
+not apply the normal-stage HTTP-error limit. Database availability can end the
+observed outage before the provider finishes its operation. Recovery time starts
+when restoration is requested, excluding the configured intentional downtime.
+The data-loss check needs completed reconciliation; a missing comparison is not
+a zero-loss result. Simulated recovery timings are recorded, not passed.
+
+Completed results are cached atomically in `scenario-checks.json` with calculation
+version and source fingerprint; reconciliation updates invalidate the cache.
+Exact measurements are deferred until the recorder has drained to avoid scanning
+a growing database during load. Missing evidence and unexecuted stages remain
+explicit. Historical runs keep their saved throughput/error limits and record new
+metrics without retroactively applying today's limits or declaring a new overall
+pass. These Results checks do not change the existing k6 exit thresholds.
+
+Faults default to **Simulation**, which changes no infrastructure. Configure a
+server-held JSON file through LOADTEST_FAULT_TARGETS to enable real targets:
+
+```json
+[
+ {"id":"router-test","label":"Test Router","adapter":"docker","container":"test-router"},
+ {"id":"pm-test","label":"Test PM","adapter":"kubernetes","context":"test-cluster","namespace":"loadtest","deployment":"pm"},
+ {"id":"cache-test","label":"Test cache","adapter":"gcp-redis","project":"test-project","region":"us-central1","instance":"test-cache"},
+ {"id":"db-test","label":"Test database","adapter":"gcp-alloydb","project":"test-project","region":"us-central1","cluster":"test-cluster","instance":"test-primary"}
+]
+```
+
+Docker/Kubernetes support outage and restart; GCP adapters support HA failover.
+The server needs the corresponding CLI and a scoped infrastructure identity.
+The supplied container does not include docker, kubectl or gcloud; install the
+needed adapter CLI in your deployment image. An explicit target/action phrase
+confirms each operation. Only one fault can run, and a fault requires a running
+load. Pause is disabled until recovery completes. Outage duration is bounded to
+1–300 seconds; run termination restores an active outage early.
+
+Before mutation, the server flushes a recovery ledger to disk. Shutdown and
+restart retry pending recovery; unresolved recovery blocks new loads. Docker
+recovery checks container identity; Kubernetes restores the configured replica count
+and verifies the rollout. HA failover verifies a healthy primary and does not
+switch back to the original primary. Verification is readiness-based, not an
+application end-to-end recovery guarantee. Real fault adapters have command-level
+tests; only simulation is exercised automatically.
+
+Results offers paginated response history and PostgreSQL reconciliation without
+CSV input. Comparison uses the merchant/payment pair, excludes baseline payments,
+and requires complete recording unless explicitly overridden. It compares the
+latest client status to a single read-only, repeatable-read database snapshot; later asynchronous state
+changes can therefore appear as mismatches. Full comparisons live in
+`reconciliation.sqlite`; `reconciliation.json` retains counts and the first 200
+discrepancies. Failed creates with no returned payment ID remain in response
+history and cannot be reconciled by ID.
+
+Grafana panel URLs must use the configured server and `/grafana/d-solo/...`.
+The iframe uses the authenticated console origin and the selected run's time
+window. New installations include RPS, API latency and transaction-processing
+latency panels from the bundled k6 dashboard. See [EC2 deployment](DEPLOYMENT.md)
+for Grafana and ALB configuration.
+
+Settings includes read-only health checks for Router and Payment Methods. The
+Superposition check performs an authenticated read of one configured default and
+supports either `x-superposition-access` or bearer-token authentication.
+Superposition's refresh wait and progress-poll interval are configurable
+independently. Changing run rate, duration, credentials, health
+endpoints, database, Grafana or polling does not invalidate fixtures; changing
+merchant mode/count, fixture Router, connector, organization/workspace/context,
+or applied defaults does.
+
+```bash
+npm run check
+npm run build
+npm test
+```
+
+To exercise read-only reconciliation against an existing PostgreSQL database with
+at least two payments, supply `PGHOST`, `PGPORT`, `PGDATABASE`, `PGUSER`, and
+`PGPASSWORD`, then run `CONSOLE_TEST_PG=1 node --test test/postgres.test.mjs`.
+Run the native engine integration tests as described in [the engine README](../k6/scenario-mix/README.md).
+
+### Local outages and restarts
+
+In the scenario editor’s **Fault targets** section, add a Card vault or PostgreSQL / Redis target, use **Check target** (read-only), then **Save scenario** to save the scenario and shared targets together. During a running load, select it in **Create fault**. Outages last 1–300 seconds; restart immediately begins recovery. Recovery is verified, recorded on the run, and continues independently of the browser. Failed recovery blocks new loads and offers **Restore**.
+
+- **Card vault:** configure the absolute path to your card-vault repository, service port `3001`. The worker verifies the listener's repository, binary and process start time before SIGTERM. Recovery runs `nix develop -c cargo r` from that repository, with logs in the data directory. Nix, lsof and ps must be available to the worker. Build the vault first so recovery fits the 120-second readiness deadline.
+- **PostgreSQL / Redis:** configure the process-compose controller port, exact process name and service port (`5432` / `6379`; vault Redis may use `6378`). Use `process-compose -p 8090 process list` against your controller to find names. The console talks to the loopback controller API directly, so its process does not need the process-compose CLI in `PATH`. For an outage, another process must remain running to keep older controllers alive; the console checks this before stopping anything. It stops only that named process, then starts it again; it does not kill the controller or delete database files.
+- **Current local setup:** start ext-services with its HTTP server enabled on a dedicated loopback controller port such as `8090` (router already owns `8080`): `nix run .#ext-services -- --no-server=false --port 8090`. Do not start a second database on the same data directory.
+
+Local PostgreSQL outage/restart is **not an HA failover**. Existing server-configured HA adapters remain available through `LOADTEST_FAULT_TARGETS`. Local adapters operate on the worker host; an EC2 container cannot control host processes merely by sharing a port number. Use infrastructure adapters there. Shared target settings persist in `console.sqlite` (earlier `local-fault-targets.json` files are read for compatibility); changes are rejected during an active fault or pending recovery. Target controls use fixed argv, with no free-form shell command field.
+
+GCP Kubernetes card-vault targets use a hard outage by default: capture deployment-owned pod identities and the replica count, scale to zero, then request zero-grace deletion of those captured pods. The hold timer starts only after no deployment-owned pods remain and each old pod UID is absent from its node’s kubelet runtime list. Preflight verifies `nodes/proxy` runtime-read access before interruption. Recovery restores the configured replica count (or the original count when unspecified) and waits for Ready and available replicas. The target’s Commands preview shows this sequence; it does not accept arbitrary shell commands. Existing explicit `outageMode: "graceful"` targets retain scale-only behavior. Runtime verification errors cause recovery rather than an assumed successful outage. No node pools or zones are stopped.
+
+Fault timelines: edit a scenario, choose **Timeline · Hold, Ramp, Fault**, and add a Fault stage. Configure Card vault / PostgreSQL / Redis under the editor’s collapsed **Fault targets** section; each service has one target and one operation. A local service or cloud card vault is interrupted for the configured downtime and always restored. Cloud PostgreSQL and Redis use managed failover. Fault steps maintain the preceding TPS. At the planned boundary, the load keeps offering that TPS while its active stage clock waits for the infrastructure change to be verified. The configured duration starts only after activation is verified. The clock is held again when recovery starts and the next stage begins only after recovery is verified. Starting the saved scenario authorizes its scheduled faults. The control plane uses the minimum active time reported by all load workers, snapshots target identities, executes each fault once, records activation/recovery in run activity, and restores active faults on Stop. Load workers receive no fault target, cloud command or infrastructure credential. A local PostgreSQL interruption is not an HA failover. Process-compose targets require its controller server enabled. Missed fault windows are recorded as errors and are never injected late.
+
+To test recovery without k6, save the target and click **Test interruption** (or **Test failover** for a managed database). Choose 1–300 seconds (default 5) for an interruption, enter the displayed confirmation, then start. **Restore now** ends the interruption early. The worker persists test status and activation/recovery events in `console.sqlite`; browser refresh does not stop recovery. Standalone tests require no active fixture/load job and block new generators until recovery finishes.
+
+Results reconciliation shows exact payment bars: matched is green, missing/status mismatch is red, and not-yet-compared is grey. The overview groups by elapsed load time (first recorded observation), with a red marker for every bucket containing a discrepancy, including rare errors. Zoom in for one bar per payment, ordered by observation; hover shows its actual time and click opens statuses, request attempts and nearby faults. Count filters, **Next discrepancy**, a paginated payment list and streamed filtered CSV support large runs without sending all rows to the browser. Transport failures with no payment ID remain separately unresolved, never silently counted as matches. Earlier comparisons require **Compare again** to build the index.
+
+The payment index and nine exact aggregation levels live in `reconciliation.sqlite`; batches update outcomes and aggregates in one transaction. Responses are capped at 800 bars (the UI normally requests at most 600). CSV uses bounded, backpressured pages. Run `npm run test:scale` for the synthetic ten-million-payment index/query benchmark. This measures the reconciliation view, not generator or database capacity.
+
+The Performance graph spans the configured active duration before Start and throughout execution. Grey marks time without samples; dotted markers show planned ramps/holds, fault activation, and interruption recovery start. Colored markers show actual events, with verified recovery in green. Hover or use Inspect time for target TPS, measured values, and stage/event details. Pause time does not shift scheduled stages. Managed failover completion has no predicted timestamp.
+
+Local vault recovery uses `nix develop -c cargo r` when the repository has a flake; otherwise it launches the existing `target/debug/locker` or `target/release/locker` executable from that repository. Preflight rejects targets with neither startup option. Retry recovery is asynchronous; the server verifies the listener/process identity and records launcher failures without holding the HTTP request open.
+
+Reconciliation also checks recorded transport failures (HTTP status 0). Known merchant/payment pairs are looked up in PostgreSQL in 1,000-row batches and saved in `transport_comparisons` inside `reconciliation.sqlite`. Found means present, not necessarily succeeded. Failures without a usable payment ID remain unresolved; a timeout does not prove the server rejected the request. These attempt counts are separate from payment-status totals, and matching remains an exact status comparison.
+
+### Fault environments
+
+In the scenario editor, expand **Fault targets**. Each service has one target, with **Local**, **Cloud**, or **Custom** configuration:
+
+- Local: card vault launcher or process-compose PostgreSQL/Redis.
+- Cloud: managed AlloyDB PostgreSQL failover, managed Redis HA failover, or Kubernetes card vault.
+- Custom: a Docker container or Kubernetes deployment; arbitrary shell commands are not accepted.
+
+Cloud PostgreSQL defaults to project `hyperswitch-dev`, region `asia-south1`, cluster `dev-hyperswitch-alloydb`, instance `dev-hyperswitch-alloydb-primary`. Edit these before saving if needed. **Check target** only describes the resource. **Test failover** requires typed confirmation and performs real standby promotion. AlloyDB failover is submitted asynchronously and its operation ID is saved in the fault ledger. In a scenario timeline, choose PostgreSQL → failover; the configured duration begins after GCP accepts the request and does not control the actual outage length. The next stage waits for that exact operation to finish successfully, the original HA primary to report READY, and the Settings database connection to read `payment_intent`. Recovery polls every five seconds for up to ten minutes; a failed operation, missing operation ID, or verification deadline keeps recovery blocked instead of declaring success. Restart recovery resumes polling a saved operation without submitting another failover.
+
+The control-plane host/container must have `gcloud` installed and a server-side identity authorized to describe the instance and invoke failover. Build `Dockerfile.cloud` on top of the stock console image to add `gcloud` and `kubectl`; the ordinary image remains available when infrastructure faults are disabled. Credentials stay on the control plane and are never mounted into load workers. Reload the control-plane worker service after updating its environment, only when no job or recovery is active.
+
+Cloud card vault defaults to Kubernetes namespace `hyperswitch`, deployment `hyperswitch-card-vault-hyperswitch-card-vault`. Its interruption scales to zero, waits for the configured downtime, and scales back to 8 replicas by default. Recovery replicas can be changed on the target. Leave Context empty to use the worker's current kubeconfig context, or specify a context explicitly. Existing non-empty namespace/deployment values are preserved.
+
+### Console interactions
+
+- **Scenarios:** searchable library with Archive/Restore. A new scenario explicitly copies the selected one. One sticky **Save scenario** saves the scenario version and shared fault targets atomically; stale edits are rejected. Navigation offers Save, Discard or Continue editing. Target environments retain independent Local/Cloud/Custom presets.
+- **Timeline:** drag a row or its handle across the full row width, use Alt+Up/Down or the move menu, and Undo moves. Stage times and inherited Hold TPS stay visible. Flow balancing is an explicit, undoable action.
+- **Fixtures:** compatibility explains the changed provisioning fields. Ready sets can be selected for Performance; failed or interrupted sets can be repaired. Busy states link to the active job.
+- **Performance:** one setup panel, a separate Smoke test dialog, explicit New run/Run again, worker allocation preview, disabled-action explanations, and live connection state. Selected scenario, fixture, run and graph filters survive section navigation.
+- **Faults:** target checks report inline. Test confirmation, countdown, restore and outcome stay in one dialog; closing it does not stop recovery. Faults execute on the master.
+- **Settings:** Connections, Database & TLS, Load generation, Workers and Grafana sections share save/discard protection. Imported certificates distinguish pending selection from the active saved CA. Worker onboarding includes live health; Grafana includes loading/retry and direct links.
+
+After a code upgrade, reload the detached control-plane worker while **no job or recovery is active** (`npm run worker -- stop`, then `npm run worker -- start`) as well as the web server. Restarting only Vite preserves the previous worker process by design.
+
+Server-side latency is payment-confirm p99 from the response `x-hs-latency` header (milliseconds). Router requests opt in with `x-hs-latency: true`, so this measures internal processing and excludes connector time. Missing or invalid headers remain unavailable; client-side latency is kept separately. New recordings persist the header value as `request_events.server_latency_ms`; historical runs without this measurement show no server latency.
+
+### Target flow completion
+
+Results evaluates run-wide **Flow completion** against a strict 100% target.
+Successful flows finishing during drain count toward this check. The target is
+at least the integrated load-plan budget and also includes additional offered
+flows during recovery gates and recorded drops. Failed or missing flows and
+scheduler drops cannot be hidden by shrinking the denominator. Incomplete or
+cancelled recordings cannot pass this check.
+
+Window throughput, TPS, and completion counts remain time-window measurements;
+a flow crossing a stage boundary or finishing during drain can make these differ
+slightly from the run total. They do not measure run-wide completion. Latency
+continues to use the existing settled, successful-request sample windows.
+
+### Connector load testing
+
+Scenarios have an optional **Connectors** section. Dummy (`stripe_test`) remains the default. In real/sandbox mode, select supported card connectors and give each a whole-number share; the shares must total 100%. The mix applies independently to each payment-flow stream without increasing total offered TPS. Selection is deterministic and uses a smoothed 100-entry schedule; each complete cycle has the exact requested mix. Every distributed worker uses global iteration-based selection.
+
+Create fixtures for that scenario, entering each connector's sandbox credentials and required account metadata. All selected accounts are provisioned for each merchant. Connector credentials are encrypted with AES-256-GCM under `.data/connector-secrets/`; job/fixture snapshots contain only opaque references. Keep that directory and its key private when moving the console. Connector credentials are never sent to load workers; workers receive merchant API credentials and connector account IDs as before. Partial provisioning can resume. Changing mix weights reuses fixtures; changing connector identities requires matching accounts.
+
+Real-connector card confirmations include synthetic browser information required by providers such as Adyen. `payment.browser_info` overrides these defaults. Sandbox cards can differ between providers: Adyen uses the successful non-3DS card from the repository's connector tests, while other connectors use the configured card/pool. Set `payment.connector_cards[connector]` to override a provider's card explicitly, including for negative tests. These defaults do not change dummy-mode traffic.
+
+Performance's **Connector throughput** metric shows confirmation responses identifying each connector. Results distinguish assigned flows from reported connector confirmations, successes/failures, and unreported confirmations. These are payment-level observations, not counts of provider HTTP attempts or fallback/retry calls. HS-only p99 uses `x-hs-latency`; full confirm p99 uses the complete HTTP request duration. Asynchronous/3DS completion is not automatically followed to settlement; existing payment success semantics still apply.
+
+The generated catalog comes from `crates/euclid/src/enums.rs` (`RoutableConnectors`) and sandbox auth/card definitions in `crates/connector_configs/toml/sandbox.toml`. Run `npm run generate:connectors` after upstream changes and `npm run check:connectors` to check drift (Python 3.11+). Non-card connectors and unsupported credential shapes are excluded from selectable options. The deployed router must support the chosen integration; fixture creation and smoke testing verify that environment, rather than treating enum membership as proof. Build/update the native recorder with `npm run build:recorder`; older recorders fail fast for connector-attributed runs. No application image rebuild is needed.
+
+Real-sandbox validation requires provider sandbox keys, required metadata, compatible test cards/currency in payment settings, and reachable router/PM services. The automated integration test uses a local mock router and two connector accounts per merchant; it does not contact Stripe or Adyen.
+
+### Import existing fixtures
+
+On **Fixtures**, choose **Import existing**, select a scenario, and enter one merchant
+or upload/paste a JSON array. Each entry contains `merchant_id`, `profile_id`,
+`api_key`, flow-dependent `publishable_key`, and a `connector_accounts` map from
+connector name to merchant connector-account ID. An example entry is:
+
+```json
+[{"merchant_id":"merchant_123","profile_id":"pro_123","api_key":"…","publishable_key":"…","connector_accounts":{"stripe":"mca_123"}}]
+```
+
+**Import and verify** checks merchant credentials and profile ownership, then checks
+that every selected connector account exists, is enabled, belongs to that profile,
+and supports the required card configuration. Publishable-key inspection requires
+the Router admin key in Connection settings. Failure details distinguish credential
+verification from setup verification. Import never provisions or repairs remote
+resources. Use a separate smoke test to check actual connector payment execution.
+Changes to required setup or credentials invalidate readiness; use **Verify** again.
+After changing destinations, explicitly reimport credentials for the new destination.
+
+### Scheduled custom fault commands
+
+Fault targets support **Built-in adapter** or **Custom commands · scheduled only**.
+Custom commands require `LOADTEST_ALLOW_CUSTOM_COMMANDS=true` on the supervisor;
+restart the console and its idle worker after enabling it. Configure the trigger,
+optional restore (omit for self-recovering failovers), absolute working directory,
+timeout, and read-only checks for healthy and fault-active states. Checks must exit
+0 only when their expected state is observed. Schedule the target in scenario stages.
+Commands execute through `/bin/sh` as the supervisor OS user, not in the browser or
+on load workers. Stop/cancellation still performs required recovery. Command output
+is discarded to avoid retaining secrets; failures identify the command stage and
+exit status. Do not embed credentials in commands. See [deployment guidance](DEPLOYMENT.md).
diff --git a/loadtest/console/compose.distributed.yaml b/loadtest/console/compose.distributed.yaml
new file mode 100644
index 0000000000..e591424b34
--- /dev/null
+++ b/loadtest/console/compose.distributed.yaml
@@ -0,0 +1,20 @@
+services:
+ console:
+ environment:
+ LOADTEST_WORKER_ENROLLMENT_TOKEN: ${LOADTEST_WORKER_ENROLLMENT_TOKEN:?set a worker enrollment token}
+ worker:
+ build:
+ context: ../..
+ dockerfile: loadtest/worker/Dockerfile
+ restart: unless-stopped
+ environment:
+ LOADTEST_CONTROL_PLANE_URL: http://console:4174
+ LOADTEST_WORKER_ENROLLMENT_TOKEN: ${LOADTEST_WORKER_ENROLLMENT_TOKEN:?set a worker enrollment token}
+ LOADTEST_WORKER_TPS: ${LOADTEST_WORKER_TPS:-250}
+ LOADTEST_WORKER_VUS: ${LOADTEST_WORKER_VUS:-2500}
+ depends_on:
+ - console
+ volumes:
+ - /data
+ ulimits:
+ nofile: { soft: 65536, hard: 65536 }
diff --git a/loadtest/console/compose.yaml b/loadtest/console/compose.yaml
new file mode 100644
index 0000000000..e155bab7ee
--- /dev/null
+++ b/loadtest/console/compose.yaml
@@ -0,0 +1,17 @@
+services:
+ console:
+ build:
+ context: ../..
+ dockerfile: loadtest/console/Dockerfile
+ restart: unless-stopped
+ init: false
+ env_file: .env
+ ports:
+ - "${CONSOLE_BIND_ADDRESS:-127.0.0.1}:4174:4174"
+ - "${CONSOLE_BIND_ADDRESS:-127.0.0.1}:4176:4176"
+ volumes:
+ - "${CONSOLE_DATA_PATH:-./.data}:/data"
+ stop_grace_period: 75s
+ ulimits:
+ nofile: { soft: 65536, hard: 65536 }
+ shm_size: 64m
diff --git a/loadtest/console/jsconfig.json b/loadtest/console/jsconfig.json
new file mode 100644
index 0000000000..6363871ed3
--- /dev/null
+++ b/loadtest/console/jsconfig.json
@@ -0,0 +1,9 @@
+{
+ "extends": "./.svelte-kit/tsconfig.json",
+ "compilerOptions": {
+ "allowJs": true,
+ "checkJs": true,
+ "moduleResolution": "bundler",
+ "target": "ES2022"
+ }
+}
diff --git a/loadtest/console/package-lock.json b/loadtest/console/package-lock.json
new file mode 100644
index 0000000000..e81678a389
--- /dev/null
+++ b/loadtest/console/package-lock.json
@@ -0,0 +1,1998 @@
+{
+ "name": "hyperswitch-loadtest-console",
+ "version": "0.1.0",
+ "lockfileVersion": 3,
+ "requires": true,
+ "packages": {
+ "": {
+ "name": "hyperswitch-loadtest-console",
+ "version": "0.1.0",
+ "dependencies": {
+ "@sveltejs/vite-plugin-svelte": "^6.2.1",
+ "pg": "^8.16.3",
+ "svelte": "^5.39.6",
+ "vite": "^7.1.9"
+ },
+ "devDependencies": {
+ "@opentelemetry/api": "1.9.0",
+ "@sveltejs/adapter-node": "5.5.7",
+ "@sveltejs/kit": "2.70.3",
+ "@types/node": "24.0.0",
+ "svelte-check": "^4.3.2",
+ "typescript": "^5.9.3"
+ }
+ },
+ "node_modules/@esbuild/aix-ppc64": {
+ "version": "0.28.2",
+ "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.28.2.tgz",
+ "integrity": "sha512-XExcO+dvLKvVtNTibSTBej1NCAbaGhWn9Ww1ZPx80qsahhPFe/8jgWP0IchNe0F3HwkU7n8ejhH8bjonqht8mQ==",
+ "cpu": [
+ "ppc64"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "aix"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/android-arm": {
+ "version": "0.28.2",
+ "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.28.2.tgz",
+ "integrity": "sha512-kXXoiPVVGQcnIYGOeaovwOURpniDBpSq4A03qkQ+BMQqtGG6HYap3xne9C1O1yo4TR3qxlCX5IqqmX6fFo2Lqg==",
+ "cpu": [
+ "arm"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "android"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/android-arm64": {
+ "version": "0.28.2",
+ "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.28.2.tgz",
+ "integrity": "sha512-5YfKeeI8qWfBZIX+u2xZC3Zlb3Os/gLS2sbEKM+I4ZOcsWmHS2WLysCcQZDAFRslDUU5Oiq44gf6PYN1vGwG5A==",
+ "cpu": [
+ "arm64"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "android"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/android-x64": {
+ "version": "0.28.2",
+ "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.28.2.tgz",
+ "integrity": "sha512-O387ite7SzUyCcy3JQX4P4bLtEA7bLLkx+esve5JHnyYfNTxcVpXZo9jhdB0lTKN44gztELTdU7nS8Nr16Fs1Q==",
+ "cpu": [
+ "x64"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "android"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/darwin-arm64": {
+ "version": "0.28.2",
+ "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.28.2.tgz",
+ "integrity": "sha512-n4KqkOQrraxHJcgjM1RvwbigfQKIKJVpM7xp+KsxiyUSrRdIXnt73VhrPAx0fV44hgfmIVKjxMN9J1t5jySVkw==",
+ "cpu": [
+ "arm64"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "darwin"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/darwin-x64": {
+ "version": "0.28.2",
+ "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.28.2.tgz",
+ "integrity": "sha512-uq6suIWYP37qzGddBKPw5QEQPi6HiLGsO7UmkpfyaYNQ3D+rN6w6WfwH+nuqcGXWvawGwxOEroO4YGnFh95azw==",
+ "cpu": [
+ "x64"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "darwin"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/freebsd-arm64": {
+ "version": "0.28.2",
+ "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.28.2.tgz",
+ "integrity": "sha512-n+I0BTSRIoy+d6RPKnEVwql5UwBJolytvY4mAOIEJorKlqgPII8ix6slVVrfZ5Tnj7glIZvloylbB/EJPMWEXw==",
+ "cpu": [
+ "arm64"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "freebsd"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/freebsd-x64": {
+ "version": "0.28.2",
+ "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.28.2.tgz",
+ "integrity": "sha512-78XJTJkvPs0kz2w61301PJjXl4g7q3JqiYMZ/M/yVI73EHBrCRTgkhu9oqG7vPqq+a/yadEW8aD+agKlk5xrmg==",
+ "cpu": [
+ "x64"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "freebsd"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/linux-arm": {
+ "version": "0.28.2",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.28.2.tgz",
+ "integrity": "sha512-XlDnu2q5yoqems+xay6wSAcg9DDD7K9RLKZEBOMZm3ckNpJBvOX20tSfby8KfrrhINDyv9V2YVZKY/SpoGJI8w==",
+ "cpu": [
+ "arm"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/linux-arm64": {
+ "version": "0.28.2",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.28.2.tgz",
+ "integrity": "sha512-pW4AC0P3it8c7do9MVM4p51FzHzdM/TZrerurgRcHJ2WTa1VQ1CIq18xncfpBJw4ojkiZZrKW2yIBWBP92j6Ug==",
+ "cpu": [
+ "arm64"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/linux-ia32": {
+ "version": "0.28.2",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.28.2.tgz",
+ "integrity": "sha512-CYbnj78HsIeA+DhgUKgFCfvNsTHFhMMrinUrMZpDXJXKN8T3XViTZ/+wtHeVxEWY8ewSzTFN+nRmSwO2tZaLUQ==",
+ "cpu": [
+ "ia32"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/linux-loong64": {
+ "version": "0.28.2",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.28.2.tgz",
+ "integrity": "sha512-buwkd8nsph4R+ajRvw0qM5Hja/TXQow3ptzWO2EbG/cqcIkHloRrdlBtQlshyYGTNFvfkfJ5tpPLVkY4DtsPfQ==",
+ "cpu": [
+ "loong64"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/linux-mips64el": {
+ "version": "0.28.2",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.28.2.tgz",
+ "integrity": "sha512-ZVykbDyk7519VwiNb9Lcj9m8XM6v5V9uKPvrEMkkEedVewf+0itkhahp4HDpgERXhwLRpWFypsGbG/J8s0QjJA==",
+ "cpu": [
+ "mips64el"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/linux-ppc64": {
+ "version": "0.28.2",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.28.2.tgz",
+ "integrity": "sha512-CAXl+Dtd9UUuJd8pKKdwh6MLm3MUMiqMPmhZ3tTSXPqfyQ3vDl6R5hZdZ/kYojK4ofXtdfSv1tFq8XzWx3heNQ==",
+ "cpu": [
+ "ppc64"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/linux-riscv64": {
+ "version": "0.28.2",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.28.2.tgz",
+ "integrity": "sha512-GeXCej4IQtU1B+QlDV8W/RRvbzI3O/Stss+/bCXv4lZls5WGRtu2a+3JkA3i4qIUlMXpcHebWpF8AkJhATowuA==",
+ "cpu": [
+ "riscv64"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/linux-s390x": {
+ "version": "0.28.2",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.28.2.tgz",
+ "integrity": "sha512-3H1weTYZPxt/WOhByszQZybS9w5lKzUn1FDMsgEChbHWQwHYQQRfBxgCcZvPhjHfKyJjIievvMmEUawJrdY9Dg==",
+ "cpu": [
+ "s390x"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/linux-x64": {
+ "version": "0.28.2",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.28.2.tgz",
+ "integrity": "sha512-4xTZr1FUmSoQW4XIWmit3tzQrUTZM+N3P0XV8xROKYF50XfI7xeO90+1bZvNwxIufQ9hDQVRJH5YhgPVF8A/HQ==",
+ "cpu": [
+ "x64"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/netbsd-arm64": {
+ "version": "0.28.2",
+ "resolved": "https://registry.npmjs.org/@esbuild/netbsd-arm64/-/netbsd-arm64-0.28.2.tgz",
+ "integrity": "sha512-sSATRjPeDBg3pdgHoQfoYBob11Kk1FGa9lui5RIHZCoCkJa9QKlvl3/vKz2usCmYYjs7ymJR/2Nnsqe+Hjt5nw==",
+ "cpu": [
+ "arm64"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "netbsd"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/netbsd-x64": {
+ "version": "0.28.2",
+ "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.28.2.tgz",
+ "integrity": "sha512-lqnzCV+mM0gIADaKihiCg6ifgfU2L3h5E33rNQBN1Y4MaVGnzryzmvvf7UHxprpQdE8hpqLolJ9Rl+SkIRDpyw==",
+ "cpu": [
+ "x64"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "netbsd"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/openbsd-arm64": {
+ "version": "0.28.2",
+ "resolved": "https://registry.npmjs.org/@esbuild/openbsd-arm64/-/openbsd-arm64-0.28.2.tgz",
+ "integrity": "sha512-AL2qJILH7lNjrDmCQDvdxMfAUIv8KMNZOvrwAQ8i8//ntL9FflhOyMJ8OZSMBb8/AWXe3/5v5S20y3zCoZWKoQ==",
+ "cpu": [
+ "arm64"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "openbsd"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/openbsd-x64": {
+ "version": "0.28.2",
+ "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.28.2.tgz",
+ "integrity": "sha512-QtiuPytchRyC4rwUKhexJdQKvDuZ6hWloi3igqPQNUJCS1/v9EiO3UTOXR6A3FoMo4fnAKbWJdqaIwhOzh8qEw==",
+ "cpu": [
+ "x64"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "openbsd"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/openharmony-arm64": {
+ "version": "0.28.2",
+ "resolved": "https://registry.npmjs.org/@esbuild/openharmony-arm64/-/openharmony-arm64-0.28.2.tgz",
+ "integrity": "sha512-WkhYDmpTjLvGlScA1rwjRUmhl4k8oXR3cIbtqWmELgU/dFeHHlEllxDvdWcNJV9rbzCexB5vz8gtNewWLgCT7Q==",
+ "cpu": [
+ "arm64"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "openharmony"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/sunos-x64": {
+ "version": "0.28.2",
+ "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.28.2.tgz",
+ "integrity": "sha512-GPMSkTOtMnv2U2F8gxe4Io6qmVs+YKyp832Etqqxr0hFngmXQ3rzwytelm3GIn7T4VviRUlf3sOgBOiTdvaf7g==",
+ "cpu": [
+ "x64"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "sunos"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/win32-arm64": {
+ "version": "0.28.2",
+ "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.28.2.tgz",
+ "integrity": "sha512-PIhhEkE9uPBleRBrQEJpUn7MBnibZzbGzYWPmY3x+YoVg/95zbjB4CxPPOQ8l5tYYM4mMaCthF8/1DIfBQQyWQ==",
+ "cpu": [
+ "arm64"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "win32"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/win32-ia32": {
+ "version": "0.28.2",
+ "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.28.2.tgz",
+ "integrity": "sha512-YmJbfTlvU7Sdn9BB+4PRES4oB6pxgS37MAONj+hBr/cpXS1aBPKXxNnDbu+QCWPj0o9dgyxeq79g6c5P8KeuYA==",
+ "cpu": [
+ "ia32"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "win32"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/win32-x64": {
+ "version": "0.28.2",
+ "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.28.2.tgz",
+ "integrity": "sha512-5ebpxr3nWMzrL/rnUI755Jkuee0bHL/Gq0WTF9lvcpv73wAp5eu8MfBUgWK9bhWvZjj7yX8etf/8tI8Ney695g==",
+ "cpu": [
+ "x64"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "win32"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@jridgewell/gen-mapping": {
+ "version": "0.3.13",
+ "resolved": "https://registry.npmjs.org/@jridgewell/gen-mapping/-/gen-mapping-0.3.13.tgz",
+ "integrity": "sha512-2kkt/7niJ6MgEPxF0bYdQ6etZaA+fQvDcLKckhy1yIQOzaoKjBBjSj63/aLVjYE3qhRt5dvM+uUyfCg6UKCBbA==",
+ "license": "MIT",
+ "dependencies": {
+ "@jridgewell/sourcemap-codec": "^1.5.0",
+ "@jridgewell/trace-mapping": "^0.3.24"
+ }
+ },
+ "node_modules/@jridgewell/remapping": {
+ "version": "2.3.5",
+ "resolved": "https://registry.npmjs.org/@jridgewell/remapping/-/remapping-2.3.5.tgz",
+ "integrity": "sha512-LI9u/+laYG4Ds1TDKSJW2YPrIlcVYOwi2fUC6xB43lueCjgxV4lffOCZCtYFiH6TNOX+tQKXx97T4IKHbhyHEQ==",
+ "license": "MIT",
+ "dependencies": {
+ "@jridgewell/gen-mapping": "^0.3.5",
+ "@jridgewell/trace-mapping": "^0.3.24"
+ }
+ },
+ "node_modules/@jridgewell/resolve-uri": {
+ "version": "3.1.2",
+ "resolved": "https://registry.npmjs.org/@jridgewell/resolve-uri/-/resolve-uri-3.1.2.tgz",
+ "integrity": "sha512-bRISgCIjP20/tbWSPWMEi54QVPRZExkuD9lJL+UIxUKtwVJA8wW1Trb1jMs1RFXo1CBTNZ/5hpC9QvmKWdopKw==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=6.0.0"
+ }
+ },
+ "node_modules/@jridgewell/sourcemap-codec": {
+ "version": "1.6.0",
+ "resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.6.0.tgz",
+ "integrity": "sha512-T7jf+5zgsZHwNJ4lvQ7/aezbyk0nNX+zJVWpmHA7VYsEx7a7qr5Rg5IbtJFqkgze5Y2sruq1RUY8Q837Od7iFw==",
+ "license": "MIT"
+ },
+ "node_modules/@jridgewell/trace-mapping": {
+ "version": "0.3.31",
+ "resolved": "https://registry.npmjs.org/@jridgewell/trace-mapping/-/trace-mapping-0.3.31.tgz",
+ "integrity": "sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw==",
+ "license": "MIT",
+ "dependencies": {
+ "@jridgewell/resolve-uri": "^3.1.0",
+ "@jridgewell/sourcemap-codec": "^1.4.14"
+ }
+ },
+ "node_modules/@napi-rs/lzma-linux-x64-gnu": {
+ "version": "1.5.1",
+ "resolved": "https://registry.npmjs.org/@napi-rs/lzma-linux-x64-gnu/-/lzma-linux-x64-gnu-1.5.1.tgz",
+ "integrity": "sha512-oTXEIha4SsuXdTA4Iyskj0kpdx2yVXdhd75c2v3xGrHFfVMsbhTPZU/nMPL4sWKo4pBHm3aucLaqGlF696dTyQ==",
+ "cpu": [
+ "x64"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": "^22.20 || ^24.12 || >=25"
+ }
+ },
+ "node_modules/@opentelemetry/api": {
+ "version": "1.9.0",
+ "resolved": "https://registry.npmjs.org/@opentelemetry/api/-/api-1.9.0.tgz",
+ "integrity": "sha512-3giAOQvZiH5F9bMlMiv8+GSPMeqg0dbaeo58/0SlA9sxSqZhnUtxzX9/2FzyhS9sWQf5S0GJE0AKBrFqjpeYcg==",
+ "dev": true,
+ "license": "Apache-2.0",
+ "peer": true,
+ "engines": {
+ "node": ">=8.0.0"
+ }
+ },
+ "node_modules/@polka/url": {
+ "version": "1.0.0-next.29",
+ "resolved": "https://registry.npmjs.org/@polka/url/-/url-1.0.0-next.29.tgz",
+ "integrity": "sha512-wwQAWhWSuHaag8c4q/KN/vCoeOJYshAIvMQwD4GpSb3OiZklFfvAgmj0VCBBImRpuF/aFgIRzllXlVX93Jevww==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/@rollup/plugin-commonjs": {
+ "version": "29.0.3",
+ "resolved": "https://registry.npmjs.org/@rollup/plugin-commonjs/-/plugin-commonjs-29.0.3.tgz",
+ "integrity": "sha512-ZaOxZceP7SOUW7Lqw5IRVweSQYWaeIPnXIGLiB690EBA3FGJTO40EEr2L5yZplJWsgTCogILRSpcAe7+U0Otdg==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@rollup/pluginutils": "^5.0.1",
+ "commondir": "^1.0.1",
+ "estree-walker": "^2.0.2",
+ "fdir": "^6.2.0",
+ "is-reference": "1.2.1",
+ "magic-string": "^0.30.3",
+ "picomatch": "^4.0.2"
+ },
+ "engines": {
+ "node": ">=16.0.0 || 14 >= 14.17"
+ },
+ "peerDependencies": {
+ "rollup": "^2.68.0||^3.0.0||^4.0.0"
+ },
+ "peerDependenciesMeta": {
+ "rollup": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/@rollup/plugin-commonjs/node_modules/is-reference": {
+ "version": "1.2.1",
+ "resolved": "https://registry.npmjs.org/is-reference/-/is-reference-1.2.1.tgz",
+ "integrity": "sha512-U82MsXXiFIrjCK4otLT+o2NA2Cd2g5MLoOVXUZjIOhLurrRxpEXzI8O0KZHr3IjLvlAH1kTPYSuqer5T9ZVBKQ==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@types/estree": "*"
+ }
+ },
+ "node_modules/@rollup/plugin-json": {
+ "version": "6.1.0",
+ "resolved": "https://registry.npmjs.org/@rollup/plugin-json/-/plugin-json-6.1.0.tgz",
+ "integrity": "sha512-EGI2te5ENk1coGeADSIwZ7G2Q8CJS2sF120T7jLw4xFw9n7wIOXHo+kIYRAoVpJAN+kmqZSoO3Fp4JtoNF4ReA==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@rollup/pluginutils": "^5.1.0"
+ },
+ "engines": {
+ "node": ">=14.0.0"
+ },
+ "peerDependencies": {
+ "rollup": "^1.20.0||^2.0.0||^3.0.0||^4.0.0"
+ },
+ "peerDependenciesMeta": {
+ "rollup": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/@rollup/plugin-node-resolve": {
+ "version": "16.0.3",
+ "resolved": "https://registry.npmjs.org/@rollup/plugin-node-resolve/-/plugin-node-resolve-16.0.3.tgz",
+ "integrity": "sha512-lUYM3UBGuM93CnMPG1YocWu7X802BrNF3jW2zny5gQyLQgRFJhV1Sq0Zi74+dh/6NBx1DxFC4b4GXg9wUCG5Qg==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@rollup/pluginutils": "^5.0.1",
+ "@types/resolve": "1.20.2",
+ "deepmerge": "^4.2.2",
+ "is-module": "^1.0.0",
+ "resolve": "^1.22.1"
+ },
+ "engines": {
+ "node": ">=14.0.0"
+ },
+ "peerDependencies": {
+ "rollup": "^2.78.0||^3.0.0||^4.0.0"
+ },
+ "peerDependenciesMeta": {
+ "rollup": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/@rollup/plugin-replace": {
+ "version": "6.0.3",
+ "resolved": "https://registry.npmjs.org/@rollup/plugin-replace/-/plugin-replace-6.0.3.tgz",
+ "integrity": "sha512-J4RZarRvQAm5IF0/LwUUg+obsm+xZhYnbMXmXROyoSE1ATJe3oXSb9L5MMppdxP2ylNSjv6zFBwKYjcKMucVfA==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@rollup/pluginutils": "^5.0.1",
+ "magic-string": "^0.30.3"
+ },
+ "engines": {
+ "node": ">=14.0.0"
+ },
+ "peerDependencies": {
+ "rollup": "^1.20.0||^2.0.0||^3.0.0||^4.0.0"
+ },
+ "peerDependenciesMeta": {
+ "rollup": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/@rollup/pluginutils": {
+ "version": "5.4.0",
+ "resolved": "https://registry.npmjs.org/@rollup/pluginutils/-/pluginutils-5.4.0.tgz",
+ "integrity": "sha512-MfPp06CjRLfXQ3wY0R8vJDYBy/MvVcc9OulEfR0B8Iv9ko+GCNaRZ+EpJYFl27LhKsZK0o420sYCRHCjfCgeUg==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@types/estree": "^1.0.0",
+ "estree-walker": "^2.0.2",
+ "picomatch": "^4.0.2"
+ },
+ "engines": {
+ "node": ">=14.0.0"
+ },
+ "peerDependencies": {
+ "rollup": "^1.20.0||^2.0.0||^3.0.0||^4.0.0"
+ },
+ "peerDependenciesMeta": {
+ "rollup": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/@rollup/rollup-android-arm-eabi": {
+ "version": "4.64.0",
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm-eabi/-/rollup-android-arm-eabi-4.64.0.tgz",
+ "integrity": "sha512-FLLpX941CD/7aBvX3GqLGBM9OvY5PGXTryPJkG5r5/OuBpZpV5k45Uo3RxAvqd35tsyc3hH1bhtz921IKzoIzg==",
+ "cpu": [
+ "arm"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "android"
+ ]
+ },
+ "node_modules/@rollup/rollup-android-arm64": {
+ "version": "4.64.0",
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm64/-/rollup-android-arm64-4.64.0.tgz",
+ "integrity": "sha512-iI32XM/jnDYJsvx5ai/za/7gWO9XoSeFFtU06/ZCaRgyilfJOjaopD3nOpk2WrTCGOyeDt4hleUiGOAnd5tHNg==",
+ "cpu": [
+ "arm64"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "android"
+ ]
+ },
+ "node_modules/@rollup/rollup-darwin-arm64": {
+ "version": "4.64.0",
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-darwin-arm64/-/rollup-darwin-arm64-4.64.0.tgz",
+ "integrity": "sha512-dRBZlbt2sEtF8Mn4MODThze9fIPdDoOhVSlXMAKy5dQbOYK9pOOoPY4Fat3OTtr0+8zbJo5TTZwlsfxY/kDNJg==",
+ "cpu": [
+ "arm64"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "darwin"
+ ]
+ },
+ "node_modules/@rollup/rollup-darwin-x64": {
+ "version": "4.64.0",
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-darwin-x64/-/rollup-darwin-x64-4.64.0.tgz",
+ "integrity": "sha512-Y3whrJOMucfkhgNkvcM93M6j8C53iEAMmPMYD99C6G1kUy4ELigLWk9ar2/4aCBSRgsql0zdlOemLgW2m5GZgQ==",
+ "cpu": [
+ "x64"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "darwin"
+ ]
+ },
+ "node_modules/@rollup/rollup-freebsd-arm64": {
+ "version": "4.64.0",
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-freebsd-arm64/-/rollup-freebsd-arm64-4.64.0.tgz",
+ "integrity": "sha512-S6S1GEzPjFF6IONYJX3AKt/799+8RgBgCcwRnUo+Ep1IvBxUbw5M51iU0TDdK2NWWVnSvCQ8yi6Em0fGASMOng==",
+ "cpu": [
+ "arm64"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "freebsd"
+ ]
+ },
+ "node_modules/@rollup/rollup-freebsd-x64": {
+ "version": "4.64.0",
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-freebsd-x64/-/rollup-freebsd-x64-4.64.0.tgz",
+ "integrity": "sha512-Ed1DPoFENkXj4IGzSB12SesV40iP6LxCCrbTIkSGIQBpOOxpBM+0kj62lmaeIHfMWTDoddqTOtqc7s8LYfn+Pw==",
+ "cpu": [
+ "x64"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "freebsd"
+ ]
+ },
+ "node_modules/@rollup/rollup-linux-arm-gnueabihf": {
+ "version": "4.64.0",
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm-gnueabihf/-/rollup-linux-arm-gnueabihf-4.64.0.tgz",
+ "integrity": "sha512-J/6xhutJPtFyIkmHdf4olOdHHKH5kOJNumojdWn+Elv5ICEYTVOa362Vw27TxsK0BLzb1le3EDlO3UbvFK1lnQ==",
+ "cpu": [
+ "arm"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ]
+ },
+ "node_modules/@rollup/rollup-linux-arm-musleabihf": {
+ "version": "4.64.0",
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm-musleabihf/-/rollup-linux-arm-musleabihf-4.64.0.tgz",
+ "integrity": "sha512-G4L/Nnx59d2LvDoV/P4S5lZ7oVLT6hodOHMacqjiq2LL2gts86KbkEBTYL53+fBt0odhf7XPIbIATGoYiJctxg==",
+ "cpu": [
+ "arm"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ]
+ },
+ "node_modules/@rollup/rollup-linux-arm64-gnu": {
+ "version": "4.64.0",
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm64-gnu/-/rollup-linux-arm64-gnu-4.64.0.tgz",
+ "integrity": "sha512-zF16pvJDEUksGYRbfnXne7pdklAyj2XDmJeYKgP93oq0cUyX9Y8O7lUo1R+IY1GagP/YBvCEDCe7eEcAKpw//g==",
+ "cpu": [
+ "arm64"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ]
+ },
+ "node_modules/@rollup/rollup-linux-arm64-musl": {
+ "version": "4.64.0",
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm64-musl/-/rollup-linux-arm64-musl-4.64.0.tgz",
+ "integrity": "sha512-nIggWn8n+w12+R5lsV+PYYoUY8vuObxPAQqJI7WES+9v0qspYuAHoZMfYM0yLxlipasT5BY9ht5W8t5c/rSCkg==",
+ "cpu": [
+ "arm64"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ]
+ },
+ "node_modules/@rollup/rollup-linux-loong64-gnu": {
+ "version": "4.64.0",
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-loong64-gnu/-/rollup-linux-loong64-gnu-4.64.0.tgz",
+ "integrity": "sha512-WLOTiHPzszP0dxIMsHpFeDSOSB5I49Mj8K4+yKE3H1X/D0JRG5XZ5jrctJLMjnUc/LUzaKiwq6EHWNJ8pup8PA==",
+ "cpu": [
+ "loong64"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ]
+ },
+ "node_modules/@rollup/rollup-linux-loong64-musl": {
+ "version": "4.64.0",
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-loong64-musl/-/rollup-linux-loong64-musl-4.64.0.tgz",
+ "integrity": "sha512-35RK9aRhh7g7Pmeu5gQ01aCvrhXzj9LoBE6xtUcEH1ns+nyTaSzxSpADmBQINu4QiTDGvmQYwo1j5hlg1rRXFw==",
+ "cpu": [
+ "loong64"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ]
+ },
+ "node_modules/@rollup/rollup-linux-ppc64-gnu": {
+ "version": "4.64.0",
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-ppc64-gnu/-/rollup-linux-ppc64-gnu-4.64.0.tgz",
+ "integrity": "sha512-RqTfnpoTjuWfPAmqK5p2edt2AMCDJWm6oTn7sKfmyx+6tRga0ip05SJ977o6udTcIiDeF/CJMUfkaN4gtWt6Aw==",
+ "cpu": [
+ "ppc64"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ]
+ },
+ "node_modules/@rollup/rollup-linux-ppc64-musl": {
+ "version": "4.64.0",
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-ppc64-musl/-/rollup-linux-ppc64-musl-4.64.0.tgz",
+ "integrity": "sha512-RQjZPigjxFvFZDijG6rjlSXxhRaTf9zLYVpGK+lVcga64oMqP1GbgVqCb46eHTTceSIgp89Ja0y5aPe3GFBYHg==",
+ "cpu": [
+ "ppc64"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ]
+ },
+ "node_modules/@rollup/rollup-linux-riscv64-gnu": {
+ "version": "4.64.0",
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-riscv64-gnu/-/rollup-linux-riscv64-gnu-4.64.0.tgz",
+ "integrity": "sha512-tjL58mgQcTRnDRpeky+Sth1MKQeYi2Ct6r3Luq9E5aTSjnM/i/JbozqZkKqp9thM5+oDSZxo+05f9kdQedfTGA==",
+ "cpu": [
+ "riscv64"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ]
+ },
+ "node_modules/@rollup/rollup-linux-riscv64-musl": {
+ "version": "4.64.0",
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-riscv64-musl/-/rollup-linux-riscv64-musl-4.64.0.tgz",
+ "integrity": "sha512-ictoRyVaoZ8C67myHef+8hhCa6IplXJJ/xUCkVCxziV4zxMZh+jvhkhGsPBLqj1S72fnqD0QH5zL4lcaa4X7DQ==",
+ "cpu": [
+ "riscv64"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ]
+ },
+ "node_modules/@rollup/rollup-linux-s390x-gnu": {
+ "version": "4.64.0",
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-s390x-gnu/-/rollup-linux-s390x-gnu-4.64.0.tgz",
+ "integrity": "sha512-8aVvZ2hfr9RLFzBQkQNmYeHLDja8fLeQAmLt757zdKN/B+8L809KlLJKctQjS22wZotptV8G6o7fVPuAs8S1tQ==",
+ "cpu": [
+ "s390x"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ]
+ },
+ "node_modules/@rollup/rollup-linux-x64-gnu": {
+ "version": "4.64.0",
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-gnu/-/rollup-linux-x64-gnu-4.64.0.tgz",
+ "integrity": "sha512-2dEF8GAcDKwshUfydD+GhosppNyBzhVUHkdFF3CXd3FpOkzj/RZzF5aoEtzklujklT5qFVRU2GK/cFeLaTNKVg==",
+ "cpu": [
+ "x64"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ]
+ },
+ "node_modules/@rollup/rollup-linux-x64-musl": {
+ "version": "4.64.0",
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-musl/-/rollup-linux-x64-musl-4.64.0.tgz",
+ "integrity": "sha512-3XHTvoo2hKkh0MiOfS7SkhHjMaaWF7P4F3drocZZaho/Z8w7h/jpnuBHm91BOQLfvrKHs1yR+zir4E8RI3XzTQ==",
+ "cpu": [
+ "x64"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ]
+ },
+ "node_modules/@rollup/rollup-openbsd-x64": {
+ "version": "4.64.0",
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-openbsd-x64/-/rollup-openbsd-x64-4.64.0.tgz",
+ "integrity": "sha512-HKtkzodL4a3KFWDXDoO61cRynAWTR3LnAE0oGtfG9lcNFpNuVYUFOByxDgNqEvic9rvaQbAj+SFwTEWDptRaIw==",
+ "cpu": [
+ "x64"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "openbsd"
+ ]
+ },
+ "node_modules/@rollup/rollup-openharmony-arm64": {
+ "version": "4.64.0",
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-openharmony-arm64/-/rollup-openharmony-arm64-4.64.0.tgz",
+ "integrity": "sha512-JBsxqiY16uyyCujtoC3s7zL+SrYyNElptD7K4V+KUoJ2V8/XG3hPWpheK+SuPwNh1cikJvIZmIdsrYXvD6PLJw==",
+ "cpu": [
+ "arm64"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "openharmony"
+ ]
+ },
+ "node_modules/@rollup/rollup-win32-arm64-msvc": {
+ "version": "4.64.0",
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-arm64-msvc/-/rollup-win32-arm64-msvc-4.64.0.tgz",
+ "integrity": "sha512-S5Qrijh37qhnUYQ0ay8WN3LuWeKjow7wTUyCOPMZtnXiBXYXdsZETI6ZLfYnQAKovltckPLBFdNeD61P2rJc7g==",
+ "cpu": [
+ "arm64"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "win32"
+ ]
+ },
+ "node_modules/@rollup/rollup-win32-ia32-msvc": {
+ "version": "4.64.0",
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-ia32-msvc/-/rollup-win32-ia32-msvc-4.64.0.tgz",
+ "integrity": "sha512-zbZ6iMmLFEsCtTdc2/y1F/cDFVNNCPF7Ae8PCT/wdPE//hGwYp6r+MyCLMFX+kOeIe09Pz6ASfnnfpSTN1FJQQ==",
+ "cpu": [
+ "ia32"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "win32"
+ ]
+ },
+ "node_modules/@rollup/rollup-win32-x64-gnu": {
+ "version": "4.64.0",
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-x64-gnu/-/rollup-win32-x64-gnu-4.64.0.tgz",
+ "integrity": "sha512-L6Hw69oNpuYaOr1zCG30v0/DqKYCSRwodPGwIcVZ/6f8SOzq9rxtL/xNVI5MO4wjli+Ko0ErK9uHJL3mNPt8wQ==",
+ "cpu": [
+ "x64"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "win32"
+ ]
+ },
+ "node_modules/@rollup/rollup-win32-x64-msvc": {
+ "version": "4.64.0",
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-x64-msvc/-/rollup-win32-x64-msvc-4.64.0.tgz",
+ "integrity": "sha512-nl+CTWIgOGszQmUz/kanfgrfFZ4qiwxKIfT/ryl3N3Ewk5tqizmYtNXiqb7Bu/fDtNgu1kyxdFiAUJNur3iysg==",
+ "cpu": [
+ "x64"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "win32"
+ ]
+ },
+ "node_modules/@standard-schema/spec": {
+ "version": "1.1.0",
+ "resolved": "https://registry.npmjs.org/@standard-schema/spec/-/spec-1.1.0.tgz",
+ "integrity": "sha512-l2aFy5jALhniG5HgqrD6jXLi/rUWrKvqN/qJx6yoJsgKhblVd+iqqU4RCXavm/jPityDo5TCvKMnpjKnOriy0w==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/@sveltejs/acorn-typescript": {
+ "version": "1.0.13",
+ "resolved": "https://registry.npmjs.org/@sveltejs/acorn-typescript/-/acorn-typescript-1.0.13.tgz",
+ "integrity": "sha512-wgKggnhZVL9Bfx1OaKKTrYY9BFRk6C8UAkQNUcIv1+llzYrIqy+RZm5HPKzn0NpEBvTVhTqB4kQyllZywsRBRQ==",
+ "license": "MIT",
+ "peerDependencies": {
+ "acorn": "^8.9.0"
+ }
+ },
+ "node_modules/@sveltejs/adapter-node": {
+ "version": "5.5.7",
+ "resolved": "https://registry.npmjs.org/@sveltejs/adapter-node/-/adapter-node-5.5.7.tgz",
+ "integrity": "sha512-uOfc9eVlI3A37RRSaKcgrheBYPrfJwC9VMqDp8x/O6tlKdcLLvHThSWD0KNIbjQ/d+7bwLGx3vx6aowAcRfd2g==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@rollup/plugin-commonjs": "^29.0.0",
+ "@rollup/plugin-json": "^6.1.0",
+ "@rollup/plugin-node-resolve": "^16.0.0",
+ "@rollup/plugin-replace": "^6.0.3",
+ "rollup": "^4.59.0"
+ },
+ "peerDependencies": {
+ "@sveltejs/kit": "^2.4.0"
+ }
+ },
+ "node_modules/@sveltejs/kit": {
+ "version": "2.70.3",
+ "resolved": "https://registry.npmjs.org/@sveltejs/kit/-/kit-2.70.3.tgz",
+ "integrity": "sha512-UDvEYuZqAMbfB/oXIoqKvbKcb7YczK5zYrzmsGV1zRJk03jntwp8dXiYoIJotxAndsKvcPFtx9H1GRSKFdSHgg==",
+ "dev": true,
+ "license": "MIT",
+ "peer": true,
+ "dependencies": {
+ "@standard-schema/spec": "^1.0.0",
+ "@sveltejs/acorn-typescript": "^1.0.9",
+ "@types/cookie": "^0.6.0",
+ "acorn": "^8.16.0",
+ "cookie": "^0.6.0",
+ "devalue": "^5.8.1",
+ "esm-env": "^1.2.2",
+ "kleur": "^4.1.5",
+ "magic-string": "^0.30.5",
+ "mrmime": "^2.0.0",
+ "set-cookie-parser": "^3.0.0",
+ "sirv": "^3.0.0"
+ },
+ "bin": {
+ "svelte-kit": "svelte-kit.js"
+ },
+ "engines": {
+ "node": ">=18.13"
+ },
+ "peerDependencies": {
+ "@opentelemetry/api": "^1.0.0",
+ "@sveltejs/vite-plugin-svelte": "^3.0.0 || ^4.0.0-next.1 || ^5.0.0 || ^6.0.0-next.0 || ^7.0.0",
+ "svelte": "^4.0.0 || ^5.0.0-next.0",
+ "typescript": "^5.3.3 || ^6.0.0",
+ "vite": "^5.0.3 || ^6.0.0 || ^7.0.0-beta.0 || ^8.0.0"
+ },
+ "peerDependenciesMeta": {
+ "@opentelemetry/api": {
+ "optional": true
+ },
+ "typescript": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/@sveltejs/load-config": {
+ "version": "0.2.3",
+ "resolved": "https://registry.npmjs.org/@sveltejs/load-config/-/load-config-0.2.3.tgz",
+ "integrity": "sha512-VT3qmUb8pRV2QrZjd8iAmtg8lf4W0TIjZbvXtz5MKei/q96teWZgGJyyidJzOjzZzvdq616eSRVeMYIQChUTAQ==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">= 18.0.0"
+ }
+ },
+ "node_modules/@sveltejs/vite-plugin-svelte": {
+ "version": "6.2.4",
+ "resolved": "https://registry.npmjs.org/@sveltejs/vite-plugin-svelte/-/vite-plugin-svelte-6.2.4.tgz",
+ "integrity": "sha512-ou/d51QSdTyN26D7h6dSpusAKaZkAiGM55/AKYi+9AGZw7q85hElbjK3kEyzXHhLSnRISHOYzVge6x0jRZ7DXA==",
+ "license": "MIT",
+ "peer": true,
+ "dependencies": {
+ "@sveltejs/vite-plugin-svelte-inspector": "^5.0.0",
+ "deepmerge": "^4.3.1",
+ "magic-string": "^0.30.21",
+ "obug": "^2.1.0",
+ "vitefu": "^1.1.1"
+ },
+ "engines": {
+ "node": "^20.19 || ^22.12 || >=24"
+ },
+ "peerDependencies": {
+ "svelte": "^5.0.0",
+ "vite": "^6.3.0 || ^7.0.0"
+ }
+ },
+ "node_modules/@sveltejs/vite-plugin-svelte-inspector": {
+ "version": "5.0.2",
+ "resolved": "https://registry.npmjs.org/@sveltejs/vite-plugin-svelte-inspector/-/vite-plugin-svelte-inspector-5.0.2.tgz",
+ "integrity": "sha512-TZzRTcEtZffICSAoZGkPSl6Etsj2torOVrx6Uw0KpXxrec9Gg6jFWQ60Q3+LmNGfZSxHRCZL7vXVZIWmuV50Ig==",
+ "license": "MIT",
+ "dependencies": {
+ "obug": "^2.1.0"
+ },
+ "engines": {
+ "node": "^20.19 || ^22.12 || >=24"
+ },
+ "peerDependencies": {
+ "@sveltejs/vite-plugin-svelte": "^6.0.0-next.0",
+ "svelte": "^5.0.0",
+ "vite": "^6.3.0 || ^7.0.0"
+ }
+ },
+ "node_modules/@types/cookie": {
+ "version": "0.6.0",
+ "resolved": "https://registry.npmjs.org/@types/cookie/-/cookie-0.6.0.tgz",
+ "integrity": "sha512-4Kh9a6B2bQciAhf7FSuMRRkUWecJgJu9nPnx3yzpsfXX/c50REIqpHY4C82bXP90qrLtXtkDxTZosYO3UpOwlA==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/@types/estree": {
+ "version": "1.0.9",
+ "resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.9.tgz",
+ "integrity": "sha512-GhdPgy1el4/ImP05X05Uw4cw2/M93BCUmnEvWZNStlCzEKME4Fkk+YpoA5OiHNQmoS7Cafb8Xa3Pya8m1Qrzeg==",
+ "license": "MIT"
+ },
+ "node_modules/@types/node": {
+ "version": "24.0.0",
+ "resolved": "https://registry.npmjs.org/@types/node/-/node-24.0.0.tgz",
+ "integrity": "sha512-yZQa2zm87aRVcqDyH5+4Hv9KYgSdgwX1rFnGvpbzMaC7YAljmhBET93TPiTd3ObwTL+gSpIzPKg5BqVxdCvxKg==",
+ "devOptional": true,
+ "license": "MIT",
+ "peer": true,
+ "dependencies": {
+ "undici-types": "~7.8.0"
+ }
+ },
+ "node_modules/@types/resolve": {
+ "version": "1.20.2",
+ "resolved": "https://registry.npmjs.org/@types/resolve/-/resolve-1.20.2.tgz",
+ "integrity": "sha512-60BCwRFOZCQhDncwQdxxeOEEkbc5dIMccYLwbxsS4TUNeVECQ/pBJ0j09mrHOl/JJvpRPGwO9SvE4nR2Nb/a4Q==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/acorn": {
+ "version": "8.19.0",
+ "resolved": "https://registry.npmjs.org/acorn/-/acorn-8.19.0.tgz",
+ "integrity": "sha512-oJlA3XiRm7Cyk6qFD2Jn8ak9B7jSy0qy00ADO3+8dpT0LSjFihQYv4C02LFCSYJV3Q37xYwwRy5m+IpIiUzqWw==",
+ "license": "MIT",
+ "peer": true,
+ "bin": {
+ "acorn": "bin/acorn"
+ },
+ "engines": {
+ "node": ">=0.4.0"
+ }
+ },
+ "node_modules/aria-query": {
+ "version": "5.3.1",
+ "resolved": "https://registry.npmjs.org/aria-query/-/aria-query-5.3.1.tgz",
+ "integrity": "sha512-Z/ZeOgVl7bcSYZ/u/rh0fOpvEpq//LZmdbkXyc7syVzjPAhfOa9ebsdTSjEBDU4vs5nC98Kfduj1uFo0qyET3g==",
+ "license": "Apache-2.0",
+ "engines": {
+ "node": ">= 0.4"
+ }
+ },
+ "node_modules/axobject-query": {
+ "version": "4.1.0",
+ "resolved": "https://registry.npmjs.org/axobject-query/-/axobject-query-4.1.0.tgz",
+ "integrity": "sha512-qIj0G9wZbMGNLjLmg1PT6v2mE9AH2zlnADJD/2tC6E00hgmhUOfEB6greHPAfLRSufHqROIUTkw6E+M3lH0PTQ==",
+ "license": "Apache-2.0",
+ "engines": {
+ "node": ">= 0.4"
+ }
+ },
+ "node_modules/chokidar": {
+ "version": "4.0.3",
+ "resolved": "https://registry.npmjs.org/chokidar/-/chokidar-4.0.3.tgz",
+ "integrity": "sha512-Qgzu8kfBvo+cA4962jnP1KkS6Dop5NS6g7R5LFYJr4b8Ub94PPQXUksCw9PvXoeXPRRddRNC5C1JQUR2SMGtnA==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "readdirp": "^4.0.1"
+ },
+ "engines": {
+ "node": ">= 14.16.0"
+ },
+ "funding": {
+ "url": "https://paulmillr.com/funding/"
+ }
+ },
+ "node_modules/clsx": {
+ "version": "2.1.1",
+ "resolved": "https://registry.npmjs.org/clsx/-/clsx-2.1.1.tgz",
+ "integrity": "sha512-eYm0QWBtUrBWZWG0d386OGAw16Z995PiOVo2B7bjWSbHedGl5e0ZWaq65kOGgUSNesEIDkB9ISbTg/JK9dhCZA==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=6"
+ }
+ },
+ "node_modules/commondir": {
+ "version": "1.0.1",
+ "resolved": "https://registry.npmjs.org/commondir/-/commondir-1.0.1.tgz",
+ "integrity": "sha512-W9pAhw0ja1Edb5GVdIF1mjZw/ASI0AlShXM83UUGe2DVr5TdAPEA1OA8m/g8zWp9x6On7gqufY+FatDbC3MDQg==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/cookie": {
+ "version": "0.7.2",
+ "resolved": "https://registry.npmjs.org/cookie/-/cookie-0.7.2.tgz",
+ "integrity": "sha512-yki5XnKuf750l50uGTllt6kKILY4nQ1eNIQatoXEByZ5dWgnKqbnqmTrBE5B4N7lrMJKQ2ytWMiTO2o0v6Ew/w==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">= 0.6"
+ }
+ },
+ "node_modules/deepmerge": {
+ "version": "4.3.1",
+ "resolved": "https://registry.npmjs.org/deepmerge/-/deepmerge-4.3.1.tgz",
+ "integrity": "sha512-3sUqbMEc77XqpdNO7FRyRog+eW3ph+GYCbj+rK+uYyRMuwsVy0rMiVtPn+QJlKFvWP/1PYpapqYn0Me2knFn+A==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=0.10.0"
+ }
+ },
+ "node_modules/devalue": {
+ "version": "5.9.4",
+ "resolved": "https://registry.npmjs.org/devalue/-/devalue-5.9.4.tgz",
+ "integrity": "sha512-sPAT4pztbu6586/hrhOnMKS17IJrvg12mXiSPSS3W5qDeN2RGgvZ0diZCm31dBbnevfVmujNO3IM2wrS4Y2Rhg==",
+ "license": "MIT"
+ },
+ "node_modules/es-errors": {
+ "version": "1.3.0",
+ "resolved": "https://registry.npmjs.org/es-errors/-/es-errors-1.3.0.tgz",
+ "integrity": "sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">= 0.4"
+ }
+ },
+ "node_modules/esbuild": {
+ "version": "0.28.2",
+ "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.28.2.tgz",
+ "integrity": "sha512-HKVLS8dvII+xoKW9kmqxbRKrnWEXfJJr/FZhhJmiqIB0e053QNYFqOBouTMO/k5sID4MvCiUCvv8b9M4h32wIA==",
+ "hasInstallScript": true,
+ "license": "MIT",
+ "bin": {
+ "esbuild": "bin/esbuild"
+ },
+ "engines": {
+ "node": ">=18"
+ },
+ "optionalDependencies": {
+ "@esbuild/aix-ppc64": "0.28.2",
+ "@esbuild/android-arm": "0.28.2",
+ "@esbuild/android-arm64": "0.28.2",
+ "@esbuild/android-x64": "0.28.2",
+ "@esbuild/darwin-arm64": "0.28.2",
+ "@esbuild/darwin-x64": "0.28.2",
+ "@esbuild/freebsd-arm64": "0.28.2",
+ "@esbuild/freebsd-x64": "0.28.2",
+ "@esbuild/linux-arm": "0.28.2",
+ "@esbuild/linux-arm64": "0.28.2",
+ "@esbuild/linux-ia32": "0.28.2",
+ "@esbuild/linux-loong64": "0.28.2",
+ "@esbuild/linux-mips64el": "0.28.2",
+ "@esbuild/linux-ppc64": "0.28.2",
+ "@esbuild/linux-riscv64": "0.28.2",
+ "@esbuild/linux-s390x": "0.28.2",
+ "@esbuild/linux-x64": "0.28.2",
+ "@esbuild/netbsd-arm64": "0.28.2",
+ "@esbuild/netbsd-x64": "0.28.2",
+ "@esbuild/openbsd-arm64": "0.28.2",
+ "@esbuild/openbsd-x64": "0.28.2",
+ "@esbuild/openharmony-arm64": "0.28.2",
+ "@esbuild/sunos-x64": "0.28.2",
+ "@esbuild/win32-arm64": "0.28.2",
+ "@esbuild/win32-ia32": "0.28.2",
+ "@esbuild/win32-x64": "0.28.2"
+ }
+ },
+ "node_modules/esm-env": {
+ "version": "1.2.2",
+ "resolved": "https://registry.npmjs.org/esm-env/-/esm-env-1.2.2.tgz",
+ "integrity": "sha512-Epxrv+Nr/CaL4ZcFGPJIYLWFom+YeV1DqMLHJoEd9SYRxNbaFruBwfEX/kkHUJf55j2+TUbmDcmuilbP1TmXHA==",
+ "license": "MIT"
+ },
+ "node_modules/esrap": {
+ "version": "2.4.0",
+ "resolved": "https://registry.npmjs.org/esrap/-/esrap-2.4.0.tgz",
+ "integrity": "sha512-CQPcneEHw/czj32uwQC52nYnax8H4SXt25FCM+LIwGZ49cMIxpOj3bP8wmzcI+Z0HIy5KkClaPhRLfCySzwHPA==",
+ "license": "MIT",
+ "dependencies": {
+ "@jridgewell/sourcemap-codec": "^1.4.15"
+ },
+ "peerDependencies": {
+ "@typescript-eslint/types": "^8.2.0"
+ },
+ "peerDependenciesMeta": {
+ "@typescript-eslint/types": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/estree-walker": {
+ "version": "2.0.2",
+ "resolved": "https://registry.npmjs.org/estree-walker/-/estree-walker-2.0.2.tgz",
+ "integrity": "sha512-Rfkk/Mp/DL7JVje3u18FxFujQlTNR2q6QfMSMB7AvCBx91NGj/ba3kCfza0f6dVDbw7YlRf/nDrn7pQrCCyQ/w==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/fdir": {
+ "version": "6.5.0",
+ "resolved": "https://registry.npmjs.org/fdir/-/fdir-6.5.0.tgz",
+ "integrity": "sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=12.0.0"
+ },
+ "peerDependencies": {
+ "picomatch": "^3 || ^4"
+ },
+ "peerDependenciesMeta": {
+ "picomatch": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/fsevents": {
+ "version": "2.3.3",
+ "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz",
+ "integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==",
+ "hasInstallScript": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "darwin"
+ ],
+ "engines": {
+ "node": "^8.16.0 || ^10.6.0 || >=11.0.0"
+ }
+ },
+ "node_modules/function-bind": {
+ "version": "1.1.2",
+ "resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.2.tgz",
+ "integrity": "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==",
+ "dev": true,
+ "license": "MIT",
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
+ "node_modules/hasown": {
+ "version": "2.0.4",
+ "resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.4.tgz",
+ "integrity": "sha512-T2UbfbBEF32wiepXIsMlTW9+dDYC6wMh/t/vYA4tuOMKqWz/n3vr1NFSxQiyP+zk2mXsoMA/i/7qV6LKut1t1A==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "function-bind": "^1.1.2"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ }
+ },
+ "node_modules/is-core-module": {
+ "version": "2.17.0",
+ "resolved": "https://registry.npmjs.org/is-core-module/-/is-core-module-2.17.0.tgz",
+ "integrity": "sha512-J/vG0zBCbIKOQFfufSwyXdMrsohyJIUNkrnmo6WZGzoM7tr/lsbfW5b2BvisL6zsyMzK9UxV9L6c7AoFbyXHOA==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "hasown": "^2.0.4"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
+ "node_modules/is-module": {
+ "version": "1.0.0",
+ "resolved": "https://registry.npmjs.org/is-module/-/is-module-1.0.0.tgz",
+ "integrity": "sha512-51ypPSPCoTEIN9dy5Oy+h4pShgJmPCygKfyRCISBI+JoWT/2oJvK8QPxmwv7b/p239jXrm9M1mlQbyKJ5A152g==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/is-reference": {
+ "version": "3.0.3",
+ "resolved": "https://registry.npmjs.org/is-reference/-/is-reference-3.0.3.tgz",
+ "integrity": "sha512-ixkJoqQvAP88E6wLydLGGqCJsrFUnqoH6HnaczB8XmDH1oaWU+xxdptvikTgaEhtZ53Ky6YXiBuUI2WXLMCwjw==",
+ "license": "MIT",
+ "dependencies": {
+ "@types/estree": "^1.0.6"
+ }
+ },
+ "node_modules/kleur": {
+ "version": "4.1.5",
+ "resolved": "https://registry.npmjs.org/kleur/-/kleur-4.1.5.tgz",
+ "integrity": "sha512-o+NO+8WrRiQEE4/7nwRJhN1HWpVmJm511pBHUxPLtp0BUISzlBplORYSmTclCnJvQq2tKu/sgl3xVpkc7ZWuQQ==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=6"
+ }
+ },
+ "node_modules/locate-character": {
+ "version": "3.0.0",
+ "resolved": "https://registry.npmjs.org/locate-character/-/locate-character-3.0.0.tgz",
+ "integrity": "sha512-SW13ws7BjaeJ6p7Q6CO2nchbYEc3X3J6WrmTTDto7yMPqVSZTUyY5Tjbid+Ab8gLnATtygYtiDIJGQRRn2ZOiA==",
+ "license": "MIT"
+ },
+ "node_modules/magic-string": {
+ "version": "0.30.21",
+ "resolved": "https://registry.npmjs.org/magic-string/-/magic-string-0.30.21.tgz",
+ "integrity": "sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ==",
+ "license": "MIT",
+ "dependencies": {
+ "@jridgewell/sourcemap-codec": "^1.5.5"
+ }
+ },
+ "node_modules/mri": {
+ "version": "1.2.0",
+ "resolved": "https://registry.npmjs.org/mri/-/mri-1.2.0.tgz",
+ "integrity": "sha512-tzzskb3bG8LvYGFF/mDTpq3jpI6Q9wc3LEmBaghu+DdCssd1FakN7Bc0hVNmEyGq1bq3RgfkCb3cmQLpNPOroA==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=4"
+ }
+ },
+ "node_modules/mrmime": {
+ "version": "2.0.1",
+ "resolved": "https://registry.npmjs.org/mrmime/-/mrmime-2.0.1.tgz",
+ "integrity": "sha512-Y3wQdFg2Va6etvQ5I82yUhGdsKrcYox6p7FfL1LbK2J4V01F9TGlepTIhnK24t7koZibmg82KGglhA1XK5IsLQ==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=10"
+ }
+ },
+ "node_modules/nanoid": {
+ "version": "3.3.20",
+ "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.20.tgz",
+ "integrity": "sha512-uKdg2G3GNCKQn9byYOpxbGqrT2fGO5KRt5J/8b3pok8rT6qxGWF6hxMyJiEYtAf+FVyYuD9hRaDqX5uPFYJ4ZQ==",
+ "funding": [
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/ai"
+ }
+ ],
+ "license": "MIT",
+ "bin": {
+ "nanoid": "bin/nanoid.cjs"
+ },
+ "engines": {
+ "node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1"
+ }
+ },
+ "node_modules/obug": {
+ "version": "2.2.1",
+ "resolved": "https://registry.npmjs.org/obug/-/obug-2.2.1.tgz",
+ "integrity": "sha512-XrsrhT5sybtKI6wakr2SPOlGZWWYbUXZ7a0jT8/QOeAPau+1X/bSegNe5YR75oJmEZQbKningirmGOEJCIk61Q==",
+ "funding": [
+ "https://github.com/sponsors/sxzz",
+ "https://opencollective.com/debug"
+ ],
+ "license": "MIT",
+ "engines": {
+ "node": ">=12.20.0"
+ }
+ },
+ "node_modules/path-parse": {
+ "version": "1.0.7",
+ "resolved": "https://registry.npmjs.org/path-parse/-/path-parse-1.0.7.tgz",
+ "integrity": "sha512-LDJzPVEEEPR+y48z93A0Ed0yXb8pAByGWo/k5YYdYgpY2/2EsOsksJrq7lOHxryrVOn1ejG6oAp8ahvOIQD8sw==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/pg": {
+ "version": "8.23.1",
+ "resolved": "https://registry.npmjs.org/pg/-/pg-8.23.1.tgz",
+ "integrity": "sha512-aL96AHANtWjPLDOLqnhx+ngp9+UK7ETEU8VJrDCGvsSSi/mGLcWYsS6Herg7lmaBJe4uwrfqsa7gTEFaSizDoQ==",
+ "license": "MIT",
+ "peer": true,
+ "dependencies": {
+ "pg-connection-string": "^2.14.1",
+ "pg-pool": "^3.14.0",
+ "pg-protocol": "^1.16.1",
+ "pg-types": "2.2.0",
+ "pgpass": "1.0.5"
+ },
+ "engines": {
+ "node": ">= 16.0.0"
+ },
+ "optionalDependencies": {
+ "pg-cloudflare": "^1.4.1"
+ },
+ "peerDependencies": {
+ "pg-native": ">=3.0.1"
+ },
+ "peerDependenciesMeta": {
+ "pg-native": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/pg-cloudflare": {
+ "version": "1.4.1",
+ "resolved": "https://registry.npmjs.org/pg-cloudflare/-/pg-cloudflare-1.4.1.tgz",
+ "integrity": "sha512-6PQbsFWZcp9EmJEwy5cGQ2La+AMWpP46lgbb8X+U/XsHIUweYDNCpeuKck5RxL2MdVFi7krbbEi5nX4Zh7JhrQ==",
+ "license": "MIT",
+ "optional": true
+ },
+ "node_modules/pg-connection-string": {
+ "version": "2.14.1",
+ "resolved": "https://registry.npmjs.org/pg-connection-string/-/pg-connection-string-2.14.1.tgz",
+ "integrity": "sha512-qR3kGNPBLpCNtz0evbKA0Y/MRFXwSSdT+pTJvYp/bXTcReZbvX1kzF0IyTc1QnxqF7AZbOeBhNL8R5mYQZV/MA==",
+ "license": "MIT"
+ },
+ "node_modules/pg-int8": {
+ "version": "1.0.1",
+ "resolved": "https://registry.npmjs.org/pg-int8/-/pg-int8-1.0.1.tgz",
+ "integrity": "sha512-WCtabS6t3c8SkpDBUlb1kjOs7l66xsGdKpIPZsg4wR+B3+u9UAum2odSsF9tnvxg80h4ZxLWMy4pRjOsFIqQpw==",
+ "license": "ISC",
+ "engines": {
+ "node": ">=4.0.0"
+ }
+ },
+ "node_modules/pg-pool": {
+ "version": "3.14.0",
+ "resolved": "https://registry.npmjs.org/pg-pool/-/pg-pool-3.14.0.tgz",
+ "integrity": "sha512-gKtPkFdQPU3DksooVLi9LsjZxrsBUZIpa+7aVx+LV5pNh0KzP4Zleud2po+ConrxbuXGBJ6Hfer6hdgpIBpBaw==",
+ "license": "MIT",
+ "peerDependencies": {
+ "pg": ">=8.0"
+ }
+ },
+ "node_modules/pg-protocol": {
+ "version": "1.16.1",
+ "resolved": "https://registry.npmjs.org/pg-protocol/-/pg-protocol-1.16.1.tgz",
+ "integrity": "sha512-p9VOFMiHB/ZbJATetbg+99PxssTVSQRnyuPSQ67mN1+1KBOjZaZ83ZQzltnxPhJwSsC3nwVjJ10DVJlerbFzLg==",
+ "license": "MIT"
+ },
+ "node_modules/pg-types": {
+ "version": "2.2.0",
+ "resolved": "https://registry.npmjs.org/pg-types/-/pg-types-2.2.0.tgz",
+ "integrity": "sha512-qTAAlrEsl8s4OiEQY69wDvcMIdQN6wdz5ojQiOy6YRMuynxenON0O5oCpJI6lshc6scgAY8qvJ2On/p+CXY0GA==",
+ "license": "MIT",
+ "dependencies": {
+ "pg-int8": "1.0.1",
+ "postgres-array": "~2.0.0",
+ "postgres-bytea": "~1.0.0",
+ "postgres-date": "~1.0.4",
+ "postgres-interval": "^1.1.0"
+ },
+ "engines": {
+ "node": ">=4"
+ }
+ },
+ "node_modules/pgpass": {
+ "version": "1.0.5",
+ "resolved": "https://registry.npmjs.org/pgpass/-/pgpass-1.0.5.tgz",
+ "integrity": "sha512-FdW9r/jQZhSeohs1Z3sI1yxFQNFvMcnmfuj4WBMUTxOrAyLMaTcE1aAMBiTlbMNaXvBCQuVi0R7hd8udDSP7ug==",
+ "license": "MIT",
+ "dependencies": {
+ "split2": "^4.1.0"
+ }
+ },
+ "node_modules/picocolors": {
+ "version": "1.1.1",
+ "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz",
+ "integrity": "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==",
+ "license": "ISC"
+ },
+ "node_modules/picomatch": {
+ "version": "4.0.7",
+ "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.7.tgz",
+ "integrity": "sha512-qcJu88Q2IWqJsDD529JKMdwGm/dvInW4HvQnRwiH9JtihJvzGOscDtHE3x1pBKeUOTysQ8kVmLnJ2kJu7yhcGA==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=12"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/jonschlinkert"
+ }
+ },
+ "node_modules/postcss": {
+ "version": "8.5.29",
+ "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.29.tgz",
+ "integrity": "sha512-49cGhUbXj8Qenv0iTMxA1cFBzxXoctpC9Ujd77t1WcbJIr6nF/eI7g/8MgxrYldFRuAXvja7xQRwavoW7kgrxQ==",
+ "funding": [
+ {
+ "type": "opencollective",
+ "url": "https://opencollective.com/postcss/"
+ },
+ {
+ "type": "tidelift",
+ "url": "https://tidelift.com/funding/github/npm/postcss"
+ },
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/ai"
+ }
+ ],
+ "license": "MIT",
+ "dependencies": {
+ "nanoid": "^3.3.19",
+ "picocolors": "^1.1.1",
+ "source-map-js": "^1.2.2"
+ },
+ "engines": {
+ "node": "^10 || ^12 || >=14"
+ }
+ },
+ "node_modules/postgres-array": {
+ "version": "2.0.0",
+ "resolved": "https://registry.npmjs.org/postgres-array/-/postgres-array-2.0.0.tgz",
+ "integrity": "sha512-VpZrUqU5A69eQyW2c5CA1jtLecCsN2U/bD6VilrFDWq5+5UIEVO7nazS3TEcHf1zuPYO/sqGvUvW62g86RXZuA==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=4"
+ }
+ },
+ "node_modules/postgres-bytea": {
+ "version": "1.0.1",
+ "resolved": "https://registry.npmjs.org/postgres-bytea/-/postgres-bytea-1.0.1.tgz",
+ "integrity": "sha512-5+5HqXnsZPE65IJZSMkZtURARZelel2oXUEO8rH83VS/hxH5vv1uHquPg5wZs8yMAfdv971IU+kcPUczi7NVBQ==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=0.10.0"
+ }
+ },
+ "node_modules/postgres-date": {
+ "version": "1.0.7",
+ "resolved": "https://registry.npmjs.org/postgres-date/-/postgres-date-1.0.7.tgz",
+ "integrity": "sha512-suDmjLVQg78nMK2UZ454hAG+OAW+HQPZ6n++TNDUX+L0+uUlLywnoxJKDou51Zm+zTCjrCl0Nq6J9C5hP9vK/Q==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=0.10.0"
+ }
+ },
+ "node_modules/postgres-interval": {
+ "version": "1.2.0",
+ "resolved": "https://registry.npmjs.org/postgres-interval/-/postgres-interval-1.2.0.tgz",
+ "integrity": "sha512-9ZhXKM/rw350N1ovuWHbGxnGh/SNJ4cnxHiM0rxE4VN41wsg8P8zWn9hv/buK00RP4WvlOyr/RBDiptyxVbkZQ==",
+ "license": "MIT",
+ "dependencies": {
+ "xtend": "^4.0.0"
+ },
+ "engines": {
+ "node": ">=0.10.0"
+ }
+ },
+ "node_modules/readdirp": {
+ "version": "4.1.2",
+ "resolved": "https://registry.npmjs.org/readdirp/-/readdirp-4.1.2.tgz",
+ "integrity": "sha512-GDhwkLfywWL2s6vEjyhri+eXmfH6j1L7JE27WhqLeYzoh/A3DBaYGEj2H/HFZCn/kMfim73FXxEJTw06WtxQwg==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">= 14.18.0"
+ },
+ "funding": {
+ "type": "individual",
+ "url": "https://paulmillr.com/funding/"
+ }
+ },
+ "node_modules/resolve": {
+ "version": "1.22.13",
+ "resolved": "https://registry.npmjs.org/resolve/-/resolve-1.22.13.tgz",
+ "integrity": "sha512-Dj/cW9zBV2aRj6XzCxuGIs3ESZKv02jixne3q6jFZYZ3/Tg09gHHviSMDL4kObh9pqSahdRHEnDoaP2gn8YLhA==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "es-errors": "^1.3.0",
+ "is-core-module": "^2.17.0",
+ "path-parse": "^1.0.7",
+ "supports-preserve-symlinks-flag": "^1.0.0"
+ },
+ "bin": {
+ "resolve": "bin/resolve"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
+ "node_modules/rollup": {
+ "version": "4.64.0",
+ "resolved": "https://registry.npmjs.org/rollup/-/rollup-4.64.0.tgz",
+ "integrity": "sha512-gjA/kFeDfffII8COoPsvLPvE16hWDTEc1+0QKQNKUkuV8iJjqsC4xXs8/FzuL0v9EV39kuxTbAgcFoTRyy2TGQ==",
+ "license": "MIT",
+ "dependencies": {
+ "@types/estree": "1.0.9"
+ },
+ "bin": {
+ "rollup": "dist/bin/rollup"
+ },
+ "engines": {
+ "node": ">=18.0.0",
+ "npm": ">=8.0.0"
+ },
+ "optionalDependencies": {
+ "@napi-rs/lzma-linux-x64-gnu": "1.5.1",
+ "@rollup/rollup-android-arm-eabi": "4.64.0",
+ "@rollup/rollup-android-arm64": "4.64.0",
+ "@rollup/rollup-darwin-arm64": "4.64.0",
+ "@rollup/rollup-darwin-x64": "4.64.0",
+ "@rollup/rollup-freebsd-arm64": "4.64.0",
+ "@rollup/rollup-freebsd-x64": "4.64.0",
+ "@rollup/rollup-linux-arm-gnueabihf": "4.64.0",
+ "@rollup/rollup-linux-arm-musleabihf": "4.64.0",
+ "@rollup/rollup-linux-arm64-gnu": "4.64.0",
+ "@rollup/rollup-linux-arm64-musl": "4.64.0",
+ "@rollup/rollup-linux-loong64-gnu": "4.64.0",
+ "@rollup/rollup-linux-loong64-musl": "4.64.0",
+ "@rollup/rollup-linux-ppc64-gnu": "4.64.0",
+ "@rollup/rollup-linux-ppc64-musl": "4.64.0",
+ "@rollup/rollup-linux-riscv64-gnu": "4.64.0",
+ "@rollup/rollup-linux-riscv64-musl": "4.64.0",
+ "@rollup/rollup-linux-s390x-gnu": "4.64.0",
+ "@rollup/rollup-linux-x64-gnu": "4.64.0",
+ "@rollup/rollup-linux-x64-musl": "4.64.0",
+ "@rollup/rollup-openbsd-x64": "4.64.0",
+ "@rollup/rollup-openharmony-arm64": "4.64.0",
+ "@rollup/rollup-win32-arm64-msvc": "4.64.0",
+ "@rollup/rollup-win32-ia32-msvc": "4.64.0",
+ "@rollup/rollup-win32-x64-gnu": "4.64.0",
+ "@rollup/rollup-win32-x64-msvc": "4.64.0",
+ "fsevents": "~2.3.2"
+ }
+ },
+ "node_modules/sade": {
+ "version": "1.8.1",
+ "resolved": "https://registry.npmjs.org/sade/-/sade-1.8.1.tgz",
+ "integrity": "sha512-xal3CZX1Xlo/k4ApwCFrHVACi9fBqJ7V+mwhBsuf/1IOKbBy098Fex+Wa/5QMubw09pSZ/u8EY8PWgevJsXp1A==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "mri": "^1.1.0"
+ },
+ "engines": {
+ "node": ">=6"
+ }
+ },
+ "node_modules/set-cookie-parser": {
+ "version": "3.1.2",
+ "resolved": "https://registry.npmjs.org/set-cookie-parser/-/set-cookie-parser-3.1.2.tgz",
+ "integrity": "sha512-5/r/lTwbJ3zQ+qwdUFZYeRNqda7P5HD8zQKqlSjdGt1/S0cjLAphHusj4Y58ahDtWn/g32xrIS58/ikOvwl0Lw==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/sirv": {
+ "version": "3.0.2",
+ "resolved": "https://registry.npmjs.org/sirv/-/sirv-3.0.2.tgz",
+ "integrity": "sha512-2wcC/oGxHis/BoHkkPwldgiPSYcpZK3JU28WoMVv55yHJgcZ8rlXvuG9iZggz+sU1d4bRgIGASwyWqjxu3FM0g==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@polka/url": "^1.0.0-next.24",
+ "mrmime": "^2.0.0",
+ "totalist": "^3.0.0"
+ },
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/source-map-js": {
+ "version": "1.2.2",
+ "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.2.tgz",
+ "integrity": "sha512-KGj/8Y43x35aZVDtt+J4mK1hoLGHULMYfSkODJNQjNDC3oW1PqPoxMwo0pLUsWM/UEGzON/NxeHywEfNXNP3Vw==",
+ "license": "BSD-3-Clause",
+ "engines": {
+ "node": ">=0.10.0"
+ }
+ },
+ "node_modules/split2": {
+ "version": "4.2.0",
+ "resolved": "https://registry.npmjs.org/split2/-/split2-4.2.0.tgz",
+ "integrity": "sha512-UcjcJOWknrNkF6PLX83qcHM6KHgVKNkV62Y8a5uYDVv9ydGQVwAHMKqHdJje1VTWpljG0WYpCDhrCdAOYH4TWg==",
+ "license": "ISC",
+ "engines": {
+ "node": ">= 10.x"
+ }
+ },
+ "node_modules/supports-preserve-symlinks-flag": {
+ "version": "1.0.0",
+ "resolved": "https://registry.npmjs.org/supports-preserve-symlinks-flag/-/supports-preserve-symlinks-flag-1.0.0.tgz",
+ "integrity": "sha512-ot0WnXS9fgdkgIcePe6RHNk1WA8+muPa6cSjeR3V8K27q9BB1rTE3R1p7Hv0z1ZyAc8s6Vvv8DIyWf681MAt0w==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">= 0.4"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
+ "node_modules/svelte": {
+ "version": "5.57.2",
+ "resolved": "https://registry.npmjs.org/svelte/-/svelte-5.57.2.tgz",
+ "integrity": "sha512-1YiPCAXT0Ct6g1vOMmSLa0Nsc3QRMvtDF32ihgglGVrugIuIK38RyDiFNXVDhtQ81TJjSO57NdMw6DyYLqSGDQ==",
+ "license": "MIT",
+ "peer": true,
+ "dependencies": {
+ "@jridgewell/remapping": "^2.3.5",
+ "@jridgewell/sourcemap-codec": "^1.6.0",
+ "@sveltejs/acorn-typescript": "^1.0.13",
+ "@types/estree": "^1.0.9",
+ "acorn": "^8.18.0",
+ "aria-query": "5.3.1",
+ "axobject-query": "^4.1.0",
+ "clsx": "^2.1.1",
+ "devalue": "^5.9.2",
+ "esm-env": "^1.2.1",
+ "esrap": "^2.3.6",
+ "is-reference": "^3.0.3",
+ "locate-character": "^3.0.0",
+ "magic-string": "^0.30.11",
+ "zimmerframe": "^1.1.2"
+ },
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/svelte-check": {
+ "version": "4.7.6",
+ "resolved": "https://registry.npmjs.org/svelte-check/-/svelte-check-4.7.6.tgz",
+ "integrity": "sha512-t2scM//ZuVbSY/T2w6FSBw1v9s2NEmh/g+sy1lqtosW5ylBV5AF4wFb1Ts9Kf3MbfPDUDJDZ9L436YT0SPTdvw==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@jridgewell/trace-mapping": "^0.3.25",
+ "@sveltejs/load-config": "^0.2.3",
+ "chokidar": "^4.0.1",
+ "fdir": "^6.2.0",
+ "picocolors": "^1.0.0",
+ "sade": "^1.7.4"
+ },
+ "bin": {
+ "svelte-check": "bin/svelte-check"
+ },
+ "engines": {
+ "node": ">= 18.0.0"
+ },
+ "peerDependencies": {
+ "svelte": "^4.0.0 || ^5.0.0-next.0",
+ "typescript": "^5.0.0 || ^6.0.0"
+ }
+ },
+ "node_modules/tinyglobby": {
+ "version": "0.2.17",
+ "resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.17.tgz",
+ "integrity": "sha512-wXR/dYpcqKmfWpEdZjiKJOwCNFndD0DMnrW/cYjVGttEkBfVgcLFHoNrlj47mjOVic9yyNu65alsgF4NQyTa2g==",
+ "license": "MIT",
+ "dependencies": {
+ "fdir": "^6.5.0",
+ "picomatch": "^4.0.4"
+ },
+ "engines": {
+ "node": ">=12.0.0"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/SuperchupuDev"
+ }
+ },
+ "node_modules/totalist": {
+ "version": "3.0.1",
+ "resolved": "https://registry.npmjs.org/totalist/-/totalist-3.0.1.tgz",
+ "integrity": "sha512-sf4i37nQ2LBx4m3wB74y+ubopq6W/dIzXg0FDGjsYnZHVa1Da8FH853wlL2gtUhg+xJXjfk3kUZS3BRoQeoQBQ==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=6"
+ }
+ },
+ "node_modules/typescript": {
+ "version": "5.9.3",
+ "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.9.3.tgz",
+ "integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==",
+ "dev": true,
+ "license": "Apache-2.0",
+ "peer": true,
+ "bin": {
+ "tsc": "bin/tsc",
+ "tsserver": "bin/tsserver"
+ },
+ "engines": {
+ "node": ">=14.17"
+ }
+ },
+ "node_modules/undici-types": {
+ "version": "7.8.0",
+ "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-7.8.0.tgz",
+ "integrity": "sha512-9UJ2xGDvQ43tYyVMpuHlsgApydB8ZKfVYTsLDhXkFL/6gfkp+U8xTGdh8pMJv1SpZna0zxG1DwsKZsreLbXBxw==",
+ "devOptional": true,
+ "license": "MIT"
+ },
+ "node_modules/vite": {
+ "version": "7.3.7",
+ "resolved": "https://registry.npmjs.org/vite/-/vite-7.3.7.tgz",
+ "integrity": "sha512-AHEzTORMbi7/7aXp7w7KZ5+DCUdSeLsJz0grY8xHpc9DHdYb0vQu6DqJfm2tOw3gDExNgPgnJTXxM6syYFHaCA==",
+ "license": "MIT",
+ "peer": true,
+ "dependencies": {
+ "esbuild": "^0.27.0 || ^0.28.0",
+ "fdir": "^6.5.0",
+ "picomatch": "^4.0.3",
+ "postcss": "^8.5.6",
+ "rollup": "^4.43.0",
+ "tinyglobby": "^0.2.15"
+ },
+ "bin": {
+ "vite": "bin/vite.js"
+ },
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ },
+ "funding": {
+ "url": "https://github.com/vitejs/vite?sponsor=1"
+ },
+ "optionalDependencies": {
+ "fsevents": "~2.3.3"
+ },
+ "peerDependencies": {
+ "@types/node": "^20.19.0 || >=22.12.0",
+ "jiti": ">=1.21.0",
+ "less": "^4.0.0",
+ "lightningcss": "^1.21.0",
+ "sass": "^1.70.0",
+ "sass-embedded": "^1.70.0",
+ "stylus": ">=0.54.8",
+ "sugarss": "^5.0.0",
+ "terser": "^5.16.0",
+ "tsx": "^4.8.1",
+ "yaml": "^2.4.2"
+ },
+ "peerDependenciesMeta": {
+ "@types/node": {
+ "optional": true
+ },
+ "jiti": {
+ "optional": true
+ },
+ "less": {
+ "optional": true
+ },
+ "lightningcss": {
+ "optional": true
+ },
+ "sass": {
+ "optional": true
+ },
+ "sass-embedded": {
+ "optional": true
+ },
+ "stylus": {
+ "optional": true
+ },
+ "sugarss": {
+ "optional": true
+ },
+ "terser": {
+ "optional": true
+ },
+ "tsx": {
+ "optional": true
+ },
+ "yaml": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/vitefu": {
+ "version": "1.1.3",
+ "resolved": "https://registry.npmjs.org/vitefu/-/vitefu-1.1.3.tgz",
+ "integrity": "sha512-ub4okH7Z5KLjb6hDyjqrGXqWtWvoYdU3IGm/NorpgHncKoLTCfRIbvlhBm7r0YstIaQRYlp4yEbFqDcKSzXSSg==",
+ "license": "MIT",
+ "workspaces": [
+ "tests/deps/*",
+ "tests/projects/*",
+ "tests/projects/workspace/packages/*"
+ ],
+ "peerDependencies": {
+ "vite": "^3.0.0 || ^4.0.0 || ^5.0.0 || ^6.0.0 || ^7.0.0 || ^8.0.0"
+ },
+ "peerDependenciesMeta": {
+ "vite": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/xtend": {
+ "version": "4.0.2",
+ "resolved": "https://registry.npmjs.org/xtend/-/xtend-4.0.2.tgz",
+ "integrity": "sha512-LKYU1iAXJXUgAXn9URjiu+MWhyUXHsvfp7mcuYm9dSUKK0/CjtrUwFAxD82/mCWbtLsGjFIad0wIsod4zrTAEQ==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=0.4"
+ }
+ },
+ "node_modules/zimmerframe": {
+ "version": "1.1.5",
+ "resolved": "https://registry.npmjs.org/zimmerframe/-/zimmerframe-1.1.5.tgz",
+ "integrity": "sha512-msJxIvYDYcoNL+PJsu+7qmpDWsYmAxTY+2TNYXXF0hzBzBk0BMecOqDOG/EckUoKCuKwObfbugIl8QpqHDXeFA==",
+ "license": "MIT"
+ }
+ }
+}
diff --git a/loadtest/console/package.json b/loadtest/console/package.json
new file mode 100644
index 0000000000..71bea71199
--- /dev/null
+++ b/loadtest/console/package.json
@@ -0,0 +1,39 @@
+{
+ "name": "hyperswitch-loadtest-console",
+ "private": true,
+ "version": "0.1.0",
+ "type": "module",
+ "scripts": {
+ "dev": "node --env-file-if-exists=.env ./node_modules/vite/bin/vite.js --host 127.0.0.1 --port 4174",
+ "dev:tls": "node --env-file-if-exists=.env scripts/database-tls.mjs dev",
+ "build": "vite build",
+ "build:recorder": "../k6/scenario-mix/recorder/build.sh",
+ "start": "node --env-file-if-exists=.env start.mjs",
+ "start:tls": "node --env-file-if-exists=.env scripts/database-tls.mjs start",
+ "check": "svelte-kit sync && svelte-check --tsconfig ./jsconfig.json",
+ "test": "node --test test/*.test.mjs",
+ "password": "node scripts/password.mjs",
+ "worker": "node --env-file-if-exists=.env scripts/worker.mjs",
+ "worker:agent": "node --env-file-if-exists=.env ../worker/agent.mjs",
+ "test:scale": "CONSOLE_SCALE_PAYMENTS=10000000 node --test test/payment-index.test.mjs",
+ "generate:connectors": "python3 scripts/connector-catalog.py",
+ "check:connectors": "python3 scripts/connector-catalog.py --check"
+ },
+ "dependencies": {
+ "@sveltejs/vite-plugin-svelte": "^6.2.1",
+ "pg": "^8.16.3",
+ "svelte": "^5.39.6",
+ "vite": "^7.1.9"
+ },
+ "devDependencies": {
+ "@sveltejs/kit": "2.70.3",
+ "@sveltejs/adapter-node": "5.5.7",
+ "@opentelemetry/api": "1.9.0",
+ "@types/node": "24.0.0",
+ "svelte-check": "^4.3.2",
+ "typescript": "^5.9.3"
+ },
+ "overrides": {
+ "cookie": "0.7.2"
+ }
+}
diff --git a/loadtest/console/scripts/connector-catalog.py b/loadtest/console/scripts/connector-catalog.py
new file mode 100644
index 0000000000..213c605576
--- /dev/null
+++ b/loadtest/console/scripts/connector-catalog.py
@@ -0,0 +1,26 @@
+#!/usr/bin/env python3
+"""Generate UI identities/auth labels from routing enum and sandbox definitions."""
+import json,re,pathlib,tomllib,sys
+root=pathlib.Path(__file__).resolve().parents[3]
+source=(root/'crates/euclid/src/enums.rs').read_text().split('pub enum RoutableConnectors {',1)[1].split('\n}',1)[0]
+config=tomllib.loads((root/'crates/connector_configs/toml/sandbox.toml').read_text())
+entries=[];attrs=[]
+for line in source.splitlines():
+ line=line.strip()
+ if line.startswith('#['):attrs.append(line);continue
+ m=re.fullmatch(r'(\w+),',line)
+ if not m:continue
+ variant=m[1];serialized=re.search(r'serde\(rename = "([^"]+)"', '\n'.join(attrs))
+ name=serialized[1] if serialized else re.sub(r'(?<!^)(?=[A-Z][a-z])','_',variant).lower()
+ dummy=any('dummy_connector' in a for a in attrs);attrs=[]
+ c=config.get(name,{})
+ auth=c.get('connector_auth',{});auth_type=next(iter(auth),None)
+ fields=[]
+ if auth_type and isinstance(auth[auth_type],dict):
+ fields=[{'name':k,'label':v if isinstance(v,str) else k.replace('_',' ').title()} for k,v in auth[auth_type].items()]
+ entries.append({'id':name,'label':name.replace('_',' ').title(),'dummy':dummy,'card':dummy or bool(c.get('credit')),'networks':[row['payment_method_type'] for row in c.get('credit',[]) if isinstance(row,dict) and isinstance(row.get('payment_method_type'),str)],'authType':auth_type or ('HeaderKey' if dummy else None),'fields':fields or ([{'name':'api_key','label':'Test key'}] if dummy else [])})
+output=json.dumps(entries,indent=2)+'\n';target=root/'loadtest/console/src/connector-catalog.json'
+if '--check' in sys.argv:
+ if not target.exists() or target.read_text()!=output:sys.exit('Connector catalog is stale; run python3 scripts/connector-catalog.py')
+else:target.write_text(output)
+print(f'{len(entries)} routing connectors')
diff --git a/loadtest/console/scripts/container.mjs b/loadtest/console/scripts/container.mjs
new file mode 100644
index 0000000000..85a297dfb6
--- /dev/null
+++ b/loadtest/console/scripts/container.mjs
@@ -0,0 +1,15 @@
+// Container shutdown owns both services; restarting SSR alone leaves jobs alive.
+import {spawn} from 'node:child_process';
+import {initializeSupervisor} from '../server/supervisor.mjs';
+const service=await initializeSupervisor();
+const web=spawn(process.execPath,['start.mjs'],{stdio:'inherit',env:process.env});
+let stopping=false;
+async function stop(signal='SIGTERM'){
+ if(stopping)return;stopping=true;
+ web.kill(signal);try{process.kill(service.pid,'SIGTERM');}catch{}
+ const deadline=Date.now()+70000;
+ while(Date.now()<deadline){try{process.kill(service.pid,0);}catch{process.exit(0);}await new Promise(r=>setTimeout(r,200));}
+ try{process.kill(service.pid,'SIGKILL');}catch{}process.exit(1);
+}
+process.on('SIGTERM',()=>stop());process.on('SIGINT',()=>stop());
+web.on('exit',()=>{if(!stopping)stop();});
diff --git a/loadtest/console/scripts/database-tls.mjs b/loadtest/console/scripts/database-tls.mjs
new file mode 100644
index 0000000000..22db84d411
--- /dev/null
+++ b/loadtest/console/scripts/database-tls.mjs
@@ -0,0 +1,44 @@
+import {access,readFile} from 'node:fs/promises';
+import {constants} from 'node:fs';
+import {spawn} from 'node:child_process';
+import {once} from 'node:events';
+import path from 'node:path';
+
+const mode=process.argv[2];
+if(!['dev','start'].includes(mode))throw new Error('Use database-tls.mjs dev or start');
+process.env.LOADTEST_DB_TLS='1';
+if(process.env.PGSSLROOTCERT){
+ const certificate=path.resolve(process.env.PGSSLROOTCERT);
+ await access(certificate,constants.R_OK);
+ process.env.PGSSLROOTCERT=certificate;
+}
+
+// A detached worker inherits its startup environment. Reload it only while idle
+// so reconciliation uses the requested CA without interrupting load generation.
+const {dataRoot,consoleRoot}=await import('../server/state.mjs');
+const descriptorPath=path.join(dataRoot,'worker-service.json');
+let descriptor=null;
+try{descriptor=JSON.parse(await readFile(descriptorPath,'utf8'));}catch{}
+let workerAlive=false;
+if(descriptor)try{process.kill(descriptor.pid,0);workerAlive=true;}catch(e){if(e.code!=='ESRCH')throw e;}
+if(descriptor&&workerAlive){
+ const rpc=async(operation)=>{
+ const response=await fetch(`${descriptor.url}/rpc`,{method:'POST',headers:{authorization:`Bearer ${descriptor.token}`,'content-type':'application/json'},body:JSON.stringify({operation,args:{}}),signal:AbortSignal.timeout(3000)});
+ if(!response.ok)throw new Error(`Worker ${operation} check failed`);return response.json();
+ };
+ try{
+ const [active,faults]=await Promise.all([rpc('active'),rpc('faults')]);
+ if(active||faults.active||faults.blocked||faults.recovering)throw new Error('Cannot enable database TLS while a job or fault recovery is active');
+ process.kill(descriptor.pid,'SIGTERM');
+ for(let i=0;i<100;i++){try{process.kill(descriptor.pid,0);await new Promise(resolve=>setTimeout(resolve,100));}catch{workerAlive=false;break;}}
+ if(workerAlive)throw new Error('Timed out while reloading the idle worker for database TLS');
+ }catch(e){if(e.code!=='ESRCH')throw e;}
+}
+const {initializeSupervisor}=await import('../server/supervisor.mjs');
+await initializeSupervisor();
+
+const entry=mode==='dev'?path.join(consoleRoot,'node_modules/vite/bin/vite.js'):path.join(consoleRoot,'start.mjs');
+const args=mode==='dev'?[entry,'--host',process.env.HOST || '127.0.0.1','--port',process.env.PORT || '4174']:[entry];
+const child=spawn(process.execPath,args,{cwd:consoleRoot,stdio:'inherit',env:process.env});
+const [code]=await once(child,'exit');
+process.exitCode=code ?? 1;
diff --git a/loadtest/console/scripts/execute.mjs b/loadtest/console/scripts/execute.mjs
new file mode 100644
index 0000000000..bc93049aac
--- /dev/null
+++ b/loadtest/console/scripts/execute.mjs
@@ -0,0 +1,67 @@
+import {resolveConnectorAccounts} from '../server/connector-fixtures.mjs';
+import {dataRoot} from '../server/state.mjs';
+import { readFile,mkdir,writeFile,rename } from 'node:fs/promises';
+import path from 'node:path';
+import { pathToFileURL } from 'node:url';
+import { isDeepStrictEqual } from 'node:util';
+
+const spec=JSON.parse(await readFile(process.argv[2],'utf8'));
+const config=JSON.parse(await readFile(spec.configPath,'utf8'));
+const {fixtures,load}=await import(pathToFileURL(path.join(spec.loadtestRoot,'k6/scenario-mix/run.mjs')).href);
+const fixturePath=spec.fixturePath || path.join(config.output,spec.mode,'fixtures');
+const jobDir=path.dirname(process.argv[2]);
+process.env.K6_PID_FILE=path.join(jobDir,'k6-pid.json');
+process.env.LOADTEST_CONSOLE_JOB='1';
+// If the web process dies, stop its generator rather than leaving an orphaned load.
+let orphaned=false;
+const watchdog=setInterval(()=>{
+ try {process.kill(spec.parentPid,0);}catch {
+ if(!orphaned){
+ orphaned=true;
+ setTimeout(async()=>{
+ const child=JSON.parse(await readFile(process.env.K6_PID_FILE,'utf8').catch(()=>'{"pid":null}'));
+ if(child.pid)try{process.kill(-child.pid,'SIGKILL');}catch{}
+ process.exit(1);
+ },60000).unref();
+ process.kill(process.pid,'SIGTERM');
+ }
+ }
+},1000);
+try {
+ await mkdir(fixturePath,{recursive:true,mode:0o700});
+ let result;
+ if(spec.kind==='fixtures') {
+ const provision={...config.fixtures,connectorPlan:config.connectors,merchant_count:spec.merchantCount ?? (spec.mode==='single'?1:1500),merchant_id_prefix:`${config.fixtures.merchant_id_prefix || 'loadtest'}_${spec.mode}_${spec.fixtureSetId?.slice(0,8) || 'legacy'}`};
+ const file=path.join(fixturePath,'provision.json');await writeFile(file,JSON.stringify(provision),{mode:0o600});
+ result=await fixtures(file,fixturePath,{connectorAccounts:resolveConnectorAccounts(config.fixtures.connectorAccounts,dataRoot),onProgress:async setup=>{const progressFile=path.join(jobDir,'fixture-progress.json');await writeFile(progressFile+'.tmp',JSON.stringify(setup),{mode:0o600});await rename(progressFile+'.tmp',progressFile);}});
+ } else if(spec.kind==='smoke') {
+ const manifest=JSON.parse(await readFile(path.join(fixturePath,'manifest.json'),'utf8'));
+ const requested=config.fixtures.superposition;
+ if(requested && (!isDeepStrictEqual(requested.defaults,manifest.superposition?.defaults)
+ || requested.organization_id!==manifest.superposition?.organization_id || requested.workspace_id!==manifest.superposition?.workspace_id)) throw new Error('Superposition configuration changed; create fixtures again');
+ await mkdir(spec.runPath,{recursive:true,mode:0o700});
+ const {fixtures:_fixtures,output:_output,...smokeConfig}=config;
+ smokeConfig.load={...smokeConfig.load,total_rps:spec.smoke.rps,duration_seconds:spec.smoke.durationSeconds};
+ delete smokeConfig.load.stages;delete smokeConfig.load.start_rps;delete smokeConfig.faultPlan;
+ const file=path.join(spec.runPath,'config.json');await writeFile(file,JSON.stringify(smokeConfig,null,2),{mode:0o600});
+ process.env.SQLITE_RECORDER_CONTROL_FILE=path.join(spec.runPath,'control.json');
+ process.env.SQLITE_RECORDER_PROGRESS_FILE=path.join(spec.runPath,'progress.json');
+ console.log(`Smoke test · ${spec.smoke.rps} RPS · ${spec.smoke.durationSeconds}s · recording disabled`);
+ result=await load(file,fixturePath,spec.runPath,spec.k6Binary,{recording:false,telemetry:true});
+ } else {
+ const manifest=JSON.parse(await readFile(path.join(fixturePath,'manifest.json'),'utf8'));
+ const requested=config.fixtures.superposition;
+ if(requested && (!isDeepStrictEqual(requested.defaults,manifest.superposition?.defaults)
+ || requested.organization_id!==manifest.superposition?.organization_id || requested.workspace_id!==manifest.superposition?.workspace_id)) throw new Error('Superposition configuration changed; create fixtures again');
+ await mkdir(spec.runPath,{recursive:true,mode:0o700});
+ const {fixtures:_fixtures,output:_output,...loadConfig}=config;
+ const file=path.join(spec.runPath,'config.json');await writeFile(file,JSON.stringify(loadConfig,null,2),{mode:0o600});
+ const binary=spec.k6Binary || process.env.K6_BINARY || path.join(spec.loadtestRoot,'k6/scenario-mix/bin/k6-sqlite');
+ await writeFile(path.join(jobDir,'phase.json'),JSON.stringify({phase:'load'}),{mode:0o600});
+ process.env.SQLITE_RECORDER_CONTROL_FILE=path.join(spec.runPath,'control.json');process.env.SQLITE_RECORDER_PROGRESS_FILE=path.join(spec.runPath,'progress.json');
+ result=await load(file,fixturePath,spec.runPath,binary);
+ }
+ await writeFile(path.join(jobDir,'result.json'),JSON.stringify(result),{mode:0o600});process.exitCode=result.exitCode || 0;
+}catch(e) {
+ console.error(e.message);await writeFile(path.join(jobDir,'result.json'),JSON.stringify({error:e.message}),{mode:0o600});process.exitCode=1;
+}finally{clearInterval(watchdog);}
diff --git a/loadtest/console/scripts/password.mjs b/loadtest/console/scripts/password.mjs
new file mode 100644
index 0000000000..1abe6f4504
--- /dev/null
+++ b/loadtest/console/scripts/password.mjs
@@ -0,0 +1,6 @@
+import { passwordHash } from '../server/auth.mjs';
+let password = '';
+for await (const chunk of process.stdin) password += chunk;
+password = password.trimEnd();
+if (password.length < 12) throw new Error('Use at least 12 characters');
+console.log(await passwordHash(password));
diff --git a/loadtest/console/scripts/worker.mjs b/loadtest/console/scripts/worker.mjs
new file mode 100644
index 0000000000..cefb769f75
--- /dev/null
+++ b/loadtest/console/scripts/worker.mjs
@@ -0,0 +1,15 @@
+import {readJson,dataRoot} from '../server/state.mjs';
+import {initializeSupervisor} from '../server/supervisor.mjs';
+import path from 'node:path';
+const command=process.argv[2] || 'status';
+if(command==='start'){const service=await initializeSupervisor();console.log(`Worker ready · PID ${service.pid}`);}
+else {
+ const service=await readJson(path.join(dataRoot,'worker-service.json'),null);
+ if(command==='stop'){
+ if(service){try{process.kill(service.pid,'SIGTERM');console.log('Worker stopping · active jobs drain and stop');}catch(e){if(e.code!=='ESRCH')throw e;}}
+ else console.log('Worker is stopped');
+ }else if(command==='status'){
+ let running=false;if(service)try{process.kill(service.pid,0);running=true;}catch{}
+ console.log(running?`Worker running · PID ${service.pid}`:'Worker is stopped');
+ }else throw Error('Use start, status or stop');
+}
diff --git a/loadtest/console/server/acceptance.mjs b/loadtest/console/server/acceptance.mjs
new file mode 100644
index 0000000000..1dd878943f
--- /dev/null
+++ b/loadtest/console/server/acceptance.mjs
@@ -0,0 +1,14 @@
+export const defaultCriteria={minimumSuccessRatio:.95,maximumErrorPercent:1,maximumConfirmP99Ms:2000,maximumDropped:0};
+export function evaluateAcceptance(run,criteria=defaultCriteria){
+ const limit={...defaultCriteria,...criteria};
+ const check=(label,actual,maximum,minimum=false)=>({label,actual,limit:maximum,outcome:actual==null?'unmeasured':(minimum?actual>=maximum:actual<=maximum)?'pass':'fail'});
+ const checks=[check('Successful TPS',run.successfulTps,(run.expectedAverageTps ?? run.offeredTps)*limit.minimumSuccessRatio,true),
+ check('HTTP errors (%)',run.errorRate,limit.maximumErrorPercent),check('Confirm p99 (ms)',run.confirmP99,limit.maximumConfirmP99Ms),
+ check('Dropped flows',run.dropped,limit.maximumDropped),check('Recording gaps',run.gaps,0)];
+ const faults=run.activity?.filter(e=>e.kind==='fault_started') || [];
+ const faultErrors=run.activity?.some(e=>e.kind==='fault_error');
+ const recovered=run.activity?.filter(e=>e.kind==='fault_restored').length || 0;
+ const resilience=faultErrors||recovered<faults.length?'incomplete':faults.length?faults.some(e=>e.message.startsWith('SIMULATED'))?'simulated':'recovery verified':'not tested';
+ const verdict=(!run.complete||['cancelled','interrupted'].includes(run.jobStatus))?'incomplete':checks.some(c=>c.outcome==='fail')?'fail':checks.some(c=>c.outcome==='unmeasured')?'unmeasured':'pass';
+ return {verdict,checks,resilience,criteria:limit};
+}
diff --git a/loadtest/console/server/auth.mjs b/loadtest/console/server/auth.mjs
new file mode 100644
index 0000000000..8f13da9236
--- /dev/null
+++ b/loadtest/console/server/auth.mjs
@@ -0,0 +1,49 @@
+import { scrypt, randomBytes, createHash, timingSafeEqual } from 'node:crypto';
+import { promisify } from 'node:util';
+import { controlDb } from './state.mjs';
+import { HttpError } from './errors.mjs';
+const derive = promisify(scrypt);
+export const sessionCookie = 'loadtest_session';
+const digest = token => createHash('sha256').update(token).digest('hex');
+let passwordChecks=0;
+
+export async function passwordHash(password) {
+ const salt = randomBytes(16).toString('hex');
+ return `scrypt:${salt}:${(await derive(password,salt,64)).toString('hex')}`;
+}
+export async function verifyPassword(password, encoded) {
+ const [algorithm,salt,key] = (encoded || '').split(':');
+ if (algorithm !== 'scrypt' || !/^[a-f0-9]{32}$/.test(salt || '') || !/^[a-f0-9]{128}$/.test(key || '')) return false;
+ const actual = await derive(password,salt,64);
+ return timingSafeEqual(actual,Buffer.from(key,'hex'));
+}
+export function authenticated(token) {
+ if (!token) return false;
+ return Boolean(controlDb().prepare('SELECT token FROM sessions WHERE token=? AND expires>?').get(digest(token),Date.now()));
+}
+export async function login(username,password,ip) {
+ const db = controlDb(), now = Date.now(), key = digest(ip);
+ if(passwordChecks>=8)throw new HttpError(429,'Login is busy. Try again shortly.');
+ // Reserve before yielding to scrypt, atomically across web processes too.
+ const reserved=db.prepare(`INSERT INTO login_limits VALUES(?,1,?) ON CONFLICT(key) DO UPDATE SET
+ failures=CASE WHEN reset_at<=? THEN 1 ELSE failures+1 END,
+ reset_at=CASE WHEN reset_at<=? THEN excluded.reset_at ELSE reset_at END
+ WHERE reset_at<=? OR failures<5 RETURNING key`).get(key,now+900000,now,now,now);
+ if(!reserved)throw new HttpError(429,'Too many attempts. Try again in 15 minutes.');
+ let valid=false;passwordChecks++;
+ try{if(password.length<=4096&&username.length<=256)valid=await verifyPassword(password,process.env.ADMIN_PASSWORD_HASH);}
+ finally{passwordChecks--;}
+ if (username !== (process.env.ADMIN_USERNAME || 'admin') || !valid) {
+ return null;
+ }
+ const token = randomBytes(32).toString('hex');
+ db.prepare('DELETE FROM sessions WHERE expires<=?').run(now);
+ db.prepare('DELETE FROM login_limits WHERE key=?').run(key);
+ db.prepare('INSERT INTO sessions VALUES(?,?)').run(digest(token),now+8*3600000);
+ return token;
+}
+export function logout(token) { if(token) controlDb().prepare('DELETE FROM sessions WHERE token=?').run(digest(token)); }
+export function sameOrigin(request,url) {
+ const origin = request.headers.get('origin');
+ return origin === (process.env.ORIGIN || url.origin);
+}
diff --git a/loadtest/console/server/certificates.mjs b/loadtest/console/server/certificates.mjs
new file mode 100644
index 0000000000..62080a510a
--- /dev/null
+++ b/loadtest/console/server/certificates.mjs
@@ -0,0 +1,40 @@
+import {X509Certificate,randomUUID} from 'node:crypto';
+import {mkdir,readFile,writeFile,rename,rm} from 'node:fs/promises';
+import {readFileSync} from 'node:fs';
+import path from 'node:path';
+
+const idPattern=/^[0-9a-f-]{36}$/;
+const pemPattern=/-----BEGIN CERTIFICATE-----[\s\S]+?-----END CERTIFICATE-----/g;
+const directory=root=>path.join(root,'certificates');
+const manifestPath=root=>path.join(directory(root),'manifest.json');
+export const certificatePath=(root,id)=>{
+ if(!idPattern.test(String(id)))throw new Error('Invalid certificate ID');
+ return path.join(directory(root),`${id}.pem`);
+};
+function metadata(root){try{return JSON.parse(readFileSync(manifestPath(root),'utf8'));}catch(e){if(e.code==='ENOENT')return [];throw e;}}
+async function saveMetadata(root,value){
+ await mkdir(directory(root),{recursive:true,mode:0o700});
+ const temporary=`${manifestPath(root)}.${process.pid}.tmp`;
+ await writeFile(temporary,JSON.stringify(value,null,2)+'\n',{mode:0o600});
+ await rename(temporary,manifestPath(root));
+}
+export function listCertificates(root){return metadata(root).map(({id,name,fingerprint,subject,issuer,validTo,certificateCount,createdAt})=>({id,name,fingerprint,subject,issuer,validTo,certificateCount,createdAt}));}
+export function hasCertificate(root,id){return Boolean(id&&metadata(root).some(item=>item.id===id));}
+export function readImportedCertificate(root,id){return readFileSync(certificatePath(root,id),'utf8');}
+export async function importCertificate(root,{name,pem}){
+ const text=String(pem||'').trim(),blocks=text.match(pemPattern)||[];
+ if(!blocks.length)throw new Error('Choose a PEM encoded CA certificate');
+ if(Buffer.byteLength(text)>1024*1024||blocks.length>20)throw new Error('Certificate bundle exceeds the 1 MiB or 20 certificate limit');
+ let certificates;try{certificates=blocks.map(block=>new X509Certificate(block));}catch{throw new Error('Certificate bundle contains an invalid X.509 certificate');}
+ const id=randomUUID(),first=certificates[0],entry={id,name:String(name||'Imported CA').trim().slice(0,100)||'Imported CA',fingerprint:first.fingerprint256,
+ subject:first.subject,issuer:first.issuer,validTo:first.validTo,certificateCount:certificates.length,createdAt:Date.now()};
+ await mkdir(directory(root),{recursive:true,mode:0o700});
+ await writeFile(certificatePath(root,id),blocks.join('\n')+'\n',{mode:0o600,flag:'wx'});
+ await saveMetadata(root,[...metadata(root),entry]);
+ return entry;
+}
+export async function removeCertificate(root,id){
+ if(!idPattern.test(String(id)))throw new Error('Invalid certificate ID');
+ await saveMetadata(root,metadata(root).filter(item=>item.id!==id));
+ await rm(certificatePath(root,id),{force:true});
+}
diff --git a/loadtest/console/server/command-faults.mjs b/loadtest/console/server/command-faults.mjs
new file mode 100644
index 0000000000..e937818d13
--- /dev/null
+++ b/loadtest/console/server/command-faults.mjs
@@ -0,0 +1,37 @@
+import {spawn} from 'node:child_process';
+import path from 'node:path';
+export function validateCommandTarget(target,{requireEnabled=true}={}){
+ if(requireEnabled&&process.env.LOADTEST_ALLOW_CUSTOM_COMMANDS!=='true')throw new Error('Custom fault commands are disabled; set LOADTEST_ALLOW_CUSTOM_COMMANDS=true on the supervisor');
+ if(!['restore','self-recovering'].includes(target.recoveryMode))throw new Error('Choose explicit restoration or self-recovery');
+ if(!['outage','failover'].includes(target.commandAction))throw new Error('Choose outage or failover');
+ if(!Number.isInteger(target.timeoutSeconds)||target.timeoutSeconds<1||target.timeoutSeconds>120)throw new Error('Command timeout must be 1–120 seconds');
+ if(!path.isAbsolute(target.workingDirectory||''))throw new Error('Use an absolute command working directory');
+ for(const field of ['triggerCommand','readyCommand','faultCheckCommand',...(target.recoveryMode==='restore'?['restoreCommand']:[])]){
+ if(typeof target[field]!=='string'||!target[field].trim()||target[field].length>8192||target[field].includes('\0'))throw new Error(`Configure ${field}`);
+ }
+ return target;
+}
+// Commands intentionally execute on the supervisor, never on distributed agents.
+// Output is discarded: arbitrary process output can contain credentials.
+export function executeFaultCommand(target,field){
+ return new Promise((resolve,reject)=>{
+ let child,timeout;
+ try{child=spawn('/bin/sh',['-c',target[field]],{cwd:target.workingDirectory,env:process.env,detached:true,stdio:'ignore'});}catch{reject(new Error(`${field} could not start`));return;}
+ const kill=()=>{try{process.kill(-child.pid,'SIGKILL');}catch{}};
+ timeout=setTimeout(()=>{kill();reject(new Error(`${field} timed out after ${target.timeoutSeconds}s`));},target.timeoutSeconds*1000);
+ child.once('error',()=>{clearTimeout(timeout);reject(new Error(`${field} could not start`));});
+ child.once('exit',(code,signal)=>{clearTimeout(timeout);if(code===0)resolve();else reject(new Error(`${field} failed (${signal||`exit ${code}`})`));});
+ });
+}
+export function commandFaultAdapter(target,{execute=executeFaultCommand}={}){
+ validateCommandTarget(target);
+ const succeeds=async field=>{try{await execute(target,field);return true;}catch{return false;}};
+ return {
+ recoveryTimeoutMs:target.timeoutSeconds*1000,
+ probe:async()=>{await execute(target,'readyCommand');return {ready:true};},
+ apply:()=>execute(target,'triggerCommand'),
+ isDown:()=>succeeds('faultCheckCommand'),
+ restore:async()=>{if(target.recoveryMode==='restore')await execute(target,'restoreCommand');},
+ verify:()=>succeeds('readyCommand')
+ };
+}
diff --git a/loadtest/console/server/connection-secrets.mjs b/loadtest/console/server/connection-secrets.mjs
new file mode 100644
index 0000000000..80b9314640
--- /dev/null
+++ b/loadtest/console/server/connection-secrets.mjs
@@ -0,0 +1,13 @@
+// A blank secret means "reuse at the same destination", never "forward elsewhere".
+export function requireBoundSecret(savedSecret,newSecret,sameDestination,label){
+ if(savedSecret&&!newSecret&&!sameDestination)throw new Error(`Enter a new ${label} when changing the connection destination or weakening TLS`);
+ return newSecret||savedSecret;
+}
+export function databaseTestConnection(saved,draft){
+ const next={...saved,...draft};
+ const identity=db=>JSON.stringify([String(db.host||'').toLowerCase(),Number(db.port||5432),db.database||'',db.user||'']);
+ const strength=db=>({disable:0,require:1,verify:2})[db.tlsMode||(db.ssl?'verify':'disable')];
+ next.password=requireBoundSecret(saved.password,draft.password,identity(saved)===identity(next)&&strength(next)>=strength(saved),'database password');
+ return next;
+}
+export const sameEndpoint=(left,right)=>new URL(left).href.replace(/\/$/,'')===new URL(right).href.replace(/\/$/,'');
diff --git a/loadtest/console/server/connector-fixtures.mjs b/loadtest/console/server/connector-fixtures.mjs
new file mode 100644
index 0000000000..a32de819a9
--- /dev/null
+++ b/loadtest/console/server/connector-fixtures.mjs
@@ -0,0 +1,29 @@
+import {randomBytes,randomUUID,createCipheriv,createDecipheriv} from 'node:crypto';
+import {mkdirSync,readFileSync,writeFileSync} from 'node:fs';
+import path from 'node:path';
+import {normalizeConnectorPlan,connectorCatalog} from '../src/connector-config.mjs';
+// Account credentials are encrypted separately from scenario, job and run snapshots.
+export function connectorSecretStore(root){
+ const directory=path.join(root,'connector-secrets');mkdirSync(directory,{recursive:true,mode:0o700});
+ const keyfile=path.join(directory,'key');let key;
+ try{key=readFileSync(keyfile);}catch(e){if(e.code!=='ENOENT')throw e;try{writeFileSync(keyfile,randomBytes(32),{flag:'wx',mode:0o600});}catch(e){if(e.code!=='EEXIST')throw e;}key=readFileSync(keyfile);}
+ return {put(value){const ref=randomUUID(),iv=randomBytes(12),cipher=createCipheriv('aes-256-gcm',key,iv);const data=Buffer.concat([cipher.update(JSON.stringify(value),'utf8'),cipher.final()]);writeFileSync(path.join(directory,ref),JSON.stringify({iv:iv.toString('base64'),tag:cipher.getAuthTag().toString('base64'),data:data.toString('base64')}),{mode:0o600,flag:'wx'});return ref;},get(ref){if(!/^[a-f0-9-]{36}$/.test(ref))throw new Error('Invalid connector credential reference');const sealed=JSON.parse(readFileSync(path.join(directory,ref),'utf8')),cipher=createDecipheriv('aes-256-gcm',key,Buffer.from(sealed.iv,'base64'));cipher.setAuthTag(Buffer.from(sealed.tag,'base64'));return JSON.parse(Buffer.concat([cipher.update(Buffer.from(sealed.data,'base64')),cipher.final()]).toString());}};
+}
+export function provisionConnectorAccounts(plan,input={},root){
+ const normalized=normalizeConnectorPlan(plan),store=connectorSecretStore(root);
+ return normalized.mix.map(({connector})=>{
+ const definition=connectorCatalog.find(c=>c.id===connector),draft=input[connector]||{};
+ const details={auth_type:definition.authType};
+ for(const field of definition.fields){const value=draft.credentials?.[field.name]||(normalized.mode==='dummy'?'local-test':'');if(typeof value!=='string'||!value.trim()||value.length>16384)throw new Error(`Enter ${definition.label}: ${field.label}`);details[field.name]=value;}
+ if(!['HeaderKey','BodyKey','SignatureKey','MultiAuthKey','NoKey'].includes(details.auth_type))throw new Error(`Credential form for ${definition.label} is not supported yet`);
+ if(draft.metadata!=null&&(typeof draft.metadata!=='object'||Array.isArray(draft.metadata)))throw new Error('Connector metadata must be a JSON object');
+ const account={connector_name:connector,connector_account_details:details,connector_type:'payment_processor',test_mode:true,business_country:'US',business_label:'default',disabled:false,payment_methods_enabled:[{payment_method:'card',payment_method_types:[{payment_method_type:'credit',card_networks:definition.networks?.length?definition.networks:['Visa','Mastercard'],recurring_enabled:true}]}],metadata:draft.metadata||{}};
+ return {connector,credentialRef:store.put(account)};
+ });
+}
+export const resolveConnectorAccounts=(refs,root)=>refs?.map(row=>{
+ const account=connectorSecretStore(root).get(row.credentialRef);
+ // Earlier console accounts used a label absent from the fixture merchant.
+ // Repair those encrypted snapshots too, so interrupted fixtures can resume.
+ return account.business_label==='loadtest'?{...account,business_label:'default'}:account;
+});
diff --git a/loadtest/console/server/connector-results.mjs b/loadtest/console/server/connector-results.mjs
new file mode 100644
index 0000000000..d09b8621bc
--- /dev/null
+++ b/loadtest/console/server/connector-results.mjs
@@ -0,0 +1,19 @@
+import {DatabaseSync} from 'node:sqlite';
+import path from 'node:path';
+import {latencyPercentile} from './successful-latency.mjs';
+export function connectorResults(directory,plan){
+ const db=new DatabaseSync(path.join(directory,'results.sqlite'),{readOnly:true});
+ try{
+ const columns=db.prepare('PRAGMA table_info(request_events)').all().map(c=>c.name);
+ if(!columns.includes('requested_connector'))return null;
+ const assigned=db.prepare("SELECT requested_connector connector,COUNT(DISTINCT flow_id) assigned FROM request_events WHERE role='measured' AND requested_connector IS NOT NULL GROUP BY requested_connector").all();
+ const confirmed=db.prepare("SELECT connector,COUNT(*) confirmations,SUM(CASE WHEN api_status_code BETWEEN 200 AND 299 AND status IN ('succeeded','requires_capture','processing') THEN 1 ELSE 0 END) successes FROM request_events WHERE role='measured' AND operation='payment_confirm' GROUP BY connector").all();
+ const reportedTotal=confirmed.filter(r=>r.connector!=null).reduce((sum,r)=>sum+r.confirmations,0);
+ const names=[...new Set([...assigned.map(r=>r.connector),...confirmed.map(r=>r.connector).filter(Boolean)])];
+ return {rows:names.map(connector=>{
+ const a=assigned.find(r=>r.connector===connector),c=confirmed.find(r=>r.connector===connector);
+ const latencies=db.prepare("SELECT server_latency_ms,latency_ms FROM request_events WHERE role='measured' AND operation='payment_confirm' AND connector=? AND api_status_code BETWEEN 200 AND 299 AND status IN ('succeeded','requires_capture','processing')").all(connector);
+ return {connector,assigned:a?.assigned||0,targetPercent:plan?.mix?.find(r=>r.connector===connector)?.weight??null,observedPercent:reportedTotal?100*(c?.confirmations||0)/reportedTotal:0,confirmations:c?.confirmations||0,successes:c?.successes||0,failures:(c?.confirmations||0)-(c?.successes||0),hsP99:latencyPercentile(latencies.map(r=>r.server_latency_ms).filter(Number.isFinite),.99),fullP99:latencyPercentile(latencies.map(r=>r.latency_ms).filter(Number.isFinite),.99)};
+ }),unattributedConfirmations:confirmed.find(r=>r.connector==null)?.confirmations||0};
+ }finally{db.close();}
+}
diff --git a/loadtest/console/server/csv-stream.mjs b/loadtest/console/server/csv-stream.mjs
new file mode 100644
index 0000000000..223cedb083
--- /dev/null
+++ b/loadtest/console/server/csv-stream.mjs
@@ -0,0 +1,11 @@
+import {queryWorker} from './workers.mjs';
+export function csvCell(value){let text=String(value??'');if(/^[=+@\-\t\r]/.test(text))text="'"+text;return '"'+text.replaceAll('"','""')+'"';}
+// Read one bounded page per pull. Cancelling the download stops further queries.
+export function csvStream(task,args,columns){
+ let cursor={},started=false,done=false;const encoder=new TextEncoder();
+ return new ReadableStream({async pull(controller){if(done)return;try{if(!started){controller.enqueue(encoder.encode(columns.join(',')+'\r\n'));started=true;return;}
+ const page=await queryWorker(task,{...args,...cursor,limit:200});if(done)return;
+ controller.enqueue(encoder.encode(page.rows.map(row=>columns.map(c=>csvCell(row[c])).join(',')).join('\r\n')+(page.rows.length?'\r\n':'')));
+ if(page.next){cursor=typeof page.next==='number'?{after:page.next}:page.next;}else{done=true;controller.close();}
+ }catch(e){done=true;controller.error(e);}},cancel(){done=true;}});
+}
diff --git a/loadtest/console/server/database-availability.mjs b/loadtest/console/server/database-availability.mjs
new file mode 100644
index 0000000000..ddcefe0ba0
--- /dev/null
+++ b/loadtest/console/server/database-availability.mjs
@@ -0,0 +1,19 @@
+import {setTimeout as wait} from 'node:timers/promises';
+
+// Measure the configured SQL connection independently of the provider operation.
+// Poll sequentially: a slow probe must not overlap with the next one.
+export function watchDatabaseAvailability({check,onChange,onSample=(_current)=>{},initial='available',intervalMs=1000}){
+ const controller=new AbortController();let previous=initial;
+ const done=(async()=>{
+ while(!controller.signal.aborted){
+ let current;
+ try{current=(await check())?.ok===true?'available':'unavailable';}
+ catch{current='unavailable';}
+ if(controller.signal.aborted)break;
+ await onSample(current);
+ if(current!==previous){previous=current;onChange(current);}
+ try{await wait(intervalMs,undefined,{signal:controller.signal});}catch{break;}
+ }
+ })();
+ return {done,stop:async()=>{controller.abort();await done;}};
+}
diff --git a/loadtest/console/server/database-options.mjs b/loadtest/console/server/database-options.mjs
new file mode 100644
index 0000000000..9365270e7f
--- /dev/null
+++ b/loadtest/console/server/database-options.mjs
@@ -0,0 +1,34 @@
+import {readFileSync} from 'node:fs';
+import path from 'node:path';
+import {dataRoot} from './state.mjs';
+import {readImportedCertificate} from './certificates.mjs';
+
+/** Build a pg connection config without forwarding UI-only fields. */
+export function databaseConnectionOptions(database,{readCa=readFileSync,readCertificate=id=>readImportedCertificate(dataRoot,id)}={}){
+ const connection={host:database.host,port:Number(database.port),database:database.database,user:database.user,password:database.password};
+ const tlsMode=database.tlsMode || (database.ssl?'verify':'disable');
+ if(tlsMode==='disable')return {...connection,ssl:false};
+ if(tlsMode==='require')return {...connection,ssl:{rejectUnauthorized:false}};
+ if(tlsMode!=='verify')throw new Error('Database TLS mode must be disable, require, or verify');
+ if(database.caCertificateId){
+ let ca;try{ca=readCertificate(database.caCertificateId);}catch(e){throw new Error(`Cannot read imported database CA certificate: ${e.message}`);}
+ if(!String(ca).includes('-----BEGIN CERTIFICATE-----'))throw new Error('Imported database CA certificate is not PEM encoded');
+ return {...connection,ssl:{rejectUnauthorized:true,ca}};
+ }
+ const caPath=String(database.caPath || '').trim();
+ if(!caPath)return {...connection,ssl:{rejectUnauthorized:true}};
+ if(!path.isAbsolute(caPath))throw new Error('Database CA certificate path must be absolute');
+ let ca;
+ try{ca=readCa(caPath,'utf8');}catch(e){throw new Error(`Cannot read database CA certificate: ${e.message}`);}
+ if(!String(ca).includes('-----BEGIN CERTIFICATE-----'))throw new Error('Database CA certificate is not PEM encoded');
+ return {...connection,ssl:{rejectUnauthorized:true,ca}};
+}
+
+export function databaseConnectionError(error,database={}){
+ if(['DEPTH_ZERO_SELF_SIGNED_CERT','SELF_SIGNED_CERT_IN_CHAIN','UNABLE_TO_VERIFY_LEAF_SIGNATURE','UNABLE_TO_GET_ISSUER_CERT_LOCALLY'].includes(error.code))return database.caCertificateId||database.caPath?'The selected CA does not trust the current database certificate. For managed database failover, use a provider-supported database proxy to handle certificate rotation.':'Database certificate is not trusted. Select its CA under Custom CA certificate.';
+ if(error.code==='ERR_TLS_CERT_ALTNAME_INVALID')return 'Database host does not match its certificate. Check the Host field.';
+ if(error.code==='CERT_HAS_EXPIRED')return 'Database certificate has expired. Update the server certificate and its CA.';
+ if(error.code==='28P01')return 'Database authentication failed. Check the username and password.';
+ if(error.code==='42501')return 'This database account needs read access to payment_intent.';
+ return `Database connection failed: ${error.message}`;
+}
diff --git a/loadtest/console/server/database-recovery-gate.mjs b/loadtest/console/server/database-recovery-gate.mjs
new file mode 100644
index 0000000000..d99db7f9a8
--- /dev/null
+++ b/loadtest/console/server/database-recovery-gate.mjs
@@ -0,0 +1,12 @@
+// SQL recovery releases traffic independently of the provider operation.
+// Do not release on an initial successful probe before failover takes effect.
+export function databaseRecoveryGate(entry,release) {
+ let pending=null;
+ return async current=>{
+ if(current==='unavailable')entry.databaseOutageObserved=true;
+ if(current!=='available'||!entry.databaseOutageObserved||entry.status!=='restoring'||entry.loadReleased)return;
+ if(pending)return pending;
+ pending=(async()=>{if(await release())entry.loadReleased=true;})();
+ try{await pending;}finally{pending=null;}
+ };
+}
diff --git a/loadtest/console/server/default-scenarios.mjs b/loadtest/console/server/default-scenarios.mjs
new file mode 100644
index 0000000000..48de65f33e
--- /dev/null
+++ b/loadtest/console/server/default-scenarios.mjs
@@ -0,0 +1,35 @@
+import {defaultCriteria} from './acceptance.mjs';
+import {loadShape} from '../src/load-shape.mjs';
+
+const definitions=[
+ {key:'card-vault-outage',name:'Card vault outage',service:'card-vault',action:'outage'},
+ {key:'db-failover',name:'DB failover',service:'postgres',action:'failover',environment:'gcp'},
+ {key:'steady-load',name:'Steady load'},
+ {key:'ramped-load',name:'Ramped load',ramped:true},
+ {key:'tenancy-steady-load',name:'Tenancy steady load',mode:'tenancy',merchantCount:100}
+];
+export const isDefaultScenario=id=>definitions.some(d=>id===`default:${d.key}`);
+
+// Built-ins are versioned definitions, never user-owned database rows. Target
+// identities are resolved from the selected environment and snapshotted at launch.
+export function defaultScenarios(environment,targets=[]){
+ return definitions.map(definition=>{
+ const target=targets.find(t=>t.serviceType===definition.service&&t.environment===environment&&t.adapter!=='simulated'&&t.actions?.includes(definition.action));
+ const unavailableReason=definition.environment&&environment!==definition.environment?'Requires GCP database failover.':!['local','gcp'].includes(environment)?'Provider execution is not available.':definition.service&&!target?`Configure a ${definition.service==='postgres'?'PostgreSQL':'card vault'} ${definition.action} fault target for this environment.`:null;
+ const stages=definition.service?[
+ {target_rps:5,duration_seconds:60},
+ {target_rps:5,duration_seconds:30,fault:{targetId:target?.id||definition.service,action:definition.action}},
+ {target_rps:5,duration_seconds:210}
+ ]:definition.ramped?[
+ {target_rps:5,duration_seconds:60},{target_rps:10,duration_seconds:60},
+ {target_rps:10,duration_seconds:60},{target_rps:5,duration_seconds:60},{target_rps:5,duration_seconds:60}
+ ]:null;
+ const load=stages?{start_rps:5,stages}:{total_rps:5,duration_seconds:300};
+ const shape=loadShape(load);
+ return {id:`default:${definition.key}`,version:definition.ramped?3:2,name:definition.name,isDefault:true,archived:false,unavailableReason,mode:definition.mode||'single',merchantCount:definition.merchantCount||1,totalRps:shape.peak,durationSeconds:shape.duration,loadShape:stages?'staged':'flat',startRps:5,stagesJson:JSON.stringify(stages||[]),load,acceptance:{...defaultCriteria},preAllocatedVusMultiplier:3,maxVusMultiplier:10,scenarios:[
+ {name:'cit_off_session',scenario:'cit_off_session',merchant_path:'modular',weight:50},
+ {name:'sdk_checkout',scenario:'sdk_checkout',merchant_path:'modular',weight:30},
+ {name:'guest',scenario:'guest',merchant_path:'modular',weight:20}
+ ]};
+ });
+}
diff --git a/loadtest/console/server/display-errors.mjs b/loadtest/console/server/display-errors.mjs
new file mode 100644
index 0000000000..df1c7d96d6
--- /dev/null
+++ b/loadtest/console/server/display-errors.mjs
@@ -0,0 +1,64 @@
+import {DatabaseSync} from 'node:sqlite';
+import path from 'node:path';
+
+// Presentation only: keep recordings and acceptance counters untouched.
+export function faultWindows(events,config={}) {
+ const labels=new Set(['Card vault',...(config.faultPlan||[]).filter(f=>f.target?.serviceType==='card-vault'||f.target?.id==='card-vault').map(f=>f.target.label)]);
+ const vault=[],database=[];let vaultStart=null,databaseStart=null;
+ for(const event of [...events].sort((a,b)=>a.at-b.at)) {
+ const isVault=[...labels].some(label=>label&&(event.message?.startsWith(`${label} ·`)||event.message?.includes(` · ${label} ·`)));
+ if(isVault&&event.kind==='fault_started')vaultStart=event.at;
+ if(isVault&&event.kind==='fault_restored'&&vaultStart!==null){vault.push([vaultStart,event.at]);vaultStart=null;}
+ if(event.kind==='database_unavailable')databaseStart??=event.at;
+ if(event.kind==='database_available'&&databaseStart!==null){database.push([databaseStart,event.at]);databaseStart=null;}
+ }
+ if(vaultStart!==null)vault.push([vaultStart,Infinity]);
+ if(databaseStart!==null)database.push([databaseStart,Infinity]);
+ return {vault,database};
+}
+export function hiddenVaultError(row,windows) {
+ const end=Number(row.observed_at),start=end-(Number(row.latency_ms)||0);
+ const overlaps=([from,to])=>start<to&&end>=from;
+ if(!windows.vault.some(overlaps)||windows.database.some(overlaps))return false;
+ return row.api_status_code>=500||
+ (row.api_status_code===0&&row.operation==='pm_session_confirm'&&row.latency_ms>=29500&&row.latency_ms<=31000&&/request timeout/i.test(row.message||''));
+}
+
+// Read new failed attempts only, instead of rescanning a live recording on each SSE tick.
+const failures=new Map();
+export function displayErrorCounts(directory,events=[],config={},until=Infinity,since=-Infinity) {
+ if(!directory)return null;
+ let db;
+ try {
+ db=new DatabaseSync(path.join(directory,'results.sqlite'),{readOnly:true});
+ db.exec('BEGIN');
+ const run=db.prepare('SELECT run_id,started_at FROM runs ORDER BY started_at DESC LIMIT 1').get();
+ if(!run)return null;
+ let entry=failures.get(directory);
+ if(!entry||entry.runId!==run.run_id){entry={runId:run.run_id,last:0,attempts:0,rows:[]};failures.set(directory,entry);if(failures.size>8)failures.delete(failures.keys().next().value);}
+ const latest=db.prepare("SELECT COALESCE(MAX(event_id),0) AS id FROM request_events").get().id;
+ const rows=db.prepare("SELECT event_id,observed_at,latency_ms,operation,api_status_code,message FROM request_events WHERE event_id>? AND event_id<=? AND run_id=? AND role='measured' AND (api_status_code=0 OR api_status_code>=400) ORDER BY event_id").all(entry.last,latest,run.run_id);
+ const newAttempts=db.prepare("SELECT COUNT(*) AS n FROM request_events WHERE event_id>? AND event_id<=? AND run_id=? AND role='measured'").get(entry.last,latest,run.run_id).n;
+ const intervalAttempts=since===-Infinity&&until===Infinity?entry.attempts+newAttempts:db.prepare("SELECT COUNT(*) AS n FROM request_events WHERE event_id<=? AND run_id=? AND role='measured' AND observed_at>? AND observed_at<=?").get(latest,run.run_id,since,until).n;
+ entry.rows.push(...rows);entry.attempts+=newAttempts;entry.last=latest;db.exec('COMMIT');
+ const windows=faultWindows(events,config);let hidden=0,intervalHidden=0,errors=0,intervalErrors=0;
+ for(const row of entry.rows){
+ const filtered=hiddenVaultError(row,windows);
+ if(filtered)hidden++;else errors++;
+ if(row.observed_at>since&&row.observed_at<=until){if(filtered)intervalHidden++;else intervalErrors++;}
+ }
+ return {hidden,intervalHidden,errors,intervalErrors,attempts:entry.attempts,intervalAttempts,startedAt:Number(run.started_at)};
+ }catch{return null;}finally{db?.close();}
+}
+export function decorateDisplayErrors(progress,directory,events,config,startedAt) {
+ const t=progress.elapsed_seconds;
+ // Never subtract a persisted counter from an asynchronous k6 counter: one
+ // can lead the other and briefly expose a timeout that is already filtered.
+ let counts=displayErrorCounts(directory,events,config);
+ if(counts&&progress.trend)counts=displayErrorCounts(directory,events,config,counts.startedAt+t*1000,counts.startedAt+(progress.trend.intervalStart||0)*1000);
+ const attempts=counts?.attempts??(Number(progress.http_attempts)||0);
+ const next={...progress,display_http_errors:counts?.errors??(Number(progress.http_errors)||0),hidden_vault_errors:counts?.hidden||0};
+ if(progress.trend){const trend=progress.trend,intervalAttempts=counts?.intervalAttempts??trend.intervalAttempts,intervalErrors=counts?.intervalErrors??trend.intervalErrors;next.trend={...trend,errorScope:'all_http_except_vault',errors:intervalAttempts?100*intervalErrors/intervalAttempts:0};}
+ next.display_error_rate=attempts?Number((100*next.display_http_errors/attempts).toFixed(2)):0;
+ return next;
+}
diff --git a/loadtest/console/server/distributed-runner.mjs b/loadtest/console/server/distributed-runner.mjs
new file mode 100644
index 0000000000..7f54a998eb
--- /dev/null
+++ b/loadtest/console/server/distributed-runner.mjs
@@ -0,0 +1,108 @@
+import path from 'node:path';
+import {controlDb} from './state.mjs';
+import {listWorkers,queueWorkerCommand} from './worker-registry.mjs';
+import {planWorkerShards,reserveRunShards} from './distributed.mjs';
+import {createWorkerBundle,artifactPath} from './worker-artifacts.mjs';
+import {mergeWorkerShards} from './merge-shards.mjs';
+
+const parsed=value=>{try{return JSON.parse(value||'{}');}catch{return {};}};
+const workerOfflineAfterMs=Number(process.env.LOADTEST_WORKER_OFFLINE_AFTER_MS||15000);
+const workerPrepareTimeoutMs=Number(process.env.LOADTEST_WORKER_PREPARE_TIMEOUT_MS||120000);
+export function aggregate(shards,{wallElapsedSeconds=null}={}){
+ const progress=shards.map(shard=>parsed(shard.progress)),active=progress.map(p=>Number(p.control?.active_seconds??p.elapsed_seconds??0));
+ const wall=progress.map(p=>Number(p.elapsed_seconds||0));
+ const result={elapsed_seconds:wallElapsedSeconds??(wall.length?Math.min(...wall):0),iterations:0,successful_tps:0,http_attempts:0,http_errors:0,dropped:0,recorder:{enqueued:0,persisted:0},flows:{},connectors:{},control:{state:shards.every(s=>s.status==='paused')?'paused':shards.some(s=>['pausing','draining'].includes(s.status))?'pausing':shards.every(s=>s.status==='ready')?'idle':'running',active_seconds:active.length?Math.min(...active):0,in_flight:0}};
+ for(const point of progress){result.iterations+=Number(point.iterations||0);result.successful_tps+=Number(point.successful_tps||0);result.http_attempts+=Number(point.http_attempts||0);result.http_errors+=Number(point.http_errors||0);result.dropped+=Number(point.dropped||0);result.recorder.enqueued+=Number(point.recorder?.enqueued||0);result.recorder.persisted+=Number(point.recorder?.persisted||0);result.control.in_flight+=Number(point.control?.in_flight||0);for(const [name,flow] of Object.entries(point.flows||{})){const target=result.flows[name]||={successes:0,failures:0,tps:0,p90_ms:null,p99_ms:null};target.successes+=Number(flow.successes||0);target.failures+=Number(flow.failures||0);target.tps+=Number(flow.tps||0);target.p90_ms=Math.max(target.p90_ms||0,Number(flow.p90_ms||0))||null;target.p99_ms=Math.max(target.p99_ms||0,Number(flow.p99_ms||0))||null;}}
+ for(const point of progress)for(const [name,c] of Object.entries(point.connectors||{})){const target=result.connectors[name]||={assigned:0,confirmed:0,successes:0};for(const key of ['assigned','confirmed','successes'])target[key]+=Number(c[key]||0);}
+ if(progress.length&&progress.every(p=>Number.isFinite(p.control?.started_flows))){
+ result.control.started_flows=progress.reduce((sum,p)=>sum+p.control.started_flows,0);
+ result.control.flow_starts={};for(const p of progress)for(const [name,count] of Object.entries(p.control.flow_starts||{}))result.control.flow_starts[name]=(result.control.flow_starts[name]||0)+count;
+ }
+ if(progress.length&&progress.every(p=>Number.isFinite(p.confirm_http_attempts)&&Number.isFinite(p.confirm_http_errors))){result.confirm_http_attempts=progress.reduce((sum,p)=>sum+p.confirm_http_attempts,0);result.confirm_http_errors=progress.reduce((sum,p)=>sum+p.confirm_http_errors,0);}
+ const percentile=values=>{const finite=values.filter(v=>Number.isFinite(v)&&v>=0).sort((a,b)=>a-b);return finite.length?finite[Math.floor((finite.length-1)*.99)]:null;};
+ result.server_p99_ms=percentile(progress.flatMap(p=>p.server_samples_ms||[]));
+ for(const [name,flow] of Object.entries(result.flows))flow.server_p99_ms=percentile(progress.flatMap(p=>p.flows?.[name]?.server_samples_ms||[]));
+ return result;
+}
+export async function launchDistributedRun({runId,runPath,config,fixturePath,onProgress=(..._args)=>{},onEvent=(..._args)=>{},onDone=(..._args)=>{}}){
+ const requiredVus=Math.ceil(Number(config.load.max_vus_multiplier||10)*(config.load.total_rps??Math.max(...config.load.stages.map(stage=>stage.target_rps)))),workers=listWorkers().filter(worker=>worker.id!=='local'),totalTps=config.load.total_rps??Math.max(...config.load.stages.map(stage=>stage.target_rps));
+ const plan=planWorkerShards(totalTps,requiredVus,workers),bundles=[];
+ for(const shard of plan)bundles.push(await createWorkerBundle({runId,config,fixturePath,workerId:shard.workerId,segmentStart:shard.segmentStart,segmentEnd:shard.segmentEnd}));
+ reserveRunShards(runId,plan,bundles.map(bundle=>({bundleId:bundle.id,sha256:bundle.sha256,totalTps})));
+ let phase='preparing',settled=false,timer,stopStarted=0,failure=null,wallStartedAt=null;
+ const prepareStarted=Date.now(),stopTimeoutMs=Number(process.env.LOADTEST_WORKER_STOP_TIMEOUT_MS||60000);
+ const shardsNow=()=>controlDb().prepare('SELECT s.*,w.last_seen FROM run_shards s JOIN load_workers w ON w.id=s.worker_id WHERE s.run_id=? ORDER BY s.id').all(runId);
+ function stop(error=null){
+ if(settled||phase==='stopping')return;
+ failure=error;phase='stopping';stopStarted=Date.now();
+ // A prepared-but-not-started worker must not receive a stale start after Stop.
+ controlDb().prepare("UPDATE worker_commands SET status='cancelled',acked_at=? WHERE run_id=? AND status='pending'").run(stopStarted,runId);
+ for(const shard of shardsNow())if(shard.status!=='complete')queueWorkerCommand(shard.worker_id,{runId,kind:'stop'});
+ onEvent('draining_workers',error?'A worker failed · stopping all load workers':'Stopping all load workers');
+ }
+ let resolveDone;
+ const done=new Promise(resolve=>{resolveDone=resolve;});
+ async function finish(error,result){
+ if(settled)return;settled=true;clearTimeout(timer);
+ try{await onDone(error,result);}finally{resolveDone();}
+ }
+ async function poll(){
+ if(settled)return;
+ try{
+ const db=controlDb(),shards=shardsNow(),now=Date.now();
+ for(const shard of shards){
+ if(!['complete','failed'].includes(shard.status)&&now-Number(shard.last_seen)>workerOfflineAfterMs){shard.status='failed';shard.error='Worker heartbeat timed out';db.prepare("UPDATE run_shards SET status='failed',error=?,updated_at=? WHERE id=?").run(shard.error,now,shard.id);}
+ else if(phase==='preparing'&&!['ready','complete','failed'].includes(shard.status)&&now-prepareStarted>workerPrepareTimeoutMs){shard.status='failed';shard.error='Worker preparation timed out';db.prepare("UPDATE run_shards SET status='failed',error=?,updated_at=? WHERE id=?").run(shard.error,now,shard.id);}
+ }
+ // Counter updates from different workers must share the coordinator's
+ // wall interval. A minimum worker clock can advance only microseconds
+ // while another worker contributes a full second of completed flows.
+ const reportedWall=Math.max(0,...shards.map(s=>Number(parsed(s.progress).elapsed_seconds||0)));
+ if(wallStartedAt===null&&reportedWall>0)wallStartedAt=now-reportedWall*1000;
+ const progress=aggregate(shards,{wallElapsedSeconds:wallStartedAt===null?0:Math.max(0,(now-wallStartedAt)/1000)});await onProgress(progress,shards);
+ if(phase!=='stopping'&&shards.some(s=>s.status==='failed'))stop(new Error(shards.find(s=>s.error)?.error||'A load worker failed'));
+ if(phase==='stopping'){
+ const drained=shards.every(s=>{
+ if(!['complete','failed'].includes(s.status))return false;
+ // An offline worker enforces a local 30s control-plane lease. Give it
+ // time to stop instead of treating a missed heartbeat as a stopped load.
+ return s.error!=='Worker heartbeat timed out'||now-Number(s.last_seen)>=45000;
+ });
+ if(drained){await finish(failure,{...progress,exitCode:failure?1:0});return;}
+ if(now-stopStarted>=stopTimeoutMs){
+ db.prepare("UPDATE run_shards SET status='failed',error=COALESCE(error,'Worker stop was not verified'),updated_at=? WHERE run_id=? AND status NOT IN ('complete','failed')").run(now,runId);
+ await finish(new Error('Worker stop was not verified before the drain timeout'),{...progress,exitCode:1});return;
+ }
+ }else if(phase==='preparing'&&shards.every(s=>s.status==='ready')){
+ const startAt=Date.now()+3000;for(const shard of shards)queueWorkerCommand(shard.worker_id,{runId,kind:'start',payload:{startAt}});
+ phase='running';onEvent('workers_ready',`${shards.length} workers ready · synchronized start scheduled`);
+ }else if(phase==='running'&&shards.every(s=>s.status==='complete')){
+ phase='merging';onEvent('merging','All workers complete · merging result shards');
+ const artifacts=shards.map(shard=>({workerId:shard.worker_id,database:artifactPath(runId,shard.worker_id,'results.sqlite'),summary:artifactPath(runId,shard.worker_id,'summary.json')}));
+ const merged=await mergeWorkerShards({runPath,runId,shards:artifacts,config}),exitCode=shards.some(s=>Number(parsed(s.progress).exitCode)===99)?99:0;
+ await finish(null,{...progress,merged,exitCode});return;
+ }
+ }catch(error){
+ if(settled)return;
+ if(phase==='stopping'){failure||=error;if(Date.now()-stopStarted>=stopTimeoutMs){await finish(failure,{});return;}}
+ else stop(error);
+ }
+ if(!settled)timer=setTimeout(poll,1000);
+ }
+ await poll();
+ return {plan,done,async control(action,payload={}){
+ if(settled||phase==='stopping')throw new Error('Run is stopping or finished');
+ const shards=shardsNow(),effectiveAt=['pause','resume'].includes(action)?Date.now()+3000:Date.now();
+ const commands=shards.map(shard=>queueWorkerCommand(shard.worker_id,{runId,kind:action,payload:{effectiveAt,...payload}}));onEvent(action,`${action[0].toUpperCase()+action.slice(1)} scheduled on ${shards.length} workers`);
+ if(['gate','release','recover'].includes(action)){
+ const deadline=Date.now()+15000;
+ for(;;){
+ const states=commands.map(command=>controlDb().prepare('SELECT status,result FROM worker_commands WHERE id=?').get(command.id));
+ const failed=states.find(state=>state?.status==='failed');if(failed)throw new Error(parsed(failed.result).error||`${action} failed on a load worker`);
+ if(states.every(state=>state?.status==='acknowledged'))break;
+ if(Date.now()>=deadline||phase==='stopping')throw new Error(`Workers did not acknowledge ${action} in time`);
+ await new Promise(resolve=>setTimeout(resolve,100));
+ }
+ }
+ },cancel(){stop();},get phase(){return phase;}};
+}
diff --git a/loadtest/console/server/distributed.mjs b/loadtest/console/server/distributed.mjs
new file mode 100644
index 0000000000..a6744e3612
--- /dev/null
+++ b/loadtest/console/server/distributed.mjs
@@ -0,0 +1,35 @@
+import {controlDb} from './state.mjs';
+import {queueWorkerCommand} from './worker-registry.mjs';
+
+export function planWorkerShards(totalTps,requiredVus,workers,{now=Date.now()}={}){
+ totalTps=Number(totalTps);requiredVus=Number(requiredVus);
+ if(!Number.isFinite(totalTps)||totalTps<=0||!Number.isFinite(requiredVus)||requiredVus<=0)throw new Error('Load capacity must be positive');
+ const vusPerTps=requiredVus/totalTps,available=workers.filter(worker=>worker.status==='idle'&&now-Number(worker.lastSeen??worker.last_seen??0)<=15000)
+ .map(worker=>{const capacityTps=Number(worker.capacityTps??worker.capacity_tps),capacityVus=Number(worker.capacityVus??worker.capacity_vus);return {...worker,capacityTps,capacityVus,effectiveTps:Math.floor(Math.min(capacityTps,capacityVus/vusPerTps))};})
+ .filter(worker=>worker.effectiveTps>0)
+ .sort((a,b)=>b.effectiveTps-a.effectiveTps||String(a.id).localeCompare(String(b.id)));
+ const selected=[];let tps=0,vus=0;
+ for(const worker of available){selected.push(worker);tps+=worker.effectiveTps;vus+=worker.capacityVus;if(tps>=totalTps&&vus>=requiredVus)break;}
+ if(tps<totalTps||vus<requiredVus)throw new Error(`Insufficient worker capacity: ${tps}/${totalTps} TPS and ${vus}/${requiredVus} VUs available`);
+ // Divide by TPS capacity while capping the last worker so the sum is exact.
+ let remaining=totalTps,start=0;
+ return selected.map((worker,index)=>{
+ const laterCapacity=selected.slice(index+1).reduce((sum,w)=>sum+w.effectiveTps,0);
+ const workersLeft=selected.length-index,share=Math.min(worker.effectiveTps,Math.max(remaining-laterCapacity,Math.min(remaining,Math.max(1,Math.round(remaining/workersLeft)))));
+ const end=Math.min(1,start+share/totalTps),shard={workerId:worker.id,workerName:worker.name,offeredTps:share,requiredVus:Math.ceil(requiredVus*share/totalTps),segmentStart:start,segmentEnd:index===selected.length-1?1:end};
+ remaining-=share;start=shard.segmentEnd;return shard;
+ });
+}
+
+export function reserveRunShards(runId,plan,payload={}){
+ const db=controlDb(),now=Date.now();
+ const insert=db.prepare("INSERT INTO run_shards(id,run_id,worker_id,status,offered_tps,segment_start,segment_end,updated_at) VALUES(?,?,?,'reserved',?,?,?,?)");
+ db.exec('BEGIN IMMEDIATE');
+ try{const result=plan.map((shard,index)=>{
+ const id=`${runId}:${index+1}`;insert.run(id,runId,shard.workerId,shard.offeredTps,shard.segmentStart,shard.segmentEnd,now);
+ const common=Array.isArray(payload)?payload[index]:payload;
+ const command=queueWorkerCommand(shard.workerId,{runId,kind:'prepare',payload:{...common,shardId:id,offeredTps:shard.offeredTps,requiredVus:shard.requiredVus,segment:{start:shard.segmentStart,end:shard.segmentEnd}}});
+ return {...shard,id,command};
+ });db.exec('COMMIT');return result;
+ }catch(error){db.exec('ROLLBACK');throw error;}
+}
diff --git a/loadtest/console/server/errors.mjs b/loadtest/console/server/errors.mjs
new file mode 100644
index 0000000000..ed1f34f213
--- /dev/null
+++ b/loadtest/console/server/errors.mjs
@@ -0,0 +1,3 @@
+export class HttpError extends Error {
+ constructor(status,message){super(message);this.status=status;}
+}
diff --git a/loadtest/console/server/execution-clock.mjs b/loadtest/console/server/execution-clock.mjs
new file mode 100644
index 0000000000..e4d761b57a
--- /dev/null
+++ b/loadtest/console/server/execution-clock.mjs
@@ -0,0 +1,33 @@
+import {loadTimeline} from '../src/load-shape.mjs';
+
+// Preserve the wall/active clock separately from compacted chart samples. A
+// plateau is a pause or recovery gate, not an extension of configured load time.
+export function executionSample(progress,load,at=Date.now()){
+ const active=progress.control?.active_seconds;
+ if(!Number.isFinite(active))return null;
+ const stages=loadTimeline(load),stage=stages.find(s=>active>=s.start&&active<s.end);
+ return {at,active,stageIndex:stage?.index??null,state:progress.control.state};
+}
+export function executionClock(samples,recording){
+ const start=Number(recording.started_at),end=Number(recording.ended_at)||Date.now();
+ const points=samples.filter(p=>Number.isFinite(p.at)&&Number.isFinite(p.active)).sort((a,b)=>a.at-b.at);
+ // Older runs retain wall time and active time in their telemetry.
+ if(!points.length)return null;
+ const first=points[0];
+ if(first.active>0)points.unshift({at:Math.max(start,first.at-first.active*1000),active:0});
+ const intervals=[];
+ for(let i=1;i<points.length;i++){
+ const a=points[i-1],b=points[i];
+ if(b.at>a.at&&a.at<end&&b.active>a.active)intervals.push({from:a.at,to:Math.min(end,b.at),activeFrom:a.active,activeTo:b.active});
+ }
+ return {points,intervals,end,active:points.at(-1).active};
+}
+export function stageIntervals(clock,stage){
+ if(!clock)return [];
+ return clock.intervals.flatMap(p=>{
+ const from=Math.max(stage.start,p.activeFrom),to=Math.min(stage.end,p.activeTo);
+ if(to<=from)return [];
+ const wall=a=>p.from+(a-p.activeFrom)/(p.activeTo-p.activeFrom)*(p.to-p.from);
+ return [{from:wall(from),to:wall(to),activeFrom:from,activeTo:to}];
+ });
+}
diff --git a/loadtest/console/server/fault-plan.mjs b/loadtest/console/server/fault-plan.mjs
new file mode 100644
index 0000000000..00bc847b9a
--- /dev/null
+++ b/loadtest/console/server/fault-plan.mjs
@@ -0,0 +1,40 @@
+import {validateCommandTarget} from './command-faults.mjs';
+import {validateTargetProvider} from '../src/environments.mjs';
+import {faultType} from '../src/fault-types.mjs';
+// Resolved once before launch; target edits cannot redirect a running scenario.
+export function snapshotFaultPlan(load,targets){
+ let at=0;const plan=[];
+ for(const [index,stage] of (load.stages || []).entries()){
+ if(stage.fault){const target=targets.find(t=>t.id===stage.fault.targetId);
+ if(!target)throw Error(`Timeline stage ${index+1}: fault target “${stage.fault.targetId}” is no longer configured`);
+ const action=target.actions.includes(stage.fault.action)?stage.fault.action:target.actions.length===1&&stage.fault.action==='restart'?target.actions[0]:null;
+ if(!action)throw Error(`Timeline stage ${index+1}: ${target.label} does not support “${stage.fault.action}”; choose ${target.actions.join(' or ')}`);
+ validateTargetProvider(target,faultType(target));
+ if(target.adapter==='command')validateCommandTarget(target);
+ plan.push({index,at,end:at+stage.duration_seconds,target:structuredClone(target),action,durationSeconds:stage.duration_seconds});
+ }at+=stage.duration_seconds;
+ }return plan;
+}
+export function faultScheduler(plan,{claim,fire,event,gate=async()=>{},release=async()=>{},recover=release}){
+ let busy=false;
+ return async(job,seconds)=>{
+ if(busy||job.loadState!=='running'||!Number.isFinite(seconds))return;
+ busy=true;
+ try{for(const step of plan){
+ if(seconds<step.at||!claim(step.index))continue;
+ if(seconds>=step.end){event('fault_error',`Step ${step.index+1}: missed fault window; no infrastructure changed`);continue;}
+ try{
+ await gate();
+ await fire(job,{targetId:step.target.id,action:step.action,durationSeconds:step.durationSeconds,confirm:`${step.action} ${step.target.id}`},step.target,{
+ // Keep the fault stage active until recovery is verified. The controller
+ // automatically re-enters the gate at its configured end boundary.
+ onStarted:()=>release(step.end),
+ onRestore:gate,
+ onRecovered:recover,
+ onAborted:()=>recover(step.end)
+ });
+ }
+ catch(e){await recover().catch(()=>{});event('fault_error',`Step ${step.index+1}: ${e.message}`);}
+ }}finally{busy=false;}
+ };
+}
diff --git a/loadtest/console/server/faults.mjs b/loadtest/console/server/faults.mjs
new file mode 100644
index 0000000000..8501a4e24b
--- /dev/null
+++ b/loadtest/console/server/faults.mjs
@@ -0,0 +1,214 @@
+import {validateCommandTarget,commandFaultAdapter} from './command-faults.mjs';
+import {isDeepStrictEqual} from 'node:util';
+import {targetEnvironment,validateTargetProvider,environmentLabel,requireSupportedEnvironment,faultCapabilities} from '../src/environments.mjs';
+import {randomUUID} from 'node:crypto';
+import {execFile} from 'node:child_process';
+import {promisify} from 'node:util';
+import {readFile,open,rename,mkdir} from 'node:fs/promises';
+import path from 'node:path';
+import {dataRoot,readJson,readJsonSync,redact,controlDb,localSettings,activeEnvironment} from './state.mjs';
+import {faultType,faultEnvironment} from '../src/fault-types.mjs';
+import {kubernetesAdapter} from './kubernetes-faults.mjs';
+import {localAdapter,processComposeController} from './local-faults.mjs';
+import {atomicJson} from './state.mjs';
+import {HttpError} from './errors.mjs';
+import {queryWorker} from './workers.mjs';
+import {watchDatabaseAvailability} from './database-availability.mjs';
+import {databaseRecoveryGate} from './database-recovery-gate.mjs';
+const exec=promisify(execFile),key=Symbol.for('hyperswitch.loadtest.faults');
+const state=globalThis[key] ||= {active:null,recovery:null,blocked:false};
+function emitSafely(emit,...args){try{emit?.(...args);}catch{console.error('Fault activity storage unavailable; recovery continues');}}
+const ledgerPath=path.join(dataRoot,'fault-ledger.json');
+const word=(value)=>{if(typeof value!=='string'||!value.match(/^[A-Za-z0-9][A-Za-z0-9_.:-]{0,180}$/))throw new Error('Invalid fault target name');return value;};
+export function validateTargets(targets,{allowLegacyDuplicates=false}={}){
+ if(!Array.isArray(targets)||targets.length>20)throw new Error('Choose at most 20 fault targets');
+ const ids=new Set(),types=new Set();return targets.map(t=>{
+ if(t.environment&&!['local','gcp','aws','azure','cloud','custom','unassigned'].includes(t.environment))throw new Error('Choose Local, Cloud or Custom');
+ word(t.id);if(ids.has(t.id))throw new Error('Duplicate fault target');ids.add(t.id);
+ if(!['command','simulated','docker','kubernetes','gcp-redis','gcp-alloydb','local-vault','process-compose','placeholder'].includes(t.adapter))throw new Error('Unsupported fault adapter');
+ if(t.adapter==='command')validateCommandTarget(t,{requireEnabled:false});
+ const fields=t.adapter==='docker'?['container']:t.adapter==='kubernetes'?['namespace','deployment',...(t.context?['context']:[])]:t.adapter.startsWith('gcp-')?['project','region','instance',...(t.adapter==='gcp-alloydb'?['cluster']:[])]:[];
+ for(const field of fields)word(t[field]);
+ if(t.outageMode!==undefined&&!['hard','graceful'].includes(t.outageMode))throw new Error('Invalid outage mode');
+ if(t.adapter==='kubernetes'&&t.recoveryReplicas!==undefined&&(!Number.isInteger(t.recoveryReplicas)||t.recoveryReplicas<1||t.recoveryReplicas>100))throw new Error('Recovery replicas must be 1–100');
+ if(['local-vault','process-compose'].includes(t.adapter)){if(!Number.isInteger(t.port)||t.port<1||t.port>65535)throw new Error('Invalid service port');if(t.adapter==='local-vault'){if(typeof t.repository!=='string'||!path.isAbsolute(t.repository))throw new Error('Use an absolute vault repository path');}else{word(t.process);if(typeof t.binary!=='string'||!(t.binary==='process-compose'||(path.isAbsolute(t.binary)&&path.basename(t.binary)==='process-compose')))throw new Error('Use process-compose or its absolute binary path');if(!Number.isInteger(t.controllerPort)||t.controllerPort<1||t.controllerPort>65535)throw new Error('Invalid controller port');}}
+ const serviceType=faultType(t);if((t.adapter==='gcp-alloydb'&&serviceType!=='postgres')||(t.adapter==='gcp-redis'&&serviceType!=='redis'))throw new Error('Cloud adapter does not match service type');if(serviceType){if(!['card-vault','postgres','redis'].includes(serviceType)||(t.adapter==='process-compose'&&serviceType==='card-vault')||(t.adapter==='local-vault'&&t.serviceType&&t.serviceType!=='card-vault'))throw new Error('Invalid fault service type');if(types.has(serviceType)&&!allowLegacyDuplicates)throw new Error(`Only one ${serviceType} fault target is allowed`);types.add(serviceType);}
+ return {...t,...(t.adapter==='kubernetes'?{outageMode:t.outageMode??(serviceType==='card-vault'?'hard':'graceful')}:{}),environment:targetEnvironment(t)||'unassigned',...(serviceType?{serviceType}:{}),label:String(t.label||t.id).slice(0,100),actions:t.adapter==='command'?[t.commandAction]:faultCapabilities[targetEnvironment(t)]?.[serviceType]?.actions||(t.adapter==='placeholder'?[]:['outage'])};
+ });
+}
+const targetsPath=path.join(dataRoot,'local-fault-targets.json');
+function storedFaultTargets(){
+ const saved=controlDb().prepare("SELECT value FROM console_preferences WHERE key='fault-targets'").get();const raw=saved?JSON.parse(saved.value):readJsonSync(targetsPath,[]),seen=new Set();
+ return raw.flatMap(target=>{const {presets={},...current}=target;return [current,...Object.entries(presets).filter(([key])=>['local','cloud','gcp','aws','azure'].includes(key)).map(([environment,preset])=>{const {presets:_,...value}=preset;return {...value,id:target.id,serviceType:faultType(target),environment:environment==='cloud'?'gcp':environment};})];}).filter(target=>{const key=`${targetEnvironment(target)}:${target.id}`;if(seen.has(key))return false;seen.add(key);return true;});
+}
+export function localFaultTargets(){const environment=activeEnvironment();return validateTargets(storedFaultTargets().filter(t=>targetEnvironment(t)===environment||!targetEnvironment(t)),{allowLegacyDuplicates:true}).filter((t,i,list)=>list.findIndex(other=>other.environment===t.environment&&other.serviceType===t.serviceType)===i);}
+export function saveLocalFaultTargets(targets){
+ if(state.active||state.recovery||state.blocked)throw new HttpError(409,'Restore the active fault before changing targets');
+ const environment=activeEnvironment();const valid=validateTargets(targets);
+ if(valid.some(t=>targetEnvironment(t)!==environment))throw new Error('Fault targets must belong to the selected environment');
+ for(const target of valid){if(target.adapter!=='placeholder')validateTargetProvider(target,faultType(target));if(target.adapter==='command')validateCommandTarget(target);}
+ const retained=storedFaultTargets().filter(t=>targetEnvironment(t)!==environment&&!(targetEnvironment(t)==null&&valid.some(v=>v.id===t.id)));
+ controlDb().prepare("INSERT INTO console_preferences VALUES('fault-targets',?) ON CONFLICT(key) DO UPDATE SET value=excluded.value").run(JSON.stringify([...retained,...valid]));return valid;
+}
+function serverTargets(){const raw=process.env.LOADTEST_FAULT_TARGETS?readJsonSync(path.resolve(process.env.LOADTEST_FAULT_TARGETS),[]):[{id:'demo',label:'Simulation · no infrastructure changes',adapter:'simulated'}];return validateTargets(raw.filter(t=>t.adapter==='simulated'||targetEnvironment(t)===activeEnvironment()),{allowLegacyDuplicates:true}).map(t=>t.adapter==='simulated'?{...t,environment:activeEnvironment()}:t);}
+export function faultTargets(){const seen=new Set(),environment=activeEnvironment();return validateTargets([...serverTargets(),...localFaultTargets()].filter(t=>t.adapter==='simulated'||targetEnvironment(t)===environment).filter(t=>{const type=faultType(t);if(!type)return true;if(seen.has(type))return false;seen.add(type);return true;}));}
+export async function checkLocalFaultTarget(input){
+ const [target]=validateTargets([input]);
+ requireSupportedEnvironment(activeEnvironment());
+ if(target.adapter!=='simulated'&&targetEnvironment(target)!==activeEnvironment())throw new Error('Fault target does not match the selected environment');
+ validateTargetProvider(target,faultType(target));
+ try{await makeFaultAdapter(target,runCommandWithTimeout(12000)).probe();}
+ catch(error){
+ if(error.code==='COMMAND_TIMEOUT'){
+ const service=target.adapter==='kubernetes'?'Kubernetes':target.adapter.startsWith('gcp-')?'Google Cloud':'Target';
+ throw new Error(`${service} did not respond within 12 seconds. Check VPN and cloud access.`);
+ }
+ throw error;
+ }
+ return {ok:true,message:'Running and reachable · no changes made'};
+}
+
+export function faultStatus(){return {environment:activeEnvironment(),targets:faultTargets().map(t=>({id:t.id,label:t.label,adapter:t.adapter,actions:t.actions,environment:faultEnvironment(t),target:t})),active:state.active?{id:state.active.id,jobId:state.active.jobId,target:state.active.target.label,targetId:state.active.target.id,databaseAvailability:state.active.databaseAvailability,loadReleased:Boolean(state.active.loadReleased),recoveryAt:state.active.downtimeStartedAt?state.active.downtimeStartedAt+state.active.seconds*1000:null,occurred:Boolean(state.active.downtimeStartedAt),action:state.active.action,status:state.active.status,simulated:state.active.target.adapter==='simulated'}:null,blocked:state.blocked,recovering:Boolean(state.recovery)};}
+async function durable(value){await mkdir(dataRoot,{recursive:true});const file=await open(ledgerPath+'.tmp','w',0o600);try{await file.writeFile(JSON.stringify(value));await file.sync();}finally{await file.close();}await rename(ledgerPath+'.tmp',ledgerPath);const directory=await open(dataRoot,'r');try{await directory.sync();}finally{await directory.close();}}
+export const runCommandWithTimeout=timeout=>async(binary,args)=>{
+ try{const {stdout}=await exec(binary,args,{timeout,maxBuffer:1024*1024,windowsHide:true});return stdout;}
+ catch(error){if(error.killed&&error.signal==='SIGTERM')throw Object.assign(new Error(`Command timed out after ${timeout} ms`),{code:'COMMAND_TIMEOUT'});throw error;}
+};
+const runCommand=runCommandWithTimeout(120000);
+export function makeFaultAdapter(target,command=runCommand,{databaseCheck=()=>queryWorker('database-test',{database:localSettings().database})}={}){
+ const t=target;
+ if(['local','gcp','aws','azure'].includes(t.environment))validateTargetProvider(t,faultType(t));
+ if(t.adapter==='command')return commandFaultAdapter(t);
+ if(['local-vault','process-compose'].includes(t.adapter))return localAdapter(t,command,t.adapter==='process-compose'&&command===runCommand?{controller:processComposeController(t)}:{});
+ if(t.adapter==='simulated')return {probe:async()=>({ready:true}),apply:async()=>{},restore:async()=>{},verify:async()=>true};
+ if(t.adapter==='docker'){
+ const inspect=async()=>JSON.parse(await command('docker',['inspect',t.container]))[0];
+ return {probe:async()=>{const info=await inspect();if(!info.State.Running||(info.State.Health && info.State.Health.Status!=='healthy'))throw new Error('Container is not healthy');return {running:true,id:info.Id};},isDown:async before=>{const info=await inspect();return info.Id===before.id&&!info.State.Running;},apply:()=>command('docker',['stop','--time','30',t.container]),restore:async before=>{if((await inspect()).Id!==before.id)throw new Error('Container identity changed');await command('docker',['start',t.container]);},verify:async before=>{const info=await inspect();return info.Id===before.id && info.State.Running && (!info.State.Health || info.State.Health.Status==='healthy');}};
+ }
+ if(t.adapter==='kubernetes')return kubernetesAdapter({...t,outageMode:t.outageMode??(faultType(t)==='card-vault'?'hard':'graceful')},command);
+ if(!['gcp-redis','gcp-alloydb'].includes(t.adapter))throw new Error('Unsupported fault adapter');
+ const group=t.adapter==='gcp-redis'?'redis':'alloydb';const flags=['--project',t.project,'--region',t.region,...(group==='alloydb'?['--cluster',t.cluster]:[])];
+ const inspect=async()=>JSON.parse(await command('gcloud',[group,'instances','describe',t.instance,...flags,'--format=json']));
+ if(group==='alloydb'){
+ const instanceName=`projects/${t.project}/locations/${t.region}/clusters/${t.cluster}/instances/${t.instance}`;
+ const operationPrefix=`projects/${t.project}/locations/${t.region}/operations/`;
+ return {
+ recoveryTimeoutMs:600000,
+ checkAvailability:()=>queryWorker('database-test',{database:localSettings().database,timeoutMillis:1000}),
+ probe:async()=>{const info=await inspect();if(!info.createTime||info.state!=='READY'||info.availabilityType!=='REGIONAL'||info.instanceType!=='PRIMARY')throw new Error('Failover target must be a ready HA primary');return {ready:true,created:info.createTime};},
+ apply:async(action,before,persist=async()=>{})=>{
+ // Persist intent first: a lost CLI response must never turn READY into proof of failover.
+ before.failoverRequested=true;await persist();
+ let response;
+ try{response=await command('gcloud',[group,'instances','failover',t.instance,...flags,'--quiet','--async','--format=json']);}
+ catch(error){
+ // Explicit API rejection proves no operation was accepted. A timeout or
+ // lost response remains ambiguous and still requires recovery verification.
+ if(/ERROR:.*\b(?:ABORTED|FAILED_PRECONDITION|INVALID_ARGUMENT|NOT_FOUND|PERMISSION_DENIED|UNAUTHENTICATED):/.test(error.message)){
+ before.failoverRejected=redact(error.message);await persist();
+ }
+ throw error;
+ }
+ const operation=JSON.parse(response);
+ if(!operation.name?.startsWith(operationPrefix)||!/^operation-[A-Za-z0-9-]+$/.test(operation.name.slice(operationPrefix.length)))throw new Error('Failover did not return a valid operation ID; completion is unverified');
+ before.operation=operation.name;await persist();
+ },
+ restore:async()=>{},
+ verify:async before=>{
+ if(!before.operation)throw new Error('Failover operation ID is missing; cannot verify completion from instance readiness');
+ if(!before.operation.startsWith(operationPrefix))throw new Error('Failover operation identity changed');
+ const operation=JSON.parse(await command('gcloud',['alloydb','operations','describe',before.operation.slice(operationPrefix.length),'--project',t.project,'--region',t.region,'--format=json']));
+ if(operation.name!==before.operation||operation.metadata?.target!==instanceName||operation.metadata?.verb!=='failover')throw new Error('Failover operation identity changed');
+ if(!operation.done)return false;
+ if(operation.error){before.failoverFailed=`AlloyDB failover failed: ${operation.error.message||operation.error.code||'unknown error'}`;return true;}
+ const info=await inspect();
+ if(info.createTime!==before.created||info.state!=='READY'||info.instanceType!=='PRIMARY'||info.availabilityType!=='REGIONAL')return false;
+ try{return (await databaseCheck()).ok===true;}catch{return false;}
+ }
+ };
+ }
+ return {probe:async()=>{const info=await inspect();if(!info.createTime||info.state!=='READY'||(group==='redis'?info.tier!=='STANDARD_HA':info.availabilityType!=='REGIONAL'||info.instanceType!=='PRIMARY'))throw new Error('Failover target must be a ready HA primary');return {ready:true,created:info.createTime};},apply:()=>command('gcloud',[group,'instances','failover',t.instance,...flags,'--quiet',...(group==='redis'?['--data-protection-mode=limited-data-loss']:[])]),restore:async()=>{},verify:async before=>{const info=await inspect();return info.createTime===before.created&&info.state==='READY'&&(group==='redis'?info.tier==='STANDARD_HA':info.instanceType==='PRIMARY'&&info.availabilityType==='REGIONAL');}};
+}
+async function verify(adapter,before){const end=Date.now()+(adapter.recoveryTimeoutMs||120000);do{if(await adapter.verify(before))return;await new Promise(r=>setTimeout(r,adapter.recoveryTimeoutMs?5000:1000));}while(Date.now()<end);throw new Error('Recovery could not be verified before the deadline; the cloud operation may still be running');}
+function observeDatabase(entry,emit,lifecycle={}){
+ if(entry.target.adapter!=='gcp-alloydb')return;
+ if(state.databaseObserver&&state.databaseObserver.id===entry.id)return;
+ const last=controlDb().prepare("SELECT kind FROM job_events WHERE job_id=? AND kind IN ('database_available','database_unavailable') ORDER BY event_id DESC LIMIT 1").get(entry.jobId);
+ const releaseLoad=databaseRecoveryGate(entry,async()=>{if(!lifecycle.onRecovered)return false;const released=await lifecycleStep(lifecycle.onRecovered,entry,emit,'Could not release the load clock after SQL recovery');if(released)emitSafely(emit,entry.jobId,'database_recovered','DB · available · load resumed; cloud operation verification continues');return released;});
+ const observer=watchDatabaseAvailability({check:makeFaultAdapter(entry.target).checkAvailability,initial:last?.kind==='database_unavailable'?'unavailable':'available',onSample:async current=>{entry.databaseAvailability=current;if(state.active?.id===entry.id)state.active.databaseAvailability=current;await releaseLoad(current);},onChange:current=>emitSafely(emit,entry.jobId,`database_${current}`,`DB · ${current}`)});
+ state.databaseObserver={id:entry.id,...observer};
+}
+async function lifecycleStep(callback,entry,emit,label){if(!callback)return true;let error;for(let attempt=0;attempt<3;attempt++){try{await callback();return true;}catch(e){error=e;if(attempt<2)await new Promise(resolve=>setTimeout(resolve,200));}}emitSafely(emit,entry.jobId,'fault_error',`${label}: ${redact(error.message)}`);return false;}
+async function restore(entry,emit,lifecycle={}){
+ if(entry.before?.failoverRejected&&!entry.before.operation){
+ if(!await lifecycleStep(lifecycle.onAborted,entry,emit,'Could not release the load clock after rejected failover'))throw new Error('Could not release the load clock after rejected failover');
+ if(state.databaseObserver&&state.databaseObserver.id===entry.id){await state.databaseObserver.stop();state.databaseObserver=null;}
+ await durable(null);state.active=null;state.blocked=false;
+ emitSafely(emit,entry.jobId,'fault_skipped',`${environmentLabel(targetEnvironment(entry.target))} · ${entry.target.label} · failover rejected · continuing`);return;
+ }
+ observeDatabase(entry,emit,lifecycle);await lifecycleStep(lifecycle.onRestore,entry,emit,'Could not hold the load clock for recovery');entry.status='restoring';state.active=entry;await durable(entry).catch(()=>{});emitSafely(emit,entry.jobId,'fault_restore',`${environmentLabel(targetEnvironment(entry.target))} · ${entry.target.label} · restoring`);const adapter=makeFaultAdapter(entry.target);await adapter.restore(entry.before);await verify(adapter,entry.before);if(state.databaseObserver&&state.databaseObserver.id===entry.id){await state.databaseObserver.stop();state.databaseObserver=null;}if(!entry.loadReleased&&!await lifecycleStep(entry.before?.failoverFailed?lifecycle.onAborted:lifecycle.onRecovered,entry,emit,'Could not release the load clock after recovery'))throw new Error('Infrastructure recovered, but the load clock could not be released');await durable(null);state.active=null;state.blocked=false;if(entry.before?.failoverFailed){emitSafely(emit,entry.jobId,'fault_error',entry.before.failoverFailed);emitSafely(emit,entry.jobId,'fault_skipped',`${environmentLabel(targetEnvironment(entry.target))} · ${entry.target.label} · failover failed · continuing`);}else emitSafely(emit,entry.jobId,'fault_restored',`${environmentLabel(targetEnvironment(entry.target))} · ${entry.target.label} · recovery verified`);}
+export async function initializeFaults(emit){if(state.recovery)return state.recovery;let saved;try{saved=await readJson(ledgerPath,null);}catch(e){state.blocked=true;throw e;}if(!saved)return;state.blocked=true;state.active=saved;state.recovery=restore(saved,emit).catch(e=>{state.blocked=true;throw e;}).finally(()=>{state.recovery=null;});return state.recovery;}
+export async function fireFault(job,input,emit,currentJob=()=>job,targetSnapshot=null,lifecycle={}){
+ if(!targetSnapshot&&faultTargets().find(t=>t.id===input.targetId)?.adapter==='command')throw new HttpError(409,'Custom commands execute only through the scenario schedule');
+ if(job.command!=='load'||job.loadState!=='running')throw new HttpError(409,'Faults require a running load');
+ return (await executeFault(job,input,emit,()=>currentJob()?.loadState==='running',targetSnapshot,lifecycle)).status;
+}
+export async function testFault(job,input,emit){
+ if(faultTargets().find(t=>t.id===input.targetId)?.adapter==='command')throw new HttpError(409,'Custom commands execute only through the scenario schedule');
+ if(job.command!=='fault-test'||job.status!=='running')throw new HttpError(409,'Fault test is not running');
+ const {completion}=await executeFault(job,input,emit,()=>true);
+ return completion;
+}
+async function executeFault(job,input,emit,isRunning,targetSnapshot=null,lifecycle={}){
+ if(state.active||state.blocked||state.recovery)throw new HttpError(409,'A fault is active or recovery is pending');
+ requireSupportedEnvironment(activeEnvironment());
+ if(input.environment&&input.environment!==activeEnvironment())throw new Error('Environment changed; reopen the fault dialog before executing');
+ const target=targetSnapshot || faultTargets().find(t=>t.id===input.targetId);if(!target||!target.actions.includes(input.action))throw new Error('Choose a configured fault target and action');
+ if(!targetSnapshot&&target.adapter!=='simulated'&&targetEnvironment(target)!==activeEnvironment())throw new Error('Fault target does not match the selected environment');
+ validateTargetProvider(target,faultType(target));
+ if(input.expectedTarget&&!isDeepStrictEqual(input.expectedTarget,target))throw new Error('Fault target changed; reopen the fault dialog before executing');
+ const phrase=`${input.action} ${target.id}`;if(input.confirm!==phrase)throw new Error(`Type ${phrase} to confirm`);
+ const seconds=Number(input.durationSeconds??30);if(!Number.isInteger(seconds)||seconds<1||seconds>300)throw new Error('Outage duration must be 1–300 seconds');
+ const entry={id:randomUUID(),jobId:job.id,target,action:input.action,status:'preflight',before:null,seconds,at:Date.now()};state.active=entry;
+ state.lifecycle=lifecycle;
+ const adapter=makeFaultAdapter(target),abort=new AbortController();state.abort=abort;
+ state.done=(async()=>{
+ let armed=false,error=null;
+ try{
+ entry.before=await adapter.probe();
+ if(abort.signal.aborted||!isRunning())throw new Error('Load stopped or paused during fault preflight');
+ entry.status='armed';await durable(entry);armed=true;
+ if(abort.signal.aborted)throw new Error('Fault cancelled before activation');
+ entry.status='active';await durable(entry);
+ observeDatabase(entry,emit,lifecycle);
+ emitSafely(emit,job.id,'fault_requested',`${environmentLabel(targetEnvironment(target))} · ${target.label} · ${input.action} requested`);
+ await adapter.apply(input.action,entry.before,()=>durable(entry));
+ if((input.action==='outage'||target.adapter==='command')&&adapter.isDown){
+ const deadline=Date.now()+60000;while(!await adapter.isDown(entry.before)){if(abort.signal.aborted)throw new Error('Outage cancelled before taking effect');if(Date.now()>=deadline)throw new Error('Outage did not take effect');await new Promise(r=>setTimeout(r,500));}
+ }
+ entry.downtimeStartedAt=Date.now();await durable(entry);
+ emitSafely(emit,job.id,'fault_started',`${target.adapter==='simulated'?'SIMULATED · ':''}${environmentLabel(targetEnvironment(target))} · ${target.label} · ${input.action}`);
+ if(!await lifecycleStep(lifecycle.onStarted,entry,emit,'Could not start the configured fault duration'))throw new Error('Load clock did not enter the fault duration');
+ await new Promise(r=>{const timer=setTimeout(r,seconds*1000);abort.signal.addEventListener('abort',()=>{clearTimeout(timer);r();},{once:true});if(abort.signal.aborted){clearTimeout(timer);r();}});
+ }catch(e){error=redact(e.message);emitSafely(emit,job.id,'fault_error',error);}
+ finally{
+ if(armed){try{await restore(entry,emit,lifecycle);}catch(e){state.active={...entry,status:'recovery_failed'};state.blocked=true;error=`Recovery failed: ${redact(e.message)}`;emitSafely(emit,job.id,'fault_error',error);}}
+ else {state.active=null;await lifecycleStep(lifecycle.onAborted,entry,emit,'Could not release the load clock after fault cancellation');}
+ state.abort=null;
+ state.done=null;
+ if(!state.blocked)state.lifecycle=null;
+ }
+ return {error,recovered:!state.blocked};
+ })();return {status:faultStatus(),completion:state.done};
+}
+export async function restoreFaults(emit){
+ if(state.done){const done=state.done;state.abort?.abort();await done;if(state.done===done)state.done=null;return faultStatus();}
+ if(state.recovery){await state.recovery;return faultStatus();}
+ if(state.active){state.blocked=true;state.recovery=restore(state.active,emit,state.lifecycle||{}).finally(()=>{state.recovery=null;if(!state.blocked)state.lifecycle=null;});await state.recovery;}
+ return faultStatus();
+}
+
+export function requestRestore(emit){
+ restoreFaults(emit).catch(e=>{state.blocked=true;if(state.active){state.active.status='recovery_failed';emitSafely(emit,state.active.jobId,'fault_error',`Recovery failed: ${redact(e.message)}`);}});
+ return faultStatus();
+}
diff --git a/loadtest/console/server/fixture-import.mjs b/loadtest/console/server/fixture-import.mjs
new file mode 100644
index 0000000000..78afc8d4bd
--- /dev/null
+++ b/loadtest/console/server/fixture-import.mjs
@@ -0,0 +1,118 @@
+import {createHash,randomUUID,timingSafeEqual} from 'node:crypto';
+import path from 'node:path';
+import {mkdir,readFile} from 'node:fs/promises';
+import {controlDb,dataRoot,configPath,readJsonSync,atomicJson,activeEnvironment} from './state.mjs';
+import {connectorSet,normalizeConnectorPlan} from '../src/connector-config.mjs';
+import {requireSupportedEnvironment} from '../src/environments.mjs';
+
+// The same requirement projection is used at verification and run admission.
+export function fixtureRequirements(config){
+ const enabled=(config.scenarios||[]).filter(f=>Number(f.weight)>0);
+ return {recurring:enabled.some(f=>['cit_off_session','cit_metadata_changed','mit','saved_card_checkout'].includes(f.scenario)),publishableKey:enabled.some(f=>f.merchant_path!=='legacy'||f.scenario==='sdk_checkout'),connectors:connectorSet(normalizeConnectorPlan(config.connectors))};
+}
+export function normalizeImportedMerchants(input,count){
+ if(!Array.isArray(input)||input.length!==count)throw new Error(`Import exactly ${count} merchant${count===1?'':'s'}`);
+ const ids=new Set();return input.map((row,i)=>{
+ if(!row||typeof row!=='object')throw new Error(`Merchant ${i+1}: expected an object`);
+ const result={};
+ for(const key of ['merchant_id','profile_id','api_key','publishable_key']){
+ const value=row[key]??'';if(typeof value!=='string'||value.length>16384||/[\r\n\0]/.test(value))throw new Error(`Merchant ${i+1}: invalid ${key}`);
+ if(key!=='publishable_key'&&!value.trim())throw new Error(`Merchant ${i+1}: ${key} is required`);
+ if(key.endsWith('_id')&&!/^[a-zA-Z0-9_-]+$/.test(value))throw new Error(`Merchant ${i+1}: invalid ${key}`);
+ result[key]=value;
+ }
+ if(ids.has(result.merchant_id))throw new Error(`Merchant ${i+1}: duplicate merchant ID`);ids.add(result.merchant_id);
+ const accounts=row.connector_accounts??{};
+ if(typeof accounts!=='object'||Array.isArray(accounts)||Object.entries(accounts).some(([k,v])=>!/^\w+$/.test(k)||typeof v!=='string'||!/^\w+$/.test(v)))throw new Error(`Merchant ${i+1}: invalid connector account mapping`);
+ result.connector_accounts={...accounts};result.merchant_connector_id=Object.values(accounts)[0]||'';return result;
+ });
+}
+export function importFingerprint(config,merchants){
+ return createHash('sha256').update(JSON.stringify({environment:config.environment,router:config.services.router,pm:config.services.modular_pm,admin:config.fixtures.admin_api_key,superposition:{endpoint:config.fixtures.superposition?.endpoint,organization_id:config.fixtures.superposition?.organization_id,workspace_id:config.fixtures.superposition?.workspace_id,defaults:config.fixtures.superposition?.defaults,context:config.fixtures.superposition?.context},requirements:fixtureRequirements(config),merchants})).digest('hex');
+}
+const equal=(a,b)=>{if(typeof a!=='string'||typeof b!=='string')return false;const x=Buffer.from(a),y=Buffer.from(b);return x.length===y.length&&timingSafeEqual(x,y);};
+export async function verifyImportedMerchants(config,merchants,{fetcher=fetch,signal=null,onProgress=(_checks,_state)=>{}}={}){
+ const requirements=fixtureRequirements(config),checks=[],accounts=new Map();
+ let phase='credentials';
+ const stages={credentials:{status:'running',completed:0,total:merchants.length*(requirements.publishableKey?3:2),failed:0},setup:{status:'pending',completed:0,total:merchants.length*requirements.connectors.length,failed:0}};
+ const report=()=>onProgress(checks,{phase,stages:structuredClone(stages),checked:checks.length});
+ const check=async(merchant,stage,label,fn)=>{
+ signal?.throwIfAborted();let result;
+ try{await fn();signal?.throwIfAborted();result={merchant,stage,label,ok:true,message:'Verified'};}
+ catch(e){if(signal?.aborted)throw e;result={merchant,stage,label,ok:false,message:e.message};}
+ checks.push(result);stages[stage].completed++;if(!result.ok)stages[stage].failed++;
+ await report();
+ };
+ const get=async(route,headers)=>{
+ const url=`${config.services.router.replace(/\/$/,'')}${route}`;let response;
+ try{response=await fetcher(url,{headers,redirect:'manual',signal:signal?AbortSignal.any([signal,AbortSignal.timeout(8000)]):AbortSignal.timeout(8000)});}catch{throw new Error('Hyperswitch is unreachable or the request timed out');}
+ if(!response.ok){await response.body?.cancel();throw new Error(`Hyperswitch returned HTTP ${response.status}${response.status===401||response.status===403?' — credentials or inspection permissions were rejected':''}`);}
+ try{return await response.json();}catch{throw new Error('Hyperswitch returned an invalid inspection response');}
+ };
+ const parallel=async inspect=>{
+ let cursor=0;const workers=await Promise.allSettled(Array.from({length:Math.min(4,merchants.length)},async()=>{while(cursor<merchants.length){signal?.throwIfAborted();await inspect(merchants[cursor++]);}}));
+ const failed=workers.find(result=>result.status==='rejected');if(failed?.status==='rejected')throw failed.reason;
+ };
+ await report();
+ await parallel(async row=>{
+ const mid=encodeURIComponent(row.merchant_id),pid=encodeURIComponent(row.profile_id);
+ await check(row.merchant_id,'credentials','Merchant API key',async()=>{const connectors=await get(`/account/${mid}/connectors`,{'api-key':row.api_key});if(!Array.isArray(connectors))throw new Error('Connector inspection did not return an account list');accounts.set(row.merchant_id,connectors);});
+ await check(row.merchant_id,'credentials','Merchant and profile ownership',async()=>{
+ const profile=await get(`/account/${mid}/business_profile/${pid}`,{'api-key':row.api_key});
+ if(profile.profile_id!==row.profile_id||profile.merchant_id!==row.merchant_id)throw new Error('Profile does not belong to this merchant');
+ });
+ if(requirements.publishableKey)await check(row.merchant_id,'credentials','Publishable key',async()=>{
+ if(!row.publishable_key)throw new Error('Publishable key is required by the selected payment flows');
+ if(!config.fixtures.admin_api_key)throw new Error('Configure the Router admin key to verify the publishable key');
+ const admin={'api-key':config.fixtures.admin_api_key,Authorization:`admin-api-key=${config.fixtures.admin_api_key}`};
+ const account=await get(`/accounts/${mid}`,admin);
+ if(account.merchant_id!==row.merchant_id||!equal(account.publishable_key,row.publishable_key))throw new Error('Publishable key does not match this merchant');
+ });
+ });
+ if(stages.credentials.failed){
+ stages.credentials.status='failed';stages.setup.status='blocked';phase='failed';await report();
+ return {ok:false,checks,phase,stages};
+ }
+ stages.credentials.status='passed';stages.setup.status='running';phase='setup';await report();
+ await parallel(async row=>{
+ const connectors=accounts.get(row.merchant_id);
+ for(const name of requirements.connectors)await check(row.merchant_id,'setup',`${name} connector`,async()=>{
+ const id=row.connector_accounts[name];if(!id)throw new Error(`No ${name} MCA ID was imported`);
+ const account=connectors.find(c=>c.merchant_connector_id===id);
+ if(!account)throw new Error('MCA ID was not found for this merchant');
+ if(account.connector_name!==name)throw new Error('MCA ID belongs to a different connector');
+ if(account.profile_id!==row.profile_id)throw new Error('MCA ID belongs to a different profile');
+ if(account.disabled!==false)throw new Error('Connector account is disabled or its enabled state could not be established');
+ const methods=account.payment_methods_enabled||[];
+ if(!methods.some(m=>m.payment_method==='card'&&m.payment_method_types?.some(t=>t.payment_method_type==='credit'&&(!requirements.recurring||t.recurring_enabled===true))))throw new Error('Connector does not have the required credit-card configuration enabled');
+ });
+ });
+ const ok=!stages.setup.failed;stages.setup.status=ok?'passed':'failed';phase=ok?'saving':'failed';await report();
+ return {ok,checks,phase,stages};
+}
+export function importedCompatibility(set,config){
+ const manifest=readJsonSync(path.join(set.path,'manifest.json'),{});
+ if(manifest.source!=='imported')return null;
+ const merchants=readJsonSync(path.join(set.path,'merchants.json'),[]);
+ return {source:'imported',verification:manifest.verification?{ok:manifest.verification.ok,at:manifest.verification.at,failed:manifest.verification.checks.filter(c=>!c.ok).length}:null,compatible:manifest.state==='ready'&&manifest.fingerprint===importFingerprint(config,merchants),connectors:manifest.connectors||[]};
+}
+export async function prepareImport(profile,input={},existing=null){
+ const config={...structuredClone(readJsonSync(configPath)),environment:activeEnvironment(),connectors:profile.connectors,scenarios:profile.scenarios,profile:{id:profile.id}};requireSupportedEnvironment(config.environment);
+ if(existing){const before=readJsonSync(path.join(existing.path,'manifest.json'),{});if(before.destination!==config.services.router||before.environment!==config.environment||before.pm!==config.services.modular_pm)throw new Error('The fixture destination changed; reimport its credentials explicitly for the new environment');}
+ const id=existing?.id||randomUUID(),directory=existing?.path||path.join(dataRoot,'imported-fixtures',id);
+ const merchants=normalizeImportedMerchants(existing?readJsonSync(path.join(directory,'merchants.json')):input.merchants,profile.merchantCount);
+ await mkdir(directory,{recursive:true,mode:0o700});
+ await atomicJson(path.join(directory,'merchants.json'),merchants);
+ await atomicJson(path.join(directory,'manifest.json'),{source:'imported',destination:config.services.router,pm:config.services.modular_pm,environment:config.environment,state:'verifying',profileId:profile.id,connectors:fixtureRequirements(config).connectors});
+ if(existing)controlDb().prepare("UPDATE fixture_sets SET status='creating' WHERE id=?").run(id);
+ else controlDb().prepare('INSERT INTO fixture_sets VALUES(?,?,?,?,?,?,NULL,?)').run(id,profile.mode,profile.merchantCount,'imported',directory,'creating',Date.now());
+ return {id,directory,merchants,config};
+}
+export async function finishImport(prepared,result){
+ const {id,directory,merchants,config}=prepared;
+ const sp=config.fixtures.superposition;
+ const superposition=sp?{organization_id:sp.organization_id,workspace_id:sp.workspace_id,defaults:sp.defaults}:undefined;
+ const merchantsSha=createHash('sha256').update(await readFile(path.join(directory,'merchants.json'))).digest('hex');
+ await atomicJson(path.join(directory,'manifest.json'),{schema_version:1,router:config.services.router,merchants_sha256:merchantsSha,merchant_count:merchants.length,superposition,source:'imported',destination:config.services.router,pm:config.services.modular_pm,environment:config.environment,state:result.ok?'ready':'failed',profileId:config.profile?.id,connectors:fixtureRequirements(config).connectors,fingerprint:importFingerprint(config,merchants),verification:{...result,at:Date.now()}});
+ controlDb().prepare('UPDATE fixture_sets SET status=? WHERE id=?').run(result.ok?'ready':'failed',id);
+}
diff --git a/loadtest/console/server/grafana-embed.mjs b/loadtest/console/server/grafana-embed.mjs
new file mode 100644
index 0000000000..dfc554a71f
--- /dev/null
+++ b/loadtest/console/server/grafana-embed.mjs
@@ -0,0 +1,58 @@
+import {createHash,randomBytes} from 'node:crypto';
+import {createServer} from 'node:http';
+import {Readable} from 'node:stream';
+import {pipeline} from 'node:stream/promises';
+import {controlDb,localSettings,panelPath} from './state.mjs';
+import {grafanaEmbedOrigin,grafanaProxyPort} from './grafana-origin.mjs';
+import {proxyGrafana} from './grafana-proxy.mjs';
+import {boundedRequest} from './request-body.mjs';
+const digest=value=>createHash('sha256').update(String(value)).digest('hex');
+const cookieName='loadtest_grafana';
+let initialized=false;
+function db(){const db=controlDb();if(!initialized){db.exec(`CREATE TABLE IF NOT EXISTS grafana_access(token_hash TEXT PRIMARY KEY,session_hash TEXT NOT NULL,expires INTEGER NOT NULL,pending INTEGER NOT NULL)`);initialized=true;}return db;}
+export function createGrafanaEmbed(sessionToken,panel){
+ const database=db(),now=Date.now(),sessionHash=digest(sessionToken||''),session=database.prepare('SELECT expires FROM sessions WHERE token=? AND expires>?').get(sessionHash,now);
+ if(!session)throw Object.assign(new Error('Authentication required'),{status:401});
+ const settings=localSettings(),route=panelPath(panel,settings.grafana.baseUrl),ticket=randomBytes(32).toString('base64url');
+ database.prepare('DELETE FROM grafana_access WHERE expires<=? OR session_hash NOT IN (SELECT token FROM sessions)').run(now);
+ database.prepare('INSERT INTO grafana_access VALUES(?,?,?,1)').run(digest(ticket),sessionHash,Math.min(session.expires,now+60000));
+ const url=new URL(route,grafanaEmbedOrigin());url.searchParams.set('embed_ticket',ticket);
+ return {url:url.href};
+}
+function authenticate(request,url){
+ const database=db(),now=Date.now(),ticket=url.searchParams.get('embed_ticket');
+ if(ticket){
+ const access=database.prepare('SELECT a.token_hash,s.expires FROM grafana_access a JOIN sessions s ON s.token=a.session_hash WHERE a.token_hash=? AND a.pending=1 AND a.expires>? AND s.expires>?').get(digest(ticket),now,now);
+ if(!access)return null;
+ const token=randomBytes(32).toString('base64url');
+ if(!database.prepare('UPDATE grafana_access SET token_hash=?,pending=0,expires=? WHERE token_hash=? AND pending=1').run(digest(token),access.expires,access.token_hash).changes)return null;
+ url.searchParams.delete('embed_ticket');
+ return new Response(null,{status:303,headers:{location:url.pathname+url.search,'set-cookie':`${cookieName}=${token}; Path=/grafana/; HttpOnly; SameSite=Strict; Max-Age=${Math.max(0,Math.floor((access.expires-now)/1000))}${url.protocol==='https:'?'; Secure':''}`,'referrer-policy':'no-referrer','cache-control':'no-store'}});
+ }
+ const token=request.headers.get('cookie')?.split(';').map(s=>s.trim()).find(s=>s.startsWith(cookieName+'='))?.slice(cookieName.length+1);
+ return token&&database.prepare('SELECT 1 FROM grafana_access a JOIN sessions s ON s.token=a.session_hash WHERE a.token_hash=? AND a.pending=0 AND a.expires>? AND s.expires>?').get(digest(token),now,now)?true:null;
+}
+export async function grafanaEmbedRequest(request){
+ const url=new URL(request.url),origin=grafanaEmbedOrigin();
+ if(url.origin!==origin||!url.pathname.startsWith('/grafana/')||!['GET','HEAD','POST'].includes(request.method))return Response.json({error:'Not found'},{status:404});
+ const auth=authenticate(request,url);if(auth instanceof Response)return auth;
+ if(!auth)return Response.json({error:'Grafana embed session required'},{status:401});
+ if(request.method==='POST'&&request.headers.get('origin')!==origin)return Response.json({error:'Invalid request origin'},{status:403});
+ try{return await proxyGrafana(await boundedRequest(request),url);}catch(error){return Response.json({error:error.status===413?error.message:'Grafana is unavailable'},{status:error.status===413?413:502,headers:{connection:'close'}});}
+}
+export async function startGrafanaProxy(){
+ const origin=grafanaEmbedOrigin();
+ const server=createServer(async(req,res)=>{
+ const abort=new AbortController();req.once('aborted',()=>abort.abort());res.once('close',()=>{if(!res.writableEnded)abort.abort();});
+ try{
+ const headers=new Headers();for(const [key,value] of Object.entries(req.headers))if(value)headers.set(key,Array.isArray(value)?value.join(','):value);
+ const url=new URL(req.url,origin);if(url.origin!==origin)throw Error('Invalid origin');
+ const options={method:req.method,headers,signal:abort.signal,...(!['GET','HEAD'].includes(req.method)?{body:/** @type {ReadableStream} */ (/** @type {unknown} */ (Readable.toWeb(req))),duplex:'half'}:{})};
+ const request=new Request(url,options);
+ const response=await grafanaEmbedRequest(request);res.writeHead(response.status,Object.fromEntries(response.headers));
+ if(response.body&&req.method!=='HEAD')await pipeline(Readable.fromWeb(/** @type {import('node:stream/web').ReadableStream} */ (/** @type {unknown} */ (response.body))),res);else res.end();
+ }catch{if(!res.headersSent)res.writeHead(502);res.end();}
+ });
+ await new Promise((resolve,reject)=>{server.once('error',reject);server.listen(grafanaProxyPort(),process.env.GRAFANA_PROXY_HOST||process.env.HOST||'127.0.0.1',()=>resolve(undefined));});
+ return server;
+}
diff --git a/loadtest/console/server/grafana-origin.mjs b/loadtest/console/server/grafana-origin.mjs
new file mode 100644
index 0000000000..5437fc74f5
--- /dev/null
+++ b/loadtest/console/server/grafana-origin.mjs
@@ -0,0 +1,8 @@
+export function grafanaProxyPort(){return Number(process.env.GRAFANA_PROXY_PORT||Number(process.env.PORT||4174)+2);}
+export function grafanaEmbedOrigin(){
+ const consoleUrl=new URL(process.env.ORIGIN||'http://127.0.0.1:4174');
+ const fallback=new URL(consoleUrl);fallback.port=String(grafanaProxyPort());
+ const embed=new URL(process.env.GRAFANA_EMBED_ORIGIN||fallback.origin);
+ if(!['http:','https:'].includes(embed.protocol)||embed.username||embed.password||embed.origin===consoleUrl.origin||embed.pathname!=='/'||embed.search||embed.hash)throw new Error('GRAFANA_EMBED_ORIGIN must be a separate HTTP(S) origin');
+ return embed.origin;
+}
diff --git a/loadtest/console/server/grafana-proxy.mjs b/loadtest/console/server/grafana-proxy.mjs
new file mode 100644
index 0000000000..70be04f56e
--- /dev/null
+++ b/loadtest/console/server/grafana-proxy.mjs
@@ -0,0 +1,43 @@
+import {localSettings,httpUrl} from './state.mjs';
+const json=(value,init)=>Response.json(value,init);
+import { upstreamPrefix, rewriteGrafana } from './grafana.mjs';
+
+export async function proxyGrafana(request,url) {
+ // Only the configured origin is reachable. Incoming identity headers and cookies are discarded.
+ const base=httpUrl(localSettings().grafana.baseUrl);
+ const trusted=httpUrl(process.env.GRAFANA_URL||'http://localhost:3002');
+ if(base.origin!==trusted.origin)return json({error:'Set GRAFANA_URL to this Grafana origin before using stored Grafana credentials'},{status:403});
+ if(!process.env.GRAFANA_TOKEN && !process.env.GRAFANA_USER)return json({error:'Set GRAFANA_TOKEN in loadtest/console/.env to a Grafana Viewer service-account token, then restart the console. For configured Grafana auth proxy deployments, set GRAFANA_USER instead.'},{status:503});
+ let destination=new URL(url.pathname+url.search,base.origin);
+ if(destination.origin!==base.origin || !destination.pathname.startsWith('/grafana/'))return json({error:'Invalid Grafana path'},{status:400});
+ if(request.method==='POST' && !/^\/grafana\/api\/(ds\/query$|datasources\/proxy\/)/.test(destination.pathname))return json({error:'Read-only Grafana proxy'},{status:403});
+ const headers=new Headers();
+ headers.set('accept',request.headers.get('accept') || '*/*');
+ if(request.headers.get('content-type'))headers.set('content-type',request.headers.get('content-type'));
+ if(process.env.GRAFANA_TOKEN)headers.set('authorization',`Bearer ${process.env.GRAFANA_TOKEN}`);
+ if(process.env.GRAFANA_USER)headers.set('x-webauth-user',process.env.GRAFANA_USER);
+ const prefix=await upstreamPrefix(base,headers);
+ destination=new URL(prefix+url.pathname.slice('/grafana'.length)+url.search,base.origin);
+ const body=request.method==='POST'?await request.arrayBuffer():undefined;
+ if(body?.byteLength>1024*1024)return json({error:'Request too large'},{status:413});
+ try {
+ const upstream=await fetch(destination,{method:request.method,headers,body,redirect:'manual',signal:AbortSignal.any([request.signal,AbortSignal.timeout(30000)])});
+ const outgoing=new Headers();
+ for(const key of ['content-type','content-disposition','content-security-policy'])if(upstream.headers.has(key))outgoing.set(key,upstream.headers.get(key));
+ const location=upstream.headers.get('location');
+ if(location) {
+ const redirect=new URL(location,destination);
+ if(redirect.origin!==base.origin || (prefix && !redirect.pathname.startsWith('/grafana/')))return json({error:'Grafana redirect is outside configured server'},{status:502});
+ outgoing.set('location',(prefix?'':'/grafana')+redirect.pathname+redirect.search);
+ }
+ outgoing.set('cache-control','no-store');
+ outgoing.set('referrer-policy','no-referrer');
+ outgoing.set('x-content-type-options','nosniff');
+ const type=upstream.headers.get('content-type') || '';
+ if(!prefix && request.method!=='HEAD' && (type.includes('text/html') || destination.pathname==='/api/frontend/settings')) {
+ return new Response(rewriteGrafana(await upstream.text(),url.origin),{status:upstream.status,headers:outgoing});
+ }
+ return new Response(upstream.body,{status:upstream.status,headers:outgoing});
+ }catch{return json({error:'Grafana is unavailable'},{status:502});}
+}
+
diff --git a/loadtest/console/server/grafana.mjs b/loadtest/console/server/grafana.mjs
new file mode 100644
index 0000000000..1e53027e52
--- /dev/null
+++ b/loadtest/console/server/grafana.mjs
@@ -0,0 +1,34 @@
+const prefixes = new Map();
+
+// Discover root-hosted Grafana without changing its deployment. A configured
+// subpath is explicit; otherwise probe health once per minute, never per asset.
+export async function upstreamPrefix(base, headers) {
+ if (base.pathname.replace(/\/$/, '') === '/grafana') return '/grafana';
+ const cached = prefixes.get(base.origin);
+ if (cached && cached.until > Date.now()) return cached.promise;
+ const promise = (async () => {
+ try {
+ const response = await fetch(new URL('/api/health', base), {
+ headers, redirect: 'manual', signal: AbortSignal.timeout(5000)
+ });
+ if (response.ok && response.headers.get('content-type')?.includes('application/json')) {
+ const health = await response.json();
+ if (health.database || health.version) return '';
+ } else await response.body?.cancel();
+ } catch { /* Existing deployments use the /grafana subpath. */ }
+ return '/grafana';
+ })();
+ prefixes.set(base.origin, {promise, until: Date.now() + 60000});
+ return promise;
+}
+
+export function rewriteGrafana(text, origin) {
+ // Grafana's bootstrap supplies paths for API calls and webpack chunks.
+ // Only path settings are changed; the token remains in server request headers.
+ return text
+ .replace(/(<base\b[^>]*href=["'])\/(?:["'])/gi, '$1/grafana/"')
+ .replace(/"appSubUrl"\s*:\s*""/g, '"appSubUrl":"/grafana"')
+ .replace(/"appUrl"\s*:\s*"[^"\n]*"/g, `"appUrl":${JSON.stringify(origin + '/grafana/')}`)
+ .replace(/((?:src|href|action)=["'])\/(?!\/|grafana(?:\/|["']))/gi, '$1/grafana/')
+ .replace(/"liveEnabled"\s*:\s*true/g, '"liveEnabled":false');
+}
diff --git a/loadtest/console/server/jobs.mjs b/loadtest/console/server/jobs.mjs
new file mode 100644
index 0000000000..a9d1fa9dd6
--- /dev/null
+++ b/loadtest/console/server/jobs.mjs
@@ -0,0 +1,384 @@
+import {prepareImport,finishImport,verifyImportedMerchants} from './fixture-import.mjs';
+import {normalizeConnectorPlan} from '../src/connector-config.mjs';
+import {provisionConnectorAccounts} from './connector-fixtures.mjs';
+import {requireSupportedEnvironment,environmentLabel} from '../src/environments.mjs';
+import {normalizePaymentFlows,assertSupportedPaymentFlows} from '../src/payment-flows.mjs';
+import {activeEnvironment} from './state.mjs';
+import {getProfile,fixtureSignature,validateFixtureSet,listFixtureSets,getFixtureSet} from './profiles.mjs';
+import {DatabaseSync} from 'node:sqlite';
+import { spawn } from 'node:child_process';
+import { randomUUID } from 'node:crypto';
+import { mkdir,appendFile } from 'node:fs/promises';
+import path from 'node:path';
+import { controlDb, initializeConfig, readJsonSync, readJson, atomicJson, dataRoot, configPath, localSettings, consoleRoot, loadtestRoot, redact, runDirectory, withConfiguredVus } from './state.mjs';
+import { queryWorker } from './workers.mjs';
+import { HttpError } from './errors.mjs';
+import { appendTelemetry,telemetryPoint } from './telemetry.mjs';
+import {decorateDisplayErrors} from './display-errors.mjs';
+import {loadShape,loadTimeline} from '../src/load-shape.mjs';
+import {initializeFaults,restoreFaults,faultStatus,faultTargets,fireFault,testFault} from './faults.mjs';
+import {snapshotFaultPlan,faultScheduler} from './fault-plan.mjs';
+import {workerFailure} from './worker-result.mjs';
+import {resolveK6Binary} from './k6-binary.mjs';
+import {launchDistributedRun} from './distributed-runner.mjs';
+import {validateResultsLimits} from '../src/results-limits.mjs';
+import {executionSample} from './execution-clock.mjs';
+
+// Share lifecycle state with adapter-node and Vite's server-module reloads.
+const key=Symbol.for('hyperswitch.loadtest.jobs');
+const manager=globalThis[key] ||= {running:new Map(),initialized:false,shuttingDown:false,recovering:false};
+const running=manager.running;
+export function initializeJobs() {
+ if(manager.initialized)return;
+ initializeConfig();const db=controlDb();
+ const interrupted=db.prepare("SELECT id,run_path FROM jobs WHERE status IN ('starting','running','pausing','paused','cancelling')").all();
+ db.prepare("UPDATE jobs SET status='interrupted',ended_at=?,error='Server restarted before job finished' WHERE status IN ('starting','running','pausing','paused','cancelling')").run(Date.now());
+ db.prepare("UPDATE fixture_sets SET status='interrupted' WHERE status='creating'").run();
+ manager.initialized=true;
+ manager.recovering=true;
+ manager.recovery=Promise.all([initializeFaults(recordActivity),...interrupted.map(stopInterrupted)]).catch(e=>{console.error('Recovery pending:',redact(e.message));}).finally(()=>{manager.recovering=false;});
+ process.once('SIGTERM',()=>{shutdownJobs().catch(console.error);});
+ process.once('SIGINT',()=>{shutdownJobs().catch(console.error);});
+}
+async function stopInterrupted({id,run_path}) {
+ const directory=path.join(dataRoot,'jobs',id),processes=[];
+ for(const {file,group} of [{file:'worker-pid.json',group:false},{file:'k6-pid.json',group:true}]) {
+ const saved=await readJson(path.join(directory,file),null).catch(()=>null);
+ if(Number.isSafeInteger(saved?.pid)&&saved.pid>1)processes.push(group?-saved.pid:saved.pid);
+ }
+ const signal=(pid,name)=>{try{process.kill(pid,name);return true;}catch(e){return e.code!=='ESRCH';}};
+ for(const pid of processes)signal(pid,'SIGTERM');
+ const deadline=Date.now()+60000;
+ while(processes.some(pid=>signal(pid,0))) {
+ if(Date.now()>=deadline){for(const pid of processes)signal(pid,'SIGKILL');break;}
+ await new Promise(resolve=>setTimeout(resolve,250));
+ }
+ if(run_path){
+ let db;try{db=new DatabaseSync(path.join(run_path,'results.sqlite'));db.exec('PRAGMA busy_timeout=5000');db.prepare("UPDATE runs SET recording_state='incomplete',error='Worker interrupted before job finished',ended_at=COALESCE(ended_at,?)").run(Date.now());}catch{/* A worker may have crashed before creating results. */}finally{db?.close();}
+ }
+}
+const parsed=value=>JSON.parse(value || '{}');
+export function finalJobStatus({cancelled=false,failure=null,recoveryError=null}={}) {
+ if(cancelled)return 'cancelled';
+ return failure || recoveryError ? 'failed' : 'complete';
+}
+export function getJob(id) {
+ const row=controlDb().prepare('SELECT * FROM jobs WHERE id=?').get(id);
+ if(!row) throw new HttpError(404,'Job not found');
+ const config=row.config_path?readJsonSync(row.config_path,{}):{};
+ const shards=row.run_path?controlDb().prepare('SELECT s.id,s.worker_id AS workerId,w.name,s.status,s.offered_tps AS offeredTps,s.error FROM run_shards s JOIN load_workers w ON w.id=s.worker_id WHERE s.run_id=? ORDER BY s.id').all(path.basename(row.run_path)):[];
+ const displayLoad=row.kind==='smoke'&&config.smoke?{total_rps:config.smoke.rps,duration_seconds:config.smoke.durationSeconds}:config.load;
+ const events=controlDb().prepare('SELECT event_id AS id,at,kind,message FROM job_events WHERE job_id=? ORDER BY event_id').all(id);
+ const progress=decorateDisplayErrors(parsed(row.progress),row.run_path,events,config,row.started_at),activeFault=faultStatus().active;
+ const restoring=row.kind==='load'&&activeFault?.jobId===row.id&&!activeFault.loadReleased&&['restoring','recovery_failed'].includes(activeFault.status);
+ const terminal=['complete','failed','cancelled','interrupted'].includes(row.status);
+ return {id:row.id,command:row.kind,mode:row.mode,status:row.status,startedAt:row.started_at,endedAt:row.ended_at,
+ exitCode:row.exit_code,runId:row.run_path?`${row.mode}:${path.basename(row.run_path)}`:undefined,
+ fixtureSetId:config.fixtureSet?.id||progress.verification?.fixtureSetId,
+ profile:displayLoad?{id:config.profile?.id,version:config.profile?.version,name:config.profile?.name,totalRps:loadShape(displayLoad).peak,durationSeconds:loadShape(displayLoad).duration,timeline:loadTimeline(displayLoad,row.kind==='smoke'?[]:config.faultPlan),scenarios:config.scenarios}:null,
+ loadState: row.kind==='load' ? (terminal?(row.status==='complete'?'completed':row.status):restoring?'recovering':row.status==='cancelling'?'pausing':progress.control?.state==='draining'?'pausing':progress.control?.state || (['starting','running'].includes(row.status)?'idle':row.status)) : null,
+ events:events.slice(-200),
+ workers:shards,faults:faultStatus(),output:row.output,progress,result:row.result?parsed(row.result):null,error:row.error==='Worker exited 99'?workerFailure(99):row.error};
+}
+export function latestReconciliation(runPath) {
+ const row=controlDb().prepare("SELECT id FROM jobs WHERE kind='reconcile' AND run_path=? ORDER BY started_at DESC LIMIT 1").get(runPath);return row?getJob(row.id):null;
+}
+export function activeJob(kind=null) {
+ initializeJobs();const row=controlDb().prepare("SELECT id FROM jobs WHERE status IN ('starting','running','pausing','paused','cancelling') AND (? IS NULL OR kind=? OR (?='generator' AND kind IN ('fixtures','load','smoke'))) ORDER BY started_at DESC LIMIT 1").get(kind,kind,kind);
+ return row?getJob(row.id):null;
+}
+function assertCanReserve(kind) {
+ if(manager.shuttingDown) throw new Error('Server is shutting down');
+ if(kind!=='reconcile'&&(faultStatus().blocked||faultStatus().active||faultStatus().recovering))throw new HttpError(409,'Fault recovery must be verified before starting another run');
+ if(manager.recovering)throw new HttpError(409,'Previous workers are stopping after restart; retry shortly');
+ if(kind==='fault-test'&&activeJob('generator'))throw new HttpError(409,'Stop the fixture or load job before testing a fault');
+ if(['fixtures','load','smoke','fault-test'].includes(kind)&&activeJob('fault-test'))throw new HttpError(409,'A fault test is already running');
+}
+function reserve(kind,mode,runPath=null) {
+ initializeJobs();assertCanReserve(kind);
+ const db=controlDb(),id=randomUUID();
+ if(kind==='reconcile' && db.prepare("SELECT id FROM jobs WHERE kind='reconcile' AND status IN ('starting','running','pausing','paused','cancelling')").get()) throw new HttpError(409,'Reconciliation is already running');
+ try {db.prepare("INSERT INTO jobs(id,kind,mode,status,started_at,run_path) VALUES(?,?,?,'starting',?,?)").run(id,kind,mode,Date.now(),runPath);}
+ catch(e) {if(e.code==='ERR_SQLITE_ERROR')throw new HttpError(409,'A fixture or load job is already running');throw e;}
+ return id;
+}
+function update(id,values) {
+ const columns=Object.keys(values);controlDb().prepare(`UPDATE jobs SET ${columns.map(k=>`${k}=?`).join(',')} WHERE id=?`).run(...Object.values(values),id);
+}
+export function recordActivity(id,kind,message) {
+ const at=Date.now(),row=controlDb().prepare('SELECT run_path FROM jobs WHERE id=?').get(id);
+ const event={id:Number(controlDb().prepare('INSERT INTO job_events(job_id,at,kind,message) VALUES(?,?,?,?)').run(id,at,kind,redact(message)).lastInsertRowid),at,kind,message:redact(message)};
+ if(row?.run_path)appendFile(path.join(row.run_path,'activity.jsonl'),JSON.stringify(event)+'\n',{mode:0o600}).catch(()=>{});
+ return event;
+}
+async function controlWorker(id,action,payload={}) {
+ // Cancellation or process exit removes the controller. Infrastructure still
+ // has to recover, but releasing a stopped load clock is no longer required.
+ if(['gate','release','recover'].includes(action)&&(['cancelling','cancelled','complete','failed','interrupted'].includes(getJob(id).status)||running.get(id)?.finished))return;
+ const worker=running.get(id);if(!worker)throw new HttpError(409,'No active load worker');
+ if(worker.distributed)return worker.control(action,payload);
+ const endpoint=(await readJson(path.join(worker.runPath,'control.json'),{})).endpoint;
+ if(!endpoint)throw new HttpError(409,'Load worker is still initializing');
+ const u=new URL(endpoint);if(u.hostname!=='127.0.0.1'||u.pathname!=='/control')throw new Error('Invalid worker control endpoint');
+ const response=await fetch(u,{method:'POST',headers:{authorization:`Bearer ${worker.controlToken}`,'content-type':'application/json'},body:JSON.stringify({action,...payload}),signal:AbortSignal.timeout(5000)});
+ if(!response.ok)throw new HttpError(409,(await response.text()).trim());
+ const control=await response.json();worker.revision=(worker.revision || 0)+1;return control;
+}
+export async function controlLoad(id,action) {
+ const job=getJob(id),worker=running.get(id);
+ if(job.command!=='load'||!worker)throw new HttpError(409,'No active load worker');
+ if(action==='pause'&&faultStatus().active)throw new HttpError(409,'Wait for fault recovery before pausing');
+ if((action==='pause'&&job.loadState!=='running')||(action==='resume'&&job.loadState!=='paused'))throw new HttpError(409,'Action is not available in this state');
+ const control=await controlWorker(id,action);update(id,{status:worker.distributed?(action==='pause'?'pausing':'running'):control.state,progress:JSON.stringify({...job.progress,...(!worker.distributed?{control}:{})})});
+ recordActivity(id,action,action==='pause'?'Pause requested · no new flows':'Load resumed');
+ if(action==='pause'&&control?.state==='paused')recordActivity(id,'paused','Load paused · active flows drained');
+ return getJob(id);
+}
+export async function startFixtureImport(input){
+ initializeJobs();assertCanReserve('fixtures');
+ const profile=getProfile(input.profileId),existing=input.fixtureSetId?getFixtureSet(input.fixtureSetId):null;
+ if(existing&&readJsonSync(path.join(existing.path,'manifest.json'))?.source!=='imported')throw new Error('Only imported fixture sets can be reverified');
+ const id=reserve('fixtures',profile.mode),abort=new AbortController();
+ let prepared;
+ try{prepared=await prepareImport(profile,input,existing);}catch(e){update(id,{status:'failed',error:redact(e.message),ended_at:Date.now()});throw e;}
+ controlDb().prepare('UPDATE fixture_sets SET job_id=? WHERE id=?').run(id,prepared.id);
+ const context={profileId:profile.id,profileVersion:profile.version,fixtureSetId:prepared.id,merchantCount:prepared.merchants.length};
+ let latest={...context,phase:'credentials',checks:[],checked:0,stages:{}};
+ update(id,{status:'running',progress:JSON.stringify({verification:latest})});
+ const task={cancel:()=>abort.abort(),done:null};running.set(id,task);
+ task.done=(async()=>{
+ let lastProgress=0,lastPhase='';
+ try{
+ const result=await verifyImportedMerchants(prepared.config,prepared.merchants,{signal:abort.signal,onProgress:(checks,state)=>{
+ latest={...context,...state,checks:[...checks]};
+ const now=Date.now();if(state.phase===lastPhase&&now-lastProgress<500)return;
+ lastProgress=now;lastPhase=state.phase;
+ update(id,{progress:JSON.stringify({verification:{...latest,checks:checks.slice(-100)}})});
+ }});
+ if(abort.signal.aborted)throw new Error('Verification cancelled');
+ await finishImport(prepared,result);
+ const failed=result.checks.find(c=>!c.ok);
+ update(id,{status:result.ok?'complete':'failed',ended_at:Date.now(),progress:JSON.stringify({verification:{...context,...result,phase:result.ok?'ready':'failed'}}),error:failed?`${failed.stage==='credentials'?'Credential':'Setup'} verification failed: ${failed.label} — ${failed.message}`:null});
+ }catch(e){
+ const phase=abort.signal.aborted?'cancelled':'failed';
+ const result={...latest,ok:false,phase,stages:Object.fromEntries(Object.entries(latest.stages||{}).map(([key,stage])=>[key,{...stage,status:stage.status==='running'?phase:stage.status}]))};
+ await finishImport(prepared,result).catch(()=>{});
+ update(id,{status:phase,ended_at:Date.now(),progress:JSON.stringify({verification:result}),error:abort.signal.aborted?'Verification cancelled':'Fixture verification could not complete'});
+ }finally{running.delete(id);}
+ })();
+ return getJob(id);
+}
+export async function startGenerator(kind,mode,selection={}) {
+ if(!['fixtures','load','smoke'].includes(kind) || !['single','tenancy'].includes(mode)) throw new Error('Invalid job');
+ // Report active recovery/test work before validating fixtures or binaries. The
+ // reserve step repeats this check to close races with work starting meanwhile.
+ initializeJobs();assertCanReserve(kind);
+ const config=structuredClone(readJsonSync(configPath));
+ config.environment=activeEnvironment();requireSupportedEnvironment(config.environment);
+ // Settings apply at launch, including when an existing profile is selected.
+ config.resultsLimits=validateResultsLimits(config.resultsLimits);
+ const configuredLoad=config.load;
+ const profile=selection.profileId?getProfile(selection.profileId,selection.version):null;
+ if(kind==='load'&&profile?.unavailableReason)throw new HttpError(409,profile.unavailableReason);
+ if(profile){mode=profile.mode;config.load=withConfiguredVus(profile.load,configuredLoad);config.scenarios=profile.scenarios;config.acceptance=profile.acceptance;config.profile={id:profile.id,version:profile.version,name:profile.name};}
+ config.scenarios=normalizePaymentFlows(config.scenarios);assertSupportedPaymentFlows(config.scenarios);
+ config.connectors=normalizeConnectorPlan(profile?.connectors);
+ if(kind==='fixtures'&&(config.connectors.mode==='real'||config.connectors.mix.length!==1||config.connectors.mix[0].connector!==config.fixtures.connector.connector_name||Object.keys(selection.connectorCredentials||{}).length))config.fixtures.connectorAccounts=provisionConnectorAccounts(config.connectors,selection.connectorCredentials,dataRoot);
+ const count=profile?.merchantCount ?? (mode==='single'?1:1500);
+ let fixtureSet,fixtureSetId;
+ if(['load','smoke'].includes(kind)) {
+ const available=listFixtureSets();
+ const chosen=selection.fixtureSetId || available.find(s=>s.compatible&&s.mode===mode&&s.merchant_count===count&&s.status==='ready')?.id;
+ if(!chosen)throw new HttpError(409,'Create a ready, compatible fixture set first');
+ fixtureSet=validateFixtureSet(chosen,{mode,merchantCount:count},config);fixtureSetId=fixtureSet.id;
+ }
+ const faultPlan=kind==='load'?snapshotFaultPlan(config.load,faultTargets()):[];
+ config.faultPlan=faultPlan;
+ let k6Binary=null,smoke=null;
+ const distributed=kind==='load'&&selection.execution==='distributed';
+ if(['load','smoke'].includes(kind)&&!distributed){
+ k6Binary=await resolveK6Binary({loadtestRoot,consoleRoot});
+ if(kind==='smoke'){
+ const rps=Number(selection.rps),durationSeconds=Number(selection.durationSeconds);
+ if(!Number.isInteger(rps)||rps<1||rps>100||!Number.isInteger(durationSeconds)||durationSeconds<1||durationSeconds>300)throw new Error('Smoke test needs 1–100 RPS and 1–300 seconds');
+ smoke={enabled:true,rps,durationSeconds};
+ }
+ }
+ const id=reserve(kind,mode);
+ try {
+ const jobDir=path.join(dataRoot,'jobs',id);await mkdir(jobDir,{recursive:true,mode:0o700});
+ config.mode=mode;
+ if(distributed)config.execution='distributed';
+ if(kind==='fixtures') {
+ const signature=fixtureSignature(config,mode,count);
+ fixtureSet=controlDb().prepare("SELECT * FROM fixture_sets WHERE signature=? AND status IN ('failed','interrupted') ORDER BY created_at DESC LIMIT 1").get(signature);
+ fixtureSetId=fixtureSet?.id || randomUUID();
+ const directory=fixtureSet?.path || path.join(config.output,mode,'fixture-sets',fixtureSetId);
+ if(fixtureSet)controlDb().prepare("UPDATE fixture_sets SET status='creating',job_id=? WHERE id=?").run(id,fixtureSetId);
+ else controlDb().prepare('INSERT INTO fixture_sets VALUES(?,?,?,?,?,?,?,?)').run(fixtureSetId,mode,count,signature,directory,'creating',id,Date.now());
+ fixtureSet={id:fixtureSetId,path:directory};
+ }
+ config.fixtureSet={id:fixtureSetId,merchantCount:count};
+ const runPath=kind==='load'?path.join(config.output,mode,'runs',`${new Date().toISOString().replace(/[:.]/g,'-')}-${mode}-${loadShape(config.load).peak}tps-${id.slice(0,8)}`):kind==='smoke'?path.join(jobDir,'smoke'):null;
+ if(runPath)await mkdir(runPath,{recursive:true,mode:0o700});
+ if(smoke)config.smoke=smoke;
+ const snapshot=path.join(jobDir,'config.json');await atomicJson(snapshot,config);
+ const spec={id,kind,mode,configPath:snapshot,runPath,loadtestRoot,parentPid:process.pid,fixturePath:fixtureSet.path,merchantCount:count,fixtureSetId,k6Binary,smoke};
+ await atomicJson(path.join(jobDir,'job.json'),spec);update(id,{config_path:snapshot,run_path:kind==='load'?runPath:null,status:'running'});
+ if(distributed){
+ await atomicJson(path.join(runPath,'config.json'),Object.fromEntries(Object.entries(config).filter(([key])=>!['fixtures','output'].includes(key))));
+ let lastElapsed=-1,lastPoint=null,remote;
+ const schedule=faultScheduler(faultPlan,{claim:index=>{const key=`scheduled step ${index+1}`;if(controlDb().prepare("SELECT 1 FROM job_events WHERE job_id=? AND kind='scheduled_fault' AND message=?").get(id,key))return false;recordActivity(id,'scheduled_fault',key);return true;},fire:(job,input,target,lifecycle)=>fireFault(job,input,recordActivity,()=>getJob(id),target,lifecycle),event:(eventKind,message)=>recordActivity(id,eventKind,message),gate:()=>controlWorker(id,'gate'),release:untilActiveSeconds=>controlWorker(id,'release',{until_active_seconds:untilActiveSeconds}),recover:untilActiveSeconds=>controlWorker(id,'recover',untilActiveSeconds===undefined?{}:{until_active_seconds:untilActiveSeconds})});
+ remote=await launchDistributedRun({runId:path.basename(runPath),runPath,config,fixturePath:fixtureSet.path,
+ onEvent:(eventKind,message)=>recordActivity(id,eventKind,message),
+ onProgress:async progress=>{try{const sample=executionSample(progress,config.load);if(sample)await appendFile(path.join(runPath,'execution.jsonl'),JSON.stringify(sample)+'\n',{mode:0o600});if(progress.elapsed_seconds>lastElapsed){lastElapsed=progress.elapsed_seconds;lastPoint=telemetryPoint(progress,lastPoint);await appendTelemetry(runPath,lastPoint);}progress.trend=lastPoint;const before=getJob(id),state=progress.control?.state;update(id,{progress:JSON.stringify(progress),status:state==='paused'?'paused':state==='pausing'?'pausing':before.status==='cancelling'?'cancelling':'running'});if(remote)await schedule(getJob(id),progress.control?.active_seconds);}catch(error){recordActivity(id,'progress_error',error.message);}},
+ onDone:async(error,result)=>{let recoveryError=null;if(faultStatus().active?.jobId===id)try{await restoreFaults(recordActivity);}catch(e){recoveryError=`Recovery was not verified: ${e.message}`;recordActivity(id,'fault_error',recoveryError);}const cancelled=getJob(id).status==='cancelling',exitCode=error?1:Number(result?.exitCode||0),failure=exitCode===99?workerFailure(99,null,await readJson(path.join(runPath,'summary.json'),{})):error?.message,status=finalJobStatus({cancelled,failure,recoveryError}),message=recoveryError || failure;update(id,{status,exit_code:exitCode,ended_at:Date.now(),progress:JSON.stringify(result||{}),result:result?JSON.stringify(result):null,error:message?redact(message):null});recordActivity(id,'finished',`distributed load ${getJob(id).status}`);running.delete(id);}
+ });
+ recordActivity(id,'started',`Distributed load started · ${mode} · ${loadShape(config.load).peak} TPS · ${remote.plan.length} workers`);
+ running.set(id,{distributed:true,done:remote.done,cancel:()=>remote.cancel(),control:(action,payload)=>remote.control(action,payload),runPath});return getJob(id);
+ }
+ const controlToken=randomUUID();
+ let output='',lastWrite=0,lastElapsed=-1,lastPoint=null,forceTimer;
+ const remember=async progress=>{
+ if(runPath && Number.isFinite(progress.elapsed_seconds) && progress.elapsed_seconds>lastElapsed){
+ lastElapsed=progress.elapsed_seconds;lastPoint=telemetryPoint(progress,lastPoint);await appendTelemetry(runPath,lastPoint);
+ const sample=executionSample(progress,config.load);if(sample)await appendFile(path.join(runPath,'execution.jsonl'),JSON.stringify(sample)+'\n',{mode:0o600});
+ }
+ };
+ const fixtureProgress=async()=>({fixtures:{completed:(await readJson(path.join(fixtureSet.path,'merchants.json'),[])).length,total:count},setup:await readJson(path.join(jobDir,'fixture-progress.json'),{stage:'merchants',superposition:{status:config.fixtures.superposition?'pending':'skipped'}})});
+ const child=spawn(process.execPath,[path.join(consoleRoot,'scripts','execute.mjs'),path.join(jobDir,'job.json')],{
+ cwd:consoleRoot,stdio:['ignore','pipe','pipe'],env:{...process.env,LOADTEST_JOB_DIR:jobDir,SQLITE_RECORDER_CONTROL_TOKEN:controlToken,SQLITE_RECORDER_PROGRESS_FILE:['load','smoke'].includes(kind)?path.join(runPath,'progress.json'):''}
+ });
+ recordActivity(id,'started',`${kind==='load'?'Load':kind==='smoke'?'Smoke test':'Fixture setup'} started · ${mode} · ${kind==='smoke'?smoke.rps:loadShape(config.load).peak} TPS`);
+ const log=(data)=>{output=(output+redact(data)).slice(-50000);};
+ child.stdout.on('data',log);child.stderr.on('data',log);
+ const schedule=faultScheduler(faultPlan,{claim:index=>{const key=`scheduled step ${index+1}`;if(controlDb().prepare("SELECT 1 FROM job_events WHERE job_id=? AND kind='scheduled_fault' AND message=?").get(id,key))return false;recordActivity(id,'scheduled_fault',key);return true;},fire:(job,input,target,lifecycle)=>fireFault(job,input,recordActivity,()=>getJob(id),target,lifecycle),event:(kind,message)=>recordActivity(id,kind,message),gate:()=>controlWorker(id,'gate'),release:untilActiveSeconds=>controlWorker(id,'release',{until_active_seconds:untilActiveSeconds}),recover:untilActiveSeconds=>controlWorker(id,'recover',untilActiveSeconds===undefined?{}:{until_active_seconds:untilActiveSeconds})});
+ const tick=setInterval(async()=>{
+ if(Date.now()-lastWrite<(faultPlan.length?200:900))return;lastWrite=Date.now();
+ try {
+ const worker=running.get(id),revision=worker?.revision || 0;
+ const phase=kind==='smoke'?{phase:'smoke'}:runPath?await readJson(path.join(jobDir,'phase.json'),{phase:'load'}):null;
+ const progress=runPath?await readJson(path.join(runPath,'progress.json'),{}):await fixtureProgress();
+ if(runPath)progress.phase=phase.phase;
+ const endpoint=kind==='load'?(await readJson(path.join(runPath,'control.json'),{})).endpoint:null;
+ if(endpoint && worker){
+ const u=new URL(endpoint);if(u.hostname!=='127.0.0.1'||u.pathname!=='/control')throw new Error('Invalid control endpoint');
+ try{const r=await fetch(u,{headers:{authorization:`Bearer ${controlToken}`},signal:AbortSignal.timeout(750)});if(r.ok)progress.control=await r.json();}catch{/* Worker may be exiting. */}
+ }
+ if((worker?.revision || 0)!==revision)return; // A newer pause/resume response wins.
+ if(['load','smoke'].includes(kind)){
+ await remember(progress);
+ progress.trend=lastPoint;
+ }
+ const before=getJob(id),state=progress.control?.state,values={output,progress:JSON.stringify(progress)};
+ if(['running','pausing','paused'].includes(state)&&before.status!=='cancelling')values.status=state;
+ if(state&&state!==before.progress.control?.state&&['pausing','paused','completed'].includes(state))recordActivity(id,state,state==='paused'?'Load paused · active flows drained':state==='pausing'?'Pausing · draining active flows':'Active load duration reached');
+ update(id,values);
+ if(kind==='load')await schedule(getJob(id),progress.control?.active_seconds);
+ }
+ catch(e) {log(`\nProgress unavailable: ${e.message}`);}
+ },faultPlan.length?250:1000);
+ const done=new Promise(resolve=>{
+ child.once('error',e=>{log(e.message);update(id,{status:'failed',error:redact(e.message),ended_at:Date.now(),output});});
+ child.once('close',async(code,signal)=>{
+ clearInterval(tick);clearTimeout(forceTimer);
+ const worker=running.get(id);if(worker)worker.finished=true;
+ let recoveryError=null;
+ if(faultStatus().active?.jobId===id)try{await restoreFaults(recordActivity);}catch(e){recoveryError=`Recovery was not verified: ${e.message}`;log(`\n${recoveryError}`);recordActivity(id,'fault_error',recoveryError);}
+ if(['load','smoke'].includes(kind))try{
+ const finalProgress=await readJson(path.join(runPath,'progress.json'),{});await remember(finalProgress);
+ finalProgress.phase=kind==='smoke'?'smoke':'load';finalProgress.trend=lastPoint;
+ update(id,{progress:JSON.stringify(finalProgress)});
+ }catch(e){log(`\nTrend unavailable: ${e.message}`);}
+ if(kind==='fixtures')try{update(id,{progress:JSON.stringify(await fixtureProgress())});}catch{}
+ const previous=getJob(id);
+ let result=await readJson(path.join(jobDir,'result.json'),null).catch(()=>null);
+ const summary=code===99 && runPath?await readJson(path.join(runPath,'summary.json'),null).catch(()=>null):null;
+ const failure=code===0?null:workerFailure(code,result,summary,signal),status=finalJobStatus({cancelled:previous.status==='cancelling',failure,recoveryError});
+ const message=recoveryError || (failure&&(kind==='smoke'?`Smoke test failed: ${failure}`:failure));
+ update(id,{status,exit_code:code ?? 1,ended_at:Date.now(),output,
+ result:result?JSON.stringify(result):null,error:message?redact(message):null});
+ if(kind==='fixtures')controlDb().prepare('UPDATE fixture_sets SET status=? WHERE id=?').run(code===0?'ready':'failed',fixtureSetId);
+ recordActivity(id,'finished',`${kind} job ${getJob(id).status}`);
+ running.delete(id);resolve();
+ });
+ });
+ const cancel=()=>{
+ child.kill('SIGTERM');
+ forceTimer=setTimeout(async()=>{
+ const k6=await readJson(path.join(jobDir,'k6-pid.json'),null).catch(()=>null);
+ if(k6?.pid)try {process.kill(-k6.pid,'SIGKILL');}catch{}
+ child.kill('SIGKILL');
+ },60000);
+ };
+ running.set(id,{cancel,done,controlToken,runPath});
+ try {await atomicJson(path.join(jobDir,'worker-pid.json'),{pid:child.pid});}
+ catch(e){cancel();await done;throw e;}
+ return getJob(id);
+ } catch(e) {update(id,{status:'failed',error:redact(e.message),ended_at:Date.now()});if(kind==='fixtures'&&fixtureSetId)controlDb().prepare("UPDATE fixture_sets SET status='failed' WHERE id=?").run(fixtureSetId);throw e;}
+}
+
+export async function startFaultTest(input) {
+ if(faultTargets().find(t=>t.id===input.targetId)?.adapter==='command')throw new HttpError(409,'Custom commands execute only through the scenario schedule');
+ const environment=activeEnvironment();requireSupportedEnvironment(environment);
+ if(input.environment&&input.environment!==environment)throw new Error('Environment changed; reopen the fault dialog before executing');
+ const id=reserve('fault-test',environment);
+ update(id,{status:'running',progress:JSON.stringify({environment,targetId:input.targetId,action:input.action,durationSeconds:input.durationSeconds})});
+ recordActivity(id,'fault_test','Standalone outage test · automatic recovery');
+ // Start preflight synchronously so the target is reserved before returning.
+ const done=testFault(getJob(id),input,recordActivity).then(result=>{
+ const cancelled=getJob(id).status==='cancelling';
+ update(id,{status:result?.error?'failed':cancelled?'cancelled':'complete',error:result?.error||null,result:JSON.stringify(result||{}),ended_at:Date.now(),exit_code:result?.error?1:0});
+ }).catch(e=>update(id,{status:'failed',error:redact(e.message),ended_at:Date.now(),exit_code:1})).finally(()=>running.delete(id));
+ running.set(id,{done,cancel:()=>{restoreFaults(recordActivity).catch(()=>{});}});
+ return getJob(id);
+}
+
+export async function startReconciliation(id,allowIncomplete=false) {
+ const directory=runDirectory(id),snapshot=await readJson(path.join(directory.path,'config.json'),{}),environment=activeEnvironment();
+ requireSupportedEnvironment(environment);
+ if(snapshot.environment&&snapshot.environment!==environment)throw new Error(`Select ${environmentLabel(snapshot.environment)} in Settings before reconciling this run`);
+ const jobId=reserve('reconcile',directory.mode,directory.path);
+ update(jobId,{status:'running'});
+ let worker;
+ const done=queryWorker('reconcile',{id,database:localSettings().database,allowIncomplete},
+ progress=>update(jobId,{progress:JSON.stringify(progress)}),value=>worker=value)
+ .then(result=>update(jobId,{status:'complete',result:JSON.stringify(result),ended_at:Date.now(),exit_code:result.mismatch||result.missing||result.transport?.missing||result.transport?.unresolved?2:0}))
+ .catch(e=>{if(getJob(jobId).status!=='cancelled')update(jobId,{status:'failed',error:redact(e.message),ended_at:Date.now(),exit_code:1});})
+ .finally(()=>running.delete(jobId));
+ running.set(jobId,{done,cancel:()=>{worker?.terminate();update(jobId,{status:'cancelled',ended_at:Date.now()});}});
+ return getJob(jobId);
+}
+export function cancelJob(id,force=false) {
+ const job=getJob(id);
+ if(!force&&job.command==='load'&&job.loadState==='pausing')throw new HttpError(409,'Wait for active flows to drain');
+ if(!['starting','running','pausing','paused','cancelling'].includes(job.status))return job;
+ if(job.status!=='cancelling'){update(id,{status:'cancelling'});running.get(id)?.cancel();}
+ return getJob(id);
+}
+export async function shutdownJobs() {
+ manager.shuttingDown=true;
+ const values=[...running.entries()];for(const [id] of values)cancelJob(id,true);
+ await Promise.all(values.map(([,v])=>v.done));
+ await restoreFaults(recordActivity);
+ await manager.recovery;
+}
+
+export function jobEvents(id,request) {
+ getJob(id);
+ const encoder=new TextEncoder();let timer;
+ const stream=new ReadableStream({
+ start(controller) {
+ let revision=0;
+ const finish=()=>{clearInterval(timer);try{controller.close();}catch{}};
+ const emit=()=>{
+ try {
+ const job=getJob(id);controller.enqueue(encoder.encode(`id: ${++revision}\nevent: progress\ndata: ${JSON.stringify(job)}\n\n`));
+ if(!['starting','running','pausing','paused','cancelling'].includes(job.status))finish();
+ }catch{finish();}
+ };
+ timer=setInterval(emit,1000);emit();request.signal.addEventListener('abort',finish,{once:true});
+ },cancel(){clearInterval(timer);}
+ });
+ return new Response(stream,{headers:{'content-type':'text/event-stream','cache-control':'no-cache, no-transform','x-accel-buffering':'no'}});
+}
diff --git a/loadtest/console/server/k6-binary.mjs b/loadtest/console/server/k6-binary.mjs
new file mode 100644
index 0000000000..5f73a801bd
--- /dev/null
+++ b/loadtest/console/server/k6-binary.mjs
@@ -0,0 +1,16 @@
+import {access} from 'node:fs/promises';
+import {constants} from 'node:fs';
+import path from 'node:path';
+
+/**
+ * @param {{configured?: string, loadtestRoot?: string, consoleRoot?: string, pathValue?: string}} [options]
+ */
+export async function resolveK6Binary({configured=process.env.K6_BINARY,loadtestRoot,consoleRoot,pathValue=process.env.PATH || ''}={}) {
+ const names=[];
+ if(configured)names.push(path.resolve(configured));
+ if(loadtestRoot)names.push(path.join(loadtestRoot,'k6/scenario-mix/bin/k6-sqlite'));
+ if(consoleRoot)names.push(path.join(consoleRoot,'bin/k6-sqlite'));
+ names.push('/usr/local/bin/k6-sqlite',...pathValue.split(path.delimiter).filter(Boolean).map(directory=>path.join(directory,'k6-sqlite')));
+ for(const candidate of [...new Set(names)])try{await access(candidate,constants.X_OK);return candidate;}catch{}
+ throw new Error('k6-sqlite not found. Run `npm run build:recorder` in loadtest/console or set K6_BINARY to the executable path.');
+}
diff --git a/loadtest/console/server/kubernetes-faults.mjs b/loadtest/console/server/kubernetes-faults.mjs
new file mode 100644
index 0000000000..7ee0a800d4
--- /dev/null
+++ b/loadtest/console/server/kubernetes-faults.mjs
@@ -0,0 +1,78 @@
+// A deleted API object is not proof that its containers have stopped. For hard
+// outages, verify captured pod UIDs against each node's kubelet runtime list.
+export function kubernetesAdapter(target,command){
+ const t=target,context=t.context?['--context',t.context]:[],flags=[...context,'--namespace',t.namespace];
+ const json=async args=>JSON.parse(await command('kubectl',args));
+ const inspect=()=>json([...flags,'get','deployment',t.deployment,'-o','json']);
+ const replicas=before=>t.recoveryReplicas??before.replicas;
+ const runtime=async node=>{
+ if(!/^[a-z0-9][a-z0-9.-]*$/.test(node))throw Error('Invalid Kubernetes node name');
+ const data=await json([...context,'get','--raw',`/api/v1/nodes/${node}/proxy/runningpods/`]);
+ if(data.kind!=='PodList'||!Array.isArray(data.items))throw Error('Kubelet did not return a runtime pod list');
+ return data.items;
+ };
+ const selector=info=>{
+ const s=info.spec.selector;
+ const fields=Object.entries(s?.matchLabels||{}).map(([key,value])=>`${key}=${value}`);
+ for(const expression of s?.matchExpressions||[]){
+ const {key,operator,values=[]}=expression;
+ if(operator==='In'||operator==='NotIn')fields.push(`${key} ${operator==='In'?'in':'notin'} (${values.join(',')})`);
+ else if(operator==='Exists')fields.push(key);
+ else if(operator==='DoesNotExist')fields.push(`!${key}`);
+ else throw Error('Unsupported deployment label selector');
+ }
+ if(!fields.length)throw Error('Deployment has no pod selector');
+ return fields.join(',');
+ };
+ const ownedPods=async info=>{
+ const sets=await json([...flags,'get','replicasets','--selector',selector(info),'-o','json']);
+ const owners=new Set(sets.items.filter(r=>r.metadata.ownerReferences?.some(o=>o.controller&&o.uid===info.metadata.uid)).map(r=>r.metadata.uid));
+ const pods=await json([...flags,'get','pods','--selector',selector(info),'-o','json']);
+ return pods.items.filter(p=>p.metadata.ownerReferences?.some(o=>o.controller&&owners.has(o.uid)));
+ };
+ const unchanged=async before=>{const info=await inspect();if(info.metadata.uid!==before.uid)throw Error('Deployment identity changed');return info;};
+ return {
+ probe:async()=>{
+ const info=await inspect(),count=info.spec.replicas;
+ if(!(count>0)||info.status.availableReplicas!==count||info.status.observedGeneration<info.metadata.generation)throw Error('Deployment is not ready');
+ const before={replicas:count,uid:info.metadata.uid};
+ if(t.outageMode==='hard'){
+ const pods=await ownedPods(info);
+ if(!pods.length)throw Error('No deployment-owned vault pods found');
+ before.pods=pods.map(p=>({name:p.metadata.name,uid:p.metadata.uid,node:p.spec.nodeName}));
+ // Check runtime access before making any infrastructure change.
+ for(const node of new Set(before.pods.map(p=>p.node))){
+ let running;try{running=await runtime(node);}catch{throw Error('Hard outage requires read access to kubelet runtime pods (nodes/proxy). Check Kubernetes permissions.');}
+ if(before.pods.filter(p=>p.node===node).some(p=>!running.some(r=>r.metadata.uid===p.uid)))throw Error('Vault pod runtime identity could not be verified');
+ }
+ before.outageMode='hard';
+ }
+ return before;
+ },
+ apply:async(action,before)=>{
+ await unchanged(before);
+ await command('kubectl',[...flags,'scale','deployment',t.deployment,'--replicas=0']);
+ if(before.outageMode==='hard')for(const pod of before.pods){
+ if(!/^[a-z0-9][a-z0-9.-]*$/.test(pod.name))throw Error('Invalid captured pod name');
+ const text=await command('kubectl',[...flags,'get','pod',pod.name,'--ignore-not-found=true','-o','json']);
+ const current=text.trim()?JSON.parse(text):null;
+ if(current?.metadata&&current.metadata.uid!==pod.uid)throw Error('Vault pod identity changed');
+ if(current?.metadata)await command('kubectl',[...flags,'delete','pod',pod.name,'--grace-period=0','--force','--wait=false','--ignore-not-found=true']);
+ }
+ },
+ isDown:async before=>{
+ const info=await unchanged(before);
+ if(info.spec.replicas!==0||(info.status.replicas||0)!==0||(info.status.availableReplicas||0)!==0||info.status.observedGeneration<info.metadata.generation)return false;
+ if(before.outageMode==='hard'){
+ if((await ownedPods(info)).length)return false;
+ for(const node of new Set(before.pods.map(p=>p.node))){
+ const running=await runtime(node);
+ if(before.pods.some(p=>p.node===node&&running.some(r=>r.metadata.uid===p.uid)))return false;
+ }
+ }
+ return true;
+ },
+ restore:async before=>{await unchanged(before);await command('kubectl',[...flags,'scale','deployment',t.deployment,`--replicas=${replicas(before)}`]);},
+ verify:async before=>{const info=await inspect(),count=replicas(before);return info.metadata.uid===before.uid&&info.spec.replicas===count&&(info.status.availableReplicas||0)>=count&&(info.status.readyReplicas??info.status.availableReplicas??0)>=count&&info.status.observedGeneration>=info.metadata.generation;}
+ };
+}
diff --git a/loadtest/console/server/latency-drift.mjs b/loadtest/console/server/latency-drift.mjs
new file mode 100644
index 0000000000..bf2e24585a
--- /dev/null
+++ b/loadtest/console/server/latency-drift.mjs
@@ -0,0 +1,21 @@
+import {latencyPercentile} from './successful-latency.mjs';
+
+// Match by flow type and time only. Never select samples by their latency.
+export function matchedLatencyDrift(samples,windows,{toleranceSeconds=5}={}){
+ const ordered=[...windows].sort((a,b)=>a.from-b.from),duration=ordered.reduce((n,w)=>n+w.to-w.from,0);
+ const width=duration/3,tolerance=Math.min(toleranceSeconds*1000,duration/12);
+ const position=at=>ordered.reduce((n,w)=>n+Math.max(0,Math.min(at,w.to)-w.from),0);
+ const rows=samples.map(row=>({...row,position:position(row.observed_at),flow:row.flow_name||String(row.flow_id||'unknown').split(':').at(-3)||'unknown'})).sort((a,b)=>a.observed_at-b.observed_at);
+ const first=[],last=[],counts=[];
+ for(const flow of [...new Set(rows.map(r=>r.flow))].sort()){
+ const type=rows.filter(r=>r.flow===flow),early=type.filter(r=>r.position<width+tolerance),late=type.filter(r=>r.position>=duration-width-tolerance);
+ const target=Math.max(type.filter(r=>r.position<width).length,type.filter(r=>r.position>=duration-width).length);
+ const count=Math.min(target,early.length,late.length);
+ if(!count)return {percent:null,reason:`Insufficient matched samples for ${flow}`,counts:[],firstMedianMs:null,lastMedianMs:null};
+ first.push(...early.slice(0,count));last.push(...late.slice(-count));counts.push({flow,count});
+ }
+ const median=rows=>latencyPercentile(rows.map(r=>r.server_latency_ms),.5),firstMedianMs=median(first),lastMedianMs=median(last);
+ const percent=firstMedianMs>0&&lastMedianMs!=null?Math.abs(100*(lastMedianMs-firstMedianMs)/firstMedianMs):firstMedianMs===0&&lastMedianMs===0?0:null;
+ const bounds=rows=>rows.length?rows.reduce((b,r)=>({from:Math.min(b.from,r.observed_at),to:Math.max(b.to,r.observed_at)}),{from:Infinity,to:-Infinity}):null;
+ return {percent,firstMedianMs,lastMedianMs,counts,samplesPerWindow:first.length,windowSeconds:width/1000,toleranceSeconds:tolerance/1000,firstWindow:bounds(first),lastWindow:bounds(last)};
+}
diff --git a/loadtest/console/server/local-faults.mjs b/loadtest/console/server/local-faults.mjs
new file mode 100644
index 0000000000..7abd73429e
--- /dev/null
+++ b/loadtest/console/server/local-faults.mjs
@@ -0,0 +1,52 @@
+import {spawn} from 'node:child_process';
+import {open,access,realpath} from 'node:fs/promises';
+import {constants} from 'node:fs';
+import net from 'node:net';
+import path from 'node:path';
+import {dataRoot,atomicJson,readJson} from './state.mjs';
+export function reachable(port){return new Promise(resolve=>{const socket=net.connect({host:'127.0.0.1',port});const done=value=>{socket.destroy();resolve(value);};socket.setTimeout(1000,()=>done(false));socket.once('connect',()=>done(true));socket.once('error',()=>done(false));});}
+const pause=ms=>new Promise(r=>setTimeout(r,ms));
+export async function nixExecutable(){
+ for(const binary of [...(process.env.PATH || '').split(path.delimiter).filter(Boolean).map(directory=>path.join(directory,'nix')),'/nix/var/nix/profiles/default/bin/nix']){
+ try{await access(binary,constants.X_OK);return binary;}catch{}
+ }
+ throw new Error('Nix is unavailable; card vault cannot be recovered. Add nix to the worker PATH before creating a fault.');
+}
+export async function vaultLaunchSpec(target){
+ await access(path.join(target.repository,'Cargo.toml'));
+ try{await access(path.join(target.repository,'flake.nix'));return {binary:await nixExecutable(),args:['develop','-c','cargo','r']};}catch(e){if(e.code!=='ENOENT')throw e;}
+ for(const mode of ['debug','release']){const binary=path.join(target.repository,'target',mode,'locker');try{await access(binary,constants.X_OK);return {binary,args:[]};}catch{}}
+ throw new Error('No vault flake.nix or executable target/debug/locker (or target/release/locker). Build the vault before testing an outage.');
+}
+export function processComposeController(target,request=fetch){
+ const origin=`http://127.0.0.1:${target.controllerPort}`;
+ const call=async(pathname,method='GET')=>{
+ let response;
+ try{response=await request(`${origin}${pathname}`,{method,signal:AbortSignal.timeout(5000)});}
+ catch(error){throw new Error(`Cannot reach process-compose controller at ${origin}: ${error.cause?.code||error.message}`);}
+ const body=await response.text();
+ if(!response.ok){const detail=body.trim();throw new Error(response.status===404?`Process ${target.process} is not configured in process-compose`:`Process-compose ${method} ${pathname} failed (${response.status})${detail?`: ${detail}`:''}`);}
+ if(!body.trim())return null;
+ try{return JSON.parse(body);}catch{throw new Error(`Process-compose returned invalid JSON for ${pathname}`);}
+ };
+ const name=encodeURIComponent(target.process);
+ return {inspect:()=>call(`/process/${name}`),list:async()=>{const result=await call('/processes');return Array.isArray(result)?result:result?.data;},stop:()=>call(`/process/stop/${name}`,'PATCH'),start:()=>call(`/process/start/${name}`,'POST')};
+}
+export function localAdapter(t,command,hooks={}){
+ const up=hooks.reachable||reachable;
+ if(t.adapter==='process-compose'){
+ const controller=hooks.controller;
+ const flags=['-p',String(t.controllerPort),'process','-a','127.0.0.1'];
+ const inspect=async()=>{if(controller)return controller.inspect();try{const result=JSON.parse(await command(t.binary,[...flags,'get',t.process,'-o','json']));const info=Array.isArray(result)?result.find(p=>p.name===t.process):result;if(!info)throw new Error('Missing process');return info;}catch(error){const reason=error.code==='ENOENT'?`process-compose binary not found: ${t.binary}`:error.message;throw new Error(`Cannot query process-compose at 127.0.0.1:${t.controllerPort} for ${t.process}: ${reason}`);}};
+ const running=info=>String(info.status).toLowerCase()==='running';
+ const identity=info=>({name:info.name,command:info.command,namespace:info.namespace});
+ const same=(info,before)=>JSON.stringify(identity(info))===JSON.stringify(before.identity);
+ const list=async()=>controller?controller.list():JSON.parse(await command(t.binary,['-p',String(t.controllerPort),'process','list','-o','json']));
+ const stop=()=>controller?controller.stop():command(t.binary,[...flags,'stop',t.process]);
+ const start=()=>controller?controller.start():command(t.binary,[...flags,'start',t.process]);
+ return {probe:async()=>{const info=await inspect();if(info.name!==t.process||!running(info)||!await up(t.port))throw new Error(`Process ${t.process} is not running and listening on port ${t.port}`);return {identity:identity(info)};},apply:async(_action,before)=>{if(!same(await inspect(),before))throw new Error('Process identity changed');const processes=await list();if(!Array.isArray(processes)||!processes.some(p=>p.name!==t.process&&running(p)))throw new Error('Interruption requires another running process to keep the process-compose controller alive');await stop();},isDown:async before=>{const info=await inspect();return same(info,before)&&!running(info)&&!await up(t.port);},restore:async before=>{const info=await inspect();if(!same(info,before))throw new Error('Process identity changed');if(running(info))return;await start();},verify:async before=>{const info=await inspect();return same(info,before)&&running(info)&&await up(t.port);}};
+ }
+ const listener=async()=>{let output;try{output=await command('lsof',['-nP',`-iTCP:${t.port}`,'-sTCP:LISTEN','-t']);}catch(e){if(e.code===1)return null;throw e;}const pids=[...new Set(output.trim().split(/\s+/).filter(Boolean))];if(!pids.length)return null;if(pids.length!==1)throw new Error('Expected one vault listener');const pid=Number(pids[0]);if(!Number.isSafeInteger(pid)||pid<=1)throw new Error('Invalid listener PID');const files=await command('lsof',['-a','-p',String(pid),'-d','cwd,txt','-Fn']);const names=files.split('\n').filter(line=>line.startsWith('n')).map(line=>line.slice(1));const repo=await realpath(t.repository);if(!names.includes(repo)||!names.some(name=>name.startsWith(repo+'/target/')&&path.basename(name)==='locker'))throw new Error('Port listener does not belong to the configured card-vault repository');const started=(await command('ps',['-p',String(pid),'-o','lstart='])).trim();if(!started)throw new Error('Vault process disappeared');return {pid,started,repository:repo};};
+ const launch=hooks.launch||(async()=>{const marker=path.join(dataRoot,`fault-${t.id}-launcher.json`);const prior=await readJson(marker,null);if(prior){let alive=false;try{process.kill(prior.pid,0);alive=true;}catch(e){if(e.code!=='ESRCH')throw e;}if(alive)return;}const spec=await vaultLaunchSpec(t);const log=await open(path.join(dataRoot,`fault-${t.id}.log`),'a',0o600);try{const child=spawn(spec.binary,spec.args,{cwd:t.repository,detached:true,stdio:['ignore',log.fd,log.fd]});await new Promise((resolve,reject)=>{child.once('spawn',resolve);child.once('error',reject);});const info={pid:child.pid,at:Date.now()};const saved=atomicJson(marker,info);child.once('exit',(code,signal)=>{saved.then(()=>atomicJson(marker,{...info,exitCode:code,signal})).catch(()=>{});});await saved;child.unref();}finally{await log.close();}});
+ return {probe:async()=>{const info=await listener();if(!info)throw new Error('Card vault is not listening');if(!hooks.launch){await vaultLaunchSpec(t);}return info;},apply:async(action,before)=>{const now=await listener();if(!now||now.pid!==before.pid||now.started!==before.started)throw new Error('Vault process identity changed');(hooks.kill||process.kill)(before.pid,'SIGTERM');const deadline=Date.now()+30000;while(await up(t.port)){if(Date.now()>deadline)throw new Error('Vault did not stop after SIGTERM');await pause(250);}},isDown:async()=>!await up(t.port),restore:async()=>{if(await up(t.port)){await listener();return;}await launch();},verify:async()=>{if(!await up(t.port)){if(!hooks.launch){const info=await readJson(path.join(dataRoot,`fault-${t.id}-launcher.json`),null);if(info&&('exitCode' in info))throw new Error(`Vault launcher exited ${info.exitCode ?? info.signal}; see fault-${t.id}.log`);}return false;}return Boolean(await listener());}};
+}
diff --git a/loadtest/console/server/merge-shards.mjs b/loadtest/console/server/merge-shards.mjs
new file mode 100644
index 0000000000..82c6f6c3b4
--- /dev/null
+++ b/loadtest/console/server/merge-shards.mjs
@@ -0,0 +1,49 @@
+import {DatabaseSync} from 'node:sqlite';
+import {copyFile,readFile,writeFile} from 'node:fs/promises';
+import path from 'node:path';
+
+const quote=value=>`'${String(value).replaceAll("'","''")}'`;
+function quantile(db,runId,flowName,percentile,column='latency_ms'){
+ const filter=flowName?' AND flow_id LIKE ?':'',args=flowName?[runId,`%:${flowName}:%`]:[runId];
+ const count=Number(db.prepare(`SELECT count(*) n FROM request_events WHERE run_id=? AND role='measured' AND operation='payment_confirm' AND ${column} IS NOT NULL${filter}`).get(...args).n);if(!count)return null;
+ const offset=Math.max(0,Math.ceil(count*percentile)-1);return Number(db.prepare(`SELECT ${column} value FROM request_events WHERE run_id=? AND role='measured' AND operation='payment_confirm' AND ${column} IS NOT NULL${filter} ORDER BY ${column} LIMIT 1 OFFSET ?`).get(...args,offset).value);
+}
+function mergeMetric(target,metric){
+ const output=target||{type:metric.type,contains:metric.contains,values:{},...(metric.thresholds?{thresholds:structuredClone(metric.thresholds)}:{})};for(const [key,value] of Object.entries(metric.values||{})){
+ if(['count','passes','fails','value'].includes(key))output.values[key]=Number(output.values[key]||0)+Number(value||0);
+ }
+ for(const [expression,result] of Object.entries(metric.thresholds||{})){const previous=output.thresholds?.[expression];output.thresholds||={};output.thresholds[expression]={...previous,...result,ok:(previous?.ok??true)&&result.ok!==false};}
+ return output;
+}
+export async function mergeWorkerShards({runPath,runId,shards,config}){
+ if(!shards.length)throw new Error('No worker result shards were uploaded');const canonical=path.join(runPath,'results.sqlite');await copyFile(shards[0].database,canonical);
+ const db=new DatabaseSync(canonical),base=db.prepare('SELECT * FROM runs LIMIT 1').get();if(!base){db.close();throw new Error('First worker shard has no run record');}
+ if(!db.prepare('PRAGMA table_info(request_events)').all().some(c=>c.name==='server_latency_ms'))db.exec('ALTER TABLE request_events ADD COLUMN server_latency_ms REAL');
+ for(const column of ['requested_connector','selected_connector_account','connector','merchant_connector_id'])if(!db.prepare('PRAGMA table_info(request_events)').all().some(c=>c.name===column))db.exec(`ALTER TABLE request_events ADD COLUMN ${column} TEXT`);
+ const original=base.run_id;for(const table of ['request_events','customers','payments'])db.prepare(`UPDATE ${table} SET run_id=? WHERE run_id=?`).run(runId,original);db.prepare('UPDATE runs SET run_id=? WHERE run_id=?').run(runId,original);
+ let enqueued=Number(base.enqueued),persisted=Number(base.persisted),started=Number(base.started_at),ended=Number(base.ended_at||0),complete=base.recording_state==='complete',error=base.error||null;
+ for(let index=1;index<shards.length;index++){
+ const alias=`shard${index}`,file=shards[index].database;db.exec(`ATTACH DATABASE ${quote(file)} AS ${alias}`);const run=db.prepare(`SELECT * FROM ${alias}.runs LIMIT 1`).get();if(!run){db.exec(`DETACH DATABASE ${alias}`);throw new Error(`Worker shard ${index+1} has no run record`);}
+ const offset=Number(db.prepare('SELECT COALESCE(MAX(event_id),0) n FROM request_events').get().n),source=quote(run.run_id),target=quote(runId);
+ const sourceColumns=db.prepare(`PRAGMA ${alias}.table_info(request_events)`).all().map(c=>c.name);
+ const connectorColumns=['requested_connector','selected_connector_account','connector','merchant_connector_id'].map(c=>sourceColumns.includes(c)?c:'NULL').join(',');
+ const serverColumn=db.prepare(`PRAGMA ${alias}.table_info(request_events)`).all().some(c=>c.name==='server_latency_ms')?'server_latency_ms':'NULL';
+ db.exec('BEGIN');try{
+ db.exec(`INSERT INTO request_events SELECT event_id+${offset},${target},attempt_id,flow_id,merchant_id,operation,role,observed_at,method,url,customer_id,merchant_reference_id,payment_id,amount,status,api_status_code,request_id,latency_ms,message,error_body,entity_type,${serverColumn},${connectorColumns} FROM ${alias}.request_events WHERE run_id=${source}`);
+ db.exec(`INSERT OR IGNORE INTO customers SELECT ${target},customer_id,merchant_id,merchant_reference_id,api_status_code,request_id,message,observed_at,response_event_id+${offset} FROM ${alias}.customers WHERE run_id=${source}`);
+ db.exec(`INSERT OR IGNORE INTO payments SELECT ${target},payment_id,merchant_id,customer_id,amount,status,role,api_status_code,request_id,message,observed_at,response_event_id+${offset} FROM ${alias}.payments WHERE run_id=${source}`);
+ db.exec('COMMIT');
+ }catch(e){db.exec('ROLLBACK');throw e;}finally{db.exec(`DETACH DATABASE ${alias}`);}
+ enqueued+=Number(run.enqueued);persisted+=Number(run.persisted);started=Math.min(started,Number(run.started_at));ended=Math.max(ended,Number(run.ended_at||0));complete&&=run.recording_state==='complete';error||=run.error;
+ }
+ const metadata={...JSON.parse(String(base.metadata||'{}')),distributed:{workers:shards.map(shard=>shard.workerId)}};
+ db.prepare('UPDATE runs SET recording_state=?,started_at=?,ended_at=?,enqueued=?,persisted=?,error=?,metadata=? WHERE run_id=?').run(complete&&enqueued===persisted?'complete':'incomplete',started,ended||null,enqueued,persisted,error,JSON.stringify(metadata),runId);
+ const aggregate={metrics:{}};for(const shard of shards){let summary={};try{summary=JSON.parse(await readFile(shard.summary,'utf8'));}catch{}for(const [name,metric] of Object.entries(summary.metrics||{}))aggregate.metrics[name]=mergeMetric(aggregate.metrics[name],metric);}
+ for(const metric of Object.values(aggregate.metrics)){const values=metric.values;if(values.passes!=null||values.fails!=null)values.rate=Number(values.passes||0)/(Number(values.passes||0)+Number(values.fails||0)||1);}
+ const addTrend=(name,flow=null,column='latency_ms')=>{const p90=quantile(db,runId,flow,.9,column),p99=quantile(db,runId,flow,.99,column);if(p99!=null)aggregate.metrics[name]={type:'trend',contains:'time',values:{'p(90)':p90,'p(99)':p99}};};
+ addTrend('payment_confirm_latency_ms');for(const scenario of config.scenarios||[])addTrend(`payment_confirm_ms_${scenario.name}`,scenario.name);
+ addTrend('payment_confirm_server_latency_ms',null,'server_latency_ms');for(const scenario of config.scenarios||[])addTrend(`payment_confirm_server_ms_${scenario.name}`,scenario.name,'server_latency_ms');
+ // Successful TPS is additive across workers. k6 exposes these as gauges.
+ for(const scenario of config.scenarios||[]){const metric=aggregate.metrics[`achieved_tps_${scenario.name}`];if(metric)metric.values.value=Number(metric.values.value||0);}
+ await writeFile(path.join(runPath,'summary.json'),JSON.stringify(aggregate,null,2)+'\n',{mode:0o600});db.close();return {database:canonical,summary:path.join(runPath,'summary.json'),workers:shards.length,enqueued,persisted};
+}
diff --git a/loadtest/console/server/profiles.mjs b/loadtest/console/server/profiles.mjs
new file mode 100644
index 0000000000..060ac34c37
--- /dev/null
+++ b/loadtest/console/server/profiles.mjs
@@ -0,0 +1,146 @@
+import {importedCompatibility} from './fixture-import.mjs';
+import {connectorSet,normalizeConnectorPlan} from '../src/connector-config.mjs';
+import {defaultScenarios,isDefaultScenario} from './default-scenarios.mjs';
+import {normalizePaymentFlows} from '../src/payment-flows.mjs';
+import {randomUUID,createHash} from 'node:crypto';
+import path from 'node:path';
+import {controlDb,publicSettings,validateSettings,readJsonSync,configPath,activeEnvironment} from './state.mjs';
+import {HttpError} from './errors.mjs';
+import {loadShape} from '../src/load-shape.mjs';
+import {snapshotFaultPlan} from './fault-plan.mjs';
+import {faultTargets,localFaultTargets,saveLocalFaultTargets} from './faults.mjs';
+const fields=['connectors','mode','merchantCount','totalRps','durationSeconds','loadShape','startRps','stagesJson','acceptance','preAllocatedVusMultiplier','maxVusMultiplier','scenarios'];
+export function profileDraft(settings=publicSettings()) {
+ return Object.fromEntries(fields.map(k=>[k,k==='connectors'?normalizeConnectorPlan(settings.connectors):k==='merchantCount'?(settings.mode==='tenancy'?1500:1):settings[k]]));
+}
+function protectDefault(id){if(isDefaultScenario(id))throw new HttpError(403,'Default scenarios cannot be edited, archived or deleted');}
+function builtInProfiles(){return defaultScenarios(activeEnvironment(),faultTargets());}
+export function saveProfile(input,id=null) {
+ protectDefault(id);
+ const db=controlDb(),existing=id?db.prepare('SELECT * FROM profiles WHERE id=?').get(id):null;
+ if(id&&!existing)throw new HttpError(404,'Scenario not found');
+ if(existing&&input.version!==existing.version)throw new HttpError(409,'Scenario changed; reload before saving');
+ const name=String(input.name || '').trim();if(!name||name.length>100)throw new Error('Choose a scenario name (1–100 characters)');
+ const merged={...publicSettings(),...profileDraft(input)};
+ const count=Number(input.merchantCount ?? (input.mode==='tenancy'?1500:1));
+ if(!Number.isInteger(count)||(input.mode==='single'?count!==1:count<2||count>1500))throw new Error('Single needs 1 merchant; Tenancy needs 2–1,500');
+ const {config}=validateSettings(merged);
+ snapshotFaultPlan(config.load,faultTargets());
+ const shape=loadShape(config.load);
+ const body={...profileDraft(merged),totalRps:shape.peak,durationSeconds:shape.duration,merchantCount:count,load:config.load,scenarios:config.scenarios,acceptance:config.acceptance};
+ id ||=randomUUID();const version=(existing?.version || 0)+1;
+ db.exec('SAVEPOINT profile_save');
+ try {
+ // Recheck inside the transaction so two web processes cannot overwrite each other.
+ const latest=db.prepare('SELECT version FROM profiles WHERE id=?').get(id);
+ if(latest&&latest.version!==input.version)throw new HttpError(409,'Scenario changed; reload before saving');
+ db.prepare('INSERT INTO profile_versions VALUES(?,?,?)').run(id,version,JSON.stringify({...body,name}));
+ const now=Date.now();
+ db.prepare('INSERT INTO profiles(id,name,version,updated_at,created_at) VALUES(?,?,?,?,?) ON CONFLICT(id) DO UPDATE SET name=excluded.name,version=excluded.version,updated_at=excluded.updated_at').run(id,name,version,now,now);
+ db.exec('RELEASE profile_save');
+ }catch(e){db.exec('ROLLBACK TO profile_save; RELEASE profile_save');throw e;}
+ return getProfile(id,version);
+}
+export function getProfile(id,version=null) {
+ if(isDefaultScenario(id)){const profile=builtInProfiles().find(p=>p.id===id);if(version!=null&&Number(version)!==profile.version)throw new HttpError(404,'Scenario version not found');return profile;}
+ const db=controlDb(),row=db.prepare('SELECT * FROM profiles WHERE id=?').get(id);
+ if(!row)throw new HttpError(404,'Scenario not found');
+ const saved=db.prepare('SELECT body FROM profile_versions WHERE profile_id=? AND version=?').get(id,version ?? row.version);
+ if(!saved)throw new HttpError(404,'Scenario version not found');
+ const body=JSON.parse(saved.body);return {id,version:version ?? row.version,updatedAt:row.updated_at,...body,createdAt:row.created_at,connectors:normalizeConnectorPlan(body.connectors),scenarios:normalizePaymentFlows(body.scenarios)};
+}
+export function saveScenario({profile,targets,expectedTargets}) {
+ const db=controlDb();db.exec('BEGIN IMMEDIATE');
+ try {
+ if(targets!==undefined){
+ if(JSON.stringify(localFaultTargets())!==expectedTargets)throw new HttpError(409,'Shared fault targets changed in another editor. Reopen this scenario before saving.');
+ saveLocalFaultTargets(targets);
+ }
+ const fromDefault=isDefaultScenario(profile.id);
+ const name=fromDefault&&profile.name===getProfile(profile.id).name?`${profile.name} (copy)`:profile.name;
+ const saved=saveProfile({...profile,name},fromDefault?null:profile.id||null),savedTargets=localFaultTargets();
+ db.exec('COMMIT');return {profile:saved,targets:savedTargets};
+ }catch(error){db.exec('ROLLBACK');throw error;}
+}
+export function archiveProfile(id,archived){
+ protectDefault(id);
+ getProfile(id);const db=controlDb();
+ if(archived)db.prepare('INSERT OR REPLACE INTO archived_profiles VALUES(?,?)').run(id,Date.now());
+ else db.prepare('DELETE FROM archived_profiles WHERE profile_id=?').run(id);
+ return {id,archived};
+}
+export function deleteProfile(id){
+ protectDefault(id);
+ getProfile(id);const db=controlDb();db.exec('SAVEPOINT profile_delete');
+ try{
+ db.prepare('DELETE FROM archived_profiles WHERE profile_id=?').run(id);
+ db.prepare('DELETE FROM profile_versions WHERE profile_id=?').run(id);
+ db.prepare('DELETE FROM profiles WHERE id=?').run(id);
+ db.exec('RELEASE profile_delete');return {id,deleted:true};
+ }catch(error){db.exec('ROLLBACK TO profile_delete; RELEASE profile_delete');throw error;}
+}
+export function listProfiles({includeArchived=false}={}) {
+ const db=controlDb();
+ return [...db.prepare('SELECT p.id,a.archived_at FROM profiles p LEFT JOIN archived_profiles a ON a.profile_id=p.id ORDER BY p.created_at DESC,p.rowid DESC').all().filter(r=>includeArchived||!r.archived_at).map(r=>({...getProfile(r.id),archived:Boolean(r.archived_at)})),...builtInProfiles()];
+}
+function canonical(value){if(Array.isArray(value))return value.map(canonical);if(value&&typeof value==='object')return Object.fromEntries(Object.keys(value).sort().map(k=>[k,canonical(value[k])]));return value;}
+export function fixtureSignature(config,mode,count) {
+ const sp=config.fixtures?.superposition || {};
+ const identity={environment:config.environment||activeEnvironment(),paymentFlowVersion:2,router:config.fixtures?.router || config.services?.router,connector:config.connectors&&!(config.connectors.mode==='dummy'&&connectorSet(config.connectors).join(',')==='stripe_test')?connectorSet(config.connectors):config.fixtures?.connector,
+ superposition:{organization_id:sp.organization_id,workspace_id:sp.workspace_id,defaults:sp.defaults,context:sp.context},mode,count};
+ return createHash('sha256').update(JSON.stringify(canonical(identity))).digest('hex');
+}
+export function getFixtureSet(id) {
+ const row=controlDb().prepare("SELECT * FROM fixture_sets WHERE id=? AND status<>'deleted'").get(id);if(!row)throw new HttpError(404,'Fixture set not found');return row;
+}
+export function deleteFixtureSet(id) {
+ const db=controlDb();
+ getFixtureSet(id);
+ if(db.prepare("SELECT 1 FROM jobs WHERE kind IN ('fixtures','load','smoke') AND status IN ('starting','running','pausing','paused','cancelling') LIMIT 1").get())throw new HttpError(409,'Finish active fixture setup and load tests before deleting fixtures');
+ // Keep a tombstone so CLI fixtures are not re-imported on the next refresh.
+ // Saved runs and provisioned remote merchants retain their existing data.
+ db.prepare("UPDATE fixture_sets SET status='deleted' WHERE id=?").run(id);
+ return {id,deleted:true};
+}
+export function listFixtureSets() {
+ const db=controlDb(),config=readJsonSync(configPath);
+ // Import existing CLI fixture sets once, without returning their credentials.
+ for(const mode of ['single','tenancy']) {
+ const directory=path.join(config.output,mode,'fixtures'),manifest=readJsonSync(path.join(directory,'manifest.json'));
+ if(manifest?.state==='ready'&&!db.prepare('SELECT id FROM fixture_sets WHERE path=?').get(directory)){
+ const provision=readJsonSync(path.join(directory,'provision.json'),config.fixtures);
+ const {merchant_count:_count,merchant_id_prefix:_prefix,...original}=provision;
+ const imported={...config,fixtures:{...original,merchant_id_prefix:config.fixtures.merchant_id_prefix}};
+ const count=manifest.merchant_count || (mode==='single'?1:1500);
+ db.prepare('INSERT INTO fixture_sets VALUES(?,?,?,?,?,?,NULL,?)').run(randomUUID(),mode,count,fixtureSignature(imported,mode,count),directory,'ready',Date.parse(manifest.ready_at)||Date.now());
+ }
+ }
+ return db.prepare("SELECT * FROM fixture_sets WHERE status<>'deleted' ORDER BY created_at DESC").all().map(({path:directory,signature,...row})=>{
+
+ const manifest=readJsonSync(path.join(directory,'manifest.json'),{});
+ if(manifest.source==='imported'){
+ let profile;try{profile=getProfile(manifest.profileId);}catch{}
+ const imported=importedCompatibility({...row,path:directory},{...config,environment:activeEnvironment(),connectors:profile?.connectors,scenarios:profile?.scenarios||[]});
+ return {...row,...imported,compatible:Boolean(profile)&&imported.compatible,destination:manifest.destination||config.services.router,label:`Imported · ${row.merchant_count} merchants`,repairable:false};
+ }
+ const job=row.job_id?db.prepare('SELECT config_path FROM jobs WHERE id=?').get(row.job_id):null;
+ const original=job?.config_path?readJsonSync(job.config_path):null;
+ const provision=readJsonSync(path.join(directory,'provision.json'),original?.fixtures);
+ const before=provision||{},after=config.fixtures||{},changes=[];
+ const compatible=signature===fixtureSignature(before.connectorPlan?{...config,connectors:before.connectorPlan}:config,row.mode,row.merchant_count);
+ const connectors=before.connectorPlan?connectorSet(before.connectorPlan):[before.connector?.connector_name||config.fixtures?.connector?.connector_name||'stripe_test'];
+ const checks=[['Router',before.router,after.router||config.services?.router],['Connector',before.connector,after.connector],['Superposition organization',before.superposition?.organization_id,after.superposition?.organization_id],['Superposition workspace',before.superposition?.workspace_id,after.superposition?.workspace_id],['Superposition defaults',before.superposition?.defaults,after.superposition?.defaults],['Superposition context',before.superposition?.context,after.superposition?.context]];
+ if(!compatible)for(const [label,a,b] of checks)if(JSON.stringify(canonical(a))!==JSON.stringify(canonical(b)))changes.push(label);
+ if(!compatible&&!changes.length)changes.push('Saved provisioning configuration');
+ return {...row,source:'created',compatible,connectors,changes,destination:before.router||original?.services?.router||'Earlier configuration',label:`${row.mode==='single'?'Single':'Tenancy'} · ${row.merchant_count} merchants`,repairable:compatible&&['failed','interrupted'].includes(row.status)};
+ }).filter(row=>row.source!=='imported'||row.status==='ready');
+}
+export function validateFixtureSet(id,profile,config) {
+ const set=getFixtureSet(id),manifest=readJsonSync(path.join(set.path,'manifest.json'));
+ if(set.status!=='ready'||manifest?.state!=='ready')throw new HttpError(409,'Select a ready fixture set');
+ if(set.mode!==profile.mode||set.merchant_count!==profile.merchantCount)throw new HttpError(409,'Fixture merchant mode/count does not match the scenario');
+ const imported=importedCompatibility(set,config);
+ if(imported){if(!imported.compatible)throw new HttpError(409,'Imported fixture verification is stale or failed; verify it for this scenario again');return set;}
+ if(set.signature!==fixtureSignature(config,profile.mode,profile.merchantCount))throw new HttpError(409,'Service or fixture settings changed; create compatible fixtures first');
+ return set;
+}
diff --git a/loadtest/console/server/queries.mjs b/loadtest/console/server/queries.mjs
new file mode 100644
index 0000000000..56f000c6ef
--- /dev/null
+++ b/loadtest/console/server/queries.mjs
@@ -0,0 +1,255 @@
+import {connectorResults} from './connector-results.mjs';
+import { DatabaseSync } from 'node:sqlite';
+import { readdir, stat, readFile } from 'node:fs/promises';
+import path from 'node:path';
+import pg from 'pg';
+import { readJson, runDirectory, configPath,dataRoot } from './state.mjs';
+import { readTelemetry } from './telemetry.mjs';
+import {runJobPresentation} from '../src/run-lifecycle.mjs';
+import {displayErrorCounts} from './display-errors.mjs';
+import {loadShape,loadTimeline} from '../src/load-shape.mjs';
+import {evaluateAcceptance} from './acceptance.mjs';
+import {successfulServerLatency} from './successful-latency.mjs';
+import {scenarioChecks} from './scenario-checks.mjs';
+import {seedPaymentIndex,outcomeWriter} from './reconciliation-index.mjs';
+import {databaseConnectionOptions,databaseConnectionError} from './database-options.mjs';
+import {diagnosticText,diagnosticBody} from '../../k6/scenario-mix/diagnostics.mjs';
+
+const value = (summary,name,key,fallback=0) => Number(summary?.metrics?.[name]?.values?.[key] ?? fallback);
+const labels = { guest:'Guest payment',cit_off_session:'CIT off-session',cit_on_session:'CIT on-session',sdk_checkout:'SDK checkout',
+ ptv_on_session:'Pay to vault · on-session',ptv_off_session:'Pay to vault · off-session',mit:'Merchant-initiated payment',
+ cit_metadata_changed:'Card metadata update',saved_card_checkout:'Saved-card checkout' };
+
+export async function describeRun(id,{includeTelemetry=true}={}) {
+ const directory = runDirectory(id);
+ const [config,summary,live] = await Promise.all([readJson(path.join(directory.path,'config.json'),{}),readJson(path.join(directory.path,'summary.json'),{}),readJson(path.join(directory.path,'progress.json'),null)]);
+ let recording = {recording_state:'missing',enqueued:0,persisted:0}, payments=0,failedCreates=0,confirmCounts=null;
+ try {
+ const db = new DatabaseSync(path.join(directory.path,'results.sqlite'),{readOnly:true});
+ try {
+ recording=db.prepare('SELECT * FROM runs ORDER BY started_at DESC LIMIT 1').get() || recording;
+ // Live progress comes from k6's counters; do not scan projections during load.
+ if(recording.ended_at) payments=Number(db.prepare("SELECT count(*) n FROM payments WHERE run_id=? AND role='measured'").get(recording.run_id).n);
+ if(recording.ended_at)failedCreates=Number(db.prepare("SELECT COUNT(*) n FROM request_events WHERE run_id=? AND role='measured' AND operation='payment_create' AND (payment_id IS NULL OR payment_id='') AND (api_status_code=0 OR api_status_code>=400)").get(recording.run_id).n);
+ if(recording.ended_at)confirmCounts=db.prepare("SELECT COUNT(*) AS attempts,COALESCE(SUM(CASE WHEN api_status_code=0 OR api_status_code>=400 THEN 1 ELSE 0 END),0) AS errors FROM request_events WHERE run_id=? AND role='measured' AND operation='payment_confirm'").get(recording.run_id);
+ } finally { db.close(); }
+ } catch(e) { if(e.code !== 'ERR_SQLITE_ERROR') throw e; }
+ const metric = summary.metrics || {};
+ const final = Boolean(summary.metrics);
+ const shape=loadShape(config.load),duration=shape.duration;
+ const wallElapsed = Math.max(0,(recording.ended_at || Date.now())-(recording.started_at || Date.now()))/1000;
+ const elapsed = Math.min(duration,wallElapsed);
+ const flows=(config.scenarios || []).map(f=>({
+ name:f.name,label:labels[f.scenario] || f.name,
+ offeredTps:Number((shape.peak*f.weight/100).toFixed(2)),
+ successes:value(summary,`scenario_success_${f.name}`,'count'),
+ successfulTps:Number(value(summary,`achieved_tps_${f.name}`,'value').toFixed(2)),
+ serverP99:metric[`payment_confirm_server_ms_${f.name}`]?.values?.['p(99)'] ?? null,
+ confirmP99:metric[`payment_confirm_ms_${f.name}`]?.values?.['p(99)'] == null ? null : Number(metric[`payment_confirm_ms_${f.name}`].values['p(99)'].toFixed(1)),
+ confirmP90:metric[`payment_confirm_ms_${f.name}`]?.values?.['p(90)'] == null ? null : Math.round(metric[`payment_confirm_ms_${f.name}`].values['p(90)']),
+ errors:value(summary,`scenario_failure_${f.name}`,'count')
+ }));
+ const result={id,...directory,path:undefined,runId:recording.run_id,startedAt:recording.started_at || (await stat(directory.path)).birthtimeMs,
+ endedAt:recording.ended_at,recordingState:recording.recording_state,
+ complete:recording.recording_state==='complete' && recording.enqueued===recording.persisted,
+ environment:config.environment||null,profile:config.profile || null,fixtureSetId:config.fixtureSet?.id,merchantCount:config.fixtureSet?.merchantCount,
+ savedSettings:{mode:config.mode,limitsSaved:Boolean(config.acceptance),requestTimeoutMs:config.load?.request_timeout_ms},
+ timeline:loadTimeline(config.load,config.faultPlan),durationSeconds:duration,elapsedSeconds:Math.round(elapsed),offeredTps:shape.peak,expectedAverageTps:shape.average,
+ iterations:live?.control?flows.reduce((s,f)=>s+f.successes+f.errors,0):value(summary,'iterations','count'),
+ serverP99:metric.payment_confirm_server_latency_ms?.values?.['p(99)'] ?? null,
+ confirmP99:metric.payment_confirm_latency_ms?.values?.['p(99)'] == null ? null : Number(metric.payment_confirm_latency_ms.values['p(99)'].toFixed(1)),
+ activeSeconds:live?.control?.active_seconds ?? elapsed,wallSeconds:live?.control?.wall_seconds ?? wallElapsed,successfulTps:Number(flows.reduce((s,f)=>s+f.successfulTps,0).toFixed(2)),
+ errorRate:Number((value(summary,'http_req_failed','rate')*100).toFixed(2)),dropped:live?.control?.dropped ?? value(summary,'dropped_iterations','count'),
+ confirmErrorRate:confirmCounts?(confirmCounts.attempts?Number((100*confirmCounts.errors/confirmCounts.attempts).toFixed(2)):0):live?.confirm_http_attempts==null?null:live.confirm_http_attempts?Number((100*live.confirm_http_errors/live.confirm_http_attempts).toFixed(2)):0,
+ enqueued:Number(recording.enqueued),persisted:Number(recording.persisted),gaps:Number(recording.enqueued)-Number(recording.persisted),payments,failedCreates,flows};
+ if (!final && live) {
+ result.live=true;result.loadState=live.control?.state || 'running';result.elapsedSeconds=Math.round(Math.min(duration,live.control?.active_seconds ?? live.elapsed_seconds));result.confirmP99=live.p99_ms ?? null;result.serverP99=live.server_p99_ms ?? null;
+ result.iterations=live.iterations;result.successfulTps=Number(live.successful_tps.toFixed(2));result.dropped=live.dropped;
+ result.errorRate=live.http_attempts ? Number((100*live.http_errors/live.http_attempts).toFixed(2)) : 0;
+ result.enqueued=live.recorder.enqueued;result.persisted=live.recorder.persisted;result.gaps=result.enqueued-result.persisted;
+ for (const f of result.flows) Object.assign(f,live.flows[f.name] ? {successfulTps:Number(live.flows[f.name].tps.toFixed(2)),successes:live.flows[f.name].successes,errors:live.flows[f.name].failures,serverP99:live.flows[f.name].server_p99_ms ?? null,confirmP90:live.flows[f.name].p90_ms,confirmP99:live.flows[f.name].p99_ms} : {});
+ }
+ // A crash-recovered job cannot be mistaken for a running or complete recording.
+ try {
+ const control=new DatabaseSync(path.join(dataRoot,'console.sqlite'),{readOnly:true});
+ try {
+ const job=control.prepare("SELECT id,status,output FROM jobs WHERE run_path=? AND kind='load' ORDER BY started_at DESC LIMIT 1").get(directory.path);
+ if(job)Object.assign(result,runJobPresentation(job.status,recording));
+ if(result.cleanupPending){result.live=false;result.loadState='completed';}
+ if(job && includeTelemetry)result.diagnostics=job.output;
+ if(job)result.activity=control.prepare('SELECT event_id AS id,at,kind,message FROM job_events WHERE job_id=? ORDER BY event_id').all(job.id);
+ if(job && ['complete','cancelled','failed','interrupted'].includes(job.status)){
+ result.loadState=job.status==='complete'?'completed':job.status;
+ result.live=false;
+ if(['cancelled','interrupted'].includes(job.status)){result.recordingState='incomplete';result.complete=false;}
+ }
+ }finally{control.close();}
+ }catch { /* Legacy CLI runs have no console job. */ }
+ if(!result.activity){const lines=await readFile(path.join(directory.path,'activity.jsonl'),'utf8').catch(e=>{if(e.code==='ENOENT')return '';throw e;});result.activity=lines.trim().split('\n').filter(Boolean).flatMap(line=>{try{return [JSON.parse(line)];}catch{return [];}}).sort((a,b)=>a.id-b.id);}
+ const reconciliation = await readJson(path.join(directory.path,'reconciliation.json'));
+ if(reconciliation) result.reconciliation=reconciliation;
+ if(live?.control)result.elapsedSeconds=Math.round(live.control.active_seconds);
+ if(!result.live&&!result.loadState)result.loadState='completed';
+ if(includeTelemetry)result.connectors=connectorResults(directory.path,config.connectors);
+ if(includeTelemetry)result.telemetry=await readTelemetry(directory.path,recording,result.activity,config);
+ const displayCounts=displayErrorCounts(directory.path,result.activity,config),hidden=displayCounts?.hidden||0;
+ result.hiddenVaultErrors=hidden;
+ result.displayErrorRate=displayCounts?Number((displayCounts.attempts?100*displayCounts.errors/displayCounts.attempts:0).toFixed(2)):result.errorRate;
+ result.acceptance=evaluateAcceptance(result,config.acceptance);
+ if(includeTelemetry)result.scenarioChecks=await scenarioChecks(directory.path,{config,recording,events:result.activity,reconciliation,jobStatus:result.jobStatus});
+ if(!result.live){
+ const successfulLatency=successfulServerLatency(directory.path,recording,result.activity,config);
+ result.serverLatencyPhases=successfulLatency?.phases??[];result.recoveryLatencySeconds=successfulLatency?.recoverySeconds??10;
+ result.serverP99=successfulLatency?.p99??null;for(const flow of result.flows)flow.serverP99=successfulLatency?.flows[flow.name]??null;
+ }
+ return result;
+}
+
+export async function listRuns() {
+ const config=await readJson(configPath), runs=[];
+ for(const mode of ['single','tenancy']) {
+ const entries=await readdir(path.join(config.output,mode,'runs'),{withFileTypes:true}).catch(e=>{if(e.code==='ENOENT')return [];throw e;});
+ for(const entry of entries) if(entry.isDirectory()) {
+ try {
+ // Navigation needs labels and recording state, not a full scan of every
+ // saved request. Calculate latency and verdicts only for the selected run.
+ const id=`${mode}:${entry.name}`,directory=runDirectory(id);
+ const saved=await readJson(path.join(directory.path,'config.json'),{});
+ let recording;
+ let db;
+ try {
+ db=new DatabaseSync(path.join(directory.path,'results.sqlite'),{readOnly:true});
+ recording=db.prepare('SELECT started_at,ended_at,recording_state FROM runs ORDER BY started_at DESC LIMIT 1').get();
+ } catch(error) { if(error.code!=='ERR_SQLITE_ERROR')throw error; }
+ finally { db?.close(); }
+ runs.push({id,mode,name:entry.name,profile:saved.profile||null,environment:saved.environment||null,fixtureSetId:saved.fixtureSet?.id,
+ startedAt:recording?.started_at || (await stat(directory.path)).birthtimeMs,endedAt:recording?.ended_at,recordingState:recording?.recording_state || 'missing'});
+ } catch { /* Skip directories without readable run artifacts. */ }
+ }
+ }
+ return runs.sort((a,b)=>b.startedAt-a.startedAt);
+}
+
+export function requestHistory({id,after=0,limit=100,search='',operation='',status='',payment='',merchant='',event=''}) {
+ const {path:directory}=runDirectory(id), db=new DatabaseSync(path.join(directory,'results.sqlite'),{readOnly:true});
+ try {
+ const predicates=['event_id>?'],args=[Number(after)];
+ if(event){predicates.push('event_id=?');args.push(Number(event));}
+ for(const [column,value] of [['operation',operation],['payment_id',payment],['merchant_id',merchant]])if(value){predicates.push(`${column}=?`);args.push(value);}
+ if(status==='transport')predicates.push('api_status_code=0');else if(status==='errors')predicates.push('(api_status_code=0 OR api_status_code>=400)');else if(status){predicates.push('api_status_code=?');args.push(Number(status));}
+ if(search){predicates.push("(payment_id LIKE ? ESCAPE '\\' OR message LIKE ? ESCAPE '\\' OR merchant_id LIKE ? ESCAPE '\\')");args.push(...Array(3).fill('%'+search.replace(/[\\%_]/g,'\\$&')+'%'));}
+ const rows=db.prepare(`SELECT event_id,flow_id,merchant_id,operation,role,observed_at,payment_id,customer_id,
+ status,api_status_code,request_id,latency_ms,message,error_body FROM request_events WHERE ${predicates.join(' AND ')} ORDER BY event_id LIMIT ?`).all(...args,limit+1);
+ return {rows:rows.slice(0,limit).map(row=>({...row,message:row.message==null?null:diagnosticText(row.message),error_body:row.error_body==null?null:diagnosticBody(row.error_body)})),next:rows.length>limit?rows[limit-1].event_id:null};
+ } finally {db.close();}
+}
+
+export function comparePayments(recorded,actual) {
+ const key=(merchant,payment)=>JSON.stringify([merchant,payment]);
+ const statuses=new Map(actual.map(r=>[key(r.merchant_id,r.payment_id),r.status]));
+ return recorded.map(r=>{
+ const databaseStatus=statuses.get(key(r.merchant_id,r.payment_id));
+ return {merchantId:r.merchant_id,paymentId:r.payment_id,recordedStatus:r.status,databaseStatus:databaseStatus ?? null,
+ outcome:databaseStatus===undefined?'missing':databaseStatus===r.status?'match':'mismatch'};
+ });
+}
+
+export async function reconcileRun({id,database,allowIncomplete=false}, progress=()=>{}) {
+ const run=await describeRun(id), {path:directory}=runDirectory(id);
+ if(!run.complete && !allowIncomplete) throw new Error('Recording is incomplete; explicitly allow incomplete data to inspect it');
+ if(!run.runId) throw new Error('No recording database');
+ if(!database.user) throw new Error('Configure a read-only database user in Settings');
+ const indexed=new DatabaseSync(path.join(directory,'results.sqlite'));
+ try{indexed.exec('PRAGMA busy_timeout=5000; CREATE INDEX IF NOT EXISTS requests_payment ON request_events(payment_id,merchant_id,event_id); CREATE INDEX IF NOT EXISTS requests_operation ON request_events(operation,event_id); CREATE INDEX IF NOT EXISTS requests_http ON request_events(api_status_code,event_id);');}finally{indexed.close();}
+ const input=new DatabaseSync(path.join(directory,'results.sqlite'),{readOnly:true});
+ const output=new DatabaseSync(path.join(directory,'reconciliation.sqlite'));
+ output.exec(`CREATE TABLE IF NOT EXISTS comparisons(merchant_id TEXT,payment_id TEXT,recorded_status TEXT,database_status TEXT,outcome TEXT); DELETE FROM comparisons;`);
+ seedPaymentIndex(output,path.join(directory,'results.sqlite'),run);
+ const writeOutcomes=outcomeWriter(output);
+ const insert=output.prepare('INSERT INTO comparisons VALUES(?,?,?,?,?)');
+ output.exec('CREATE TABLE IF NOT EXISTS transport_comparisons(merchant_id TEXT,payment_id TEXT,attempts INTEGER,database_status TEXT,outcome TEXT); DELETE FROM transport_comparisons;');
+ const insertTransport=output.prepare('INSERT INTO transport_comparisons VALUES(?,?,?,?,?)');
+ const pool=new pg.Pool({...databaseConnectionOptions(database),max:1,connectionTimeoutMillis:5000});
+ let client;
+ const result={runId:run.runId,recordingState:run.recordingState,comparedAt:new Date().toISOString(),match:0,mismatch:0,missing:0,total:0,discrepancies:[],truncated:false};
+ const started=Date.now();
+ const expected=Number(input.prepare("SELECT COUNT(*) AS n FROM payments WHERE run_id=? AND role='measured'").get(run.runId).n);
+ result.expected=expected;result.timeline=[{t:0,match:0,mismatch:0,missing:0,compared:0}];
+ const report=()=>progress({compared:result.total,expected,match:result.match,mismatch:result.mismatch,missing:result.missing,elapsedSeconds:(Date.now()-started)/1000,timeline:result.timeline});
+ report();
+ try {
+ client=await pool.connect();
+ await client.query('BEGIN ISOLATION LEVEL REPEATABLE READ READ ONLY');await client.query("SET LOCAL statement_timeout='30s'");
+ let last='',lastMerchant='';
+ const batch=input.prepare("SELECT merchant_id,payment_id,status FROM payments WHERE run_id=? AND role='measured' AND (payment_id,merchant_id)>(?,?) ORDER BY payment_id,merchant_id LIMIT 100");
+ for(;;) {
+ const recorded=batch.all(run.runId,last,lastMerchant);if(!recorded.length)break;
+ const actual=await client.query(`SELECT p.merchant_id,p.payment_id,p.status::text AS status FROM payment_intent p
+ JOIN unnest($1::text[],$2::text[]) AS wanted(merchant_id,payment_id)
+ ON p.merchant_id=wanted.merchant_id AND p.payment_id=wanted.payment_id`,[recorded.map(r=>r.merchant_id),recorded.map(r=>r.payment_id)]);
+ output.exec('BEGIN');
+ try {
+ const comparisons=comparePayments(recorded,actual.rows);writeOutcomes(comparisons);
+ for(const row of comparisons) {
+ result[row.outcome]++;result.total++;insert.run(row.merchantId,row.paymentId,row.recordedStatus,row.databaseStatus,row.outcome);
+ if(row.outcome!=='match') {if(result.discrepancies.length<200) result.discrepancies.push(row);else result.truncated=true;}
+ }
+ output.exec('COMMIT');
+ } catch(e) {output.exec('ROLLBACK');throw e;}
+ last=recorded.at(-1).payment_id;lastMerchant=recorded.at(-1).merchant_id;
+ result.timeline.push({t:(Date.now()-started)/1000,match:result.match,mismatch:result.mismatch,missing:result.missing,compared:result.total});
+ if(result.timeline.length>600)result.timeline=result.timeline.filter((_,i,all)=>i%2===0||i===all.length-1);
+ report();
+ }
+ const transport={attempts:0,checkedPayments:0,found:0,missing:0,unresolved:0,byOperation:[],details:[],truncated:false};
+ const totals=input.prepare("SELECT COUNT(*) AS attempts,SUM(CASE WHEN payment_id IS NULL OR payment_id='' OR merchant_id IS NULL OR merchant_id='' THEN 1 ELSE 0 END) AS unresolved FROM request_events WHERE run_id=? AND api_status_code=0").get(run.runId);
+ transport.attempts=Number(totals.attempts);transport.unresolved=Number(totals.unresolved||0);
+ transport.byOperation=input.prepare("SELECT operation,COUNT(*) AS attempts,SUM(CASE WHEN payment_id IS NULL OR payment_id='' OR merchant_id IS NULL OR merchant_id='' THEN 1 ELSE 0 END) AS unresolved FROM request_events WHERE run_id=? AND api_status_code=0 GROUP BY operation").all(run.runId);
+ input.exec('CREATE TEMP TABLE failed_payment_pairs(merchant_id TEXT,payment_id TEXT,attempts INTEGER)');
+ input.prepare("INSERT INTO failed_payment_pairs SELECT merchant_id,payment_id,COUNT(*) FROM request_events WHERE run_id=? AND api_status_code=0 AND payment_id IS NOT NULL AND payment_id!='' AND merchant_id IS NOT NULL AND merchant_id!='' GROUP BY merchant_id,payment_id").run(run.runId);
+ input.exec('CREATE INDEX failed_payment_pairs_cursor ON failed_payment_pairs(payment_id,merchant_id)');
+ const failedBatch=input.prepare('SELECT * FROM failed_payment_pairs WHERE (payment_id,merchant_id)>(?,?) ORDER BY payment_id,merchant_id LIMIT 1000');
+ const discrepancyMap=new Map(result.discrepancies.map(r=>[JSON.stringify([r.merchantId,r.paymentId]),r]));
+ last='';lastMerchant='';
+ for(;;){
+ const rows=failedBatch.all(last,lastMerchant);if(!rows.length)break;
+ const actual=await client.query(`SELECT p.merchant_id,p.payment_id,p.status::text AS status FROM payment_intent p JOIN unnest($1::text[],$2::text[]) AS wanted(merchant_id,payment_id) ON p.merchant_id=wanted.merchant_id AND p.payment_id=wanted.payment_id`,[rows.map(r=>r.merchant_id),rows.map(r=>r.payment_id)]);
+ output.exec('BEGIN');
+ try{const comparisons=comparePayments(rows,actual.rows);for(const [index,comparison] of comparisons.entries()){
+ const row=rows[index];
+ const outcome=comparison.outcome==='missing'?'missing':'found';transport[outcome]++;transport.checkedPayments++;
+ const detail={merchantId:comparison.merchantId,paymentId:comparison.paymentId,attempts:row.attempts,databaseStatus:comparison.databaseStatus,outcome};
+ insertTransport.run(detail.merchantId,detail.paymentId,detail.attempts,detail.databaseStatus,outcome);
+ if(transport.details.length<100)transport.details.push(detail);else transport.truncated=true;
+ const discrepancy=discrepancyMap.get(JSON.stringify([detail.merchantId,detail.paymentId]));if(discrepancy)discrepancy.reason=outcome==='missing'?'Transport failure; payment not found':'Transport failure; recorded status differs from PostgreSQL';
+ }output.exec('COMMIT');}catch(e){output.exec('ROLLBACK');throw e;}
+ last=rows.at(-1).payment_id;lastMerchant=rows.at(-1).merchant_id;
+ }
+ result.transport=transport;
+ result.creationUnknown=Number(output.prepare("SELECT COUNT(*) n FROM reconciliation_payments WHERE outcome='creation_unknown'").get().n);
+ result.confirmationFailed=Number(output.prepare("SELECT COUNT(*) n FROM reconciliation_payments WHERE failure_category='confirmation_failed'").get().n);
+ result.failedAttempts=Number(input.prepare("SELECT COUNT(*) n FROM request_events WHERE run_id=? AND role='measured' AND (api_status_code=0 OR api_status_code>=400)").get(run.runId).n);
+ result.accounted=result.total+result.creationUnknown;
+ await client.query('COMMIT');
+ if(!result.accounted) throw new Error('No recorded measured payments or failed creates in this run');
+ result.elapsedSeconds=(Date.now()-started)/1000;
+ const {atomicJson}=await import('./state.mjs');await atomicJson(path.join(directory,'reconciliation.json'),result);
+ return result;
+ } finally {
+ if(client) {await client.query('ROLLBACK').catch(()=>{});client.release();}await pool.end();input.close();output.close();
+ }
+}
+
+export async function testDatabase(database,timeoutMillis=5000) {
+ if(!database.user)throw new Error('Enter a database username to test the connection.');
+ const port=Number(database.port);if(!Number.isInteger(port)||port<1||port>65535)throw new Error('Invalid database port');
+ const timeout=Math.max(100,Math.min(5000,Number(timeoutMillis)||5000));
+ const client=new pg.Client({...databaseConnectionOptions({...database,port}),connectionTimeoutMillis:timeout,query_timeout:timeout});
+ try {
+ await client.connect();await client.query('BEGIN READ ONLY');await client.query(`SET LOCAL statement_timeout='${timeout}ms'`);
+ await client.query('SELECT merchant_id,payment_id,status FROM payment_intent LIMIT 0');
+ const result=await client.query('SELECT current_user AS username,current_database() AS database');
+ return {ok:true,...result.rows[0],testedAt:new Date().toISOString(),message:'Connected · payment_intent is readable'};
+ }catch(e){throw new Error(databaseConnectionError(e,database));}
+ finally{await client.end().catch(()=>{});}
+}
diff --git a/loadtest/console/server/query-worker.mjs b/loadtest/console/server/query-worker.mjs
new file mode 100644
index 0000000000..96ea7c4f17
--- /dev/null
+++ b/loadtest/console/server/query-worker.mjs
@@ -0,0 +1,9 @@
+import { parentPort, workerData } from 'node:worker_threads';
+import { listRuns, describeRun, requestHistory, reconcileRun, testDatabase } from './queries.mjs';
+import {paymentBars,paymentPage,paymentDetail,nextDiscrepancy} from './reconciliation-index.mjs';
+try {
+ const {task,args}=workerData;
+ const result=task==='payment-bars'?paymentBars(args):task==='payment-page'?paymentPage(args):task==='payment-detail'?paymentDetail(args):task==='next-discrepancy'?nextDiscrepancy(args):task==='list'?await listRuns():task==='run'?await describeRun(args.id):task==='requests'?requestHistory(args)
+ :task==='database-test'?await testDatabase(args.database,args.timeoutMillis):task==='reconcile'?await reconcileRun(args,p=>parentPort.postMessage({progress:p})):null;
+ parentPort.postMessage({result});
+} catch(e) {parentPort.postMessage({error:e.message});}
diff --git a/loadtest/console/server/reconciliation-index.mjs b/loadtest/console/server/reconciliation-index.mjs
new file mode 100644
index 0000000000..f4e4aadfd0
--- /dev/null
+++ b/loadtest/console/server/reconciliation-index.mjs
@@ -0,0 +1,95 @@
+import {DatabaseSync} from 'node:sqlite';
+import {existsSync} from 'node:fs';
+import path from 'node:path';
+import {runDirectory} from './state.mjs';
+const outcomes=['match','missing','mismatch','pending','creation_unknown'];
+export const bucketWidths=[1000,4000,16000,64000,256000,1024000,4096000,16384000,65536000];
+export function createPaymentIndex(db){
+ db.exec(`PRAGMA journal_mode=WAL; PRAGMA busy_timeout=5000;
+ CREATE TABLE IF NOT EXISTS reconciliation_meta(key TEXT PRIMARY KEY,value REAL);
+ CREATE TABLE IF NOT EXISTS reconciliation_payments(id INTEGER PRIMARY KEY,elapsed_ms INTEGER NOT NULL,merchant_id TEXT NOT NULL,payment_id TEXT NOT NULL,recorded_status TEXT,database_status TEXT,outcome TEXT NOT NULL);
+ CREATE INDEX IF NOT EXISTS recon_time ON reconciliation_payments(elapsed_ms,id);
+ CREATE INDEX IF NOT EXISTS recon_outcome_time ON reconciliation_payments(outcome,elapsed_ms,id);
+ CREATE TABLE IF NOT EXISTS reconciliation_buckets(level INTEGER,bucket INTEGER,matched INTEGER DEFAULT 0,missing INTEGER DEFAULT 0,mismatch INTEGER DEFAULT 0,pending INTEGER DEFAULT 0,PRIMARY KEY(level,bucket));`);
+ const columns=new Set(db.prepare('PRAGMA table_info(reconciliation_payments)').all().map(r=>r.name));
+ for(const [name,type] of Object.entries({event_id:'INTEGER',operation:'TEXT',api_status_code:'INTEGER',message:'TEXT',error_body:'TEXT',failure_category:'TEXT'}))if(!columns.has(name))db.exec(`ALTER TABLE reconciliation_payments ADD COLUMN ${name} ${type}`);
+ if(!db.prepare('PRAGMA table_info(reconciliation_buckets)').all().some(r=>r.name==='creation_unknown'))db.exec('ALTER TABLE reconciliation_buckets ADD COLUMN creation_unknown INTEGER DEFAULT 0');
+ db.exec("DROP INDEX IF EXISTS recon_identity; CREATE UNIQUE INDEX recon_identity ON reconciliation_payments(merchant_id,payment_id) WHERE payment_id!=''; CREATE INDEX IF NOT EXISTS recon_failure_time ON reconciliation_payments(failure_category,elapsed_ms,id)");
+}
+export function seedPaymentIndex(db,source,run){
+ createPaymentIndex(db);db.prepare('ATTACH DATABASE ? AS recording').run(source);
+ try{db.exec('BEGIN');db.exec('DELETE FROM reconciliation_payments; DELETE FROM reconciliation_buckets; DELETE FROM reconciliation_meta;');
+ db.exec(`CREATE TEMP TABLE first_observed AS SELECT merchant_id,payment_id,MIN(observed_at) AS at FROM recording.request_events WHERE payment_id IS NOT NULL AND payment_id!='' GROUP BY merchant_id,payment_id;
+ CREATE UNIQUE INDEX first_observed_identity ON first_observed(merchant_id,payment_id);`);
+ db.prepare(`INSERT INTO reconciliation_payments(elapsed_ms,merchant_id,payment_id,recorded_status,outcome)
+ SELECT MAX(0,CAST(COALESCE(f.at,p.observed_at)-? AS INTEGER)),p.merchant_id,p.payment_id,p.status,'pending' FROM recording.payments p LEFT JOIN first_observed f ON f.merchant_id=p.merchant_id AND f.payment_id=p.payment_id WHERE p.run_id=? AND p.role='measured' ORDER BY COALESCE(f.at,p.observed_at),p.merchant_id,p.payment_id`).run(run.startedAt,run.runId);
+ db.exec('DROP TABLE first_observed');
+ // Keep attempts without an ID as evidence, without inventing application payments.
+ db.prepare(`INSERT INTO reconciliation_payments(elapsed_ms,merchant_id,payment_id,outcome,event_id,operation,api_status_code,message,error_body,failure_category)
+ SELECT MAX(0,CAST(observed_at-? AS INTEGER)),COALESCE(merchant_id,''),'','creation_unknown',event_id,operation,api_status_code,message,error_body,'creation_unknown'
+ FROM recording.request_events WHERE run_id=? AND role='measured' AND operation='payment_create' AND (payment_id IS NULL OR payment_id='') AND (api_status_code=0 OR api_status_code>=400) ORDER BY observed_at,event_id`).run(run.startedAt,run.runId);
+ // A final failed confirmation is distinct from its database status comparison.
+ db.prepare(`UPDATE reconciliation_payments SET (event_id,operation,api_status_code,message,error_body,failure_category)=(
+ SELECT e.event_id,e.operation,e.api_status_code,e.message,e.error_body,'confirmation_failed' FROM recording.request_events e
+ WHERE e.run_id=? AND e.role='measured' AND e.merchant_id=reconciliation_payments.merchant_id AND e.payment_id=reconciliation_payments.payment_id AND e.operation='payment_confirm'
+ AND (e.api_status_code=0 OR e.api_status_code>=400) AND NOT EXISTS(SELECT 1 FROM recording.request_events later WHERE later.run_id=e.run_id AND later.merchant_id=e.merchant_id AND later.payment_id=e.payment_id AND later.operation='payment_confirm' AND later.event_id>e.event_id AND later.api_status_code BETWEEN 200 AND 299)
+ ORDER BY e.event_id DESC LIMIT 1) WHERE payment_id!=''`).run(run.runId);
+ rebuildBuckets(db);
+ const end=db.prepare('SELECT MAX(elapsed_ms) AS end FROM reconciliation_payments').get().end||0;
+ db.prepare('INSERT INTO reconciliation_meta VALUES(?,?)').run('duration',Math.max(run.durationSeconds*1000,end+1,1));
+ db.prepare('INSERT INTO reconciliation_meta VALUES(?,?)').run('startedAt',run.startedAt);
+ db.exec('COMMIT');}catch(e){db.exec('ROLLBACK');throw e;}finally{db.exec('DETACH DATABASE recording');}
+}
+export function rebuildBuckets(db){
+ db.exec('DELETE FROM reconciliation_buckets');
+ const insert=db.prepare(`INSERT INTO reconciliation_buckets SELECT ?,CAST(elapsed_ms/? AS INTEGER),SUM(outcome='match'),SUM(outcome='missing'),SUM(outcome='mismatch'),SUM(outcome='pending'),SUM(outcome='creation_unknown') FROM reconciliation_payments GROUP BY CAST(elapsed_ms/? AS INTEGER)`);
+ bucketWidths.forEach((width,level)=>insert.run(level,width,width));
+}
+export function outcomeWriter(db){
+ const update=db.prepare('UPDATE reconciliation_payments SET database_status=?,outcome=? WHERE merchant_id=? AND payment_id=? RETURNING elapsed_ms');
+ const bucket=db.prepare('UPDATE reconciliation_buckets SET matched=matched+?,missing=missing+?,mismatch=mismatch+?,pending=pending-? WHERE level=? AND bucket=?');
+ return rows=>{
+ const deltas=new Map();
+ for(const row of rows){const saved=update.get(row.databaseStatus,row.outcome,row.merchantId,row.paymentId);if(!saved)continue;
+ bucketWidths.forEach((width,level)=>{const n=Math.floor(saved.elapsed_ms/width),key=`${level}:${n}`,counts=deltas.get(key)||[0,0,0,0,level,n];counts[outcomes.indexOf(row.outcome)]++;counts[3]++;deltas.set(key,counts);});
+ }
+ for(const counts of deltas.values())bucket.run(...counts);
+ };
+}
+function openIndex(id){const db=new DatabaseSync(path.join(runDirectory(id).path,'reconciliation.sqlite'),{readOnly:true});db.exec('PRAGMA busy_timeout=5000');return db;}
+const filterSql=filter=>filter==='discrepancies'?"outcome IN ('missing','mismatch','creation_unknown')":filter==='confirmation_failed'?"failure_category='confirmation_failed'":outcomes.includes(filter)?'outcome=?':'1=1';
+const filterArgs=filter=>outcomes.includes(filter)?[filter]:[];
+const counts=row=>({match:Number(row?.matched||0),missing:Number(row?.missing||0),mismatch:Number(row?.mismatch||0),pending:Number(row?.pending||0),creation_unknown:Number(row?.creation_unknown||0)});
+export function paymentBars({id,from=0,to,bars=400,filter='all',detailLimit=600,view='auto'}){
+ if(!existsSync(path.join(runDirectory(id).path,'reconciliation.sqlite')))return {preparing:true};
+ const db=openIndex(id);
+ try{
+ if(!db.prepare("SELECT 1 FROM sqlite_master WHERE name='reconciliation_payments'").get())return {legacy:true};
+ const savedDuration=db.prepare("SELECT value FROM reconciliation_meta WHERE key='duration'").get()?.value;if(!savedDuration)return {preparing:true};const duration=savedDuration;
+ from=Math.max(0,Number(from)||0);to=Math.min(duration,to==null?duration:Number(to));bars=Math.max(20,Math.min(800,Math.floor(Number(bars)||400)));detailLimit=Math.max(bars,Math.min(800,Math.floor(Number(detailLimit)||600)));
+ if(!Number.isFinite(to)||to<=from)throw Error('Invalid chart time range');
+ const hasAttempts=db.prepare('PRAGMA table_info(reconciliation_buckets)').all().some(r=>r.name==='creation_unknown');
+ const totals=counts(db.prepare(`SELECT SUM(matched) matched,SUM(missing) missing,SUM(mismatch) mismatch,SUM(pending) pending${hasAttempts?',SUM(creation_unknown) creation_unknown':''} FROM reconciliation_buckets WHERE level=0`).get());
+ // Probe only enough rows to choose detail or aggregation; never transfer all payments.
+ const rows=db.prepare(`SELECT * FROM reconciliation_payments WHERE elapsed_ms>=? AND elapsed_ms<? AND ${filterSql(filter)} ORDER BY elapsed_ms,id LIMIT ?`).all(from,to,...filterArgs(filter),detailLimit+1);
+ if(rows.length<=detailLimit&&view!=='timeline')return {mode:'payments',from,to,duration,totals,rows};
+ let level=bucketWidths.findIndex(w=>(to-from)/w<=bars);if(level<0)level=bucketWidths.length-1;const width=bucketWidths[level];
+ const result=filter==='confirmation_failed'?db.prepare(`SELECT CAST(elapsed_ms/? AS INTEGER) bucket,SUM(outcome='match') matched,SUM(outcome='missing') missing,SUM(outcome='mismatch') mismatch,SUM(outcome='pending') pending,0 creation_unknown FROM reconciliation_payments WHERE elapsed_ms>=? AND elapsed_ms<? AND failure_category='confirmation_failed' GROUP BY bucket ORDER BY bucket`).all(width,from,to):db.prepare(`SELECT bucket,matched,missing,mismatch,pending${hasAttempts?',creation_unknown':''} FROM reconciliation_buckets WHERE level=? AND bucket>=? AND bucket<=? ORDER BY bucket`).all(level,Math.floor(from/width),Math.floor((to-1)/width));
+ // Partial edge buckets use indexed exact queries; the interior uses pre-aggregates.
+ for(const row of result){const a=Math.max(from,row.bucket*width),b=Math.min(to,(row.bucket+1)*width);if(a!==row.bucket*width||b!==(row.bucket+1)*width)Object.assign(row,db.prepare(`SELECT SUM(outcome='match') matched,SUM(outcome='missing') missing,SUM(outcome='mismatch') mismatch,SUM(outcome='pending') pending,SUM(outcome='creation_unknown') creation_unknown FROM reconciliation_payments WHERE elapsed_ms>=? AND elapsed_ms<? AND ${filterSql(filter)}`).get(a,b,...filterArgs(filter)));row.from=a;row.to=b;}
+ return {mode:'buckets',from,to,duration,width,totals,rows:result.map(row=>({...row,...counts(row)}))};
+ }finally{db.close();}
+}
+export function paymentPage({id,from=0,to=Number.MAX_SAFE_INTEGER,filter='discrepancies',afterTime=-1,afterId=0,limit=100,search=''}){
+ limit=Math.max(1,Math.min(200,Math.floor(Number(limit)||100)));
+ const db=openIndex(id);try{
+ const rows=db.prepare(`SELECT * FROM reconciliation_payments WHERE elapsed_ms>=? AND elapsed_ms<? AND (elapsed_ms,id)>(?,?) AND ${filterSql(filter)} ${search?"AND (payment_id LIKE ? ESCAPE '\\' OR merchant_id LIKE ? ESCAPE '\\')":''} ORDER BY elapsed_ms,id LIMIT ?`).all(Number(from),Number(to),Number(afterTime),Number(afterId),...filterArgs(filter),...(search?Array(2).fill('%'+search.replace(/[\\%_]/g,'\\$&')+'%'):[]),Math.min(200,Number(limit)||100)+1);
+ const end=rows[Math.min(limit,200)-1];return {rows:rows.slice(0,limit),next:rows.length>limit?{afterTime:end.elapsed_ms,afterId:end.id}:null};
+ }finally{db.close();}
+}
+export function nextDiscrepancy({id,after=0}){
+ const db=openIndex(id);try{return db.prepare("SELECT elapsed_ms,id FROM reconciliation_payments WHERE outcome IN ('missing','mismatch','creation_unknown') AND elapsed_ms>=? ORDER BY elapsed_ms,id LIMIT 1").get(Number(after))||null;}finally{db.close();}
+}
+export function paymentDetail({id,payment,merchant,rowId}){
+ const db=openIndex(id);try{const row=rowId?db.prepare('SELECT * FROM reconciliation_payments WHERE id=?').get(Number(rowId)):db.prepare('SELECT * FROM reconciliation_payments WHERE payment_id=? AND merchant_id=?').get(payment,merchant);if(!row)throw Error('Payment or attempt not found');return row;}finally{db.close();}
+}
diff --git a/loadtest/console/server/request-body.mjs b/loadtest/console/server/request-body.mjs
new file mode 100644
index 0000000000..5a48cc5ea6
--- /dev/null
+++ b/loadtest/console/server/request-body.mjs
@@ -0,0 +1,12 @@
+import {HttpError} from './errors.mjs';
+export async function boundedRequest(request,limit=1024*1024){
+ if(!request.body)return request;
+ if(Number(request.headers.get('content-length')||0)>limit)throw new HttpError(413,'Request body exceeds 1 MiB');
+ const reader=request.body.getReader(),chunks=[];let bytes=0;
+ try{for(;;){const {done,value}=await reader.read();if(done)break;bytes+=value.byteLength;if(bytes>limit)throw new HttpError(413,'Request body exceeds 1 MiB');chunks.push(value);}}
+ // Cancelling the adapter's stream destroys the TCP socket before a 413 can
+ // reach the client. Return a close-delimited rejection instead of buffering
+ // or draining the remaining untrusted body.
+ catch(error){reader.releaseLock();throw error;}
+ return new Request(request,{body:Buffer.concat(chunks)});
+}
diff --git a/loadtest/console/server/scenario-checks.mjs b/loadtest/console/server/scenario-checks.mjs
new file mode 100644
index 0000000000..6bf2024033
--- /dev/null
+++ b/loadtest/console/server/scenario-checks.mjs
@@ -0,0 +1,257 @@
+import {DatabaseSync} from 'node:sqlite';
+import {readFile,writeFile,rename} from 'node:fs/promises';
+import {createHash,randomUUID} from 'node:crypto';
+import path from 'node:path';
+import {loadTimeline,loadShape} from '../src/load-shape.mjs';
+import {defaultResultsLimits,validateResultsLimits} from '../src/results-limits.mjs';
+import {executionClock,stageIntervals} from './execution-clock.mjs';
+import {latencyPercentile,settledLatencyWindows,containedLatencySample,mergeLatencyWindows} from './successful-latency.mjs';
+import {matchedLatencyDrift} from './latency-drift.mjs';
+import {testCasePlan} from '../src/result-test-cases.mjs';
+
+export const scenarioChecksVersion=16;
+const terminal=new Set(['complete','failed','cancelled','interrupted']);
+const successful=row=>row.api_status_code>=200&&row.api_status_code<300&&['succeeded','requires_capture','processing'].includes(row.status);
+const inWindow=(at,windows)=>windows.some(w=>at>=w.from&&at<w.to);
+const overlaps=(row,windows)=>windows.some(w=>row.observed_at>=w.from&&row.observed_at-Math.max(0,row.latency_ms||0)<w.to);
+const seconds=windows=>windows.reduce((sum,w)=>sum+(w.to-w.from)/1000,0);
+function clipInterval(window,from,to){
+ const active=at=>window.activeFrom+(at-window.from)/(window.to-window.from)*(window.activeTo-window.activeFrom);
+ return {...window,from,to,activeFrom:active(from),activeTo:active(to)};
+}
+function withoutOutages(windows,outages){
+ return outages.reduce((parts,outage)=>parts.flatMap(w=>{
+ if(outage.to<=w.from||outage.from>=w.to)return [w];
+ const result=[];if(outage.from>w.from)result.push(clipInterval(w,w.from,outage.from));if(outage.to<w.to)result.push(clipInterval(w,outage.to,w.to));return result;
+ }),windows);
+}
+function offeredWork(stage,windows){
+ const rate=a=>stage.from+(stage.target-stage.from)*(a-stage.start)/(stage.end-stage.start);
+ return windows.reduce((sum,w)=>sum+(rate(w.activeFrom)+rate(w.activeTo))/2*(w.activeTo-w.activeFrom),0);
+}
+const percentile=(values,p)=>latencyPercentile([...values],p);
+const readJson=async file=>{try{return JSON.parse(await readFile(file,'utf8'));}catch(e){if(e.code==='ENOENT')return null;throw e;}};
+async function lines(file){try{return (await readFile(file,'utf8')).split('\n').filter(Boolean).flatMap(line=>{try{return [JSON.parse(line)];}catch{return [];}});}catch(e){if(e.code==='ENOENT')return [];throw e;}}
+
+// Fault occurrences are bound to the scheduler's stable stage index, rather
+// than to a service label (the same DB can fail over more than once).
+export function faultOccurrences(events,stages,end){
+ const result=[];let stageIndex=null,current=null;
+ for(const event of [...events].sort((a,b)=>a.at-b.at)){
+ if(event.kind==='scheduled_fault'){stageIndex=Number(event.message?.match(/scheduled step (\d+)/)?.[1])-1;continue;}
+ if(event.kind==='fault_requested'||(event.kind==='fault_started'&&!current)){
+ const stage=stages.find(s=>s.index===stageIndex&&s.fault)||stages.filter(s=>s.fault)[result.length];
+ if(!stage)continue;
+ current={stageIndex:stage.index,from:event.at,to:end,restoreAt:null,recoveredAt:null,unavailable:false,simulated:event.message?.startsWith('SIMULATED')||false};result.push(current);
+ }
+ if(!current)continue;
+ if(event.kind==='fault_started'){current.startedAt??=event.at;current.simulated||=event.message?.startsWith('SIMULATED')||false;}
+ if(event.kind==='fault_restore')current.restoreAt=event.at;
+ if(event.kind==='database_unavailable'){current.unavailable=true;current.unavailableAt??=event.at;}
+ if(event.kind==='database_available'&&current.unavailable){current.recoveredAt??=event.at;current.to=event.at;}
+ if(event.kind==='fault_restored'){
+ current.recoveredAt??=event.at;current.to=current.recoveredAt;current=null;
+ }
+ if(event.kind==='fault_skipped'){current.skipped=true;current.to=event.at;current=null;}
+ }
+ return result;
+}
+
+function bucket(){return {requests:0,errors:0,paymentRequests:0,paymentErrors:0,failedCreates:0,completed:0,successes:0,latencies:[],driftSamples:[]};}
+function check(id,label,actual,limit,unit,{minimum=false,state='complete',record=false}={}){
+ const outcome=state==='not_run'?'not_run':state==='in_progress'?'in_progress':state==='partial'?'not_measured':record||limit==null?'recorded':actual==null?'not_measured':(minimum?actual>=limit:actual<=limit)?'pass':'fail';
+ return {id,label,actual,limit:record?null:limit,unit,comparison:minimum?'≥':'≤',outcome};
+}
+const groupVerdict=checks=>checks.some(c=>c.outcome==='fail')?'fail':checks.some(c=>c.outcome==='in_progress')?'in_progress':checks.every(c=>c.outcome==='not_run')?'not_run':checks.some(c=>['not_measured','not_run'].includes(c.outcome))?'incomplete':checks.some(c=>c.outcome==='pass')?'pass':'recorded';
+
+export function evaluateScenarioChecks({config,recording,events=[],samples=[],requests=[],flows=[],reconciliation=null,jobStatus=null,now=Date.now(),measurementsAvailable=true,control=null}){
+ const limits=config.resultsLimits?validateResultsLimits(config.resultsLimits):{...defaultResultsLimits};
+ // Only limits stored with the run can produce historical pass/fail claims.
+ const saved=Boolean(config.resultsLimits);
+ const legacy=config.acceptance||{};
+ const throughputLimit=saved?limits.minimumThroughputPercent:legacy.minimumSuccessRatio==null?null:legacy.minimumSuccessRatio*100;
+ const errorLimit=saved?limits.maximumHttpErrorPercent:legacy.maximumErrorPercent??null;
+ const finished=terminal.has(jobStatus)||Boolean(recording.ended_at&&!jobStatus);
+ const end=Number(recording.ended_at)||now,clock=executionClock(samples,{...recording,ended_at:end});
+ const stages=loadTimeline(config.load,config.faultPlan),faults=faultOccurrences(events,stages,end),outages=faults.filter(f=>!f.skipped).map(f=>({from:f.from,to:f.to}));
+ const groups=[];
+ for(const stage of stages){
+ const execution=stageIntervals(clock,stage),windows=withoutOutages(execution,outages),reached=clock?.active??0;
+ const state=!clock?(finished?'partial':'in_progress'):!execution.length?'not_run':reached>=stage.end-0.05?'complete':finished?'partial':'in_progress';
+ const kind=stage.from===stage.target?'hold':'ramp';
+ if(!stage.fault)groups.push({id:`stage-${stage.index}`,stageIndex:stage.index,kind,title:`${stage.index+1}. ${kind==='hold'?'Hold':'Ramp'} · ${stage.from===stage.target?stage.target:`${stage.from} → ${stage.target}`} TPS`,configuredSeconds:stage.end-stage.start,state,windows,stage,bucket:bucket()});
+ const fault=faults.find(f=>f.stageIndex===stage.index);
+ if(stage.fault){
+ const windows=fault&&!fault.skipped?[{from:fault.from,to:fault.to}]:[];
+ groups.push({id:`fault-${stage.index}`,stageIndex:stage.index,kind:'fault',target:stage.fault.target,title:`${stage.index+1}. ${stage.fault.target} · ${stage.fault.action==='failover'?'Failover':'Outage'} · ${stage.from===stage.target?stage.target:`${stage.from} → ${stage.target}`} TPS`,state:!fault?'not_run':fault.skipped?'partial':fault.recoveredAt?'complete':finished?'partial':'in_progress',windows,fault,bucket:bucket()});
+ {
+ const recoveredAt=fault?.recoveredAt,until=(recoveredAt??end)+limits.recoveryWindowSeconds*1000;
+ const next=faults.find(f=>recoveredAt!=null&&f.from>recoveredAt);
+ const to=Math.min(until,end,next?.from??Infinity);
+ groups.push({id:`recovery-${stage.index}`,stageIndex:stage.index,kind:'recovery',title:`After ${stage.fault.target} recovery · first ${limits.recoveryWindowSeconds}s`,state:recoveredAt==null?'not_run':to>=until?'complete':finished?'partial':'in_progress',windows:recoveredAt!=null&&to>recoveredAt?[{from:recoveredAt,to}]:[],bucket:bucket()});
+ }
+ }
+ }
+ const recoveryWindows=groups.filter(g=>g.kind==='recovery').flatMap(g=>g.windows);
+ for(const group of groups)if(['hold','ramp'].includes(group.kind))group.windows=withoutOutages(group.windows,recoveryWindows);
+ const normalWindows=groups.filter(g=>['hold','ramp'].includes(g.kind)).flatMap(g=>g.windows);
+ const steadyIds=new Set(testCasePlan(config,groups).find(p=>p.id==='TC-02')?.groupIds||[]);
+ const latencyWindows=settledLatencyWindows({normalWindows,faults,startedAt:recording.started_at,end,settlingSeconds:limits.recoveryWindowSeconds});
+ for(const group of groups)group.latencyWindows=group.kind==='fault'?latencyWindows.outage.filter(w=>w.stageIndex===group.stageIndex):group.kind==='recovery'?latencyWindows.recovery.filter(w=>w.stageIndex===group.stageIndex):mergeLatencyWindows(group.windows.flatMap(w=>[...latencyWindows.normal,...latencyWindows.recovery].flatMap(s=>{
+ const from=Math.max(w.from,s.from),to=Math.min(w.to,s.to);return to>from?[{from,to}]:[];
+ })));
+ const steadyLatencyWindows=mergeLatencyWindows(groups.filter(g=>steadyIds.has(g.id)).flatMap(g=>g.latencyWindows.flatMap(w=>latencyWindows.normal.flatMap(n=>{const from=Math.max(w.from,n.from),to=Math.min(w.to,n.to);return to>from?[{from,to}]:[];}))));
+
+ const steadyDrift=[],steadyLatencies=[];
+ const stateBuckets={normal:bucket(),outage:bucket(),recovery:bucket()};
+ const stateFor=(at,faultOverlap=false,recoveryOverlap=false)=>faultOverlap||inWindow(at,outages)?'outage':recoveryOverlap||inWindow(at,recoveryWindows)?'recovery':inWindow(at,normalWindows)?'normal':null;
+ // Request intervals overlapping an outage never pollute normal-stage limits,
+ // including a timeout returned after recovery. All raw failures remain in the
+ // fault group and run-wide recording; no Performance display filter is used.
+ const confirmations={attempts:0,successful:0,outageAttempts:0,outageFailures:0};
+ for(const row of requests){
+ const faultOverlap=overlaps(row,outages),recoveryOverlap=overlaps(row,recoveryWindows);
+ const paymentRequest=['payment_create','payment_confirm'].includes(row.operation),httpFailed=row.api_status_code===0||row.api_status_code>=400;
+ if(row.operation==='payment_confirm'){
+ if(faultOverlap||inWindow(row.observed_at,outages)){confirmations.outageAttempts++;if(!successful(row))confirmations.outageFailures++;}
+ else {confirmations.attempts++;if(successful(row))confirmations.successful++;}
+ }
+ const state=stateFor(row.observed_at,faultOverlap,recoveryOverlap);
+ if(state){const b=stateBuckets[state];b.requests++;if(httpFailed)b.errors++;if(paymentRequest){b.paymentRequests++;if(httpFailed)b.paymentErrors++;}
+ }
+ const hasLatency=row.operation==='payment_confirm'&&successful(row)&&Number.isFinite(row.server_latency_ms)&&row.server_latency_ms>=0;
+ if(hasLatency&&containedLatencySample(row,steadyLatencyWindows)){
+ steadyLatencies.push(row.server_latency_ms);
+ steadyDrift.push(row);
+ }
+ if(hasLatency)for(const [phase,windows] of Object.entries(latencyWindows))if(containedLatencySample(row,windows))stateBuckets[phase].latencies.push(row.server_latency_ms);
+ for(const group of groups){
+ // Recovery latency uses the settled post-recovery interval; its other
+ // observations retain their original first-window measurements.
+ if(hasLatency&&containedLatencySample(row,group.latencyWindows))group.bucket.latencies.push(row.server_latency_ms);
+ if(!inWindow(row.observed_at,group.windows)&&!(group.kind==='fault'&&overlaps(row,group.windows)))continue;
+ if(group.kind!=='fault'&&faultOverlap)continue;
+ if(['hold','ramp'].includes(group.kind)&&recoveryOverlap)continue;
+ const b=group.bucket;if(paymentRequest){b.paymentRequests++;if(httpFailed)b.paymentErrors++;}b.requests++;if(row.api_status_code===0||row.api_status_code>=400){b.errors++;if(row.operation==='payment_create')b.failedCreates++;}
+ if(row.operation==='payment_confirm'&&successful(row)&&Number.isFinite(row.server_latency_ms)&&row.server_latency_ms>=0){
+ if(group.kind==='hold'&&clock&&containedLatencySample(row,group.latencyWindows)){
+ b.driftSamples.push(row);
+ }
+ }
+ }
+ }
+ let runFlows=0,successfulFlows=0;
+ for(const row of flows){
+ runFlows++;if(row.success)successfulFlows++;
+ const interval={observed_at:row.at,latency_ms:Math.max(0,row.at-(row.startedAt??row.at))};
+ const affected=overlaps(interval,outages)||overlaps(interval,recoveryWindows);
+ const state=stateFor(row.at,overlaps(interval,outages),overlaps(interval,recoveryWindows));if(state){stateBuckets[state].completed++;if(row.success)stateBuckets[state].successes++;}
+ for(const group of groups){
+ if(!inWindow(row.at,group.windows))continue;
+ if(['hold','ramp'].includes(group.kind)&&affected)continue;
+ group.bucket.completed++;if(row.success)group.bucket.successes++;
+ }
+ }
+ const steadyBucket=bucket();let steadySeconds=0,steadyExpected=0;
+ for(const group of groups){
+ const {bucket:b,state,kind}=group,opts={state:!measurementsAvailable&&!finished&&state!=='not_run'?'in_progress':state};
+ const duration=seconds(group.windows);
+ const expected=group.stage?offeredWork(group.stage,group.windows):null;
+ if(kind==='hold'&&steadyIds.has(group.id)){
+ steadySeconds+=duration;steadyExpected+=expected;
+ for(const key of ['requests','errors','paymentRequests','paymentErrors','completed','successes'])steadyBucket[key]+=b[key];
+ for(const value of b.latencies)steadyBucket.latencies.push(value);
+ }
+ const normal=kind==='hold'||kind==='ramp';
+ const tps=measurementsAvailable&&duration>0?b.successes/duration:null;
+ const throughput=measurementsAvailable&&normal&&expected>0?100*b.successes/expected:null;
+ const recoveryExpected=kind==='recovery'?stages.reduce((sum,s)=>sum+offeredWork(s,stageIntervals(clock,s).flatMap(w=>group.windows.flatMap(r=>{
+ const from=Math.max(w.from,r.from),to=Math.min(w.to,r.to);return to>from?[clipInterval(w,from,to)]:[];
+ }))),0):null;
+ const rows=[];
+ if(normal)rows.push(check('throughput','Window throughput vs offered',throughput,throughputLimit,'%',{...opts,minimum:true}));
+ else if(kind==='recovery')rows.push(check('throughput','Throughput restored',recoveryExpected>0&&tps!=null?100*b.successes/recoveryExpected:null,throughputLimit,'%',{...opts,minimum:true}));
+ rows.push(check('tps','Successful TPS',tps,null,'TPS',{...opts,record:true}));
+ rows.push(check('errors','HTTP errors',b.paymentRequests?100*b.paymentErrors/b.paymentRequests:null,normal?errorLimit:null,'%',opts));
+ if(kind==='fault'){
+ rows.push(check('failed','Failed requests',measurementsAvailable?b.errors:null,null,'requests',{...opts,record:true}));
+ rows.push(check('failed-creation','Failed payment creation during outage',measurementsAvailable?b.failedCreates:null,null,'requests',{...opts,record:true}));
+ }
+ rows.push(check('completed','Flows completed in window',measurementsAvailable&&group.windows.length?b.successes:null,null,'flows',{...opts,record:true}));
+ for(const p of [.5,.95,.99])rows.push(check(`p${p*100}`,`Server-side latency · p${p*100}`,percentile(b.latencies,p),saved&&p===.99&&kind!=='fault'?(kind==='recovery'||(group.latencyWindows.length&&group.latencyWindows.every(w=>latencyWindows.recovery.some(r=>w.from>=r.from&&w.to<=r.to)))?limits.maximumRecoveryP99Ms:kind==='ramp'?limits.maximumRampP99Ms:limits.maximumHoldP99Ms):null,'ms',opts));
+ if(kind==='hold'){
+ const matched=matchedLatencyDrift(b.driftSamples,group.latencyWindows);
+ rows.push({...check('drift','Latency drift',matched.percent,saved?limits.maximumLatencyDriftPercent:null,'%',opts),matched});
+ }
+ if(kind==='fault'){
+ const f=group.fault,recoveryStart=f?.unavailableAt??f?.restoreAt,recovered=f?.recoveredAt!=null&&recoveryStart!=null;
+ const elapsed=recoveryStart!=null?(end-recoveryStart)/1000:null,expired=!recovered&&elapsed>limits.maximumRecoverySeconds;
+ rows.unshift({...check('recovery',f?.unavailableAt!=null?'Database availability restored after outage':'Recovery after restoration starts',recovered?Math.max(0,(f.recoveredAt-recoveryStart)/1000):expired?elapsed:null,saved?limits.maximumRecoverySeconds:null,'s',{...opts,state:expired?'complete':state,record:f?.simulated}),lowerBound:expired});
+ if(f?.simulated)group.title=`Simulation · ${group.title}`;
+ }
+ group.checks=rows;group.verdict=groupVerdict(rows);group.durationSeconds=duration;group.successfulFlows=b.successes;group.latencySamples=b.latencies.length;
+ delete group.bucket;delete group.stage;delete group.fault;delete group.windows;delete group.latencyWindows;
+ }
+ if(stages.some(s=>s.fault)){
+ const verified=reconciliation?.recordingState==='complete'&&Number.isFinite(reconciliation.missing)&&reconciliation.total===reconciliation.expected;
+ const checks=[check('lost','Acknowledged payments lost',verified?reconciliation.missing:null,saved?limits.maximumLostPayments:null,'payments',{state:finished?'complete':'in_progress'})];
+ groups.push({id:'integrity',kind:'integrity',title:'Data integrity',checks,verdict:groupVerdict(checks)});
+ }
+ const normalSeconds=seconds(withoutOutages(normalWindows,recoveryWindows));
+ const states=Object.entries(stateBuckets).map(([state,b])=>({state,count:b.latencies.length,p50:percentile(b.latencies,.5),p95:percentile(b.latencies,.95),p99:percentile(b.latencies,.99),windowExpected:state==='normal'?normalWindows.length>0:state==='outage'?faults.some(f=>f.startedAt!=null||f.unavailableAt!=null):faults.some(f=>f.recoveredAt!=null),windowSeconds:seconds(latencyWindows[state]),errors:measurementsAvailable?b.paymentErrors:null,requests:measurementsAvailable?b.paymentRequests:null,tps:state==='normal'&&normalSeconds>0&&measurementsAvailable?b.successes/normalSeconds:null}));
+ const steadyOpts={state:!finished?'in_progress':!measurementsAvailable||groups.some(g=>steadyIds.has(g.id)&&g.state!=='complete')?'partial':'complete'};
+ const steadyChecks=[
+ check('throughput','Window throughput vs offered',measurementsAvailable&&steadyExpected>0?100*steadyBucket.successes/steadyExpected:null,throughputLimit,'%',{...steadyOpts,minimum:true}),
+ check('tps','Successful TPS',measurementsAvailable&&steadySeconds>0?steadyBucket.successes/steadySeconds:null,null,'TPS',{...steadyOpts,record:true}),
+ check('errors','HTTP errors',steadyBucket.paymentRequests?100*steadyBucket.paymentErrors/steadyBucket.paymentRequests:null,errorLimit,'%',steadyOpts),
+ check('completed','Flows completed in window',measurementsAvailable&&steadySeconds>0?steadyBucket.successes:null,null,'flows',{...steadyOpts,record:true}),
+ ...[.5,.95,.99].map(p=>check(`p${p*100}`,`Server-side latency · p${p*100}`,percentile(steadyLatencies,p),saved&&p===.99?limits.maximumHoldP99Ms:null,'ms',steadyOpts))
+ ];
+ const matched=matchedLatencyDrift(steadyDrift,steadyLatencyWindows);
+ steadyChecks.push({...check('drift','Latency drift',matched.percent,saved?limits.maximumLatencyDriftPercent:null,'%',steadyOpts),matched});
+ const steady={checks:steadyChecks,durationSeconds:steadySeconds,successfulFlows:steadyBucket.successes};
+ // Confirmations include drain responses. Setup failures and expected outage
+ // impact are recorded separately, never counted as failed confirmations.
+ // Window throughput remains a time-based diagnostic, never a completion ratio.
+ const shape=loadShape(config.load),planned=Math.round(shape.average*shape.duration);
+ const dropped=Number.isFinite(control?.dropped)?Math.max(0,control.dropped):0;
+ const admitted=Number.isFinite(control?.started_flows)?Math.max(0,control.started_flows):runFlows;
+ const expected=confirmations.attempts;
+ const completionState=!finished?'in_progress':!measurementsAvailable||['cancelled','interrupted'].includes(jobStatus)||recording.recording_state!=='complete'||!clock||Math.max(clock.active,control?.active_seconds||0)<shape.duration-.05?'partial':'complete';
+ const completion={expected,planned,started:admitted,successful:confirmations.successful,dropped,scope:'payment_confirm_outside_outage',outageAttempts:confirmations.outageAttempts,outageFailures:confirmations.outageFailures,
+ check:check('completion','Payment confirmations succeeded outside outage',measurementsAvailable&&expected>0?100*confirmations.successful/expected:null,saved?100:null,'%',{minimum:true,state:completionState})};
+ const checks=[...groups.filter(g=>!steadyIds.has(g.id)).flatMap(g=>g.checks),...(steadyIds.size?steadyChecks:[]),completion.check],passed=checks.filter(c=>c.outcome==='pass').length,evaluated=checks.filter(c=>['pass','fail'].includes(c.outcome)).length,total=checks.filter(c=>c.limit!=null).length;
+ const measuredVerdict=groupVerdict(checks);
+ // Legacy snapshots only cover part of this checklist. Keep their measured
+ // failures, but do not promote a historical run to a new overall pass.
+ const verdict=!finished?'in_progress':['cancelled','interrupted'].includes(jobStatus)||recording.recording_state!=='complete'?'incomplete':!saved&&measuredVerdict==='pass'?'recorded':measuredVerdict;
+ return {version:scenarioChecksVersion,httpErrorScope:'payment_create_and_confirm',latencySettlingSeconds:limits.recoveryWindowSeconds,steady,completion,limits,limitsSaved:saved,groups,states,testCasePlan:testCasePlan(config,groups),passed,evaluated,total,verdict};
+}
+
+export async function scenarioChecks(directory,{config,recording,events=[],reconciliation=null,jobStatus=null}){
+ const progress=await readJson(path.join(directory,'progress.json'));
+ const control=progress?.control?{started_flows:progress.control.started_flows,dropped:progress.control.dropped,active_seconds:progress.control.active_seconds}:null;
+ const fingerprint=createHash('sha256').update(JSON.stringify({version:scenarioChecksVersion,config,recording,events,reconciliation,jobStatus,control})).digest('hex');
+ const file=path.join(directory,'scenario-checks.json');
+ const finished=terminal.has(jobStatus)||Boolean(recording.ended_at&&!jobStatus);
+ if(finished){const saved=await readJson(file);if(saved?.fingerprint===fingerprint)return saved.summary;}
+ let samples=await lines(path.join(directory,'execution.jsonl'));
+ if(!samples.length)samples=(await lines(path.join(directory,'telemetry.jsonl'))).map(p=>({at:recording.started_at+p.t*1000,active:p.activeSeconds??p.t,state:p.state}));
+ const args={config,recording,events,samples,reconciliation,jobStatus,control};let db;
+ // Results can be opened while load is running. Do not repeatedly scan a
+ // growing recorder DB; exact checks are evaluated once it has drained.
+ if(!finished)return evaluateScenarioChecks({...args,measurementsAvailable:false});
+ try{
+ db=new DatabaseSync(path.join(directory,'results.sqlite'),{readOnly:true});db.exec('BEGIN');
+ const cols=new Set(db.prepare('PRAGMA table_info(request_events)').all().map(c=>c.name));
+ const optional=['server_latency_ms','latency_ms','status'].map(c=>cols.has(c)?c:`NULL AS ${c}`).join(',');
+ const requestStart=cols.has('latency_ms')?'observed_at-COALESCE(latency_ms,0)':'observed_at';
+ const requests=db.prepare(`SELECT flow_id,operation,api_status_code,observed_at,${optional},CASE WHEN flow_id IS NULL THEN ${requestStart} ELSE MIN(${requestStart}) OVER (PARTITION BY flow_id) END AS flow_started_at FROM request_events WHERE run_id=? AND role='measured'`).iterate(recording.run_id);
+ // Iterate request rows once; aggregate flow completions in SQLite so a
+ // multi-request payment is never counted as several completed flows.
+ const flows=db.prepare(`SELECT MIN(observed_at-COALESCE(latency_ms,0)) AS startedAt,MAX(observed_at) AS at,MAX(CASE WHEN operation='payment_confirm' AND api_status_code>=200 AND api_status_code<300 AND status IN ('succeeded','requires_capture','processing') THEN 1 ELSE 0 END) AS success FROM request_events WHERE run_id=? AND role='measured' AND flow_id IS NOT NULL GROUP BY flow_id`).iterate(recording.run_id);
+ const summary=evaluateScenarioChecks({...args,requests,flows});
+ if(finished){const temp=`${file}.${randomUUID()}.tmp`;await writeFile(temp,JSON.stringify({fingerprint,summary})+'\n',{mode:0o600});await rename(temp,file);}
+ return summary;
+ }catch(error){if(error.code==='ERR_SQLITE_ERROR')return evaluateScenarioChecks({...args,measurementsAvailable:false});throw error;}finally{db?.close();}
+}
diff --git a/loadtest/console/server/screens.mjs b/loadtest/console/server/screens.mjs
new file mode 100644
index 0000000000..fb7a92a719
--- /dev/null
+++ b/loadtest/console/server/screens.mjs
@@ -0,0 +1,18 @@
+import {publicSettings,runDirectory} from './state.mjs';
+import {listProfiles,listFixtureSets,profileDraft} from './profiles.mjs';
+import {workerCommand} from './supervisor.mjs';
+import {queryWorker} from './workers.mjs';
+export async function screenData(url,screen){
+ const settings=publicSettings(),profiles=listProfiles({includeArchived:screen==='scenarios'}),fixtures=listFixtureSets();
+ let profileId=url.searchParams.get('profile') || profiles[0]?.id;
+ const job=await workerCommand('active',{kind:['performance','fixtures'].includes(screen)?'generator':null});
+ if(screen==='fixtures'&&job?.progress?.verification?.profileId)profileId=job.progress.verification.profileId;
+ if(screen==='scenarios'||screen==='fixtures')return {settings,profiles,fixtures,profileId,job,profileTemplate:profileDraft(settings)};
+ const runs=await queryWorker('list');
+ const requested=url.searchParams.get('run');
+ const selected=screen==='results'?(runs.some(run=>run.id===requested)?requested:runs[0]?.id):(runs.some(run=>run.id===requested)?requested:(job?.command==='load'?job.runId:null));
+ const run=selected?await queryWorker('run',{id:selected}):null;
+ const reconciliationJob=screen==='results'&&selected?await workerCommand('latest-reconciliation',{path:runDirectory(selected).path}):null;
+ const generator=await workerCommand('active',{kind:'generator'});
+ return {settings,profiles,fixtures,profileId,reconciliationJob,busy:generator!=null,job:['load','smoke'].includes(job?.command)?job:null,runs,run,fixtureSetId:url.searchParams.get('fixtures') || job?.fixtureSetId};
+}
diff --git a/loadtest/console/server/service-checks.mjs b/loadtest/console/server/service-checks.mjs
new file mode 100644
index 0000000000..808fd87c2a
--- /dev/null
+++ b/loadtest/console/server/service-checks.mjs
@@ -0,0 +1,33 @@
+import {httpUrl} from './state.mjs';
+
+export async function testServiceEndpoint(kind,endpoint,{fetcher=fetch}={}){
+ if(!['router','modularPm','superposition'].includes(kind))throw new Error('Unknown service');
+ // Service endpoints may include an API prefix (for example `/v2` locally
+ // or `/v1` in cloud). Preserve that prefix when constructing the probe URL.
+ const base=httpUrl(endpoint),url=new URL(base);
+ url.pathname=`${url.pathname.replace(/\/$/,'')}/health`;
+ const started=performance.now();
+ let response;
+ try{response=await fetcher(url,{method:'GET',redirect:'manual',signal:AbortSignal.timeout(5000)});}
+ catch(e){throw new Error(`${kind==='modularPm'?'Payment methods':kind==='superposition'?'Superposition':'Router'} is unreachable: ${e.message}`);}
+ await response.body?.cancel().catch(()=>{});
+ const latencyMs=Math.round(performance.now()-started);
+ if(!response.ok)throw new Error(`Health check returned HTTP ${response.status}`);
+ return {ok:true,status:response.status,latencyMs,message:`Reachable · HTTP ${response.status} · ${latencyMs} ms`};
+}
+
+export async function testSuperpositionEndpoint(config,{fetcher=fetch}={}){
+ const key=Object.keys(config.defaults || {})[0];
+ if(!key)throw new Error('Configure at least one Superposition default before testing');
+ if(!config.token)throw new Error('Configure a Superposition token before testing');
+ const base=httpUrl(config.endpoint),url=new URL(`/default-config/${encodeURIComponent(key)}`,base);
+ const auth=config.access_header==='x-superposition-access'?{'x-superposition-access':config.token}:{Authorization:`Bearer ${config.token}`};
+ const started=performance.now();
+ let response;
+ try{response=await fetcher(url,{method:'GET',headers:{...auth,'x-org-id':config.organization_id,'x-workspace':config.workspace_id},redirect:'manual',signal:AbortSignal.timeout(5000)});}
+ catch(e){throw new Error(`Superposition is unreachable: ${e.message}`);}
+ await response.body?.cancel().catch(()=>{});
+ const latencyMs=Math.round(performance.now()-started);
+ if(!response.ok)throw new Error(`Authenticated config check returned HTTP ${response.status}`);
+ return {ok:true,status:response.status,latencyMs,message:`Authenticated · HTTP ${response.status} · ${latencyMs} ms`};
+}
diff --git a/loadtest/console/server/state.mjs b/loadtest/console/server/state.mjs
new file mode 100644
index 0000000000..859893d76e
--- /dev/null
+++ b/loadtest/console/server/state.mjs
@@ -0,0 +1,309 @@
+import {isDeepStrictEqual} from 'node:util';
+import { DatabaseSync } from 'node:sqlite';
+import { mkdirSync, readFileSync, writeFileSync, chmodSync } from 'node:fs';
+import { readFile, writeFile, rename } from 'node:fs/promises';
+import path from 'node:path';
+import {loadShape} from '../src/load-shape.mjs';
+import {defaultCriteria} from './acceptance.mjs';
+import {validateResultsLimits} from '../src/results-limits.mjs';
+import {decodeStages,encodeStages} from '../src/ramp-editor.mjs';
+import {validateEnvironment} from '../src/environments.mjs';
+import {normalizePaymentFlows} from '../src/payment-flows.mjs';
+import {hasCertificate} from './certificates.mjs';
+import {requireBoundSecret,databaseTestConnection,sameEndpoint} from './connection-secrets.mjs';
+
+export const consoleRoot = path.resolve(process.env.LOADTEST_CONSOLE_ROOT || process.cwd());
+export const loadtestRoot = path.resolve(process.env.LOADTEST_ROOT || path.join(consoleRoot, '..'));
+export const dataRoot = path.resolve(process.env.LOADTEST_DATA_DIR || path.join(consoleRoot, '.data'));
+export const configPath = path.join(dataRoot, 'config.json');
+export const localPath = path.join(dataRoot, 'settings.json');
+export const workerPath = path.join(consoleRoot, 'server', 'query-worker.mjs');
+let database;
+
+export function controlDb() {
+ if (database) return database;
+ mkdirSync(dataRoot, { recursive: true, mode: 0o700 });
+ database = new DatabaseSync(path.join(dataRoot, 'console.sqlite'));
+ chmodSync(path.join(dataRoot, 'console.sqlite'), 0o600);
+ database.exec(`PRAGMA journal_mode=WAL; PRAGMA busy_timeout=5000;
+ CREATE TABLE IF NOT EXISTS console_preferences(key TEXT PRIMARY KEY,value TEXT NOT NULL);
+ CREATE TABLE IF NOT EXISTS archived_profiles(profile_id TEXT PRIMARY KEY,archived_at INTEGER NOT NULL);
+ CREATE TABLE IF NOT EXISTS profiles(id TEXT PRIMARY KEY,name TEXT NOT NULL,version INTEGER NOT NULL,updated_at INTEGER NOT NULL);
+ CREATE TABLE IF NOT EXISTS profile_versions(profile_id TEXT NOT NULL,version INTEGER NOT NULL,body TEXT NOT NULL,PRIMARY KEY(profile_id,version));
+ CREATE TABLE IF NOT EXISTS fixture_sets(id TEXT PRIMARY KEY,mode TEXT NOT NULL,merchant_count INTEGER NOT NULL,signature TEXT NOT NULL,path TEXT NOT NULL,status TEXT NOT NULL,job_id TEXT,created_at INTEGER NOT NULL);
+ CREATE TABLE IF NOT EXISTS sessions(token TEXT PRIMARY KEY,expires INTEGER NOT NULL);
+ CREATE TABLE IF NOT EXISTS login_limits(key TEXT PRIMARY KEY,failures INTEGER NOT NULL,reset_at INTEGER NOT NULL);
+ CREATE TABLE IF NOT EXISTS jobs(id TEXT PRIMARY KEY,kind TEXT NOT NULL,mode TEXT,status TEXT NOT NULL,
+ started_at INTEGER NOT NULL,ended_at INTEGER,exit_code INTEGER,run_path TEXT,config_path TEXT,
+ output TEXT NOT NULL DEFAULT '',progress TEXT NOT NULL DEFAULT '{}',result TEXT,error TEXT);
+ CREATE TABLE IF NOT EXISTS job_events(event_id INTEGER PRIMARY KEY AUTOINCREMENT,job_id TEXT NOT NULL,at INTEGER NOT NULL,kind TEXT NOT NULL,message TEXT NOT NULL);
+ CREATE INDEX IF NOT EXISTS events_job ON job_events(job_id,event_id);
+ CREATE TABLE IF NOT EXISTS load_workers(id TEXT PRIMARY KEY,name TEXT NOT NULL,token_hash TEXT NOT NULL UNIQUE,status TEXT NOT NULL,
+ labels TEXT NOT NULL DEFAULT '{}',capacity_tps INTEGER NOT NULL,capacity_vus INTEGER NOT NULL,version TEXT,created_at INTEGER NOT NULL,last_seen INTEGER NOT NULL);
+ CREATE TABLE IF NOT EXISTS worker_commands(id TEXT PRIMARY KEY,worker_id TEXT NOT NULL,run_id TEXT,revision INTEGER NOT NULL,kind TEXT NOT NULL,
+ payload TEXT NOT NULL,status TEXT NOT NULL,created_at INTEGER NOT NULL,acked_at INTEGER,result TEXT,
+ UNIQUE(worker_id,revision),FOREIGN KEY(worker_id) REFERENCES load_workers(id));
+ CREATE INDEX IF NOT EXISTS worker_commands_pending ON worker_commands(worker_id,status,revision);
+ CREATE TABLE IF NOT EXISTS run_shards(id TEXT PRIMARY KEY,run_id TEXT NOT NULL,worker_id TEXT NOT NULL,status TEXT NOT NULL,
+ offered_tps REAL NOT NULL,segment_start REAL NOT NULL,segment_end REAL NOT NULL,artifact_path TEXT,error TEXT,updated_at INTEGER NOT NULL,
+ progress TEXT NOT NULL DEFAULT '{}',
+ FOREIGN KEY(worker_id) REFERENCES load_workers(id));
+ CREATE INDEX IF NOT EXISTS run_shards_run ON run_shards(run_id);
+ DROP INDEX IF EXISTS single_generator;
+ CREATE UNIQUE INDEX single_generator ON jobs((1))
+ WHERE kind IN ('fixtures','load','smoke') AND status IN ('starting','running','pausing','paused','cancelling');`);
+ if(!database.prepare("SELECT 1 FROM pragma_table_info('run_shards') WHERE name='progress'").get())database.exec("ALTER TABLE run_shards ADD COLUMN progress TEXT NOT NULL DEFAULT '{}'");
+ if(!database.prepare("SELECT 1 FROM pragma_table_info('profiles') WHERE name='created_at'").get()){
+ // Older records only have a last-saved timestamp; preserve that as the
+ // creation-time fallback once, then keep it unchanged on subsequent edits.
+ database.exec('ALTER TABLE profiles ADD COLUMN created_at INTEGER NOT NULL DEFAULT 0; UPDATE profiles SET created_at=updated_at WHERE created_at=0');
+ }
+ return database;
+}
+
+export function readJsonSync(file, fallback = null) {
+ try { return JSON.parse(readFileSync(file, 'utf8')); }
+ catch (e) { if (e.code === 'ENOENT') return fallback; throw e; }
+}
+export async function readJson(file, fallback = null) {
+ try { return JSON.parse(await readFile(file, 'utf8')); }
+ catch (e) { if (e.code === 'ENOENT') return fallback; throw e; }
+}
+export async function atomicJson(file, value) {
+ const temporary = `${file}.${process.pid}.tmp`;
+ await writeFile(temporary, JSON.stringify(value, null, 2) + '\n', { mode: 0o600 });
+ await rename(temporary, file);
+}
+
+export function initializeConfig() {
+ mkdirSync(dataRoot, { recursive: true, mode: 0o700 });
+ if (!readJsonSync(configPath)) {
+ const source = path.resolve(process.env.LOADTEST_CONFIG_FILE || path.join(loadtestRoot, 'loadtest.config.json'));
+ const legacy = readJsonSync(source);
+ const config = legacy || readJsonSync(path.join(loadtestRoot, 'loadtest.config.example.json'));
+ if (!config) throw new Error('Load-test configuration is missing');
+ config.output = legacy ? path.resolve(path.dirname(source), config.output || 'artifacts') : path.join(dataRoot, 'artifacts');
+ writeFileSync(configPath, JSON.stringify(config, null, 2), { mode: 0o600 });
+ }
+}
+
+export function localSettings() {
+ const defaultPanels=[
+ {title:'RPS',url:'/grafana/d-solo/k6/k6-load-testing-results?panelId=17'},
+ {title:'API latency',url:'/grafana/d-solo/k6/k6-load-testing-results?panelId=13&var-Measurement=http_req_duration'},
+ {title:'TP latencies',url:'/grafana/d-solo/k6/k6-load-testing-results?panelId=5&var-Measurement=payment_confirm_latency_ms'}
+ ];
+ const saved=readJsonSync(localPath, readJsonSync(path.join(consoleRoot, '.console-state.json'), {}));
+ const pgSslMode=process.env.PGSSLMODE || '';
+ const forcedTlsMode=process.env.LOADTEST_DB_TLS==='1'||['verify-ca','verify-full'].includes(pgSslMode)?'verify':pgSslMode==='require'?'require':'';
+ const base={mode:'single',grafana:{baseUrl:process.env.GRAFANA_URL || 'http://localhost:3002',panels:defaultPanels,presetsVersion:1},
+ smokeTest:{enabled:true,rps:1,durationSeconds:10},database:{host:process.env.PGHOST || '127.0.0.1',port:Number(process.env.PGPORT || 5432),
+ database:process.env.PGDATABASE || 'hyperswitch_db',user:process.env.PGUSER || '',password:process.env.PGPASSWORD || '',tlsMode:forcedTlsMode || 'disable',caPath:process.env.PGSSLROOTCERT || '',caCertificateId:''}};
+ return {
+ ...base,...saved,grafana:{...base.grafana,...saved.grafana,
+ panels:saved.grafana?.presetsVersion===1?(saved.grafana.panels || []):[...defaultPanels,...(saved.grafana?.panels || [])]},
+ database:{...base.database,...saved.database,tlsMode:forcedTlsMode || saved.database?.tlsMode || (saved.database?.ssl?'verify':'disable'),...(forcedTlsMode&&process.env.PGSSLROOTCERT?{caPath:process.env.PGSSLROOTCERT}:{})},smokeTest:{...base.smokeTest,...saved.smokeTest}
+ };
+}
+
+export function activeEnvironment(){
+ initializeConfig();const c=readJsonSync(configPath),l=localSettings();
+ if(c.environment||l.environment)return c.environment||l.environment;
+ const targets=controlDb().prepare("SELECT value FROM console_preferences WHERE key='fault-targets'").get();
+ let loopback=false;try{loopback=['localhost','127.0.0.1','[::1]'].includes(new URL(c.services.router).hostname);}catch{}
+ if(targets){const list=JSON.parse(targets.value);if(list.length&&list.every(t=>t.environment==='cloud'||t.adapter?.startsWith('gcp-')))return loopback?'unassigned':'gcp';}
+ if(loopback)return 'local';
+ return 'unassigned';
+}
+const connectionBundle=(config,local)=>({services:config.services,fixtures:config.fixtures,target_headers:config.target_headers,database:local.database,grafana:local.grafana});
+function settingsSource(environment){
+ const c=structuredClone(readJsonSync(configPath)),l=structuredClone(localSettings()),active=activeEnvironment();
+ if(environment&&environment!==active){
+ validateEnvironment(environment);
+ const saved=l.environmentProfiles?.[environment];
+ const source=saved||{services:{router:environment==='local'?'http://127.0.0.1:8080':'https://router.invalid',modular_pm:environment==='local'?'http://127.0.0.1:8081/v2':'https://payment-methods.invalid/v2'},fixtures:{...c.fixtures,admin_api_key:'',connector:{connector_name:'stripe_test',connector_account_details:{auth_type:'HeaderKey',api_key:'local-test'},test_mode:true},superposition:{endpoint:environment==='local'?'http://127.0.0.1:8082':'https://superposition.invalid',token:'',organization_id:environment==='local'?'localorg':'',workspace_id:environment==='local'?'dev':'',defaults:c.fixtures.superposition?.defaults}},target_headers:{},database:{host:environment==='local'?'127.0.0.1':'',port:5432,database:'hyperswitch_db',user:'',password:'',tlsMode:environment==='local'?'disable':'verify',caPath:'',caCertificateId:''},grafana:{baseUrl:'http://localhost:3002',panels:[]}};
+ Object.assign(c,{services:source.services,fixtures:source.fixtures,target_headers:source.target_headers});Object.assign(l,{database:source.database,grafana:source.grafana});
+ }
+ return {config:c,local:l,environment:environment||active};
+}
+export function environmentDatabase(environment){return settingsSource(environment).local.database;}
+export function publicSettings(environment=null) {
+ initializeConfig();
+ const source=settingsSource(environment),c=source.config,l=source.local,sp=c.fixtures?.superposition||{};
+ return {
+ customFaultCommands:process.env.LOADTEST_ALLOW_CUSTOM_COMMANDS==='true',
+ environment:source.environment,mode: l.mode, router: c.services.router, modularPm: c.services.modular_pm,
+ adminApiKey: '', hasAdminApiKey: Boolean(c.fixtures.admin_api_key), connector: c.fixtures.connector?.connector_name || 'stripe_test',
+ totalRps: loadShape(c.load).peak, durationSeconds: loadShape(c.load).duration,
+ loadShape:c.load.stages?'staged':'flat',startRps:c.load.start_rps ?? c.load.stages?.[0]?.target_rps ?? 10,stagesJson:JSON.stringify(c.load.stages || [{target_rps:100,duration_seconds:60},{target_rps:500,duration_seconds:60},{target_rps:1000,duration_seconds:1800}],null,2),
+ acceptance:{...defaultCriteria,...c.acceptance},
+ resultsLimits:validateResultsLimits(c.resultsLimits),
+ preAllocatedVusMultiplier: c.load.pre_allocated_vus_multiplier ?? 3, maxVusMultiplier: c.load.max_vus_multiplier ?? 10,
+ scenarios: normalizePaymentFlows(c.scenarios),
+ superposition: { endpoint: sp.endpoint, token: '', hasToken: Boolean(sp.token), accessHeader:sp.access_header || 'authorization', organizationId: sp.organization_id,
+ workspaceId: sp.workspace_id, refreshSeconds: sp.refresh_interval_seconds ?? 30,pollSeconds:sp.poll_interval_seconds ?? 5, defaultsJson: JSON.stringify(sp.defaults || {}, null, 2) },
+ grafana: { baseUrl: l.grafana.baseUrl, panels: l.grafana.panels || [], hasToken: Boolean(process.env.GRAFANA_TOKEN), hasIdentity: Boolean(process.env.GRAFANA_TOKEN || process.env.GRAFANA_USER) },
+ smokeTest:l.smokeTest,workerEnrollmentConfigured:Boolean(process.env.LOADTEST_WORKER_ENROLLMENT_TOKEN),
+ database: { host: l.database.host, port: l.database.port, database: l.database.database, user: l.database.user,
+ tlsMode:l.database.tlsMode || (l.database.ssl?'verify':'disable'),caPath:l.database.caPath || '',caCertificateId:l.database.caCertificateId || '', password: '', hasPassword: Boolean(l.database.password) }
+ };
+}
+
+export const flows = ['guest','cit_on_session','cit_off_session','ptv_on_session','ptv_off_session','cit_metadata_changed','sdk_checkout','mit','saved_card_checkout'];
+export function configuredVus(load={}) {
+ const pre=Number(load.pre_allocated_vus_multiplier ?? 3),max=Number(load.max_vus_multiplier ?? 10);
+ if(!(Number.isFinite(pre)&&Number.isFinite(max)&&pre>0&&max>=pre))throw new Error('VU multipliers must satisfy 0 < preallocated <= max');
+ return {pre_allocated_vus_multiplier:pre,max_vus_multiplier:max};
+}
+export function withConfiguredVus(load,settings) { return {...load,...configuredVus(settings),...(settings?.request_timeout_ms!=null?{request_timeout_ms:settings.request_timeout_ms}:{})}; }
+export function httpUrl(value) {
+ const u = new URL(value);
+ if (!['http:', 'https:'].includes(u.protocol) || u.username || u.password) throw new Error('Use an HTTP(S) URL without embedded credentials');
+ return u;
+}
+export function panelPath(value, base) {
+ const u = httpUrl(new URL(value, httpUrl(base)).href);
+ if (u.origin !== new URL(base).origin) throw new Error('Set Settings → Grafana → Base URL to this Grafana server before adding its panels');
+ const route = u.pathname.match(/^\/(?:grafana\/)?(d|d-solo)\/(.+)$/);
+ if (!route) throw new Error('Paste a Grafana panel embed URL or a dashboard URL with a selected panel');
+ const selected = u.searchParams.get('panelId') || u.searchParams.get('viewPanel');
+ const panel = selected?.match(/^panel-(\d+)$/)?.[1] || selected;
+ if (!panel) throw new Error('Select a panel in Grafana, then use Share → Embed. A dashboard URL alone does not identify the panel');
+ u.pathname = '/grafana/d-solo/' + route[2];
+ u.searchParams.set('panelId', panel);
+ if(!u.searchParams.has('theme'))u.searchParams.set('theme','light');
+ u.searchParams.delete('viewPanel');
+ return u.pathname + u.search;
+}
+
+export function validateSettings(input) {
+ const source=settingsSource(input.environment),current=source.config,local=source.local;
+ if(input.loadShape!=null&&!['flat','staged'].includes(input.loadShape))throw new Error('Invalid load shape');
+ if (!['single','tenancy'].includes(input.mode)) throw new Error('Invalid merchant mode');
+ for (const value of [input.router,input.modularPm,input.superposition.endpoint,input.grafana.baseUrl]) httpUrl(value);
+ if (!Array.isArray(input.scenarios) || !input.scenarios.length || input.scenarios.length > 50) throw new Error('Choose 1–50 flows');
+ const names = new Set();
+ for (const f of input.scenarios) {
+ if (!/^[A-Za-z0-9_]{1,80}$/.test(f.name) || names.has(f.name) || !flows.includes(f.scenario)
+ || !Number.isFinite(Number(f.weight)) || Number(f.weight) < 0 || Number(f.weight) > 100) throw new Error('Invalid or duplicate flow');
+ names.add(f.name);
+ }
+ if (input.scenarios.reduce((s,f)=>s+Number(f.weight),0) !== 100) throw new Error('Flow weights must total 100%');
+ for (const v of [input.totalRps,input.durationSeconds]) if (!Number.isSafeInteger(Number(v)) || v < 1) throw new Error('Rate and duration must be positive integers');
+ const defaults = JSON.parse(input.superposition.defaultsJson);
+ if (!defaults || typeof defaults !== 'object' || Array.isArray(defaults)) throw new Error('Defaults must be an object');
+ const refresh = Number(input.superposition.refreshSeconds);
+ if (!Number.isFinite(refresh) || refresh < 0) throw new Error('Invalid refresh wait');
+ const poll = Number(input.superposition.pollSeconds ?? 5);
+ if (!Number.isFinite(poll) || poll < 0.25 || poll > 60) throw new Error('Superposition poll interval must be 0.25–60 seconds');
+ const accessHeader=String(input.superposition.accessHeader || 'authorization');
+ if(!['authorization','x-superposition-access'].includes(accessHeader))throw new Error('Invalid Superposition authentication method');
+ const {pre_allocated_vus_multiplier:pre,max_vus_multiplier:max}=configuredVus({
+ pre_allocated_vus_multiplier:input.preAllocatedVusMultiplier ?? current.load.pre_allocated_vus_multiplier,
+ max_vus_multiplier:input.maxVusMultiplier ?? current.load.max_vus_multiplier
+ });
+ const dbPort = Number(input.database.port);
+ if (!Number.isInteger(dbPort) || dbPort < 1 || dbPort > 65535) throw new Error('Invalid database port');
+ const tlsMode=String(input.database.tlsMode || (input.database.ssl?'verify':'disable'));
+ if(!['disable','require','verify'].includes(tlsMode))throw new Error('Invalid database TLS mode');
+ const caPath=String(input.database.caPath || '').trim();
+ if(caPath&&!path.isAbsolute(caPath))throw new Error('Database CA certificate path must be absolute');
+ const caCertificateId=String(input.database.caCertificateId || '').trim();
+ if(caCertificateId&&!hasCertificate(dataRoot,caCertificateId))throw new Error('Imported database CA certificate does not exist');
+ const panels = (input.grafana.panels || []).map(p=>({ title: String(p.title).slice(0,100), url: panelPath(p.url,input.grafana.baseUrl) }));
+ const next = structuredClone(current);
+ next.services = { ...next.services,router: input.router,modular_pm:input.modularPm };
+ next.load = { ...next.load,total_rps:Number(input.totalRps),duration_seconds:Number(input.durationSeconds),pre_allocated_vus_multiplier:pre,max_vus_multiplier:max };
+ delete next.load.phases;
+ delete next.load.stages;delete next.load.start_rps;
+ if(input.loadShape==='staged'){
+ const stages=JSON.parse(input.stagesJson);
+ if(!Array.isArray(stages)||stages.length<1||stages.length>50||stages.some(s=>!Number.isFinite(s.target_rps)||s.target_rps<=0||!Number.isInteger(s.duration_seconds)||s.duration_seconds<1))throw new Error('Choose 1–50 positive TPS stages with integer durations');
+ const start=Number(input.startRps);if(!Number.isFinite(start)||start<0)throw new Error('Starting TPS must be nonnegative');
+ next.load.stages=encodeStages(decodeStages(JSON.stringify(stages),start),start);next.load.start_rps=start;delete next.load.total_rps;delete next.load.duration_seconds;
+ }
+ const criteria={...defaultCriteria,...input.acceptance};
+ for(const v of Object.values(criteria))if(!Number.isFinite(Number(v))||Number(v)<0)throw new Error('Invalid acceptance criteria');
+ if(criteria.minimumSuccessRatio>1||criteria.maximumErrorPercent>100)throw new Error('Invalid acceptance percentage');
+ next.acceptance=Object.fromEntries(Object.keys(defaultCriteria).map(k=>[k,Number(criteria[k])]));
+ next.resultsLimits=validateResultsLimits(input.resultsLimits??current.resultsLimits);
+ next.scenarios = normalizePaymentFlows(input.scenarios).map(f=>({name:f.name,scenario:f.scenario,merchant_path:f.merchant_path,weight:Number(f.weight)}));
+ next.fixtures.router = input.router;
+ if (input.adminApiKey) next.fixtures.admin_api_key = input.adminApiKey;
+ next.fixtures.connector.connector_name = input.connector;
+ next.fixtures.superposition = { ...next.fixtures.superposition,endpoint:input.superposition.endpoint,
+ access_header:accessHeader,organization_id:input.superposition.organizationId,workspace_id:input.superposition.workspaceId,defaults,refresh_interval_seconds:refresh,poll_interval_seconds:poll };
+ if (input.superposition.token) next.fixtures.superposition.token = input.superposition.token;
+ const smoke=input.smokeTest || local.smokeTest;
+ if(typeof smoke.enabled!=='boolean'||!Number.isInteger(Number(smoke.rps))||smoke.rps<1||smoke.rps>100||!Number.isInteger(Number(smoke.durationSeconds))||smoke.durationSeconds<1||smoke.durationSeconds>300)throw new Error('Invalid smoke-test defaults');
+ next.environment=validateEnvironment(input.environment||activeEnvironment());
+ return {config:next,local:{ ...local,environment:next.environment,mode:input.mode,grafana:{baseUrl:input.grafana.baseUrl,panels,presetsVersion:1},smokeTest:{enabled:smoke.enabled,rps:Number(smoke.rps),durationSeconds:Number(smoke.durationSeconds)}, database:{
+ host:input.database.host,port:dbPort,database:input.database.database,user:input.database.user,tlsMode,caPath,caCertificateId,
+ password:input.database.password || local.database.password } }};
+}
+
+export async function saveSettings(input,{databaseTest=async database=>(await import('./workers.mjs')).queryWorker('database-test',{database})}={}) {
+ initializeConfig();
+ const beforeConfig=readJsonSync(configPath),beforeLocal=localSettings(),before=activeEnvironment();
+ const {config,local}=validateSettings(input);
+ const assertCredentials=()=>{
+ const source=settingsSource(input.environment);
+ requireBoundSecret(source.config.fixtures.admin_api_key,input.adminApiKey,sameEndpoint(source.config.services.router,input.router),'Router admin key');
+ requireBoundSecret(source.config.fixtures.superposition?.token,input.superposition.token,sameEndpoint(source.config.fixtures.superposition.endpoint,input.superposition.endpoint),'Superposition token');
+ databaseTestConnection(source.local.database,input.database);
+ };
+ if(config.environment!==before||!isDeepStrictEqual({...connectionBundle(config,local),grafana:null},{...connectionBundle(beforeConfig,beforeLocal),grafana:null})){
+ const busy=()=>Boolean(controlDb().prepare("SELECT 1 FROM jobs WHERE status IN ('starting','running','pausing','paused','cancelling') LIMIT 1").get());
+ const ledgerPath=path.join(dataRoot,'fault-ledger.json'),recovery=readJsonSync(ledgerPath);
+ if(busy()||recovery){
+ // A failed TLS probe must not prevent repairing its own settings after load has stopped.
+ // Keep provider, endpoint, credentials and every other connection frozen.
+ const withoutTls=({tlsMode,caPath,caCertificateId,...database})=>database;
+ const comparable=(c,l)=>({...connectionBundle(c,l),grafana:null,database:withoutTls(l.database)});
+ const tlsRepair=!busy()&&before===config.environment&&recovery?.target?.adapter==='gcp-alloydb'&&recovery.action==='failover'&&['restoring','recovery_failed'].includes(recovery.status)&&isDeepStrictEqual(comparable(config,local),comparable(beforeConfig,beforeLocal));
+ if(!tlsRepair)throw new Error('Finish active jobs and fault recovery before changing environment or connections');
+ assertCredentials();
+ if((await databaseTest(local.database))?.ok!==true)throw new Error('Database TLS repair could not be verified; settings were not saved');
+ if(busy()||!isDeepStrictEqual(recovery,readJsonSync(ledgerPath)))throw new Error('Recovery state changed while testing the database; retry saving settings');
+ }
+ }
+ assertCredentials();
+ local.environmentProfiles={...beforeLocal.environmentProfiles};
+ if(before!=='unassigned')local.environmentProfiles[before]=connectionBundle(beforeConfig,beforeLocal);
+ local.environmentProfiles[config.environment]=connectionBundle(config,local);
+ await atomicJson(configPath,config);await atomicJson(localPath,local);
+ return publicSettings();
+}
+
+export async function saveConnections(input,options) {
+ // Connection edits never depend on an unsaved profile in another screen.
+ const current=publicSettings(input.environment);
+ for(const key of ["environment","router","modularPm","adminApiKey","connector","superposition","grafana","database","smokeTest","preAllocatedVusMultiplier","maxVusMultiplier","resultsLimits"])if(input[key]!==undefined)current[key]=input[key];
+ return saveSettings(current,options);
+}
+
+export function superpositionConnection(draft={},environment=null) {
+ initializeConfig();
+ const saved=settingsSource(environment).config.fixtures?.superposition || {};
+ const defaults=draft.defaultsJson?JSON.parse(draft.defaultsJson):saved.defaults;
+ return {
+ ...saved,endpoint:draft.endpoint || saved.endpoint,token:requireBoundSecret(saved.token,draft.token,sameEndpoint(saved.endpoint,draft.endpoint||saved.endpoint),'Superposition token'),
+ access_header:draft.accessHeader || saved.access_header || 'authorization',
+ organization_id:draft.organizationId || saved.organization_id,workspace_id:draft.workspaceId || saved.workspace_id,defaults
+ };
+}
+
+export function runDirectory(id) {
+ const match = /^(single|tenancy):([A-Za-z0-9][A-Za-z0-9._-]*)$/.exec(id);
+ if (!match) throw new Error('Invalid run ID');
+ const c = readJsonSync(configPath);
+ return { mode:match[1], name:match[2], path:path.join(c.output,match[1],'runs',match[2]) };
+}
+
+export function redact(value) {
+ let text = String(value);
+ const c = readJsonSync(configPath,{fixtures:{}}), l = localSettings();
+ const secrets = [...Object.values(l.environmentProfiles||{}).flatMap(profile=>[profile.fixtures?.admin_api_key,profile.fixtures?.superposition?.token,profile.database?.password,...Object.values(profile.fixtures?.connector?.connector_account_details||{})]),...Object.values(c.fixtures.connector?.connector_account_details||{}),c.fixtures.admin_api_key,c.fixtures.superposition?.token,l.database.password,process.env.GRAFANA_TOKEN,process.env.ROUTER_ADMIN_API_KEY,process.env.SUPERPOSITION_TOKEN];
+ for (let s of secrets) { if (typeof s === 'string' && s.startsWith('${')) s = process.env[s.slice(2,-1)]; if(s) text=text.replaceAll(s,'[redacted]'); }
+ return text;
+}
diff --git a/loadtest/console/server/successful-latency.mjs b/loadtest/console/server/successful-latency.mjs
new file mode 100644
index 0000000000..694d38862d
--- /dev/null
+++ b/loadtest/console/server/successful-latency.mjs
@@ -0,0 +1,70 @@
+import {DatabaseSync} from 'node:sqlite';
+import path from 'node:path';
+import {faultWindows} from './display-errors.mjs';
+export const successfulConfirmWhere="operation='payment_confirm' AND role='measured' AND api_status_code>=200 AND api_status_code<300 AND status IN ('succeeded','requires_capture','processing') AND server_latency_ms IS NOT NULL AND server_latency_ms>=0";
+export function latencyPercentile(values,percentile){
+ if(!values.length)return null;
+ values.sort((a,b)=>a-b);const index=(values.length-1)*percentile,low=Math.floor(index),high=Math.ceil(index);
+ return values[low]+(values[high]-values[low])*(index-low);
+}
+export const latencyP99=values=>latencyPercentile(values,.99);
+export function mergeLatencyWindows(windows){
+ const merged=[];
+ for(const window of [...windows].sort((a,b)=>a.from-b.from)){
+ const previous=merged.at(-1);
+ if(previous&&previous.to>=window.from&&previous.stageIndex===window.stageIndex)previous.to=Math.max(previous.to,window.to);
+ else merged.push({...window});
+ }
+ return merged;
+}
+// Select by recorded state boundaries, never by the magnitude of a latency.
+export function settledLatencyWindows({normalWindows,faults,startedAt,end,settlingSeconds}){
+ const settling=settlingSeconds*1000,activeFaults=faults.filter(f=>!f.skipped);
+ const clip=(from,to)=>mergeLatencyWindows(normalWindows.flatMap(w=>{
+ const a=Math.max(from,w.from),b=Math.min(to,w.to);return b>a?[{from:a,to:b}]:[];
+ }));
+ const normal=clip(startedAt+settling,Math.min(end,activeFaults[0]?.from??end));
+ const outage=[],recovery=[];
+ for(const fault of activeFaults){
+ const onset=fault.unavailableAt??fault.startedAt;
+ const until=Math.min(fault.restoreAt??end,fault.recoveredAt??end,end);
+ if(onset!=null&&until>onset+settling)outage.push({from:onset+settling,to:until,stageIndex:fault.stageIndex});
+ if(fault.recoveredAt!=null){
+ const next=activeFaults.find(f=>f.from>fault.recoveredAt);
+ recovery.push(...clip(fault.recoveredAt+settling,Math.min(next?.from??end,end)).map(w=>({...w,stageIndex:fault.stageIndex})));
+ }
+ }
+ return {normal,outage,recovery};
+}
+export function containedLatencySample(row,windows){
+ const end=row.observed_at,start=row.flow_started_at??end-Math.max(0,row.latency_ms||0);
+ return windows.some(w=>start>=w.from&&end>=start&&end<w.to);
+}
+export function latencyPhase(row,windows,recoverySeconds=10){
+ const end=row.observed_at,start=end-(row.latency_ms||0),outages=[...windows.vault,...windows.database];
+ const overlap=([from,to])=>start<to&&end>=from;
+ if(outages.some(overlap))return 'outage';
+ if(outages.filter(([,to])=>Number.isFinite(to)).map(([,to])=>[to,to+recoverySeconds*1000]).some(overlap))return 'recovery';
+ return 'normal';
+}
+const cache=new Map();
+export function successfulServerLatency(directory,recording,events=[],config={}){
+ const windows=faultWindows(events,config),recoverySeconds=10;
+ const key=recording?.ended_at?`${directory}:${recording.run_id}:${recording.persisted}:${recording.ended_at}:${JSON.stringify(windows)}`:null;
+ if(key&&cache.has(key))return cache.get(key);
+ let db;
+ try{
+ db=new DatabaseSync(path.join(directory,'results.sqlite'),{readOnly:true});
+ if(!db.prepare('PRAGMA table_info(request_events)').all().some(c=>c.name==='server_latency_ms'))return null;
+ const all=[],flows={},phases={normal:[],outage:[],recovery:[]};
+ for(const row of db.prepare(`SELECT flow_id,server_latency_ms,observed_at,latency_ms FROM request_events WHERE run_id=? AND ${successfulConfirmWhere}`).iterate(recording.run_id)){
+ if(!Number.isFinite(row.server_latency_ms))continue;
+ all.push(row.server_latency_ms);const name=String(row.flow_id).split(':').at(-3);(flows[name]??=[]).push(row.server_latency_ms);
+ phases[latencyPhase(row,windows,recoverySeconds)].push(row.server_latency_ms);
+ }
+ const result={p99:latencyP99(all),flows:Object.fromEntries(Object.entries(flows).map(([name,values])=>[name,latencyP99(values)])),recoverySeconds,
+ phases:Object.entries(phases).map(([state,values])=>({state,count:values.length,p50:latencyPercentile(values,.5),p95:latencyPercentile(values,.95),p99:latencyP99(values)}))};
+ if(key){cache.set(key,result);if(cache.size>8)cache.delete(cache.keys().next().value);}
+ return result;
+ }catch(error){if(error.code==='ERR_SQLITE_ERROR')return null;throw error;}finally{db?.close();}
+}
diff --git a/loadtest/console/server/supervisor.mjs b/loadtest/console/server/supervisor.mjs
new file mode 100644
index 0000000000..30a9a64d10
--- /dev/null
+++ b/loadtest/console/server/supervisor.mjs
@@ -0,0 +1,119 @@
+// SSR is only a client of this worker service. Browser and web-server lifetimes
+// have no ownership of generators, pause state, fault recovery or reconciliation.
+import {openSync,closeSync} from 'node:fs';
+import {spawn} from 'node:child_process';
+import {createServer} from 'node:http';
+import {mkdir,readFile,writeFile,rm} from 'node:fs/promises';
+import {randomUUID,timingSafeEqual} from 'node:crypto';
+import {fileURLToPath} from 'node:url';
+import path from 'node:path';
+import {dataRoot,consoleRoot,redact} from './state.mjs';
+import {HttpError} from './errors.mjs';
+const descriptor=path.join(dataRoot,'worker-service.json'),lock=path.join(dataRoot,'worker-service.lock');
+const protocolVersion=6;
+const alive=pid=>{try{process.kill(pid,0);return true;}catch{return false;}};
+const wait=ms=>new Promise(resolve=>setTimeout(resolve,ms));
+let starting;
+async function readService(){try{return JSON.parse(await readFile(descriptor,'utf8'));}catch{return null;}}
+async function serviceRequest(service,operation,args={},timeout=15000){
+ const response=await fetch(`${service.url}/rpc`,{method:'POST',headers:{authorization:`Bearer ${service.token}`,'content-type':'application/json'},body:JSON.stringify({operation,args}),signal:AbortSignal.timeout(timeout)});
+ const result=await response.json();if(!response.ok)throw new HttpError(response.status,result.error);return result;
+}
+async function replaceOutdatedService(service,actual){
+ let active=null;try{active=await serviceRequest(service,'active',{},2000);}catch(error){if(error.status!==404)throw error;}
+ if(active)throw new HttpError(409,`Worker service protocol ${actual||'legacy'} is outdated. Stop the active ${active.command} job, then restart the console.`);
+ try{process.kill(service.pid,'SIGTERM');}catch(error){if(error.code!=='ESRCH')throw error;}
+ for(let i=0;i<100&&alive(service.pid);i++)await wait(100);
+ if(alive(service.pid))throw new HttpError(503,'Outdated worker service did not stop; run npm run worker -- stop and retry');
+ await rm(descriptor,{force:true});
+}
+export async function initializeSupervisor() {
+ if(starting)return starting;
+ starting=(async()=>{
+ await mkdir(dataRoot,{recursive:true,mode:0o700});
+ let launched=false;
+ for(let i=0;i<150;i++){
+ const service=await readService();
+ if(service&&alive(service.pid)){
+ try{
+ const response=await fetch(`${service.url}/health`,{headers:{authorization:`Bearer ${service.token}`},signal:AbortSignal.timeout(500)});
+ if(response.ok){const health=await response.json();if(health.protocol===protocolVersion)return service;await replaceOutdatedService(service,health.protocol);}
+ }catch(error){if(error instanceof HttpError)throw error;}
+ }
+ if(!launched){
+ const log=openSync(path.join(dataRoot,'worker.log'),'a',0o600);
+ try{const child=spawn(process.execPath,[path.join(consoleRoot,'server','supervisor.mjs'),'serve'],{cwd:consoleRoot,detached:true,stdio:['ignore',log,log],env:process.env});child.on('error',()=>{});child.unref();launched=true;}finally{closeSync(log);}
+ }
+ await wait(100);
+ }
+ throw new HttpError(503,'Worker service unavailable; check the worker log and restart it');
+ })().finally(()=>{starting=null;});
+ return starting;
+}
+export async function workerCommand(operation,args={}) {
+ const service=await initializeSupervisor();
+ return serviceRequest(service,operation,args);
+}
+export function jobEvents(id,request){
+ let timer,busy=false,closed=false;
+ const encoder=new TextEncoder();
+ const stream=new ReadableStream({start(controller){
+ const close=()=>{if(closed)return;closed=true;clearInterval(timer);try{controller.close();}catch{}};
+ const emit=async()=>{if(busy||closed)return;busy=true;try{const job=await workerCommand('job',{id});if(!closed){controller.enqueue(encoder.encode(`event: progress\ndata: ${JSON.stringify(job)}\n\n`));if(!['starting','running','pausing','paused','cancelling'].includes(job.status))close();}}catch(e){if(!closed)controller.enqueue(encoder.encode(`event: unavailable\ndata: ${JSON.stringify({error:e.message})}\n\n`));}finally{busy=false;}};
+ timer=setInterval(emit,1000);request.signal.addEventListener('abort',close,{once:true});emit();
+ },cancel(){closed=true;clearInterval(timer);}});
+ return new Response(stream,{headers:{'content-type':'text/event-stream','cache-control':'no-cache, no-transform','x-accel-buffering':'no'}});
+}
+async function serve(){
+ await mkdir(dataRoot,{recursive:true,mode:0o700});
+ try{await mkdir(lock,{mode:0o700});}catch(e){
+ if(e.code!=='EEXIST')throw e;
+ const owner=JSON.parse(await readFile(path.join(lock,'owner.json'),'utf8').catch(()=>'null'));
+ // Never steal a live worker's lock. Missing owner can mean another process
+ // has just acquired it; retry on a subsequent startup rather than racing.
+ if(owner&&alive(owner.pid))return;
+ if(!owner){const {stat}=await import('node:fs/promises');if(Date.now()-(await stat(lock)).mtimeMs<15000)return;}
+ await rm(lock,{recursive:true,force:true});return serve();
+ }
+ await writeFile(path.join(lock,'owner.json'),JSON.stringify({pid:process.pid}),{mode:0o600});
+ const jobs=await import('./jobs.mjs'),faults=await import('./faults.mjs'),registry=await import('./worker-registry.mjs');jobs.initializeJobs();registry.registerLocalWorker();
+ const localHeartbeat=setInterval(()=>registry.registerLocalWorker(),5000);localHeartbeat.unref();
+ const token=randomUUID();let shuttingDown=false;
+ const server=createServer(async(req,res)=>{
+ const provided=Buffer.from(req.headers.authorization || ''),expected=Buffer.from(`Bearer ${token}`);
+ if(provided.length!==expected.length||!timingSafeEqual(provided,expected)){res.writeHead(401);res.end();return;}
+ res.setHeader('content-type','application/json');
+ try{
+ if(req.url==='/health'&&req.method==='GET'){res.end(JSON.stringify({ready:true,protocol:protocolVersion}));return;}
+ if(req.url!=='/rpc'||req.method!=='POST')throw new HttpError(404,'Not found');
+ if(shuttingDown)throw new HttpError(503,'Worker is shutting down');
+ let text='';for await(const chunk of req){text+=chunk;if(text.length>1024*1024)throw new HttpError(413,'Request too large');}
+ const {operation,args:a={}}=JSON.parse(text);let result;
+ switch(operation){
+ case 'save-scenario':result=(await import('./profiles.mjs')).saveScenario(a);break;
+ case 'active':result=jobs.activeJob(a.kind);break;
+ case 'job':result=jobs.getJob(a.id);break;
+ case 'latest-reconciliation':result=jobs.latestReconciliation(a.path);break;
+ case 'import-fixtures':result=await jobs.startFixtureImport(a);break;
+ case 'start':result=await jobs.startGenerator(a.kind,a.mode,a);break;
+ case 'cancel':result=jobs.cancelJob(a.id);break;
+ case 'control':result=await jobs.controlLoad(a.id,a.action);break;
+ case 'reconcile':result=await jobs.startReconciliation(a.id,a.allowIncomplete);break;
+ case 'fault-targets':result=faults.localFaultTargets();break;
+ case 'save-fault-targets':result=await faults.saveLocalFaultTargets(a.targets);break;
+ case 'check-fault-target':result=await faults.checkLocalFaultTarget(a);break;
+ case 'test-fault':result=await jobs.startFaultTest(a);break;
+ case 'faults':result=faults.faultStatus();break;
+ case 'fault':result=await faults.fireFault(jobs.getJob(a.jobId),a,jobs.recordActivity,()=>jobs.getJob(a.jobId));break;
+ case 'restore':result=faults.requestRestore(jobs.recordActivity);break;
+ default:throw new HttpError(404,'Unknown operation');
+ }
+ res.end(JSON.stringify(result));
+ }catch(e){res.statusCode=e.status || 400;res.end(JSON.stringify({error:redact(e.message)}));}
+ });
+ await new Promise(resolve=>server.listen(0,'127.0.0.1',()=>resolve(undefined)));
+ await writeFile(descriptor,JSON.stringify({pid:process.pid,url:`http://127.0.0.1:${/** @type {import('node:net').AddressInfo} */(server.address()).port}`,token,protocol:protocolVersion}),{mode:0o600});
+ const stop=async()=>{if(shuttingDown)return;shuttingDown=true;clearInterval(localHeartbeat);await jobs.shutdownJobs();server.close();await rm(descriptor,{force:true});await rm(lock,{recursive:true,force:true});process.exit(0);};
+ process.once('SIGTERM',stop);process.once('SIGINT',stop);
+}
+if(process.argv[1]===fileURLToPath(import.meta.url)&&process.argv[2]==='serve')serve().catch(async e=>{await writeFile(path.join(dataRoot,'worker-error.log'),redact(e.stack)+'\n',{mode:0o600}).catch(()=>{});process.exitCode=1;});
diff --git a/loadtest/console/server/telemetry.mjs b/loadtest/console/server/telemetry.mjs
new file mode 100644
index 0000000000..22ca1746b1
--- /dev/null
+++ b/loadtest/console/server/telemetry.mjs
@@ -0,0 +1,122 @@
+import {compactSamples} from '../src/chart-timeline.mjs';
+import { appendFile } from 'node:fs/promises';
+import { createReadStream } from 'node:fs';
+import { createInterface } from 'node:readline';
+import path from 'node:path';
+import {DatabaseSync} from 'node:sqlite';
+import {faultWindows,hiddenVaultError} from './display-errors.mjs';
+import {successfulConfirmWhere,latencyP99} from './successful-latency.mjs';
+
+const legacyStarts=new Map();
+const completedFlows=p=>Object.values(p.flows||{}).reduce((sum,f)=>sum+(Number(f.successes)||0)+(Number(f.failures)||0),0);
+const admitted=p=>Number.isFinite(p.started)?p.started:completedFlows(p)+(Number(p.inFlight)||0);
+
+export function telemetryPoint(progress,previous=null) {
+ if(!Number.isFinite(progress.elapsed_seconds))return null;
+ const successes=Object.values(progress.flows || {}).reduce((sum,flow)=>sum+(Number(flow.successes)||0),0);
+ const completed=Object.values(progress.flows||{}).reduce((sum,flow)=>sum+(Number(flow.successes)||0)+(Number(flow.failures)||0),0);
+ const started=Number.isFinite(progress.control?.started_flows)?progress.control.started_flows:completed+(Number(progress.control?.in_flight)||0);
+ const interval=progress.elapsed_seconds-(previous?.t || 0);
+ const httpAttempts=Number(progress.http_attempts)||0,httpErrors=Number(progress.http_errors)||0;
+ const confirmHttpAttempts=progress.confirm_http_attempts ?? null,confirmHttpErrors=progress.confirm_http_errors ?? null;
+ const attemptsDelta=Math.max(0,httpAttempts-(previous?.httpAttempts||0)),errorsDelta=Math.max(0,httpErrors-(previous?.httpErrors||0));
+ // Use counter deltas over the displayed interval, including the final partial sample.
+ return {t:progress.elapsed_seconds,successes,started,tps:interval>0?Math.max(0,started-(previous?admitted(previous):0))/interval:0,
+ successfulTps:interval>0?(successes-(previous?.successes || 0))/interval:0,
+ httpAttempts,httpErrors,confirmHttpAttempts,confirmHttpErrors,errorScope:'all_http',intervalStart:previous?.t||0,intervalAttempts:attemptsDelta,intervalErrors:errorsDelta,errors:attemptsDelta?100*errorsDelta/attemptsDelta:0,
+ recorded:progress.recorder.persisted,serverP99:progress.server_p99_ms ?? null,p99:progress.p99_ms ?? null,activeSeconds:progress.control?.active_seconds ?? progress.elapsed_seconds,
+ state:progress.control?.state || 'running',offeredTps:progress.control?.offered_tps ?? null,
+ inFlight:progress.control?.in_flight ?? null,backlog:progress.recorder.enqueued-progress.recorder.persisted,
+ connectors:Object.fromEntries(Object.entries(progress.connectors||{}).map(([name,c])=>[name,{...c,tps:interval>0?Math.max(0,c.confirmed-(previous?.connectors?.[name]?.confirmed||0))/interval:0}])),
+ flows:Object.fromEntries(Object.entries(progress.flows || {}).map(([name,f])=>{const started=progress.control?.flow_starts?.[name]??((Number(f.successes)||0)+(Number(f.failures)||0));const old=previous?.flows?.[name];return [name,{successes:Number(f.successes)||0,failures:Number(f.failures)||0,started,serverP99:f.server_p99_ms ?? null,p90:f.p90_ms,p99:f.p99_ms,tps:interval>0?Math.max(0,started-(old?.started??((Number(old?.successes)||0)+(Number(old?.failures)||0))))/interval:0,successfulTps:interval>0?((Number(f.successes)||0)-(old?.successes || 0))/interval:0}];}))};
+}
+export async function appendTelemetry(directory,point) {
+ if(point)await appendFile(path.join(directory,'telemetry.jsonl'),JSON.stringify(point)+'\n',{mode:0o600});
+}
+// Earlier recordings contain completion counters only. Reconstruct their traffic
+// from the first HTTP attempt per flow, including attempts that never returned an ID.
+function recordedStarts(directory,recording){
+ if(!recording?.ended_at)return null;
+ const key=`${directory}:${recording.ended_at}:${recording.persisted}`;
+ if(legacyStarts.has(key))return legacyStarts.get(key);
+ let db;const bins=new Map();
+ try{db=new DatabaseSync(path.join(directory,'results.sqlite'),{readOnly:true});
+ for(const row of db.prepare('SELECT flow_id,MIN(observed_at-latency_ms) AS at FROM request_events WHERE run_id=? GROUP BY flow_id').iterate(recording.run_id)){
+ const t=Math.max(0,Math.ceil((Number(row.at)-recording.started_at)/100)/10),name=String(row.flow_id).split(':').at(-3),key=`${t}:${name}`;
+ const bin=bins.get(key)||{t,name,count:0};bin.count++;bins.set(key,bin);
+ }
+ }catch{return null;}finally{db?.close();}
+ const starts=[...bins.values()].sort((a,b)=>a.t-b.t);
+ legacyStarts.set(key,starts);if(legacyStarts.size>8)legacyStarts.delete(legacyStarts.keys().next().value);
+ return starts;
+}
+export function startedTelemetry(points,starts=null){
+ let previous=null,index=0,total=0;const byFlow={};
+ return points.map(point=>{
+ if(starts){while(index<starts.length&&starts[index].t<=point.t){const count=starts[index].count??1;total+=count;byFlow[starts[index].name]=(byFlow[starts[index].name]||0)+count;index++;}}
+ const started=point.started??(starts?total:Math.max(previous?.started||0,admitted(point))),interval=point.t-(previous?.t||0);
+ const flows=Object.fromEntries(Object.entries(point.flows||{}).map(([name,f])=>{const count=f.started??(starts?byFlow[name]||0:Object.keys(point.flows).length===1?started:(Number(f.successes)||0)+(Number(f.failures)||0));return [name,{...f,started:count,successfulTps:f.successfulTps??f.tps,tps:interval>0?Math.max(0,count-(previous?.flows?.[name]?.started||0))/interval:0}];}));
+ const next={...point,flows,started,successfulTps:point.successfulTps??point.tps,tps:interval>0?Math.max(0,started-(previous?.started||0))/interval:0};previous=next;return next;
+ });
+}
+// Restore latency intervals when an older supervisor omitted the chart field.
+export function restoreServerLatency(points,rows,startedAt,replace=false){
+ const iterator=rows[Symbol.iterator]();let current=iterator.next(),previous=0;
+ const percentile=values=>{values.sort((a,b)=>a-b);return values.length?values[Math.floor((values.length-1)*.99)]:null;};
+ const result=points.map(point=>{
+ const values=[],flows={};
+ while(!current.done&&(current.value.observed_at-startedAt)/1000<=point.t){
+ const row=current.value,value=row.server_latency_ms;current=iterator.next();
+ if((row.observed_at-startedAt)/1000<=previous||!Number.isFinite(value)||value<0)continue;
+ if(values.length<8192)values.push(value);
+ const name=String(row.flow_id).split(':').at(-3);flows[name]||=[];if(flows[name].length<8192)flows[name].push(value);
+ }
+ previous=point.t;
+ return {...point,serverP99:replace?latencyP99(values):point.serverP99===undefined?percentile(values):point.serverP99,flows:Object.fromEntries(Object.entries(point.flows||{}).map(([name,f])=>[name,{...f,serverP99:replace?latencyP99(flows[name]||[]):f.serverP99===undefined?percentile(flows[name]||[]):f.serverP99}]))};
+ });
+ iterator.return?.();return result;
+}
+function recoverServerLatency(directory,recording,points){
+ if(!recording?.started_at)return points;
+ let db;
+ try{db=new DatabaseSync(path.join(directory,'results.sqlite'),{readOnly:true});
+ if(!db.prepare('PRAGMA table_info(request_events)').all().some(c=>c.name==='server_latency_ms'))return points;
+ const rows=db.prepare(`SELECT observed_at,flow_id,server_latency_ms FROM request_events WHERE run_id=? AND ${successfulConfirmWhere} ORDER BY observed_at,event_id`).iterate(recording.run_id);
+ return restoreServerLatency(points,rows,recording.started_at,true);
+ }catch{return points;}finally{db?.close();}
+}
+export function restoreDisplayErrors(points,rows,startedAt,events=[],config={}){
+ const iterator=rows[Symbol.iterator]();let current=iterator.next(),attempts=0,errors=0,hidden=0,previousAttempts=0,previousErrors=0;
+ const windows=faultWindows(events,config);
+ const result=points.map(point=>{
+ while(!current.done&&(current.value.observed_at-startedAt)/1000<=point.t){
+ const row=current.value;attempts++;
+ if(row.api_status_code===0||row.api_status_code>=400){if(hiddenVaultError(row,windows))hidden++;else errors++;}
+ current=iterator.next();
+ }
+ const delta=attempts-previousAttempts,failed=errors-previousErrors;previousAttempts=attempts;previousErrors=errors;
+ return {...point,errorScope:'all_http_except_vault',displayHttpAttempts:attempts,displayHttpErrors:errors,hiddenVaultErrors:hidden,errors:delta?100*failed/delta:0};
+ });iterator.return?.();return result;
+}
+function recoverDisplayErrors(directory,recording,points,events,config){
+ if(!recording?.started_at)return points;
+ let db;
+ try{db=new DatabaseSync(path.join(directory,'results.sqlite'),{readOnly:true});
+ const columns=new Set(db.prepare('PRAGMA table_info(request_events)').all().map(c=>c.name));
+ const optional=['latency_ms','message'].map(c=>columns.has(c)?c:`NULL AS ${c}`).join(',');
+ const rows=db.prepare(`SELECT observed_at,api_status_code,operation,${optional} FROM request_events WHERE run_id=? AND role='measured' ORDER BY observed_at,event_id`).iterate(recording.run_id);
+ return restoreDisplayErrors(points,rows,recording.started_at,events,config);
+ }catch{return points;}finally{db?.close();}
+}
+export async function readTelemetry(directory,recording=null,events=[],config={}) {
+ const stream=createReadStream(path.join(directory,'telemetry.jsonl'),{encoding:'utf8'});
+ const lines=createInterface({input:stream,crlfDelay:Infinity});let points=[];
+ try {
+ for await(const line of lines){
+ try {const point=JSON.parse(line);if(Number.isFinite(point.t))points.push(point);}catch{/* Ignore an interrupted trailing write. */}
+ if(points.length>3600)points=compactSamples(points);
+ }
+ }catch(e){if(e.code!=='ENOENT')throw e;}
+ finally{lines.close();stream.destroy();}
+ return compactSamples(startedTelemetry(recoverDisplayErrors(directory,recording,recoverServerLatency(directory,recording,points),events,config),points.some(p=>p.started==null)?recordedStarts(directory,recording):null));
+}
diff --git a/loadtest/console/server/worker-artifacts.mjs b/loadtest/console/server/worker-artifacts.mjs
new file mode 100644
index 0000000000..2542cd1310
--- /dev/null
+++ b/loadtest/console/server/worker-artifacts.mjs
@@ -0,0 +1,41 @@
+import {createHash,randomUUID} from 'node:crypto';
+import {createWriteStream} from 'node:fs';
+import {mkdir,readFile,writeFile,rename,rm,stat} from 'node:fs/promises';
+import {Readable} from 'node:stream';
+import {pipeline} from 'node:stream/promises';
+import path from 'node:path';
+import {dataRoot,controlDb} from './state.mjs';
+import {HttpError} from './errors.mjs';
+
+const identifier=/^[A-Za-z0-9][A-Za-z0-9._:-]{0,199}$/;
+const digest=value=>createHash('sha256').update(value).digest('hex');
+const bundleDirectory=path.join(dataRoot,'worker-bundles'),artifactDirectory=path.join(dataRoot,'worker-artifacts');
+export function workerLoadConfig(config){
+ const load=structuredClone(config.load||{});
+ if(Array.isArray(load.stages))load.stages=load.stages.map(({fault:_fault,...stage})=>stage);
+ return Object.fromEntries(['connectors','mode','services','scenarios','payment','sdk','target_headers','thresholds','acceptance','profile','fixtureSet']
+ .filter(key=>config[key]!==undefined).map(key=>[key,structuredClone(config[key])]).concat([['load',load]]));
+}
+export async function createWorkerBundle({runId,config,fixturePath,workerId,segmentStart=0,segmentEnd=1}){
+ const [manifest,merchants]=await Promise.all([readFile(path.join(fixturePath,'manifest.json'),'utf8'),readFile(path.join(fixturePath,'merchants.json'),'utf8')]);
+ const all=JSON.parse(merchants),start=Math.floor(all.length*segmentStart),end=segmentEnd===1?all.length:Math.floor(all.length*segmentEnd),assigned=all.slice(start,Math.max(start+1,end));
+ const fixtureManifest={...JSON.parse(manifest),merchant_count:assigned.length,merchants_sha256:digest(JSON.stringify(assigned))};
+ const body=JSON.stringify({schemaVersion:1,runId,workerId,config:workerLoadConfig(config),manifest:fixtureManifest,merchants:assigned}),id=randomUUID();
+ await mkdir(bundleDirectory,{recursive:true,mode:0o700});await writeFile(path.join(bundleDirectory,`${id}.json`),body,{mode:0o600,flag:'wx'});
+ return {id,sha256:digest(body),bytes:Buffer.byteLength(body)};
+}
+export async function readWorkerBundle(id,workerId){
+ if(!identifier.test(id))throw new Error('Invalid bundle ID');const body=await readFile(path.join(bundleDirectory,`${id}.json`),'utf8');const bundle=JSON.parse(body);
+ if(bundle.workerId!==workerId)throw new HttpError(403,'Bundle belongs to another worker');return {body,sha256:digest(body)};
+}
+export async function storeWorkerArtifact({workerId,runId,name,body,contentLength}){
+ if(!identifier.test(runId)||!['results.sqlite','summary.json','progress.json','diagnostics.log'].includes(name))throw new Error('Invalid worker artifact');
+ if(!controlDb().prepare('SELECT 1 FROM run_shards WHERE run_id=? AND worker_id=?').get(runId,workerId))throw new HttpError(403,'Worker is not assigned to this run');
+ if(contentLength&&contentLength>2_000_000_000)throw new HttpError(413,'Worker artifact exceeds 2 GB');
+ const directory=path.join(artifactDirectory,runId,workerId);await mkdir(directory,{recursive:true,mode:0o700});
+ const target=path.join(directory,name),temporary=`${target}.${process.pid}.tmp`;let bytes=0;
+ const limiter=new TransformStream({transform(chunk,controller){bytes+=chunk.byteLength;if(bytes>2_000_000_000)throw new Error('Worker artifact exceeds 2 GB');controller.enqueue(chunk);}});
+ try{await pipeline(Readable.fromWeb(body.pipeThrough(limiter)),createWriteStream(temporary,{mode:0o600,flags:'wx'}));await rename(temporary,target);}catch(error){await rm(temporary,{force:true});throw error;}
+ const size=(await stat(target)).size;return {name,size,path:target};
+}
+export function artifactPath(runId,workerId,name){if(!identifier.test(runId)||!identifier.test(workerId))throw new Error('Invalid artifact identity');return path.join(artifactDirectory,runId,workerId,name);}
diff --git a/loadtest/console/server/worker-registry.mjs b/loadtest/console/server/worker-registry.mjs
new file mode 100644
index 0000000000..d2fd5abc1d
--- /dev/null
+++ b/loadtest/console/server/worker-registry.mjs
@@ -0,0 +1,54 @@
+import {createHash,randomBytes,randomUUID,timingSafeEqual} from 'node:crypto';
+import {controlDb} from './state.mjs';
+import {HttpError} from './errors.mjs';
+
+const hash=value=>createHash('sha256').update(String(value)).digest('hex');
+const parsed=value=>{try{return JSON.parse(value||'{}');}catch{return {};}};
+const safeEqual=(left,right)=>{const a=Buffer.from(String(left)),b=Buffer.from(String(right));return a.length===b.length&&timingSafeEqual(a,b);};
+const publicWorker=row=>({id:row.id,name:row.name,status:Date.now()-row.last_seen>15000?'offline':row.status,labels:parsed(row.labels),capacityTps:row.capacity_tps,capacityVus:row.capacity_vus,version:row.version,lastSeen:row.last_seen,createdAt:row.created_at});
+
+export function listWorkers(){return controlDb().prepare('SELECT * FROM load_workers ORDER BY name,id').all().map(publicWorker);}
+export function enrollWorker(input,providedToken,expectedToken=process.env.LOADTEST_WORKER_ENROLLMENT_TOKEN){
+ if(!expectedToken||!safeEqual(providedToken,expectedToken))throw new HttpError(401,'Worker enrollment is not authorized');
+ const name=String(input.name||'').trim(),capacityTps=Number(input.capacityTps),capacityVus=Number(input.capacityVus);
+ if(!/^[A-Za-z0-9][A-Za-z0-9._-]{0,79}$/.test(name)||!Number.isInteger(capacityTps)||capacityTps<1||!Number.isInteger(capacityVus)||capacityVus<1)throw new Error('Worker needs a valid name and positive TPS/VU capacity');
+ const id=randomUUID(),token=randomBytes(32).toString('base64url'),now=Date.now();
+ controlDb().prepare("INSERT INTO load_workers(id,name,token_hash,status,labels,capacity_tps,capacity_vus,version,created_at,last_seen) VALUES(?,?,?,'idle',?,?,?,?,?,?)")
+ .run(id,name,hash(token),JSON.stringify(input.labels||{}),capacityTps,capacityVus,String(input.version||''),now,now);
+ return {id,token};
+}
+export function registerLocalWorker(input={}){
+ const db=controlDb(),id='local',now=Date.now(),existing=db.prepare('SELECT * FROM load_workers WHERE id=?').get(id),token=input.token||randomBytes(32).toString('base64url');
+ if(existing){db.prepare("UPDATE load_workers SET status='idle',last_seen=?,version=?,capacity_tps=?,capacity_vus=? WHERE id=?").run(now,String(input.version||process.version),Number(input.capacityTps||100),Number(input.capacityVus||1000),id);return {id,token:null};}
+ db.prepare("INSERT INTO load_workers(id,name,token_hash,status,labels,capacity_tps,capacity_vus,version,created_at,last_seen) VALUES(?,'Local worker',?,'idle','{\"environment\":\"local\"}',?,?,?,?,?)")
+ .run(id,hash(token),Number(input.capacityTps||100),Number(input.capacityVus||1000),String(input.version||process.version),now,now);return {id,token};
+}
+export function authenticateWorker(id,token){const row=controlDb().prepare('SELECT * FROM load_workers WHERE id=?').get(id);if(!row||!safeEqual(row.token_hash,hash(token)))throw new HttpError(401,'Worker authentication failed');return row;}
+export function heartbeatWorker(id,token,input={}){
+ authenticateWorker(id,token);const status=['idle','reserved','preparing','ready','running','pausing','paused','draining','uploading','failed'].includes(input.status)?input.status:'idle',db=controlDb();
+ db.prepare('UPDATE load_workers SET status=?,last_seen=?,version=COALESCE(?,version) WHERE id=?').run(status,Date.now(),input.version||null,id);
+ if(input.runId){
+ const shardStatus=['reserved','preparing','ready','running','pausing','paused','draining','uploading','complete','failed'].includes(input.runStatus)?input.runStatus:null;
+ if(shardStatus)db.prepare('UPDATE run_shards SET status=?,error=?,progress=?,updated_at=? WHERE run_id=? AND worker_id=?').run(shardStatus,input.error?String(input.error).slice(0,1000):null,JSON.stringify(input.progress||{}),Date.now(),input.runId,id);
+ }
+ return {ok:true,serverTime:Date.now()};
+}
+export function queueWorkerCommand(workerId,{runId=null,kind,payload={}}){
+ const db=controlDb();if(!db.prepare('SELECT 1 FROM load_workers WHERE id=?').get(workerId))throw new Error('Worker does not exist');
+ const revision=(db.prepare('SELECT COALESCE(MAX(revision),0)+1 AS revision FROM worker_commands WHERE worker_id=?').get(workerId).revision),id=randomUUID();
+ db.prepare("INSERT INTO worker_commands(id,worker_id,run_id,revision,kind,payload,status,created_at) VALUES(?,?,?,?,?,?,'pending',?)").run(id,workerId,runId,revision,kind,JSON.stringify(payload),Date.now());
+ return {id,runId,revision,kind,payload};
+}
+export function pendingWorkerCommands(id,token,after=0){authenticateWorker(id,token);return controlDb().prepare("SELECT id,run_id,revision,kind,payload,created_at FROM worker_commands WHERE worker_id=? AND revision>? AND status='pending' ORDER BY revision LIMIT 20").all(id,after).map(row=>({id:row.id,runId:row.run_id,revision:row.revision,kind:row.kind,payload:parsed(row.payload),createdAt:row.created_at}));}
+export function acknowledgeWorkerCommand(id,token,commandId,input={}){
+ authenticateWorker(id,token);const db=controlDb(),command=db.prepare("SELECT run_id,kind FROM worker_commands WHERE id=? AND worker_id=? AND status='pending'").get(commandId,id);
+ if(!command)throw new HttpError(409,'Worker command is missing or already acknowledged');
+ const failed=input.ok===false,result=db.prepare("UPDATE worker_commands SET status=?,acked_at=?,result=? WHERE id=? AND worker_id=? AND status='pending'").run(failed?'failed':'acknowledged',Date.now(),JSON.stringify(input.result||{}),commandId,id);
+ if(!result.changes)throw new HttpError(409,'Worker command is missing or already acknowledged');
+ if(failed&&command.run_id){
+ const message=String(input.result?.error||`${command.kind} command failed`).slice(0,1000);
+ db.prepare("UPDATE run_shards SET status='failed',error=?,updated_at=? WHERE run_id=? AND worker_id=? AND status NOT IN ('complete','failed')").run(message,Date.now(),command.run_id,id);
+ }
+ return {ok:true};
+}
+export function removeWorker(id){if(id==='local')throw new Error('The local worker cannot be removed');const db=controlDb();if(db.prepare("SELECT 1 FROM run_shards WHERE worker_id=? AND status IN ('reserved','preparing','ready','running','pausing','paused','draining','uploading')").get(id))throw new HttpError(409,'Drain the worker before removing it');db.prepare('DELETE FROM worker_commands WHERE worker_id=?').run(id);db.prepare('DELETE FROM load_workers WHERE id=?').run(id);return {deleted:true};}
diff --git a/loadtest/console/server/worker-result.mjs b/loadtest/console/server/worker-result.mjs
new file mode 100644
index 0000000000..947e474901
--- /dev/null
+++ b/loadtest/console/server/worker-result.mjs
@@ -0,0 +1,11 @@
+export function workerFailure(code, result, summary, signal) {
+ if (code === 0) return null;
+ if (result?.error) return result.error;
+ if (code === 99) {
+ const failed = Object.entries(summary?.metrics || {}).flatMap(([name, metric]) =>
+ Object.entries(metric.thresholds || {}).filter(([, check]) => check.ok === false)
+ .map(([expression]) => `${name} (${expression})`));
+ return `Load completed but k6 thresholds failed${failed.length ? ': ' + failed.join(', ') : ''}. Open Results → Responses for recorded errors.`;
+ }
+ return `Worker exited ${code ?? signal}`;
+}
diff --git a/loadtest/console/server/workers.mjs b/loadtest/console/server/workers.mjs
new file mode 100644
index 0000000000..b3a06c5bc6
--- /dev/null
+++ b/loadtest/console/server/workers.mjs
@@ -0,0 +1,19 @@
+import { Worker } from 'node:worker_threads';
+import { workerPath } from './state.mjs';
+import { HttpError } from './errors.mjs';
+let active=0;
+export function queryWorker(task,args={},onProgress=(_value)=>{},onWorker=(_value)=>{}) {
+ if(active>=4) return Promise.reject(new HttpError(503,'Server is busy; retry shortly'));
+ active++;
+ return new Promise((resolve,reject)=>{
+ let worker;
+ // Test runners and host launchers may add process-only flags that workers reject.
+ try {worker=new Worker(workerPath,{workerData:{task,args},execArgv:[]});}
+ catch(e){active--;reject(e);return;}
+ onWorker(worker);
+ let settled=false;
+ const finish=(error,result=undefined)=>{if(settled)return;settled=true;active--;error?reject(error):resolve(result);};
+ worker.on('message',m=>{if(m.progress)onProgress(m.progress);else finish(m.error?new Error(m.error):null,m.result);});
+ worker.once('error',e=>finish(e));worker.once('exit',code=>{if(!settled)finish(new Error(`Worker stopped (${code})`));});
+ });
+}
diff --git a/loadtest/console/src/App.svelte b/loadtest/console/src/App.svelte
new file mode 100644
index 0000000000..69cd451492
--- /dev/null
+++ b/loadtest/console/src/App.svelte
@@ -0,0 +1,2 @@
+<script>import RunScreen from "./RunScreen.svelte"; export let data;</script>
+<RunScreen {data}/>
diff --git a/loadtest/console/src/Brand.svelte b/loadtest/console/src/Brand.svelte
new file mode 100644
index 0000000000..ffa0873add
--- /dev/null
+++ b/loadtest/console/src/Brand.svelte
@@ -0,0 +1,6 @@
+<span class="brand-lockup" aria-label="Testbench"><span class="wordmark">testbench</span></span>
+
+<style>
+.brand-lockup{display:inline-flex;align-items:center;gap:6px;white-space:nowrap;color:#7d7b86}.wordmark{font-family:Inter,ui-sans-serif,sans-serif;font-size:16px;font-weight:300;letter-spacing:-.15px;line-height:1.2}
+@media(max-width:600px){.brand-lockup{gap:6px}.wordmark{font-size:15px;letter-spacing:-.2px}}
+</style>
diff --git a/loadtest/console/src/ConnectionStatus.svelte b/loadtest/console/src/ConnectionStatus.svelte
new file mode 100644
index 0000000000..ca5d113efb
--- /dev/null
+++ b/loadtest/console/src/ConnectionStatus.svelte
@@ -0,0 +1,8 @@
+<script>
+import {onMount} from 'svelte';
+export let state='connecting';export let updatedAt=0;
+let now=Date.now();onMount(()=>{const timer=setInterval(()=>now=Date.now(),1000);return()=>clearInterval(timer);});
+$: stale=updatedAt>0&&now-updatedAt>15000;
+</script>
+<span class:unhealthy={state!=='connected'||stale} class="connection" role="status">{state==='connected'&&!stale?'● Connected':state==='connecting'?'Connecting…':'Reconnecting…'}{#if updatedAt&&(stale||state!=='connected')} · last update {Math.max(0,Math.floor((now-updatedAt)/1000))}s ago{/if}</span>
+<style>.connection{font-size:11px;color:#027a48}.unhealthy{color:#b7781c}</style>
diff --git a/loadtest/console/src/ConnectorCredentials.svelte b/loadtest/console/src/ConnectorCredentials.svelte
new file mode 100644
index 0000000000..6cc2007ab9
--- /dev/null
+++ b/loadtest/console/src/ConnectorCredentials.svelte
@@ -0,0 +1,12 @@
+<script>
+import {connectorCatalog,defaultConnectorPlan} from './connector-config.mjs';
+export let plan=defaultConnectorPlan();export let value={};
+function update(connector,field,text){value={...value,[connector]:{...value[connector],credentials:{...value[connector]?.credentials,[field]:text}}};}
+function metadata(connector,text){value={...value,[connector]:{...value[connector],metadataText:text}};}
+</script>
+{#if plan.mode==='real'||plan.mix.length>1}
+<section class="connector-credentials"><h2>Connector credentials</h2><p>Sandbox accounts for each merchant in this fixture set.</p>
+{#each plan.mix as row (row.connector)}{@const definition=connectorCatalog.find(c=>c.id===row.connector)}<fieldset><legend>{definition?.label||row.connector}</legend><div class="fields">{#each definition?.fields||[] as field}<label>{field.label}<input type="password" autocomplete="new-password" value={value[row.connector]?.credentials?.[field.name]||''} oninput={e=>update(row.connector,field.name,e.currentTarget.value)}/></label>{/each}</div><details><summary>Account metadata</summary><label>Connector-specific metadata · JSON<textarea rows="3" value={value[row.connector]?.metadataText||''} oninput={e=>metadata(row.connector,e.currentTarget.value)} placeholder={'{}'}></textarea></label></details></fieldset>{/each}
+</section>
+{/if}
+<style>.connector-credentials{grid-column:1/-1;border-top:1px solid var(--border);padding-top:16px}.connector-credentials p{font-size:12px;color:var(--muted)}fieldset{border:1px solid var(--border);border-radius:7px;padding:16px;margin:12px 0}legend{font-size:13px;font-weight:550}details{margin-top:12px}textarea{font-family:monospace}</style>
diff --git a/loadtest/console/src/ConnectorMix.svelte b/loadtest/console/src/ConnectorMix.svelte
new file mode 100644
index 0000000000..56ae37492e
--- /dev/null
+++ b/loadtest/console/src/ConnectorMix.svelte
@@ -0,0 +1,17 @@
+<script>
+import {connectorCatalog,defaultConnectorPlan,connectorPlanError,supportedConnectorAuth} from './connector-config.mjs';
+export let value=defaultConnectorPlan();
+let choice='';
+$: options=connectorCatalog.filter(c=>c.card&&supportedConnectorAuth.has(c.authType)&&c.dummy===(value.mode==='dummy')&&!value.mix.some(r=>r.connector===c.id));
+$: error=connectorPlanError(value);
+function mode(mode){value=mode==='dummy'?defaultConnectorPlan():{mode,mix:[]};choice='';}
+function add(){if(!choice)return;const mix=[...value.mix,{connector:choice,weight:0}];const base=Math.floor(100/mix.length);value={...value,mix:mix.map((r,i)=>({...r,weight:base+(i<100%mix.length?1:0)}))};choice='';}
+function remove(index){value={...value,mix:value.mix.filter((_,i)=>i!==index)};}
+</script>
+<div class="connector-mix">
+<label>Connector mode<select value={value.mode} onchange={e=>mode(e.currentTarget.value)}><option value="dummy">Dummy</option><option value="real">Real connectors · sandbox</option></select></label>
+{#each value.mix as row,i (row.connector)}<div class="connector-row"><span>{connectorCatalog.find(c=>c.id===row.connector)?.label||row.connector}</span><label>Traffic · %<input type="number" min="1" max="100" step="1" bind:value={row.weight}/></label><button type="button" class="quiet" aria-label={`Remove ${row.connector}`} onclick={()=>remove(i)}>Remove</button></div>{/each}
+{#if options.length}<div class="connector-add"><label>Add connector<select bind:value={choice}><option value="">Choose connector</option>{#each options as option}<option value={option.id}>{option.label}</option>{/each}</select></label><button type="button" class="secondary" disabled={!choice||value.mix.length>=20} onclick={add}>Add</button></div>{/if}
+{#if error}<p class="invalid" role="status">{error}</p>{/if}
+</div>
+<style>.connector-mix{max-width:560px;margin-top:14px}.connector-mix>label{max-width:260px}.connector-row{display:grid;grid-template-columns:1fr 100px auto;gap:16px;align-items:center;padding:12px 0;border-bottom:1px solid var(--border)}.connector-add{display:flex;gap:12px;align-items:end;margin-top:16px}.connector-add label{flex:1}.connector-mix p{font-size:12px}</style>
diff --git a/loadtest/console/src/ConnectorResults.svelte b/loadtest/console/src/ConnectorResults.svelte
new file mode 100644
index 0000000000..6c0eabd295
--- /dev/null
+++ b/loadtest/console/src/ConnectorResults.svelte
@@ -0,0 +1,3 @@
+<script>export let result;const number=v=>v==null?'—':Number(v).toLocaleString(undefined,{maximumFractionDigits:1});</script>
+{#if result?.rows?.length}<section class="connector-results"><h2>Connectors</h2><div class="table-wrap"><table><thead><tr><th>Connector</th><th>Assigned flows</th><th>Target / routed</th><th>Reported confirmations</th><th>Succeeded</th><th>Failed</th><th>HS-only p99</th><th>Full confirm p99</th></tr></thead><tbody>{#each result.rows as row}<tr><td>{row.connector}</td><td>{number(row.assigned)}</td><td>{number(row.targetPercent)}% / {number(row.observedPercent)}%</td><td>{number(row.confirmations)}</td><td>{number(row.successes)}</td><td>{number(row.failures)}</td><td>{number(row.hsP99)} ms</td><td>{number(row.fullP99)} ms</td></tr>{/each}</tbody></table></div>{#if result.unattributedConfirmations}<p>{number(result.unattributedConfirmations)} confirmation responses did not report a connector.</p>{/if}</section>{/if}
+<style>.connector-results{margin:24px 0;background:var(--surface);border:1px solid var(--border);border-radius:var(--radius);padding:20px}.connector-results h2{margin-bottom:16px}.connector-results p{font-size:12px;color:var(--muted)}</style>
diff --git a/loadtest/console/src/FaultSettings.svelte b/loadtest/console/src/FaultSettings.svelte
new file mode 100644
index 0000000000..78ca11ffc6
--- /dev/null
+++ b/loadtest/console/src/FaultSettings.svelte
@@ -0,0 +1,97 @@
+<script>
+import InfoTooltip from './InfoTooltip.svelte';
+import Icon from './Icon.svelte';
+import {environmentLabel} from './environments.mjs';
+import {onMount,tick} from 'svelte';
+import {fade,fly} from 'svelte/transition';
+import {faultTypes,faultType,faultEnvironment,configureFaultTarget,faultCommandPreview,faultTargetResource,faultAccessNote} from './fault-types.mjs';
+import {api} from './api.js';
+export let targets=[];export let baseline='';export let environment='local';
+let customAllowed=false;
+function executionMode(target,index,mode){targets[index]=mode==='command'?{...target,adapter:'command',commandAction:'outage',actions:['outage'],recoveryMode:'restore',timeoutSeconds:15,workingDirectory:'',triggerCommand:'',restoreCommand:'',readyCommand:'',faultCheckCommand:''}:configureFaultTarget(target,environment);targets=[...targets];resetCheck(target.id);}
+let pending=false,message='',selected=null,seconds=5,confirm='',testError='',testDialog,testJob=null,fault=null,checks={},checking={},now=Date.now(),testTargetId='',connected=true,checkTimers={};
+$: dirty=JSON.stringify(targets)!==baseline;
+
+$: testing=Boolean(fault?.active||fault?.blocked||fault?.recovering||testJob&&['starting','running','cancelling'].includes(testJob.status));
+$: remaining=fault?.active?.recoveryAt?Math.max(0,Math.ceil((fault.active.recoveryAt-now)/1000)):null;
+onMount(()=>{api.settings().then(s=>customAllowed=s.customFaultCommands).catch(()=>{});let disposed=false,busy=false;const refresh=async()=>{if(busy)return;busy=true;try{const status=await api.faults();if(disposed)return;fault=status;const id=testJob?.id||status.active?.jobId||sessionStorage.getItem('last-fault-test');if(id){const job=await api.job(id);if(!disposed&&job.command==='fault-test'){testJob=job;testTargetId=job.progress?.targetId||status.active?.targetId||testTargetId;}}connected=true;}catch(e){if(!disposed)connected=false;}finally{busy=false;now=Date.now();}};refresh();const timer=setInterval(refresh,1000);return()=>{disposed=true;clearInterval(timer);Object.values(checkTimers).forEach(clearTimeout);};});
+async function openTest(target){selected=target;seconds=5;confirm='';testError='';if(testTargetId!==target.id&&!testing){testJob=null;sessionStorage.removeItem('last-fault-test');}await tick();testDialog.showModal();}
+function closeTest(){testDialog?.close();selected=null;testError='';}
+async function startTest(){pending=true;testError='';try{testJob=await api.testFault({environment:selected.environment,expectedTarget:structuredClone(selected),targetId:selected.id,action:selected.actions?.[0]||'outage',durationSeconds:seconds,confirm});testTargetId=selected.id;sessionStorage.setItem('last-fault-test',testJob.id);fault=testJob.faults;}catch(e){testError=e.message;}finally{pending=false;}}
+async function restoreNow(){pending=true;try{fault=await api.restoreFault();}catch(e){testError=e.message;}finally{pending=false;}}
+function clearCheckTimer(id){if(checkTimers[id])clearTimeout(checkTimers[id]);const {[id]:_,...rest}=checkTimers;checkTimers=rest;}
+function resetCheck(id){clearCheckTimer(id);checks={...checks,[id]:null};}
+function resetAllChecks(){Object.values(checkTimers).forEach(clearTimeout);checkTimers={};checks={};}
+function scheduleCheckReset(id){clearCheckTimer(id);checkTimers={...checkTimers,[id]:setTimeout(()=>resetCheck(id),2400)};}
+function checkState(id){return checking[id]?'checking':checks[id]?.ok?'success':checks[id]?'failed':'idle';}
+function checkLabel(state){return state==='checking'?'Checking…':state==='success'?'Succeeded':state==='failed'?'Failed':'Check target';}
+
+function add(type){if(pending||targets.some(t=>faultType(t)===type))return;const spec=faultTypes.find(t=>t.type===type);targets=[...targets,configureFaultTarget({id:type,label:spec.label,serviceType:type,adapter:spec.adapter,port:spec.port,...(type==='card-vault'?{repository:''}:{binary:'process-compose',controllerPort:8090,process:type==='redis'?'r1':'p1'})},environment)];}
+async function check(target){const id=target.id,fingerprint=JSON.stringify(target);resetCheck(id);checking={...checking,[id]:true};try{const result=await api.checkFaultTarget(structuredClone(target));if(JSON.stringify(targets.find(t=>t.id===id))===fingerprint){checks={...checks,[id]:{ok:true,message:result.message}};scheduleCheckReset(id);}}catch(e){if(JSON.stringify(targets.find(t=>t.id===id))===fingerprint)checks={...checks,[id]:{ok:false,message:e.message}};}finally{checking={...checking,[id]:false};}}
+</script>
+
+
+{#each targets as target,index}
+<fieldset oninput={()=>resetCheck(target.id)} onchange={()=>resetCheck(target.id)}>
+<legend>{faultTypes.find(t=>t.type===faultType(target))?.label || target.label}</legend>
+{#if faultAccessNote(target)}<p class="target-access-note" role="note"><Icon name="info" size={16}/><span>{faultAccessNote(target)}</span></p>{/if}
+{#if faultEnvironment(target)==='unassigned'}<p>This legacy target has no provider. Review its service and assign it to {environmentLabel(environment)} before use.</p><label>Service<select bind:value={target.serviceType}><option value="">Choose service</option>{#each faultTypes as type}<option value={type.type}>{type.label}</option>{/each}</select></label><button type="button" class="secondary" disabled={!target.serviceType||testing} onclick={()=>{targets[index]=configureFaultTarget(target,environment);targets=[...targets];resetAllChecks();}}>Assign to {environmentLabel(environment)}</button>{/if}
+
+<div class="execution-field"><div class="field-title"><label for={`fault-execution-${target.id}`}>Execution</label><InfoTooltip id={`fault-execution-info-${target.id}`} label="Fault execution information" text={(target.adapter==='command'?"Custom commands run as the supervisor’s OS user at the scenario’s scheduled times. Do not put credentials in commands. Checks must be read-only and exit 0 only when the expected state is observed.":"Built-in adapters trigger and restore faults automatically at the scenario’s scheduled times.")+(!customAllowed?" Custom commands require LOADTEST_ALLOW_CUSTOM_COMMANDS=true and an idle supervisor restart.":"")}/></div><select id={`fault-execution-${target.id}`} value={target.adapter==='command'?'command':'builtin'} disabled={testing} onchange={e=>executionMode(target,index,e.currentTarget.value)}><option value="builtin">Built-in adapter</option><option value="command" disabled={!customAllowed&&target.adapter!=='command'}>Custom commands · scheduled only</option></select></div>
+
+<details class="target-config"><summary>Configuration <span>{environmentLabel(faultEnvironment(target))}{#if target.adapter!=='placeholder'} · {target.adapter}{/if}</span></summary><div class="fields" inert={testing}>
+<label>Name<input bind:value={target.label}/></label><label>Target ID<input readonly value={target.id}/></label>
+{#if faultEnvironment(target)==='custom'}<label>Adapter<select bind:value={target.adapter}><option value="docker">Docker</option><option value="kubernetes">Kubernetes</option></select></label>{/if}
+{#if faultEnvironment(target)==='local'&&target.adapter!=='command'}<label>Service port<input type="number" min="1" max="65535" bind:value={target.port}/></label>{/if}
+{#if target.adapter==='command'}
+
+<label>Action<select bind:value={target.commandAction} onchange={()=>{target.actions=[target.commandAction];targets=[...targets];}}><option value="outage">Outage</option><option value="failover">Failover</option></select></label>
+<label>Recovery<select bind:value={target.recoveryMode}><option value="restore">Run restore command</option><option value="self-recovering">Self-recovering</option></select></label>
+<label>Working directory<input bind:value={target.workingDirectory} placeholder="/absolute/path"/></label>
+<label>Command timeout · seconds<input type="number" min="1" max="120" bind:value={target.timeoutSeconds}/></label>
+<label>Trigger command<textarea rows="2" bind:value={target.triggerCommand}></textarea></label>
+{#if target.recoveryMode==='restore'}<label>Restore command<textarea rows="2" bind:value={target.restoreCommand}></textarea></label>{/if}
+<label>Healthy / recovered check command<textarea rows="2" bind:value={target.readyCommand}></textarea></label>
+<label>Fault active check command<textarea rows="2" bind:value={target.faultCheckCommand}></textarea></label>
+{:else if target.adapter==='placeholder'}
+{#if environment==='aws'}<label>Account ID<input placeholder="AWS account ID" bind:value={target.accountId}/></label><label>Region<input placeholder="AWS region" bind:value={target.region}/></label><label>Resource ARN<input placeholder="Resource ARN" bind:value={target.resourceId}/></label>{:else}<label>Subscription ID<input placeholder="Azure subscription ID" bind:value={target.subscriptionId}/></label><label>Resource group<input placeholder="Resource group" bind:value={target.resourceGroup}/></label><label>Location<input placeholder="Azure location" bind:value={target.region}/></label><label>Resource ID<input placeholder="Resource ID" bind:value={target.resourceId}/></label>{/if}
+{:else if target.adapter==='local-vault'}
+<label>Vault repository<input placeholder="/absolute/path/hyperswitch-card-vault" bind:value={target.repository}/></label>
+{:else if target.adapter==='process-compose'}
+<label>Controller port<input type="number" bind:value={target.controllerPort}/></label><label>Process name<input bind:value={target.process}/></label>
+{:else if target.adapter.startsWith('gcp-')}
+<label>Project<input bind:value={target.project}/></label><label>Region<input bind:value={target.region}/></label>{#if target.adapter==='gcp-alloydb'}<label>Cluster<input bind:value={target.cluster}/></label>{/if}<label>Primary instance<input bind:value={target.instance}/></label>
+{:else if target.adapter==='docker'}<label>Container<input bind:value={target.container}/></label>
+{:else if target.adapter==='kubernetes'}<label>Context<input placeholder="Master’s current context" bind:value={target.context}/></label><label>Namespace<input bind:value={target.namespace}/></label><label>Deployment<input bind:value={target.deployment}/></label>{#if faultEnvironment(target)==='gcp'&&faultType(target)==='card-vault'}<label>Recovery replicas<input type="number" min="1" max="100" bind:value={target.recoveryReplicas}/></label>{/if}
+{/if}
+</div>
+{#if faultCommandPreview(target)}<details class="commands"><summary>Commands</summary><pre class="command-preview">{faultCommandPreview(target)}</pre></details>{/if}</details>
+<div class="actions"><button type="button" class="secondary check-button" class:check-success={checks[target.id]?.ok} class:check-failed={checks[target.id]&& !checks[target.id].ok} disabled={pending||testing||checking[target.id]||checks[target.id]?.ok||faultEnvironment(target)==='unassigned'||['aws','azure'].includes(environment)} title={checks[target.id]?.message || ''} aria-live="polite" onclick={()=>check(target)}>{#key checkState(target.id)}<span class="check-label" in:fly={{y:5,duration:150}} out:fade={{duration:90}}>{checkLabel(checkState(target.id))}</span>{/key}</button>{#if target.adapter!=='command'}<button type="button" class="secondary" disabled={pending||dirty||testing||faultEnvironment(target)==='unassigned'||['aws','azure'].includes(environment)} onclick={()=>openTest(target)}>{target.actions?.[0]==='failover'?'Test failover':'Test interruption'}</button>{/if}<button type="button" class="icon-button danger" disabled={pending||testing} aria-label={`Remove ${target.label}`} onclick={()=>{clearCheckTimer(target.id);targets=targets.filter((_,i)=>i!==index);}}><Icon name="close"/></button></div>
+{#if checks[target.id]&&!checks[target.id].ok}<p class="invalid" role="alert">{checks[target.id].message}</p>{/if}
+{#if dirty}<small>Save scenario to enable interruption testing.</small>{/if}
+{#if testJob&&testTargetId===target.id}<button type="button" class="quiet test-status" onclick={()=>openTest(target)}>{testJob.status==='complete'?'✓ Recovery verified':`${target.label} · ${fault?.active?.status||testJob.status}`} · View details</button>{/if}
+</fieldset>
+{/each}
+<dialog class="fault-dialog test-dialog" bind:this={testDialog} aria-labelledby="fault-test-title" onclose={()=>selected=null}>
+{#if selected}<div>
+<div class="section-head"><div><h1 id="fault-test-title">Test {selected.actions?.[0]==='failover'?'failover':'interruption'}</h1><p>{selected.label} · {environmentLabel(environment)}</p><small>{faultTargetResource(selected)}</small></div><button type="button" class="icon-button" aria-label="Close test" onclick={closeTest}><Icon name="close"/></button></div>
+{#if testJob&&testTargetId===selected.id}
+<div class="test-progress" role="status"><strong>{testJob.status==='complete'?'Recovery verified':fault?.active?.status||testJob.status}</strong>{#if remaining!==null&&fault?.active?.status==='active'}<p>{remaining}s until recovery begins</p>{/if}{#if !connected}<p>Reconnecting… The server continues the test.</p>{/if}{#if testJob.error}<p class="invalid">{testJob.error}</p>{/if}<ol>{#each testJob.events||[] as event}<li>{event.message}</li>{/each}</ol>{#if testing}<button type="button" class="secondary" disabled={pending} onclick={restoreNow}>Restore now</button>{:else}<button type="button" class="secondary" onclick={()=>{testJob=null;testTargetId='';sessionStorage.removeItem('last-fault-test');confirm='';}}>Test again</button>{/if}</div>
+{:else}<p class="test-explanation">{selected.actions?.[0]==='failover'?'Promotes the managed standby and verifies that the primary becomes ready.':'Stops the service for the selected downtime, restores it, and verifies recovery.'}</p>
+{#if selected.actions?.[0]!=='failover'}<label>Downtime · seconds<input type="number" min="1" max="300" bind:value={seconds}/></label>{/if}
+<label>Confirm by typing <strong>{selected.actions?.[0]||'outage'} {selected.id}</strong><input autocomplete="off" bind:value={confirm}/></label>
+
+<div class="actions"><button type="button" class="secondary" onclick={closeTest}>Cancel</button><button type="button" onclick={startTest} disabled={pending||testing||confirm!==`${selected.actions?.[0]||'outage'} ${selected.id}`||!Number.isInteger(seconds)||seconds<1||seconds>300}>{pending?'Starting…':'Start test'}</button></div>{/if}
+{#if testError}<div class="message error" role="alert">{testError}</div>{/if}</div>{/if}
+</dialog>
+{#if message}<p role="status">{message}</p>{/if}
+<div class="actions">{#each faultTypes as type}<button type="button" class="secondary" disabled={pending||testing||targets.some(t=>faultType(t)===type.type)} onclick={()=>add(type.type)}>+ {type.label}</button>{/each}</div>
+
+<style>
+.target-access-note{display:flex;align-items:flex-start;gap:10px;margin:0 0 16px;padding:12px 14px;border:1px solid var(--border);border-radius:6px;background:var(--accent-soft);color:var(--ink);font-size:12px;line-height:1.6}.target-access-note :global(svg){flex-shrink:0;margin-top:2px;color:var(--accent)}
+
+.execution-field{display:grid;gap:8px}.execution-field>select{margin-top:0}.field-title{display:flex;align-items:center}.field-title label{margin:0}
+
+.target-config{margin-top:16px}.target-config>summary{font-size:12px;min-height:24px;justify-content:flex-start}.target-config>summary>span{font-size:11px;color:var(--muted);font-weight:400;margin-left:auto}.target-config[open]>.fields{margin-top:16px}.commands{margin-top:16px}.commands summary{font-size:11px}.test-status{display:block;margin:12px 0 0;min-height:28px;padding:4px 0;font-size:11px;text-align:left}.test-progress ol{padding-left:20px;max-height:240px;overflow:auto;font-size:12px}.test-progress li{padding:5px 0;color:var(--muted)}.test-progress strong{font-size:17px}.command-preview{white-space:pre-wrap;overflow-wrap:anywhere;background:var(--surface-muted);padding:12px;border-radius:6px;font-size:11px}.test-dialog .section-head{margin-bottom:16px}.test-dialog .test-explanation{padding:12px;background:var(--surface-muted);border-radius:8px}.test-dialog strong{display:block;margin-top:4px;color:var(--ink)}.test-dialog .message{margin-top:16px}fieldset{border:1px solid var(--border);border-radius:8px;padding:20px;margin:16px 0;min-width:0}legend{font-weight:550;font-size:13px;padding:0 8px;color:var(--ink)}fieldset>.actions{margin-top:20px}fieldset>small{display:block;font-size:11px;margin-top:8px;text-align:right}.check-button{min-width:112px;overflow:hidden;transition:background-color .18s ease,color .18s ease,border-color .18s ease,box-shadow .18s ease}.check-label{display:inline-flex;align-items:center;justify-content:center}.check-button.check-success:disabled{background:var(--success-soft);border-color:#b5d9c4;color:var(--success);cursor:default;opacity:1;box-shadow:0 0 0 2px color-mix(in srgb,var(--success) 10%,transparent)}
+@media(max-width:600px){fieldset{padding:14px}.target-config>summary{flex-wrap:wrap}.target-config>summary>span{margin-left:0}.actions{justify-content:flex-start}.target-config[open]>.fields{gap:14px}fieldset>small{text-align:left}}
+</style>
diff --git a/loadtest/console/src/FixtureImport.svelte b/loadtest/console/src/FixtureImport.svelte
new file mode 100644
index 0000000000..cfacbef646
--- /dev/null
+++ b/loadtest/console/src/FixtureImport.svelte
@@ -0,0 +1,27 @@
+<script>
+ import InfoTooltip from './InfoTooltip.svelte';
+ import ImportVerification from './ImportVerification.svelte';
+ import {importView} from './import-state.mjs';
+ import {api} from './api.js';import {connectorSet} from './connector-config.mjs';
+ export let profile;export let disabled=false;
+ /** @type {any} */
+ export let job=null;export let onstart=(_job)=>{};export let onreset=()=>{};export let onbusy=(_value)=>{};export let oncancel=()=>{};
+ let format='form',merchantId='',profileId='',apiKey='',publishableKey='',accounts={},json='',pending=false,error='',clearedJob='';
+ const merchantExample=JSON.stringify([{merchant_id:'merchant_123',profile_id:'pro_123',api_key:'...',publishable_key:'...',connector_accounts:{stripe:'mca_123'}}],null,2);
+ $: names=connectorSet(profile?.connectors);
+ $: view=importView(job);
+ $: collapsed=pending||view?.busy||view?.phase==='ready';
+ $: if(view?.phase==='ready'&&clearedJob!==job?.id){clearedJob=job?.id;apiKey='';publishableKey='';json='';accounts={};}
+ function edited(){if(pending||view?.busy)return;error='';onreset();}
+ function reset(){error='';onreset();}
+ async function loadFile(event){edited();const file=event.currentTarget.files?.[0];if(!file)return;if(file.size>900000){error='Choose a JSON file smaller than 900 KB';return;}json=await file.text();}
+ async function submit(){if(disabled||pending||view?.busy)return;pending=true;onbusy(true);error='';onreset();try{const merchants=format==='json'||profile?.mode==='tenancy'?JSON.parse(json):[{merchant_id:merchantId,profile_id:profileId,api_key:apiKey,publishable_key:publishableKey,connector_accounts:accounts}];const value=await api.importFixtures({profileId:profile.id,merchants});onstart(value);}catch(e){error=e.message;}finally{pending=false;onbusy(false);}}
+</script>
+<div class="import-form"><p>Import existing fixtures <InfoTooltip id="fixture-import-info" label="Fixture import information" text="Use existing merchants and connector accounts without changing their remote configuration. Verification checks credentials, ownership, and the connector setup required by this scenario. Configure the Router admin key in Connection settings for publishable-key inspection. Use a separate smoke test to check payment execution."/></p>
+{#if !collapsed}<div class="import-inputs" oninput={edited} onchange={edited}>{#if profile?.mode!=='tenancy'}<label>Import format<select bind:value={format}><option value="form">Single merchant</option><option value="json">JSON</option></select></label>{/if}
+{#if format==='json'||profile?.mode==='tenancy'}<label>Merchant JSON file<input type="file" accept=".json,application/json" onchange={loadFile} disabled={disabled||pending}/></label><div class="import-field"><div class="field-title"><label for="import-merchant-json">Merchant JSON</label><InfoTooltip id="merchant-json-info" label="Merchant JSON information" text={`Import exactly ${profile?.merchantCount} merchant${profile?.merchantCount===1?'':'s'} as a JSON array, including credentials and the connector-to-MCA-ID mapping.`}/></div><textarea id="import-merchant-json" rows="12" bind:value={json} placeholder={merchantExample} autocomplete="off" spellcheck="false"></textarea></div>
+{:else}<div class="fields"><label>Merchant ID<input bind:value={merchantId} autocomplete="off"/></label><label>Profile ID<input bind:value={profileId} autocomplete="off"/></label><label>API key<input type="password" bind:value={apiKey} autocomplete="new-password"/></label><div class="import-field"><div class="field-title"><label for="import-publishable-key">Publishable key</label><InfoTooltip id="publishable-key-info" label="Publishable key information" text="Required for SDK and modular payment-method calls."/></div><input id="import-publishable-key" type="password" bind:value={publishableKey} autocomplete="new-password"/></div>{#each names as name}<label>{name} MCA ID<input bind:value={accounts[name]} autocomplete="off"/></label>{/each}</div>{/if}
+</div>{:else}<p class="import-summary">{profile?.merchantCount} {profile?.merchantCount===1?'merchant':'merchants'} · {names.join(', ')}</p>{/if}
+<ImportVerification {job} {pending} {error}/>
+<div class="actions">{#if view?.busy}<button type="button" class="secondary" disabled={job?.status==='cancelling'} onclick={oncancel}>{job?.status==='cancelling'?'Cancelling…':'Cancel'}</button>{:else if view?.phase==='ready'}<button type="button" class="quiet" onclick={reset}>Import another</button><a class="button" href={`/performance?profile=${profile.id}&fixtures=${view.fixtureSetId}`}>Use fixture →</a>{:else}<button type="button" disabled={disabled||pending||!profile} onclick={submit}>{pending?'Verifying…':view?'Try again':'Import and verify'}</button>{/if}</div></div>
+<style>.import-inputs{display:grid;gap:16px}.import-summary{color:var(--muted)}.import-field{display:grid;gap:8px;align-content:start}.field-title{display:flex;align-items:center}.field-title label{margin:0}.import-form{grid-column:1/-1;border-top:1px solid var(--border);padding-top:16px;display:grid;gap:16px}.import-form p{font-size:12px;margin:0}textarea{width:100%;font-family:monospace;line-height:1.6;tab-size:2}.actions{justify-content:flex-end}</style>
diff --git a/loadtest/console/src/FixtureMenu.svelte b/loadtest/console/src/FixtureMenu.svelte
new file mode 100644
index 0000000000..985567c5c2
--- /dev/null
+++ b/loadtest/console/src/FixtureMenu.svelte
@@ -0,0 +1,20 @@
+<script>
+ import {tick,onMount} from 'svelte';import Icon from './Icon.svelte';
+ export let id;export let href='';export let disabled=false;export let deleting=false;export let ondelete=()=>{};
+ let open=false,confirm=false,root,trigger,panel,left=0,top=0;
+ function close(){open=false;confirm=false;}
+ async function toggle(){if(open){close();return;}open=true;await tick();const rect=trigger.getBoundingClientRect(),height=panel.offsetHeight;left=Math.max(12,rect.right-180);top=rect.bottom+6;if(top+height>window.innerHeight-12)top=Math.max(12,rect.top-height-6);panel.querySelector('a,button')?.focus();}
+ function keyboard(event){if(!open)return;if(event.key==='Escape'){event.preventDefault();close();trigger.focus();}else if(['ArrowDown','ArrowUp','Home','End'].includes(event.key)){event.preventDefault();const items=[...panel.querySelectorAll('a,button:not(:disabled)')],index=items.indexOf(document.activeElement);items[event.key==='Home'?0:event.key==='End'?items.length-1:(index+(event.key==='ArrowDown'?1:-1)+items.length)%items.length]?.focus();}else if(event.key==='Tab')close();}
+ onMount(()=>{document.addEventListener('scroll',close,true);return()=>document.removeEventListener('scroll',close,true);});
+</script>
+<svelte:window onpointerdown={event=>{if(open&&!root?.contains(event.target))close();}} onkeydown={keyboard} onresize={close}/>
+<div class="fixture-menu" bind:this={root}>
+ <button bind:this={trigger} type="button" class="quiet menu-trigger" aria-label={`Fixture actions ${id.slice(0,8)}`} aria-haspopup="menu" aria-expanded={open} {disabled} onclick={toggle}><Icon name="more"/></button>
+ {#if open}<div bind:this={panel} class="menu-panel" role="menu" aria-label="Fixture actions" style:left={`${left}px`} style:top={`${top}px`}>
+ {#if confirm}<p>Delete fixture?</p><button role="menuitem" class="danger" disabled={deleting} onclick={ondelete}>{deleting?'Deleting…':'Delete'}</button><button role="menuitem" disabled={deleting} onclick={close}>Cancel</button>
+ {:else}{#if href}<a role="menuitem" {href} onclick={close}>Use fixture <Icon name="arrow" size={14}/></a>{/if}<button role="menuitem" class="danger" onclick={()=>confirm=true}>Delete</button>{/if}
+ </div>{/if}
+</div>
+<style>
+.fixture-menu{display:flex;justify-content:flex-end}.menu-trigger{display:inline-flex;align-items:center;justify-content:center;width:32px;height:32px;padding:0;border-radius:6px}.menu-panel{position:fixed;z-index:100;width:180px;padding:5px;border:1px solid var(--border);border-radius:8px;background:var(--surface,#fff);box-shadow:0 6px 20px #18253b18;text-align:left}.menu-panel a,.menu-panel button{display:flex;align-items:center;justify-content:space-between;width:100%;padding:9px 10px;border:0;border-radius:4px;background:transparent;color:var(--ink);font-size:12px;font-weight:450;text-decoration:none;text-align:left}.menu-panel a:hover,.menu-panel button:hover{background:var(--hover-bg)}.menu-panel .danger{color:var(--danger)}.menu-panel p{margin:6px 10px;font-size:12px;color:var(--muted)}
+</style>
diff --git a/loadtest/console/src/FixtureScreen.svelte b/loadtest/console/src/FixtureScreen.svelte
new file mode 100644
index 0000000000..8f9d717728
--- /dev/null
+++ b/loadtest/console/src/FixtureScreen.svelte
@@ -0,0 +1,50 @@
+<script>
+export let data;
+import FixtureMenu from './FixtureMenu.svelte';
+import {importBusy,acceptImportUpdate,matchesImport} from './import-state.mjs';
+import {environments,environmentLabel} from './environments.mjs';
+import Icon from './Icon.svelte';
+import FixtureImport from './FixtureImport.svelte';
+let fixtureMode=data.job?.progress?.verification?'import':'create',importJob=data.job?.progress?.verification?data.job:null,importPending=false;
+function imported(value){if(!matchesImport(value,profileId))return;importJob=value;busyJob=value;watch(value,'import');}
+async function cancelImport(value){try{const result=await api.cancel(value.id);if(value.id===importJob?.id)importJob=result;busyJob=result;}catch(e){error=e.message;}}
+import ConnectorCredentials from './ConnectorCredentials.svelte';
+import {defaultConnectorPlan,connectorSet} from './connector-config.mjs';
+let connectorCredentials={},credentialProfile='';
+$: if(profileId!==credentialProfile){credentialProfile=profileId;connectorCredentials={};}
+import {setQuery} from './navigation.mjs';import ConnectionStatus from './ConnectionStatus.svelte';import {watchJobStream} from './job-stream.mjs';
+import {fixtureSteps} from './fixture-steps.mjs';
+import {onMount} from 'svelte';import {api} from './api.js';import FollowingLog from './FollowingLog.svelte';
+let pendingDelete=null,deleting=false;
+let settings=data.settings,profiles=data.profiles,profileId=data.profileId || profiles[0]?.id,sets=data.fixtures,job=data.job?.command==='fixtures'?data.job:null,busyJob=data.job,pending=false,error='',events,connection='connecting',updatedAt=0;
+$: providerSupported=environments.find(e=>e.id===(settings?.environment||'local'))?.supported;
+$: steps=fixtureSteps(job);
+$: repairable=sets.some(set=>set.repairable&&set.mode===profile?.mode&&set.merchant_count===profile?.merchantCount);
+$: profile=profiles.find(p=>p.id===profileId);
+let importContext='';
+$: {const context=JSON.stringify([profileId,profile?.version,settings]);if(importContext&&importContext!==context){importJob=null;}importContext=context;}
+$: active=['starting','running','pausing','paused','cancelling'].includes(busyJob?.status) && busyJob?.command!=='reconcile';
+async function start(){pending=true;error='';try{const credentials=Object.fromEntries(Object.entries(connectorCredentials).map(([id,row])=>[id,{credentials:row.credentials,metadata:row.metadataText?JSON.parse(row.metadataText):{}}]));job=await api.start('fixtures',{mode:profile.mode,profileId:profile.id,version:profile.version,connectorCredentials:credentials});connectorCredentials={};busyJob=job;sets=await api.fixtures();watch();}catch(e){error=e.message;}finally{pending=false;}}
+let observation=0;
+function watch(value=job,destination='create'){events?.close();const generation=++observation,id=value.id;events=watchJobStream(id,async next=>{if(generation!==observation||next.id!==id)return;
+if(destination==='import'){if(!acceptImportUpdate(importJob,next,profileId))return;importJob=next;}else job=next;
+busyJob=next;if(!importBusy(next)){events?.close();sets=await api.fixtures();if(destination==='create'&&next.error)error=next.error;}},(state,at)=>{connection=state;updatedAt=at;});}
+
+async function removeFixtures(){if(deleting||!pendingDelete)return;deleting=true;error='';try{await api.deleteFixtures(pendingDelete.id);sets=await api.fixtures();pendingDelete=null;}catch(e){error=e.message;}finally{deleting=false;}}
+async function stop(){try{job=await api.cancel(job.id);busyJob=job;}catch(e){error=e.message;}}
+onMount(()=>{const connections=async()=>{try{[sets,settings]=await Promise.all([api.fixtures(),api.settings()]);error='';}catch(e){error=e.message;}};window.addEventListener('console-connections-saved',connections);if(importJob&&active)watch(importJob,'import');else if(job&&active)watch();const poll=setInterval(async()=>{try{const r=await fetch('/api/jobs');if(r.ok){busyJob=await r.json();if(busyJob?.progress?.verification&&busyJob.id!==importJob?.id){profileId=busyJob.progress.verification.profileId||profileId;fixtureMode='import';imported(busyJob);}else if(busyJob?.command==='fixtures'&&!busyJob.progress?.verification&&busyJob.id!==job?.id){job=busyJob;watch();}}}catch{}},3000);return()=>{events?.close();clearInterval(poll);window.removeEventListener('console-connections-saved',connections);};});
+</script>
+<svelte:head><title>Fixtures · Testbench</title></svelte:head>
+<main><div class="section-head"><div><h1>Fixtures</h1><p>Prepare the merchants and connections your scenarios need.</p></div><button class="secondary" onclick={()=>window.dispatchEvent(new Event('console-settings'))}>Connection settings</button></div>{#if error}<div class="message error" role="alert">{error}</div>{/if}
+<section class="fixture-setup surface"><label>Fixture source<select bind:value={fixtureMode} disabled={pending||importPending||active}><option value="create">Create new</option><option value="import">Import existing</option></select></label>{#if !providerSupported}<p role="status">{environmentLabel(settings.environment)} execution is not available. Select Local or GCP in Settings.</p>{/if}<div class="load-controls"><label>Scenario<select disabled={pending||importPending||active} bind:value={profileId} onchange={()=>setQuery({profile:profileId})}>{#each profiles as p}<option value={p.id}>{p.name} · {p.mode==='tenancy'?'Tenancy':'Single'} · v{p.version}</option>{/each}</select></label><div class="fixture-summary"><strong>{profile?.mode==='tenancy'?'Tenancy':'Single'} · {profile?.merchantCount} {profile?.merchantCount===1?'merchant':'merchants'}</strong><p>{fixtureMode==='import'?'Verification uses the Router and PM connections in Settings.':'Provisioning uses the connections and Superposition defaults in Settings.'}</p></div></div>{#if fixtureMode==='create'}<div class="actions"><button disabled={pending||active||!profile||!providerSupported} onclick={start}>{pending?'Starting…':active?'Job in progress':repairable?'Repair fixtures':'Create fixtures'}</button></div><ConnectorCredentials plan={profile?.connectors||defaultConnectorPlan()} bind:value={connectorCredentials}/>{:else}{#key `${profileId}:${profile?.version}:${settings.environment}:${settings.routerBaseUrl}:${settings.pmBaseUrl}`}<FixtureImport {profile} job={importJob} disabled={pending||active||!providerSupported} onstart={imported} onreset={()=>importJob=null} onbusy={value=>importPending=value} oncancel={()=>cancelImport(importJob)}/>{/key}{/if}{#if (active&&!busyJob.progress?.verification)||repairable}<p class="muted">{active?`${busyJob.command} · ${busyJob.status}`:'Resumes the interrupted fixture set and reuses existing merchants.'}</p>{/if}{#if active&&busyJob.command!=='fixtures'&&!busyJob.progress?.verification}<a class="quiet" href="/performance">View active job →</a>{/if}</section>
+{#if job&&!job.progress?.verification}<section class="activity"><div class="section-head"><div><h2>Fixture setup · {job.status}</h2>{#if active}<ConnectionStatus state={connection} {updatedAt}/>{/if}</div>{#if active}<button class="secondary danger" onclick={stop}>Stop</button>{/if}</div><p role="status">{job.progress?.fixtures?.completed ?? 0} / {job.progress?.fixtures?.total ?? profile?.merchantCount} merchants provisioned</p><progress aria-label="Fixture provisioning progress" value={job.status==='complete'?(job.progress?.fixtures?.total ?? profile?.merchantCount):(job.progress?.fixtures?.completed ?? 0)} max={job.progress?.fixtures?.total ?? profile?.merchantCount}></progress><div class="setup-steps" aria-label="Fixture setup steps">{#each steps as step,i}<div class="setup-step" class:running={step.status==='running'} class:complete={step.status==='complete'}><span class="step-number">{#if step.status==='complete'}<Icon name="check"/>{:else}{i+1}{/if}</span><div><strong>{step.label}</strong><span>{step.status==='running'?'In progress':step.status==='complete'?'Complete':step.status==='failed'?'Failed':step.status==='skipped'?'Skipped':'Pending'}</span></div>{#if step.detail}<p role="status">{step.detail}</p>{/if}{#if step.label==='Service refresh'&&step.status==='running'&&step.total>0}<progress aria-label="Superposition service refresh progress" value={step.total-step.remaining} max={step.total}></progress>{/if}</div>{/each}</div><details class="fixture-events"><summary>Activity · {job.events?.length || 0} events</summary><ol>{#each job.events || [] as event}<li><time>{new Date(event.at).toLocaleTimeString()}</time><span>{event.message}</span></li>{/each}</ol></details><details class="diagnostics"><summary>Provisioning output</summary><FollowingLog output={job.output || ''} label="Provisioning output"/></details></section>{/if}
+<section class="fixture-list"><div class="section-head panels-head"><h2>Fixture sets</h2></div><div class="table-wrap fixture-sets surface"><table><thead><tr><th>Set</th><th>Source</th><th>Mode</th><th>Merchants</th><th>Status</th><th><span class="sr-only">Actions</span></th></tr></thead><tbody>{#each sets as set}<tr><td><strong>{set.id.slice(0,8)}</strong><small class="fixture-meta">{new Date(set.created_at).toLocaleString()}</small><small class="fixture-meta">{set.destination}</small></td><td><span class="source-tag" class:imported={set.source==='imported'}>{set.source==='imported'?'Imported':'Created'}</span></td><td>{set.mode==='tenancy'?'Tenancy':'Single'}</td><td>{set.merchant_count}</td><td>{set.source==='imported'?(!set.compatible?'Verification required':'Ready'):!set.compatible?'Needs refresh':set.status==='ready'?'Ready':set.status==='creating'?'Preparing':set.status==='interrupted'?'Interrupted':set.status==='failed'?'Failed':set.status}{#if !set.compatible}<small class="fixture-meta">{set.source==='imported'?'Import again to verify current connections.':'Provisioning settings changed.'}</small>{/if}</td><td><FixtureMenu id={set.id} href={set.status==='ready'&&set.compatible&&set.mode===profile?.mode&&set.merchant_count===profile?.merchantCount&&JSON.stringify(set.connectors||['stripe_test'])===JSON.stringify(connectorSet(profile?.connectors))?`/performance?profile=${profileId}&fixtures=${set.id}`:''} disabled={active||pending||deleting} deleting={deleting&&pendingDelete?.id===set.id} ondelete={()=>{pendingDelete=set;removeFixtures();}}/></td></tr>{/each}</tbody></table>{#if !sets.length}<p class="muted">No fixtures yet. Create or import one above.</p>{/if}</div></section></main>
+
+
+<style>
+
+
+ .fixture-list{max-width:1000px}.source-tag{display:inline-block;padding:4px 7px;border-radius:4px;background:var(--hover-bg);color:var(--muted);font-size:11px}.source-tag.imported{background:var(--accent-soft);color:var(--accent)}.fixture-sets th:last-child,.fixture-sets td:last-child{width:48px;padding-right:12px}.fixture-sets td:first-child{max-width:270px}.fixture-sets td:nth-child(5){max-width:200px}
+.fixture-setup{padding:20px;margin-bottom:24px;display:grid;grid-template-columns:minmax(0,1fr) auto;gap:12px 24px;align-items:center}.fixture-setup .load-controls{border:0;padding:0;margin:0;gap:24px}.fixture-setup>.actions{margin:0;align-self:end}.fixture-setup>p{grid-column:1/-1;margin:0;font-size:11px}.fixture-summary p{max-width:340px}.fixture-meta{display:block;font-size:11px;color:var(--muted);margin-top:5px;overflow-wrap:anywhere}.fixture-sets{padding:0}.fixture-sets>p{padding:20px}.setup-steps{display:grid;grid-template-columns:repeat(4,minmax(0,1fr));margin:24px 0;gap:20px}.setup-step{display:grid;grid-template-columns:26px 1fr;gap:8px;border-top:2px solid var(--border);padding-top:14px;align-content:start}.setup-step.running{border-color:var(--accent)}.setup-step.complete{border-color:var(--success)}.setup-step>div{display:flex;flex-direction:column;gap:5px}.setup-step strong{font-size:12px;font-weight:550}.setup-step span,.setup-step p{font-size:11px;color:var(--muted)}.setup-step .step-number{display:flex;align-items:center;justify-content:center;width:24px;height:24px;border-radius:50%;background:#eef1f6;color:var(--muted);font-size:11px}.setup-step.running .step-number{background:var(--accent-soft);color:var(--accent)}.setup-step.complete .step-number{background:var(--success-soft);color:var(--success)}.setup-step p{grid-column:2;margin:0;line-height:1.4}.setup-step.complete>div>span{color:var(--success)}.setup-step progress{grid-column:2;margin:4px 0 0}.fixture-events{padding-top:16px;border-top:1px solid var(--border)}.fixture-events ol{margin-top:14px}.activity>.section-head{margin-bottom:16px}.activity>.section-head h2{margin:0}.activity>p{font-size:12px;margin:0}.activity>.diagnostics{border:0;border-top:1px solid var(--border);border-radius:0;padding:16px 0 0}
+@media(max-width:1000px){.fixture-setup{grid-template-columns:1fr}.fixture-setup>.actions{justify-self:end}}@media(max-width:650px){.fixture-setup{padding:16px}.setup-steps{grid-template-columns:1fr 1fr;gap:18px 12px}.fixture-setup .load-controls{grid-template-columns:1fr}.fixture-setup>.actions{justify-self:stretch}.fixture-setup>.actions>button{width:100%}}
+</style>
diff --git a/loadtest/console/src/FlowMix.svelte b/loadtest/console/src/FlowMix.svelte
new file mode 100644
index 0000000000..1269f13c1c
--- /dev/null
+++ b/loadtest/console/src/FlowMix.svelte
@@ -0,0 +1,35 @@
+<script>
+import {tick} from 'svelte';import Icon from './Icon.svelte';
+import {flowCatalog,flowLabel,newFlow,balanceWeights,flowAvailable} from './flow-catalog.mjs';
+export let flows;export let disabled=false;
+let expanded=null,picker,search='',searchInput,undo=null;
+$: allocated=flows.reduce((sum,flow)=>sum+Number(flow.weight||0),0);
+$: choices=flowCatalog.filter(([,label])=>label.toLowerCase().includes(search.trim().toLowerCase()));
+async function openPicker(){search='';picker.showModal();await tick();searchInput.focus();}
+function add(type){flows=[...flows,newFlow(type,flows)];picker.close();expanded=flows.length-1;}
+function remove(index){undo=structuredClone(flows);flows=flows.filter((_,i)=>i!==index);expanded=null;}
+</script>
+<section class="mix" aria-labelledby="mix-title">
+<div class="section-head"><div><h2 id="mix-title">Flow mix</h2><p class:invalid={allocated!==100}>{allocated===100?'100% allocated':allocated<100?`${100-allocated}% remaining`:`${allocated-100}% over allocated`}</p></div><button type="button" class="secondary" disabled={disabled} onclick={openPicker}><Icon name="plus"/> Add flow</button></div>
+<div class="mix-tools">{#if allocated<100&&flows.length}<button type="button" class="quiet" disabled={disabled} onclick={()=>{undo=structuredClone(flows);flows=balanceWeights(flows);}}>Distribute remaining {100-allocated}%</button>{/if}{#if allocated!==100&&flows.length}<button type="button" class="quiet" disabled={disabled} onclick={()=>{undo=structuredClone(flows);flows=balanceWeights(flows,true);}}>Normalize to 100%</button>{/if}{#if undo}<button type="button" class="quiet" onclick={()=>{flows=undo;undo=null;}}>Undo</button>{/if}</div><div class="flow-list">
+{#each flows as flow,index}
+<div class="flow-row">
+<button type="button" class="quiet flow-name" disabled={disabled} aria-expanded={expanded===index} aria-controls={`flow-options-${index}`} onclick={()=>expanded=expanded===index?null:index}>{flowLabel(flow.scenario)}<span aria-hidden="true" class="chevron">{expanded===index?'⌃':'⌄'}</span></button>
+<label class="flow-weight"><input aria-label={`${flowLabel(flow.scenario)} weight`} type="number" min="0" max="100" required disabled={disabled} bind:value={flow.weight}/><span>%</span></label>
+<button type="button" class="icon-button danger" disabled={disabled} aria-label={`Remove ${flowLabel(flow.scenario)}`} onclick={()=>remove(index)}><Icon name="close"/></button>
+</div>
+{#if expanded===index}
+<div class="flow-options fields" id={`flow-options-${index}`}>
+<label>Flow<select disabled={disabled} bind:value={flow.scenario}>{#each flowCatalog as [type,label]}<option value={type} disabled={!flowAvailable(type)}>{label}{flowAvailable(type)?'':' · Not yet supported'}</option>{/each}</select></label>
+
+<label class="internal-name">Internal name <span>Used in run metrics</span><input disabled={disabled} required bind:value={flow.name}/></label>
+</div>
+{/if}
+{/each}
+{#if !flows.length}<p class="muted">Add a flow to configure the traffic mix.</p>{/if}
+</div>
+</section>
+<dialog bind:this={picker} aria-labelledby="picker-title"><div class="section-head"><h2 id="picker-title">Add flow</h2><button type="button" class="icon-button" aria-label="Close flow picker" onclick={()=>picker.close()}><Icon name="close"/></button></div><input type="search" aria-label="Search flows" placeholder="Search flows" bind:this={searchInput} bind:value={search}/><div class="choices">{#each choices as [type,label]}<button type="button" class="quiet choice" disabled={!flowAvailable(type)} onclick={()=>add(type)}>{label}{flowAvailable(type)?'':' · Not yet supported'}<span aria-hidden="true">+</span></button>{/each}{#if !choices.length}<p>No flows found.</p>{/if}</div></dialog>
+<style>
+.mix-tools{display:flex;gap:8px;font-size:12px;margin-bottom:8px;flex-wrap:wrap}.mix{background:var(--surface);border:1px solid var(--border);border-radius:var(--radius);padding:20px;margin:20px 0}.mix .section-head{margin-bottom:14px}.mix h2{font-size:15px}.mix p{font-size:12px}.flow-row{display:grid;grid-template-columns:minmax(0,1fr) 90px 32px;gap:14px;align-items:center;border-top:1px solid var(--border);padding:8px 0}.flow-name{justify-content:flex-start;text-align:left;padding:8px;gap:14px;font-size:13px;white-space:normal}.chevron{margin-left:auto;color:var(--subtle)}.flow-weight{display:flex;align-items:center;gap:7px}.flow-weight input{margin:0;text-align:center;width:68px;min-height:34px}.flow-weight span{font-size:12px}.flow-options{padding:16px;background:var(--surface-muted);border-radius:7px;margin-bottom:8px}.internal-name span{font-weight:400;color:var(--muted)}.internal-name{grid-column:1/-1}.internal-name input{max-width:420px}.choices{margin-top:14px;max-height:340px;overflow:auto;display:grid;gap:4px}.choice{justify-content:space-between;width:100%;padding:12px;text-align:left;font-weight:400}.mix-tools:empty{display:none}@media(max-width:600px){.flow-row{gap:6px;grid-template-columns:minmax(0,1fr) 76px 32px}.flow-name{flex-wrap:wrap;gap:3px}.chevron{display:none}.flow-weight input{width:55px}}
+</style>
diff --git a/loadtest/console/src/FollowingLog.svelte b/loadtest/console/src/FollowingLog.svelte
new file mode 100644
index 0000000000..5dea530e34
--- /dev/null
+++ b/loadtest/console/src/FollowingLog.svelte
@@ -0,0 +1,23 @@
+<script>
+ import { tick } from 'svelte';
+ import { k6Output } from './k6-output.mjs';
+ export let output = '';
+ export let label = 'k6 output';
+ let element;
+ let following = true;
+
+ function scrolled(){if(element.scrollHeight>element.clientHeight+24)following=element.scrollHeight-element.scrollTop-element.clientHeight<24;}
+ async function update(_output){await tick();if(element && following)element.scrollTop=element.scrollHeight;}
+ async function follow(){following=true;await update(output);}
+ $: update(output);
+ $: display = k6Output(output);
+</script>
+
+<div class="output-toolbar"><span>{label}</span><button class="quiet" aria-pressed={following} onclick={() => {if(following)following=false;else follow();}}>{following ? 'Following output' : 'Follow output ↓'}</button></div>
+<pre bind:this={element} onscroll={scrolled} aria-label={label}>{#if display.progress}<span>{display.before}{display.before ? '\n\n' : ''}</span><span aria-label="Current k6 progress">{display.progress}</span><span>{display.after ? '\n\n' : ''}{display.after}</span>{:else}{display.history}{/if}</pre>
+
+<style>
+ .output-toolbar{display:flex;align-items:center;justify-content:space-between;gap:12px;margin-bottom:8px;color:#667085;font-size:12px}
+ .output-toolbar button{min-height:28px;font-size:12px}
+ pre{width:100%;max-width:none!important;margin:0;background:#182235!important;color:#dce6f3!important;border-radius:8px;padding:16px!important;min-height:180px;max-height:none!important;overflow-x:auto;white-space:pre!important;line-height:1.55}
+</style>
diff --git a/loadtest/console/src/GrafanaMetrics.svelte b/loadtest/console/src/GrafanaMetrics.svelte
new file mode 100644
index 0000000000..be1996b296
--- /dev/null
+++ b/loadtest/console/src/GrafanaMetrics.svelte
@@ -0,0 +1,20 @@
+<script>
+import GrafanaPanel from './GrafanaPanel.svelte';
+import {unifiedPerformancePanels} from './grafana-panels.mjs';
+export let run;
+export let grafana;
+$: panels=unifiedPerformancePanels(run);
+</script>
+{#if panels.length}
+<section class="grafana-metrics" aria-label="Grafana metrics">
+ {#if grafana?.hasIdentity}
+ <div class="grafana-grid">{#each panels as panel (panel.title)}<GrafanaPanel {panel} url={panel.url} baseUrl={grafana.baseUrl}/>{/each}</div>
+ {:else}
+ <p class="metrics-note">Configure Grafana access in the console to load embedded panels.</p>
+ {/if}
+</section>
+{/if}
+<style>
+.grafana-metrics{margin-bottom:16px}.metrics-note{margin:0 0 14px;color:var(--muted);font-size:12px}.grafana-grid{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:14px}
+@media(max-width:1000px){.grafana-grid{grid-template-columns:1fr}}
+</style>
diff --git a/loadtest/console/src/GrafanaPanel.svelte b/loadtest/console/src/GrafanaPanel.svelte
new file mode 100644
index 0000000000..9b75f9905d
--- /dev/null
+++ b/loadtest/console/src/GrafanaPanel.svelte
@@ -0,0 +1,16 @@
+<script>
+import {onMount} from 'svelte';
+export let panel;export let url;export let baseUrl;
+let loaded=false,failed=false,attempt=0,timer,embedUrl='',mounted=false;
+async function retry(){const current=++attempt;loaded=false;failed=false;embedUrl='';clearTimeout(timer);timer=setTimeout(()=>{if(!loaded)failed=true;},15000);
+ try{const response=await fetch(`/api/grafana/embed?panel=${encodeURIComponent(url)}`);if(!response.ok)throw Error('Embed unavailable');const result=await response.json();if(current===attempt)embedUrl=result.url;}catch{if(current===attempt)failed=true;}}
+onMount(()=>{mounted=true;return()=>{attempt++;clearTimeout(timer);};});
+$: if(mounted&&url)retryFor(url);
+function retryFor(_url){retry();}
+</script>
+<article class="grafana-panel">
+{#if !loaded}<p role="status">{failed?'Panel is taking longer to load.':'Loading panel…'}{#if failed}<button class="quiet" onclick={retry}>Retry</button>{/if}</p>{/if}
+{#if embedUrl}<iframe title={panel.title} src={embedUrl} sandbox="allow-scripts allow-same-origin" referrerpolicy="no-referrer" onload={()=>{loaded=true;failed=false;clearTimeout(timer);}} onerror={()=>failed=true}></iframe>{/if}
+<a class="quiet panel-link" aria-label={`Open ${panel.title} in Grafana`} href={new URL(url.replace(/^\/grafana/,''),baseUrl||'http://localhost:3000').href} target="_blank" rel="noreferrer">Open ↗</a>
+</article>
+<style>p{font-size:12px;color:var(--muted);padding:8px}.quiet{font-size:12px}.panel-link{display:block;text-align:right;padding:8px 12px}</style>
diff --git a/loadtest/console/src/Icon.svelte b/loadtest/console/src/Icon.svelte
new file mode 100644
index 0000000000..bb4803a893
--- /dev/null
+++ b/loadtest/console/src/Icon.svelte
@@ -0,0 +1,26 @@
+<script>
+export let name;
+export let size=16;
+const paths={
+ settings:'M19.391 8.939 L19.807 10.255 L21.759 9.819 L21.759 14.181 L19.807 13.745 L19.391 15.061 L19.391 15.061 L18.755 16.287 L20.443 17.358 L17.358 20.443 L16.287 18.755 L15.061 19.391 L15.061 19.391 L13.745 19.807 L14.181 21.759 L9.819 21.759 L10.255 19.807 L8.939 19.391 L8.939 19.391 L7.713 18.755 L6.642 20.443 L3.557 17.358 L5.245 16.287 L4.609 15.061 L4.609 15.061 L4.193 13.745 L2.241 14.181 L2.241 9.819 L4.193 10.255 L4.609 8.939 L4.609 8.939 L5.245 7.713 L3.557 6.642 L6.642 3.557 L7.713 5.245 L8.939 4.609 L8.939 4.609 L10.255 4.193 L9.819 2.241 L14.181 2.241 L13.745 4.193 L15.061 4.609 L15.061 4.609 L16.287 5.245 L17.358 3.557 L20.443 6.642 L18.755 7.713 L19.391 8.939Z',
+ scenarios:'M4 4h6v6H4z M14 4h6v6h-6z M4 14h6v6H4z M14 14h6v6h-6z',
+ fixtures:'M4 7l8-4 8 4-8 4-8-4Z M4 7v10l8 4 8-4V7 M12 11v10',
+ performance:'M3 12h4l3-8 4 16 3-8h4',
+ results:'M5 20V10 M12 20V4 M19 20v-7',
+ logout:'M9 4H4v16h5 M14 7l5 5-5 5 M8 12h11',
+ plus:'M12 5v14 M5 12h14',
+ close:'M6 6l12 12 M18 6 6 18',
+ arrow:'M5 12h14 M13 6l6 6-6 6',
+ back:'M19 12H5 M11 6l-6 6 6 6',
+ check:'M5 12l4 4L19 6',
+ search:'M21 21l-5-5 M18 10a8 8 0 1 1-16 0 8 8 0 0 1 16 0',
+ more:'M5 12h.01 M12 12h.01 M19 12h.01',
+ grip:'M8 5h.01 M16 5h.01 M8 12h.01 M16 12h.01 M8 19h.01 M16 19h.01',
+ bolt:'m13 2-8 12h6l-1 8 9-13h-7l1-7Z',
+ shield:'M12 3l8 3v6c0 5-8 9-8 9s-8-4-8-9V6l8-3Z M8 12l3 3 5-6',
+ clock:'M12 8v5l3 2 M22 12a10 10 0 1 1-20 0 10 10 0 0 1 20 0',
+ chevron:'m8 5 7 7-7 7',
+ info:'M12 11v6 M12 7h.01 M22 12a10 10 0 1 1-20 0 10 10 0 0 1 20 0'
+};
+</script>
+<svg class="ui-icon" width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d={paths[name]||paths.info}/>{#if name==='settings'}<circle cx="12" cy="12" r="3"/>{/if}</svg>
diff --git a/loadtest/console/src/ImportVerification.svelte b/loadtest/console/src/ImportVerification.svelte
new file mode 100644
index 0000000000..de88a19d83
--- /dev/null
+++ b/loadtest/console/src/ImportVerification.svelte
@@ -0,0 +1,31 @@
+<script>
+ import Icon from './Icon.svelte';
+ import {importView} from './import-state.mjs';
+ /** @type {any} */ export let job=null;export let pending=false;export let error='';
+ let checkPage=0,lastJobId='';
+ $: view=importView(job);
+ $: if(job?.id!==lastJobId){lastJobId=job?.id||'';checkPage=0;}
+</script>
+{#if error}<p class="inline-error" role="alert">{error}</p>
+{:else if pending&&!view}<p class="verification-message" role="status" aria-live="polite"><span class="spinner"></span>Verifying…</p>
+{:else if view}
+ <div class="inline-verification" class:passed={view.phase==='ready'} class:failed={view.phase==='failed'}>
+ <div class="verification-message" role={view.phase==='failed'?'alert':'status'} aria-live="polite">
+ {#if view.busy}<span class="spinner"></span>{:else}<Icon name={view.phase==='ready'?'check':view.phase==='failed'?'close':'info'} size={16}/>{/if}
+ <div><strong>{view.title}</strong>{#if view.detail}<p>{view.detail}</p>{/if}</div>
+ </div>
+ <ol class="verification-stages" aria-label="Import verification stages">
+ {#each view.stages as stage,index}<li class:passed={stage.status==='passed'} class:failed={stage.status==='failed'} class:running={stage.status==='running'} aria-current={stage.status==='running'?'step':undefined}>
+ <span class="stage-marker">{#if stage.status==='passed'}<Icon name="check" size={12}/>{:else}{index+1}{/if}</span>
+ <span>{stage.label}{#if stage.status==='running'&&stage.total!==null}<small>{stage.completed} / {stage.total}</small>{:else if stage.status==='blocked'}<small>Not run</small>{/if}</span>
+ </li>{/each}
+ </ol>
+ {#if view.checks.length}<details class="verification-details"><summary>Details · {job?.progress?.verification.checked??view.checks.length} checks{#if view.failures.length} · {view.failures.length} failed{/if}</summary>
+ <div class="table-wrap"><table><thead><tr><th>Merchant</th><th>Check</th><th>Result</th></tr></thead><tbody>{#each view.checks.slice(checkPage*100,(checkPage+1)*100) as check}<tr><td>{check.merchant}</td><td>{check.label}</td><td class:passed={check.ok} class:failed={!check.ok}>{check.ok?'Verified':check.message}</td></tr>{/each}</tbody></table></div>
+ {#if view.checks.length>100}<div class="check-pages"><button type="button" class="quiet" disabled={checkPage===0} onclick={()=>checkPage--}>Previous</button><span>{checkPage*100+1}–{Math.min((checkPage+1)*100,view.checks.length)} / {view.checks.length}</span><button type="button" class="quiet" disabled={(checkPage+1)*100>=view.checks.length} onclick={()=>checkPage++}>Next</button></div>{/if}
+ </details>{/if}
+ </div>
+{/if}
+<style>
+.inline-verification{min-width:0;color:var(--ink)}.verification-message{display:flex;align-items:flex-start;gap:8px;margin:0;font-size:12px;line-height:1.6}.verification-message strong{font-weight:550}.verification-message p{margin:4px 0 0;overflow-wrap:anywhere}.verification-message :global(svg){flex-shrink:0;margin-top:2px}.passed{color:var(--success)}.failed,.inline-error{color:var(--danger)}.inline-error{font-size:12px;line-height:1.6;margin:0;overflow-wrap:anywhere}.verification-stages{display:flex;flex-wrap:wrap;list-style:none;gap:16px 24px;margin:16px 0 0;padding:0}.verification-stages li{display:flex;align-items:center;gap:7px;font-size:12px;color:var(--muted)}.verification-stages li.passed{color:var(--success)}.verification-stages li.failed{color:var(--danger)}.verification-stages li.running{color:var(--accent)}.stage-marker{display:inline-flex;align-items:center;justify-content:center;width:20px;height:20px;border:1px solid var(--border);border-radius:50%;font-size:10px;flex-shrink:0}.running .stage-marker{border-color:var(--accent)}.passed .stage-marker{border-color:var(--success)}small{display:block;margin-top:3px;font-size:10px}.spinner{width:14px;height:14px;margin-top:3px;flex-shrink:0;border:2px solid var(--border);border-top-color:var(--accent);border-radius:50%;animation:verify-spin .8s linear infinite}.verification-details{margin-top:16px;color:var(--muted)}summary{font-size:11px}.table-wrap{margin-top:12px}th,td{font-size:11px;padding:10px}td{overflow-wrap:anywhere}.check-pages{display:flex;justify-content:flex-end;align-items:center;gap:12px;margin-top:8px;font-size:11px}@keyframes verify-spin{to{transform:rotate(360deg)}}@media(prefers-reduced-motion:reduce){.spinner{animation:none}}
+</style>
diff --git a/loadtest/console/src/InfoTooltip.svelte b/loadtest/console/src/InfoTooltip.svelte
new file mode 100644
index 0000000000..e411e9c8a5
--- /dev/null
+++ b/loadtest/console/src/InfoTooltip.svelte
@@ -0,0 +1,29 @@
+<script>
+ import {tick,onMount} from 'svelte';
+ import Icon from './Icon.svelte';
+ export let id;
+ export let text;
+ export let label='More information';
+ let open=false,button,bubble,left=12,top=12;
+ async function show(){
+ open=true;await tick();if(!open||!button||!bubble)return;
+ const anchor=button.getBoundingClientRect(),box=bubble.getBoundingClientRect();
+ left=Math.max(12,Math.min(anchor.left,window.innerWidth-box.width-12));
+ top=anchor.bottom+8;
+ if(top+box.height>window.innerHeight-12)top=Math.max(12,anchor.top-box.height-8);
+ }
+ onMount(()=>{document.addEventListener('scroll',hide,true);return()=>document.removeEventListener('scroll',hide,true);});
+ function hide(){open=false;}
+ function leave(){if(document.activeElement!==button)hide();}
+</script>
+<svelte:window onkeydown={event=>{if(open&&event.key==='Escape'){event.preventDefault();event.stopPropagation();hide();}}} onresize={hide} onscroll={hide}/>
+<span class="info-tooltip">
+ <button bind:this={button} type="button" class="info-trigger" aria-label={label} aria-describedby={open?id:undefined} onmouseenter={show} onmouseleave={leave} onfocus={show} onblur={hide} onclick={show}><Icon name="info" size={15}/></button>
+ {#if open}<span bind:this={bubble} {id} role="tooltip" class="info-content" style:left={`${left}px`} style:top={`${top}px`}>{text}</span>{/if}
+</span>
+<style>
+.info-tooltip{display:inline-flex;vertical-align:middle;margin-left:5px;font-size:12px;font-weight:400;line-height:1.5}
+.info-trigger{display:inline-flex;align-items:center;justify-content:center;min-height:24px;min-width:24px;padding:3px;border:0;border-radius:4px;background:transparent;color:var(--muted);box-shadow:none;vertical-align:middle;cursor:help}
+.info-trigger:hover{color:var(--accent);background:var(--accent-soft)}.info-trigger:focus-visible{outline:2px solid var(--accent);outline-offset:2px}
+.info-content{position:fixed;z-index:1000;width:max-content;max-width:min(340px,calc(100vw - 24px));padding:10px 12px;border:1px solid var(--border);border-radius:6px;background:var(--surface,#fff);color:var(--ink);box-shadow:0 3px 12px #18253b14;font-size:12px;font-weight:400;line-height:1.6;white-space:normal;overflow-wrap:anywhere;text-align:left;pointer-events:none}
+</style>
diff --git a/loadtest/console/src/LiveChart.svelte b/loadtest/console/src/LiveChart.svelte
new file mode 100644
index 0000000000..f229ff1629
--- /dev/null
+++ b/loadtest/console/src/LiveChart.svelte
@@ -0,0 +1,113 @@
+<script>
+ import {onMount} from 'svelte';
+ import {plannedEvents,stageWallTimes,executionPhases,targetAt,wallToActive,availabilityGraphEvents,metricValue,metricSeries,chartHorizon} from './chart-timeline.mjs';
+ export let showMetrics=true;
+ export let points=[];
+ export let allPoints=[];
+ export let timeline=[];
+ export let durationSeconds=0;
+ export let activity=[];
+ export let startedAt=0;
+ export let flow='all';
+ export let flows=[];
+ export let metric='tps';
+ /** @type {any} */
+ export let runStatus=null;
+ let root,plotWidth=900;
+ let hover=null;
+ function inspect(event){
+ const svg=event.currentTarget,rect=svg.getBoundingClientRect();
+ const coordinate=(event.clientX-rect.left)*plotWidth/rect.width;
+ if(coordinate<48||coordinate>plotWidth-16){hover=null;return;}
+ hover={t:(coordinate-48)/span*end,left:Math.max(8,Math.min(rect.width-236,event.clientX-rect.left+14)),top:Math.max(8,Math.min(rect.height-110,event.clientY-rect.top-90))};
+ }
+ const formatValue=value=>value==null||!Number.isFinite(value)?'—':metric==='backlog'?Math.round(value).toLocaleString():`${value.toFixed(metric==='tps'?2:1)}${['p99','serverP99'].includes(metric)?' ms':metric==='errors'?'%':''}`;
+ onMount(()=>{const observer=new ResizeObserver(entries=>plotWidth=Math.max(260,entries[0].contentRect.width));observer.observe(root);return()=>observer.disconnect();});
+ $: span=plotWidth-64;
+ const choices={connectorTps:'Connector throughput · confirmations / second',tps:'Successful flows / second',p99:'Client-side latency · ms',serverP99:'Server-side latency · ms',errors:'HTTP errors · %',backlog:'Pending writes · events'};
+ $: rawSamples=points.filter(point=>Number.isFinite(point?.t));
+ $: successful=metric==='connectorTps'?rawSamples.map(p=>({t:p.t,value:Object.values(p.connectors||{}).reduce((sum,c)=>sum+(c.tps||0),0)})):metricSeries(rawSamples,metric,flow);
+ $: timingPoints=allPoints.length?allPoints:points;
+ $: wallTimeline=stageWallTimes(timeline,timingPoints,activity,startedAt);
+ $: offered=metric==='tps'&&flow==='all'?wallTimeline.flatMap(stage=>[
+ {t:stage.wallStart,value:stage.from},
+ {t:stage.wallEnd,value:stage.target}
+ ]):[];
+ $: connectorNames=[...new Set(rawSamples.flatMap(p=>Object.keys(p.connectors||{})))];
+ const connectorColors=['#0967e8','#24764d','#9d651b','#9555b5','#d2573d'];
+ $: connectorLines=connectorNames.map((name,i)=>({name,color:connectorColors[i%connectorColors.length],points:rawSamples.map((p,index)=>{const previous=rawSamples[index-1],count=p.connectors?.[name]?.confirmed;return {t:p.t,value:Number.isFinite(count)?Math.max(0,count-(previous?.connectors?.[name]?.confirmed||0))/Math.max(.001,p.t-(previous?.t||0)):p.connectors?.[name]?.tps??0};})}));
+ $: maximum=metric==='errors'?100:Math.max(1,...(metric==='connectorTps'?connectorLines.flatMap(c=>c.points):[...successful,...offered]).map(p=>Number(p.value)||0))*1.15;
+ $: planned=plannedEvents(timeline);
+ $: end=chartHorizon(timingPoints,durationSeconds,timeline,activity,startedAt);
+ $: recordedUntil=Math.min(end,rawSamples.at(-1)?.t||0);
+ $: x=t=>48+Number(t)/end*span;
+ const y=value=>220-(Number(value)||0)/maximum*185;
+ const line=(values,horizon,scale,width)=>values.map((p,i)=>`${i?'L':'M'}${(48+p.t/horizon*width).toFixed(1)},${(220-p.value/scale*185).toFixed(1)}`).join(' ');
+ $: valid=successful.filter(p=>p.value!=null&&Number.isFinite(p.value));
+ // Connect measured samples, including explicit zeros, with pointed peaks.
+ $: measuredValues=valid;
+ $: measuredPath=line(measuredValues,end,maximum,span);
+ $: offeredPath=line(offered,end,maximum,span);
+ const markerColor=e=>e.kind==='failover_requested'?'#5277b8':e.kind==='database_unavailable'?'#c43b36':e.kind==='database_available'?'#398453':e.kind==='fault_requested'?'#c43b36':e.kind==='fault_started'?'#8f2420':e.kind==='fault_restore'?'#d68a25':e.kind==='fault_restored'?'#398453':'#8793a5';
+ $: markers=availabilityGraphEvents(activity,timeline).map(e=>({...e,t:Math.max(0,(e.at-startedAt)/1000)})).filter(e=>e.t>=0&&e.t<=end);
+ $: phases=executionPhases(timeline,timingPoints,activity,startedAt,end);
+ $: hoveredSample=hover&&hover.t<=recordedUntil?(metric==='tps'?rawSamples.find(p=>p.t>=hover.t)||rawSamples.at(-1):rawSamples.reduce((nearest,p)=>!nearest||Math.abs(p.t-hover.t)<Math.abs(nearest.t-hover.t)?p:nearest,null)):null;
+ $: hoveredValue=hoveredSample?metricValue(hoveredSample,metric,flow):null;
+ $: hoveredPhase=hover?phases.find(p=>hover.t>=p.start&&hover.t<p.end):null;
+ $: hoveredEvent=hover?markers.filter(e=>Math.abs(e.t-hover.t)<end*8/span).sort((a,b)=>Math.abs(a.t-hover.t)-Math.abs(b.t-hover.t))[0]:null;
+ $: hoveredTarget=hover?targetAt(wallToActive(hover.t,timingPoints),timeline):null;
+</script>
+<section class="chart" aria-label="Load metrics over time">
+ <div class="chart-head"><h2>{showMetrics?'Load timeline':'Load controls'}</h2>
+ {#if runStatus}<div class="actions">
+ {#if runStatus.live!==false}
+ {#if runStatus.state==='idle'||(runStatus.state==='starting'&&runStatus.startLoad)}<button class="secondary" disabled={runStatus.pending||runStatus.startBlocked} onclick={runStatus.smokeTest}>Run smoke test</button><button disabled={runStatus.pending||runStatus.startBlocked} onclick={runStatus.startLoad}>{runStatus.pending?'Starting…':'Start load'}</button>
+ {:else if runStatus.stopping}<button class="secondary danger" disabled aria-busy="true">Stopping…</button>
+ {:else if runStatus.smoke}<button class="secondary" disabled={runStatus.pending} onclick={runStatus.cancel}>Stop smoke test</button>
+ {:else}
+ {#if runStatus.state==='running'}<button disabled={runStatus.pending||runStatus.faultActive} onclick={runStatus.pause}>Ⅱ Pause</button>{/if}
+ {#if runStatus.state==='pausing'}<button disabled>Draining active flows…</button>{/if}
+ {#if runStatus.state==='paused'}<button disabled={runStatus.pending} onclick={runStatus.resume}>▶ Resume</button>{/if}
+ {#if ['running','paused','pausing','recovering','starting'].includes(runStatus.state)}<button class="secondary danger" disabled={runStatus.pending} onclick={runStatus.cancel}>Stop</button>{/if}
+ {/if}
+ {:else}<button class="secondary" onclick={runStatus.runAgain}>Run again</button>{#if !runStatus.smoke}<a class="button" href={runStatus.resultsUrl}>View results</a>{/if}{/if}
+ </div>{/if}
+ </div>
+ {#if runStatus}<div class="run-toolbar timeline-run-toolbar">
+ <div><span class="state-badge" class:running={!runStatus.stopping&&(runStatus.state==='running'||runStatus.smoke)} class:paused={runStatus.state==='paused'} title={runStatus.reason} role="status">{runStatus.stopping?'Stopping…':runStatus.stateLabel||(runStatus.state==='idle'?'Ready':null)||runStatus.state[0].toUpperCase()+runStatus.state.slice(1)}</span><strong>{runStatus.label}</strong><span class="run-clock">{runStatus.clock}</span></div>
+ </div>
+ {#if runStatus.stopping}<p class="stop-notice" role="status">Stop requested · waiting for active requests to finish and fault recovery to be verified.</p>{/if}
+ {/if}
+ <slot/>
+ <div class="chart-filters" hidden={!showMetrics}>{#if flows.length>1}<select aria-label="Flow" disabled={['errors','backlog','connectorTps'].includes(metric)} bind:value={flow}><option value="all">All flows</option>{#each flows as item}<option value={item.name}>{item.label}</option>{/each}</select>{/if}<select aria-label="Metric" bind:value={metric}>{#each Object.entries(choices) as [key,label]}<option value={key}>{label}</option>{/each}</select></div>
+ {#if metric==='connectorTps'}<div class="connector-legend">{#each connectorLines as connector}<span style:color={connector.color}>{connector.name}</span>{/each}</div>{/if}
+ <div class="plot" hidden={!showMetrics} bind:this={root}>
+ <svg onpointermove={inspect} onpointerleave={()=>hover=null} viewBox={`0 0 ${plotWidth} 255`} role="img" aria-label={`${choices[metric]} over the full ${Math.round(end)} second test; grey indicates unexecuted time`}>
+ <rect x={x(recordedUntil)} y="35" width={Math.max(0,x(end)-x(recordedUntil))} height="185" fill="#f0f2f5"/>
+ {#each planned as event}<line x1={x(event.t)} x2={x(event.t)} y1="35" y2="220" stroke={event.kind==='fault'||event.kind==='recovery'?'#d68a25':'#b7bfcc'} stroke-width="0.7" stroke-dasharray="2 6"><title>{event.t.toFixed(1)}s · {event.label}</title></line>{/each}
+ {#each [0,.5,1] as fraction}<line x1="48" x2={plotWidth-16} y1={y(maximum*fraction)} y2={y(maximum*fraction)} stroke="#e9edf3"/><text x="37" y={y(maximum*fraction)+4} text-anchor="end">{(maximum*fraction).toFixed(metric==='tps'?1:0)}</text>{/each}
+ {#if metric==='connectorTps'}{#each connectorLines as connector}<path d={line(connector.points,end,maximum,span)} fill="none" stroke={connector.color} stroke-width="1.2"><title>{connector.name}</title></path>{/each}{:else if valid.length}<path d={`${measuredPath} L${x(valid.at(-1).t)},220 L${x(measuredValues[0].t)},220 Z`} fill="#0561e20a"/><path d={measuredPath} fill="none" stroke="#0561e2" stroke-width="1.1"><title>{metric==='tps'?'Successfully completed flows per second':choices[metric]}</title></path>{/if}
+ {#if offered.some(p=>p.value!=null)}<path d={offeredPath} fill="none" stroke="#98a2b3" stroke-width="0.8" stroke-dasharray="4 4"><title>Target flow rate</title></path>{/if}
+ {#each markers as event}<line x1={x(event.t)} x2={x(event.t)} y1="28" y2="220" stroke={markerColor(event)} stroke-dasharray={event.kind==='failover_requested'?'4 3':undefined} stroke-width="0.8"><title>{event.t.toFixed(1)}s · {event.message}</title></line><circle cx={x(event.t)} cy="25" r="2.3" fill={markerColor(event)}><title>{event.t.toFixed(1)}s · {event.message}</title></circle>{/each}
+ {#if hover}<line x1={x(hover.t)} x2={x(hover.t)} y1="35" y2="220" stroke="#8793a5" stroke-width=".7" stroke-dasharray="3 3"/>{#if hoveredValue!=null}<circle cx={x(hoveredSample.t)} cy={y(hoveredValue)} r="2.5" fill="#0561e2"/>{/if}{/if}
+ {#if hover}<text class="hover-seconds" x={Math.max(78,Math.min(plotWidth-46,x(hover.t)))} y="243" text-anchor="middle">{hover.t.toFixed(1)}s</text>{:else}<text x="48" y="243">0s</text><text x={48+span/2} y="243" text-anchor="middle">{Math.round(end/2)}s</text><text x={plotWidth-16} y="243" text-anchor="end">{Math.round(end)}s</text>{/if}
+ {#if !valid.length}<text x={48+span/2} y="130" text-anchor="middle">{rawSamples.length?'No metric samples yet':'Not run yet'}</text>{/if}
+ </svg>
+ {#if hover}<div class="chart-tooltip" style:left={`${hover.left}px`} style:top={`${hover.top}px`}>
+ <strong>{hover.t.toFixed(1)}s <span>{hoveredSample?hoveredPhase?.label||'Load': 'Not run yet'}</span></strong>
+ {#if hoveredSample&&metric==='connectorTps'}{#each connectorLines as connector}<div style:color={connector.color}>{connector.name} <b>{(hoveredSample.connectors?.[connector.name]?.tps??0).toFixed(2)} / s</b></div>{/each}{:else if hoveredSample}<div>{choices[metric]} <b>{formatValue(hoveredValue)}</b></div>{#if metric==='tps'&&flow==='all'&&hoveredTarget!=null}<div>Target <b>{hoveredTarget.toFixed(1)} TPS</b></div>{/if}{/if}
+ {#if hoveredEvent}<p>{hoveredEvent.message} · {hoveredEvent.t.toFixed(1)}s</p>{/if}
+ </div>{/if}
+ </div>
+</section>
+<style>
+.connector-legend{display:flex;gap:16px;flex-wrap:wrap;font-size:12px;padding:0 20px 12px;}
+.chart-filters[hidden],.plot[hidden]{display:none}
+
+.chart{background:var(--surface);border:1px solid var(--border);border-radius:var(--radius);padding:20px;margin:0 0 16px}.chart-head{display:flex;align-items:center;justify-content:space-between;gap:16px}.chart-head h2{font-size:14px;margin:0}.chart-filters{display:flex;justify-content:flex-end;gap:8px;margin-top:12px}.chart-filters select{width:180px;min-height:34px;margin:0;font-size:12px;border-color:transparent;background-color:transparent;box-shadow:none;padding-left:8px}.plot{position:relative;margin:4px 0 0}svg{display:block;width:100%;height:255px}text{fill:var(--subtle);font-size:11px;font-family:inherit}
+@media(max-width:600px){.chart{padding:16px}.chart-head{align-items:flex-start;flex-wrap:wrap;gap:12px}.chart-head .actions{margin-left:auto}.chart-filters{width:100%}.chart-filters select{width:50%;flex:1;min-width:0}svg{height:230px}}
+
+.timeline-run-toolbar{flex-direction:row;justify-content:flex-start;align-items:center;flex-wrap:wrap;gap:12px 20px;border:0;border-bottom:1px solid var(--border);padding:12px 0 16px;margin:0 0 12px;border-radius:0;background:none}.chart-head .actions{display:flex;justify-content:flex-end;flex-wrap:wrap;margin:0 0 0 auto}.stop-notice{font-size:12px;color:var(--muted);margin:0 0 12px}
+.hover-seconds{fill:var(--ink);font-weight:500}
+.chart-tooltip{position:absolute;pointer-events:none;width:220px;padding:10px 12px;background:var(--surface);border:1px solid var(--border);border-radius:6px;box-shadow:0 3px 12px #18253b14;font-size:11px;z-index:2}.chart-tooltip strong{display:flex;justify-content:space-between;gap:8px;margin-bottom:7px;font-size:12px}.chart-tooltip strong span{font-weight:400;color:var(--muted)}.chart-tooltip div{display:flex;justify-content:space-between;gap:10px;line-height:1.8;color:var(--muted)}.chart-tooltip b{font-weight:500;color:var(--ink)}.chart-tooltip p{margin:6px 0 0;line-height:1.4}
+</style>
diff --git a/loadtest/console/src/MetricsView.svelte b/loadtest/console/src/MetricsView.svelte
new file mode 100644
index 0000000000..5e06ec2125
--- /dev/null
+++ b/loadtest/console/src/MetricsView.svelte
@@ -0,0 +1,19 @@
+<script>
+import GrafanaMetrics from './GrafanaMetrics.svelte';
+export let value='native';
+export let run;
+export let grafana;
+</script>
+<div class="metrics-switch" class:grafana-selected={value==='grafana'} role="group" aria-label="Metrics source">
+ <button type="button" class:active={value==='native'} aria-pressed={value==='native'} onclick={()=>value='native'}>Native</button>
+ <button type="button" class:active={value==='grafana'} aria-pressed={value==='grafana'} onclick={()=>value='grafana'}>Grafana</button>
+</div>
+{#if value==='native'}<slot/>{:else}<GrafanaMetrics {run} {grafana}/>{/if}
+<style>
+.metrics-switch{position:relative;display:grid;grid-template-columns:repeat(2,1fr);width:max-content;margin:0 0 16px auto;padding:3px;border-radius:9px;background:var(--surface-muted);box-shadow:inset 0 0 0 1px var(--border);gap:2px;isolation:isolate}
+.metrics-switch::before{content:'';position:absolute;z-index:-1;top:3px;bottom:3px;left:3px;width:calc((100% - 8px)/2);border-radius:6px;background:var(--surface);box-shadow:inset 0 0 0 1px var(--border-strong),0 1px 2px #18263b08;transition:transform 220ms cubic-bezier(.2,.8,.2,1)}
+.metrics-switch.grafana-selected::before{transform:translateX(calc(100% + 2px))}
+.metrics-switch button{--button-bg:transparent;--button-fg:var(--muted);--button-border:transparent;--button-hover-bg:transparent;--button-hover-fg:var(--ink);--button-hover-border:transparent;min-width:82px;min-height:30px;padding:6px 16px;font-size:12px;font-weight:550;border-radius:6px;transition:color 160ms ease}
+.metrics-switch button.active{--button-fg:var(--accent);--button-hover-fg:var(--accent-hover)}
+@media(prefers-reduced-motion:reduce){.metrics-switch::before,.metrics-switch button{transition:none}}
+</style>
diff --git a/loadtest/console/src/PaymentChart.svelte b/loadtest/console/src/PaymentChart.svelte
new file mode 100644
index 0000000000..b4b72591c3
--- /dev/null
+++ b/loadtest/console/src/PaymentChart.svelte
@@ -0,0 +1,71 @@
+<script>
+import Icon from './Icon.svelte';
+import {onMount} from 'svelte';
+import {page} from '$app/stores';
+import {api} from './api.js';
+import {setQuery} from './navigation.mjs';
+import ResponseBrowser from './ResponseBrowser.svelte';
+import {executionPhases} from './chart-timeline.mjs';
+export let run;export let revision=0;export let running=false;
+/** @type {any} */ export let result=null;
+let data=null,listing=null,error='',busy=false,request=0,mounted=false,measured=false,root,width=900,observer,timer,hover=null,hoverCursor=0,brush=null,drawer,selected=null,detailBusy=false;
+let filter=$page.url.searchParams.get('outcome')||'all',from=Number($page.url.searchParams.get('from')||0),to=$page.url.searchParams.has('to')?Number($page.url.searchParams.get('to')):null,stack=[{}],search='',knownRevision=revision;
+const labels={match:'Status matched',missing:'ID not found',mismatch:'Status mismatch',pending:'Not compared',creation_unknown:'Creation unverified',confirmation_failed:'Confirmation failed'};
+$: plotWidth=Math.max(260,width);
+$: plotRight=plotWidth-12;
+$: plotSpan=plotRight-40;
+$: visibleKeys=['all','confirmation_failed'].includes(filter)?['match','missing','mismatch','pending','creation_unknown']:filter==='discrepancies'?['missing','mismatch','creation_unknown']:[filter];
+$: maximum=Math.max(1,...(data?.mode==='buckets'?data.rows.map(row=>visibleKeys.reduce((sum,k)=>sum+(row[k]||0),0)):[1]));
+$: phases=executionPhases(run.timeline||[],run.telemetry||[],run.activity||[],run.startedAt,data?.duration/1000||0);
+$: visiblePhases=phases.map(phase=>({...phase,from:Math.max(data?.from||0,phase.start*1000),to:Math.min(data?.to||0,phase.end*1000)})).filter(phase=>phase.to>phase.from);
+const phaseAt=ms=>phases.find(phase=>ms>=phase.start*1000&&ms<phase.end*1000)?.label||'';
+const countLabel=(label,count)=>count==null?label:`${label} · ${count.toLocaleString()}`;
+$: exportUrl=`/api/runs/${encodeURIComponent(run.id)}/export?${new URLSearchParams({kind:'payments',filter,from:String(from),...(to==null?{}:{to:String(to)}),search})}`;
+$: if(mounted&&revision!==knownRevision){knownRevision=revision;if(!running)load(false);}
+const time=ms=>`${(ms/1000).toFixed(ms%1000?1:0)}s`;
+const x=ms=>40+(ms-data.from)/(data.to-data.from)*plotSpan;
+function sync(){setQuery({outcome:filter==='all'?null:filter,from:from||null,to});}
+async function load(reset=true){if(!mounted||!measured)return;const token=++request;busy=true;error='';if(reset)stack=[{}];try{const options={view:'timeline',from,...(to==null?{}:{to}),filter,bars:Math.max(50,Math.min(600,Math.floor(width/5)))};const next=await api.paymentBars(run.id,options);if(token!==request)return;data=next;hover=null;if(!next.legacy&&!next.preparing)listing=await api.paymentPage(run.id,{from,...(to==null?{}:{to}),filter,search,...stack.at(-1)});}catch(e){if(token===request)error=running?'Preparing payment view…':e.message;}finally{if(token===request)busy=false;}}
+function change(){hover=null;sync();load();}
+function zoom(a,b){from=Math.max(0,Math.floor(a));to=Math.max(from+1,Math.min(data.duration,Math.ceil(b)));change();}
+function reset(){from=0;to=null;change();}
+async function nextError(){try{const row=await api.nextDiscrepancy(run.id,to==null?from:to);if(!row){error='No later discrepancies. Reset the view to start again.';return;}filter='discrepancies';zoom(Math.max(0,row.elapsed_ms-100),row.elapsed_ms+101);}catch(e){error=e.message;}}
+function pointer(event){const rect=event.currentTarget.getBoundingClientRect();return Math.max(data.from,Math.min(data.to,data.from+((event.clientX-rect.left)/rect.width*plotWidth-40)/plotSpan*(data.to-data.from)));}
+function inspect(event){if(!data||data.legacy||data.preparing)return;const at=pointer(event);hoverCursor=at;hover=data.mode==='buckets'?data.rows.find(row=>at>=row.from&&at<row.to):data.rows[Math.max(0,Math.min(data.rows.length-1,Math.floor((at-data.from)/(data.to-data.from)*data.rows.length)))];}
+const equalsPrimary=event=>event.button===0;
+function brushEnd(event){if(data?.mode==='payments'){if(equalsPrimary(event)&&hover)openPayment(hover);return;}if(brush==null)return;const end=pointer(event),begin=brush;brush=null;if(Math.abs(end-begin)>(data.to-data.from)*.015)zoom(Math.min(begin,end),Math.max(begin,end));else if(hover){if(data.mode==='payments')openPayment(hover);else zoom(hover.from,hover.to);}}
+async function openPayment(row){selected=row;drawer.showModal();detailBusy=true;try{selected=await api.paymentDetail(run.id,{rowId:row.id,payment:row.payment_id,merchant:row.merchant_id});}catch(e){error=e.message;}finally{detailBusy=false;}}
+async function pageList(next){stack=next?[...stack,listing.next]:stack.slice(0,-1);load(false);}
+onMount(()=>{mounted=true;observer=new ResizeObserver(entries=>{width=entries[0].contentRect.width;if(!measured){measured=true;load();}});observer.observe(root);timer=setInterval(()=>{if(measured&&running&&!busy)load(false);},2000);return()=>{mounted=false;request++;observer.disconnect();clearInterval(timer);};});
+</script>
+<section bind:this={root} class="payment-chart" aria-label="Payment reconciliation">
+<div class="toolbar"><label>Show<select bind:value={filter} onchange={change}><option value="all">All outcomes</option><option value="match">{countLabel('Status matched',data?.totals?.match)}</option><option value="discrepancies">Needs attention</option><option value="creation_unknown">{countLabel('Creation unverified',data?.totals?.creation_unknown)}</option><option value="confirmation_failed">{countLabel('Confirmation failed',result?.confirmationFailed)}</option><option value="missing">{countLabel('ID not found',data?.totals?.missing)}</option><option value="mismatch">{countLabel('Status mismatch',data?.totals?.mismatch)}</option><option value="pending">{countLabel('Not compared',data?.totals?.pending)}</option></select></label><div class="actions">{#if data?.totals?.missing||data?.totals?.mismatch||data?.totals?.creation_unknown}<button class="quiet" disabled={busy} onclick={nextError}>Next issue</button>{/if}{#if from||to!=null}<button class="quiet" onclick={reset}>Full timeline</button>{/if}</div></div>
+{#if error}<p class="invalid" role="alert">{error}<button class="quiet" onclick={()=>load()}>Retry</button></p>{/if}
+{#if data?.legacy}<p>Payment bars are unavailable for this earlier run.</p>
+{:else if data?.preparing}<p role="status">Preparing payment view…</p>
+{:else if data}
+<div class="plot" aria-busy={busy}>
+<svg viewBox={`0 0 ${plotWidth} 260`} role="img" aria-label="Recorded outcomes over elapsed time, with hold, ramp and verified outage periods. Green: status matched; red: status discrepancies; amber: creation unverified; grey: not compared. Drag to zoom." onpointermove={inspect} onpointerleave={()=>{if(brush==null)hover=null;}} onpointerdown={e=>{inspect(e);if(e.button===0&&data.mode==='buckets'){brush=pointer(e);e.currentTarget.setPointerCapture(e.pointerId);}}} onpointerup={brushEnd} onpointercancel={()=>brush=null}>
+{#each visiblePhases as phase}<g><title>{phase.label} · {time(phase.start*1000)}–{time(phase.end*1000)}{phase.kind==='outage'?' · verified interruption through recovery':''}</title><rect x={x(phase.from)} y="35" width={x(phase.to)-x(phase.from)} height="185" fill={phase.kind==='outage'?'#c43b3608':phase.kind==='ramp'?'#0561e205':'transparent'}/><rect x={x(phase.from)} y="13" width={Math.max(0,x(phase.to)-x(phase.from)-1)} height="15" rx="2" fill={phase.kind==='outage'?'#fbe5e3':phase.kind==='ramp'?'#e7effb':'#f0f2f5'}/>{#if x(phase.to)-x(phase.from)>phase.label.length*4.5+2}<text class="phase-label" x={(x(phase.from)+x(phase.to))/2} y="24" text-anchor="middle">{phase.label}</text>{/if}</g>{/each}
+{#each (data.mode==='payments'?[0,1]:[0,.5,1]) as fraction}<line x1="40" x2={plotRight} y1={220-fraction*185} y2={220-fraction*185} stroke="#e7ebf2"/><text x="33" y={224-fraction*185} text-anchor="end">{Math.round(maximum*fraction).toLocaleString()}</text>{/each}
+{#each data.rows as row,index}
+{#if data.mode==='payments'}<rect x={40+(index+.5)/data.rows.length*plotSpan-Math.min(12,Math.max(.5,plotSpan/data.rows.length-1))/2} y="35" width={Math.min(12,Math.max(.5,plotSpan/data.rows.length-1))} height="185" fill={row.outcome==='match'?'#398453':row.outcome==='pending'?'#a5adba':'#c43b36'}/>
+{:else}{@const green=visibleKeys.includes('match')?row.match:0}{@const red=(visibleKeys.includes('missing')?row.missing:0)+(visibleKeys.includes('mismatch')?row.mismatch:0)}{@const amber=visibleKeys.includes('creation_unknown')?row.creation_unknown||0:0}{@const grey=visibleKeys.includes('pending')?row.pending:0}{@const barWidth=Math.max(.5,x(row.to)-x(row.from)-1)}
+<rect x={x(row.from)} y={220-green/maximum*185} width={barWidth} height={green/maximum*185} fill="#398453"/>
+<rect x={x(row.from)} y={220-(green+red)/maximum*185} width={barWidth} height={red/maximum*185} fill="#c43b36"/>
+<rect x={x(row.from)} y={220-(green+red+amber)/maximum*185} width={barWidth} height={amber/maximum*185} fill="#d68a25"/>
+<rect x={x(row.from)} y={220-(green+red+amber+grey)/maximum*185} width={barWidth} height={grey/maximum*185} fill="#a5adba"/>
+{/if}{/each}
+{#if brush!=null&&hover}<rect x={x(Math.min(brush,hover.from??hover.elapsed_ms))} y="28" width={Math.abs(x(hover.to??hover.elapsed_ms)-x(brush))} height="192" fill="#0561e222"/>{/if}
+{#if hover}<line x1={x(hoverCursor)} x2={x(hoverCursor)} y1="28" y2="220" stroke="#8793a5" stroke-width=".7" stroke-dasharray="3 3"/><text class="hover-seconds" x={Math.max(70,Math.min(plotRight-30,x(hoverCursor)))} y="245" text-anchor="middle">{time(data.mode==='payments'?hover.elapsed_ms:hoverCursor)}</text>{:else}
+<text x="40" y="245">{data.mode==='payments'?'Payment 1':time(data.from)}</text><text x={plotRight} y="245" text-anchor="end">{data.mode==='payments'?`Payment ${data.rows.length.toLocaleString()}`:time(data.to)}</text>{/if}
+{#if !data.rows.length}<text x={plotWidth/2} y="125" text-anchor="middle">No payments in this view</text>{/if}
+</svg>
+<div class="tooltip" role="status">{#if hover}{#if data.mode==='payments'}<strong>{time(hover.elapsed_ms)}</strong><span>{labels[hover.outcome]}</span><span>{hover.payment_id}</span>{:else}<strong>{time(hover.from)}–{time(hover.to)}</strong><span>{phaseAt(hover.from)} · {hover.match.toLocaleString()} matched · {(hover.missing+hover.mismatch).toLocaleString()} status differences{hover.creation_unknown?` · ${hover.creation_unknown} creation unverified`:''}{hover.pending?` · ${hover.pending} pending`:''}</span>{/if}{:else}<span>Hover to inspect · drag to zoom</span>{/if}</div>
+</div>
+<details class="payment-list"><summary>Inspect payments and failed attempts</summary><div class="list-head"><form onsubmit={e=>{e.preventDefault();load();}}><input aria-label="Search payments" placeholder="Payment or merchant ID" bind:value={search}/><button class="secondary" disabled={busy}>Search</button></form><a class="quiet" href={exportUrl} download>Export CSV</a></div>
+{#if listing}<div class="table-wrap"><table><thead><tr><th>Time / payment or attempt</th><th>Client / database status</th><th>Outcome</th></tr></thead><tbody>{#each listing.rows as row}<tr><td><button class="quiet payment-link" onclick={()=>openPayment(row)}>{row.payment_id||`Create attempt #${row.event_id}`}</button><small>{time(row.elapsed_ms)} · {row.merchant_id}</small></td><td>{row.recorded_status||'—'} / {row.database_status||'—'}{#if row.failure_category}<small>{row.api_status_code||'Timeout / transport error'} · {row.message||row.operation}</small>{/if}</td><td>{labels[row.outcome]}{#if row.failure_category==='confirmation_failed'}<small>Confirmation failed</small>{/if}</td></tr>{:else}<tr><td colspan="3">No outcomes match.</td></tr>{/each}</tbody></table></div><div class="actions"><button class="secondary" disabled={busy||stack.length===1} onclick={()=>pageList(false)}>Previous</button><small>Page {stack.length}</small><button class="secondary" disabled={busy||!listing.next} onclick={()=>pageList(true)}>Next</button></div>{/if}</details>
+{:else}<p role="status">{busy?'Loading payment outcomes…':'Compare recorded payments to display outcomes.'}</p>{/if}
+</section>
+<dialog class="payment-drawer" bind:this={drawer} aria-label="Payment details"><div class="section-head"><h2>{selected?.payment_id?'Payment details':'Failed create attempt'}</h2><button class="icon-button" aria-label="Close payment details" onclick={()=>drawer.close()}><Icon name="close"/></button></div>{#if selected}<p>{selected.payment_id||`Attempt #${selected.event_id}`}<br/><small>{selected.merchant_id} · {time(selected.elapsed_ms)}</small></p><div class="detail-status"><span>Recorded <strong>{selected.recorded_status||'—'}</strong></span><span>Database <strong>{selected.database_status||'—'}</strong></span><span>{labels[selected.outcome]}{#if selected.failure_category==='confirmation_failed'}<strong>Confirmation failed · {selected.api_status_code||'transport error'}</strong>{/if}</span></div>{#if !selected.payment_id}<p>No payment ID was returned. This response cannot establish whether the application created a payment.</p>{/if}{#if detailBusy}<p>Loading…</p>{:else}{#key selected.id}<ResponseBrowser runId={run.id} payment={selected.payment_id} merchant={selected.merchant_id} event={selected.payment_id?'':String(selected.event_id)}/>{/key}{/if}{/if}</dialog>
+<style>.toolbar,.toolbar label,.list-head,.list-head form{display:flex;align-items:center;gap:12px;flex-wrap:wrap}.toolbar{justify-content:space-between}.toolbar label{font-size:12px}.toolbar select{width:220px;min-height:34px;margin:0}.toolbar .actions{margin:0}.plot{margin-top:10px}svg{display:block;width:100%;height:260px;touch-action:none;user-select:none}text{font-size:11px;fill:#8793a5}.tooltip{min-height:32px;font-size:12px;display:flex;gap:12px;align-items:center;flex-wrap:wrap;color:#344054;background:#f7f9fc;padding:8px 12px;border-radius:8px;overflow-wrap:anywhere}small{font-size:11px;color:#667085}.hover-seconds{fill:var(--ink);font-weight:500}.phase-label{fill:#667085;font-size:9px}.payment-list{margin-top:20px;padding-top:18px;border-top:1px solid var(--border)}.payment-list summary{cursor:pointer;font-size:13px;font-weight:600}.list-head{margin:12px 0;justify-content:space-between}.list-head input{width:220px;margin:0}.list-head a{font-size:12px}.payment-link{white-space:normal;padding-left:0;font-size:12px;overflow-wrap:anywhere;text-align:left}td{font-size:12px}td small{display:block}.payment-drawer{margin:0 0 0 auto;height:100dvh;max-height:100dvh;width:min(800px,95vw);max-width:none;border-radius:14px 0 0 14px;padding:24px;overflow:auto}.detail-status{display:flex;gap:24px;flex-wrap:wrap;font-size:12px;margin:20px 0}.detail-status strong{display:block}@media(max-width:600px){.toolbar{gap:0}.toolbar .actions{flex-wrap:wrap}.payment-drawer{padding:16px}}</style>
diff --git a/loadtest/console/src/ProfileEditor.svelte b/loadtest/console/src/ProfileEditor.svelte
new file mode 100644
index 0000000000..57ab81a403
--- /dev/null
+++ b/loadtest/console/src/ProfileEditor.svelte
@@ -0,0 +1,49 @@
+<script>
+import Icon from './Icon.svelte';
+import ConnectorMix from './ConnectorMix.svelte';
+import {defaultConnectorPlan,connectorPlanError} from './connector-config.mjs';
+import {environmentLabel} from './environments.mjs';
+import {onMount} from 'svelte';import UnsavedChanges from './UnsavedChanges.svelte';import {beforeNavigate,goto} from '$app/navigation';
+import FaultSettings from './FaultSettings.svelte';
+import {api} from './api.js';import RampEditor from './RampEditor.svelte';import FlowMix from './FlowMix.svelte';import {profileSummary} from './flow-catalog.mjs';import {loadShape} from './load-shape.mjs';
+export let profile;export let creating=false;
+let environment='local';
+let draft=structuredClone(profile),baseline,pending=false,error='',notice='',rampValid=true,targets=[],sharedTargets=[],targetBaseline='',targetsLoaded=false,leaveDialog,allowLeave=false,editorForm,flowMixOpen=false,tenancyCount=profile.mode==='tenancy'?profile.merchantCount:1500;
+async function refreshTargets(){try{const [status,saved]=await Promise.all([api.faults(),api.faultTargets()]);environment=status.environment;targets=status.targets;if(!targetsLoaded){sharedTargets=saved;targetBaseline=JSON.stringify(saved);targetsLoaded=true;}}catch(e){error=e.message;}}
+$: faultDirty=targetsLoaded&&JSON.stringify(sharedTargets)!==targetBaseline;
+$: availableTargets=[...targets.filter(t=>!sharedTargets.some(s=>s.id===t.id)&&!JSON.parse(targetBaseline||'[]').some(s=>s.id===t.id)),...sharedTargets.map(t=>({...t,actions:t.actions||[]}))];
+draft.connectors ||=defaultConnectorPlan();
+if(creating){draft.name='New scenario';delete draft.id;delete draft.version;}baseline=creating?'':JSON.stringify(draft);
+$: dirty=JSON.stringify(draft)!==baseline||faultDirty;
+$: saveAsNew=!creating&&profile.isDefault&&draft.id===profile.id;
+$: summary=(()=>{if(draft.loadShape!=='staged')return profileSummary(draft);try{const shape=loadShape({start_rps:Number(draft.startRps),stages:JSON.parse(draft.stagesJson)});return profileSummary({...draft,totalRps:shape.peak,durationSeconds:shape.duration});}catch{return 'Configure valid load stages';}})();
+$: allocated=draft.scenarios.reduce((sum,flow)=>sum+Number(flow.weight||0),0);
+$: if(allocated!==100)flowMixOpen=true;
+$: merchantValid=draft.mode==='single'?Number(draft.merchantCount)===1:Number.isInteger(Number(draft.merchantCount))&&Number(draft.merchantCount)>=2&&Number(draft.merchantCount)<=1500;
+$: canSave=!connectorPlanError(draft.connectors)&&draft.name.trim().length>0&&merchantValid&&allocated===100&&draft.scenarios.every(flow=>Number.isFinite(flow.weight)&&flow.weight>=0&&flow.weight<=100)&& (draft.loadShape!=='staged'||rampValid);
+function setMerchantMode(mode){if(draft.mode==='tenancy')tenancyCount=draft.merchantCount;draft.mode=mode;draft.merchantCount=mode==='single'?1:Number(tenancyCount)||1500;}
+beforeNavigate(navigation=>{if(allowLeave){allowLeave=false;return;}if(pending){navigation.cancel();return;}if(dirty&&navigation.to){navigation.cancel();leaveDialog.ask().then(leave=>{if(leave){allowLeave=true;if(navigation.to.url.origin===location.origin)goto(navigation.to.url,{replaceState:navigation.type==='popstate'});else location.href=navigation.to.url.href;}});}});
+onMount(()=>{refreshTargets();window.addEventListener('console-connections-saved',refreshTargets);const unload=e=>{if(dirty){e.preventDefault();e.returnValue='';}};window.addEventListener('beforeunload',unload);return()=>{window.removeEventListener('beforeunload',unload);window.removeEventListener('console-connections-saved',refreshTargets);};});
+async function save(){const invalid=editorForm?.querySelector(':invalid');if(invalid){for(let element=invalid.parentElement;element;element=element.parentElement)if(element.tagName==='DETAILS')element.open=true;invalid.focus();}if(!canSave||!targetsLoaded||!editorForm.reportValidity())return false;pending=true;error='';notice='';try{const result=await api.saveScenario({profile:draft,...(faultDirty?{targets:sharedTargets,expectedTargets:targetBaseline}:{})});draft=result.profile;sharedTargets=result.targets;targetBaseline=JSON.stringify(sharedTargets);baseline=JSON.stringify(draft);notice='Scenario saved';window.dispatchEvent(new Event('console-connections-saved'));return true;}catch(e){error=e.message;const area=editorForm.querySelector(e.message.match(/fault|vault|target|replica|controller/i)?'.fault-settings':'.basics');if(area?.tagName==='DETAILS')area.open=true;area?.scrollIntoView({block:'center',behavior:'smooth'});return false;}finally{pending=false;}}
+async function submit(){if(await save())await goto(`/scenarios?tab=scenarios&view=edit&profile=${encodeURIComponent(draft.id)}`,{replaceState:true,keepFocus:true,noScroll:true});}
+</script>
+<div class="section-head"><div><a class="quiet" href="/scenarios"><Icon name="back"/> Back to scenarios</a><h1>{creating?'New scenario':draft.name}</h1><p>{summary}</p></div></div>
+{#if error}<div class="message error" role="alert">{error}</div>{/if}
+<UnsavedChanges bind:this={leaveDialog} save={save}/>
+{#if saveAsNew}<p class="muted">Default scenario · Changes save as a new scenario.</p>{:else if creating}<p class="muted">Starting from: {profile.name}</p>{/if}
+<form bind:this={editorForm} onsubmit={e=>{e.preventDefault();submit();}}>
+<fieldset disabled={pending}>
+<div class="basics" class:staged={draft.loadShape==='staged'} class:multiple={draft.mode==='tenancy'}><label>Scenario name<input required maxlength="100" bind:value={draft.name}/></label><label>Merchant setup<select value={draft.mode} onchange={event=>setMerchantMode(event.currentTarget.value)}><option value="single">Single merchant</option><option value="tenancy">Multiple merchants</option></select></label>{#if draft.mode==='tenancy'}<label>Number of merchants<input required type="number" min="2" max="1500" bind:value={draft.merchantCount}/></label>{/if}{#if draft.loadShape==='flat'}<label>Offered TPS<input required type="number" min="1" bind:value={draft.totalRps}/></label><label>Duration · seconds<input required type="number" min="1" bind:value={draft.durationSeconds}/></label>{/if}</div>
+<div class="shape"><label>Load shape<select bind:value={draft.loadShape}><option value="flat">Constant TPS</option><option value="staged">Timeline · Hold, Ramp, Fault</option></select></label></div>
+{#if draft.loadShape==='staged'}<RampEditor targets={availableTargets} bind:startRps={draft.startRps} bind:stagesJson={draft.stagesJson} bind:valid={rampValid}/>{/if}
+<details class="editor-section flow-section" bind:open={flowMixOpen}><summary>Flow mix <span>{draft.scenarios.length} flows · {allocated}% allocated</span></summary><FlowMix bind:flows={draft.scenarios} disabled={pending}/></details>
+<details class="editor-section"><summary>Connectors <span>{draft.connectors.mode==='dummy'?'Dummy':`${draft.connectors.mix.length} sandbox connectors`}</span></summary><ConnectorMix bind:value={draft.connectors}/></details>
+<details class="advanced"><summary>Advanced <span>Acceptance thresholds</span></summary><div class="fields"><label>Minimum success ratio<input required type="number" min="0" max="1" step="0.01" bind:value={draft.acceptance.minimumSuccessRatio}/></label><label>Maximum HTTP errors · %<input required type="number" min="0" max="100" bind:value={draft.acceptance.maximumErrorPercent}/></label><label>Maximum client-side latency · ms<input required type="number" min="0" bind:value={draft.acceptance.maximumConfirmP99Ms}/></label><label>Maximum dropped flows<input required type="number" min="0" bind:value={draft.acceptance.maximumDropped}/></label></div></details>
+</fieldset>
+<details class="advanced fault-settings"><summary>Fault targets <span>{sharedTargets.length} configured · {environmentLabel(environment)}</span></summary><p class="muted">Target changes save with this scenario. Existing runs keep their snapshots.</p>{#if targetsLoaded}<FaultSettings {environment} bind:targets={sharedTargets} baseline={targetBaseline}/>{:else}<p role="status">Loading targets…</p>{/if}</details>
+<div class="flow-footer editor-save"><span class="save-status" role="status">{pending?'Saving…':dirty?(faultDirty?'Unsaved scenario / shared-target changes':'Unsaved changes'):notice || (saveAsNew?'Default scenario':`Saved · version ${draft.version}`)}</span><div class="actions"><button type="submit" disabled={pending||!dirty||!canSave||!targetsLoaded}>{#if !pending}<Icon name="check"/>{/if}{pending?'Saving…':saveAsNew?'Save as new scenario':'Save scenario'}</button></div></div>
+{#if error}<p class="invalid" role="alert">{error}</p>{/if}{#if !canSave}<p class="invalid" role="status">{!draft.name.trim()?'Enter a scenario name.':!merchantValid?'Choose between 2 and 1,500 merchants.':allocated!==100?`Flow weights must total 100% (${allocated}% allocated).`:'Review the highlighted flow or timeline fields.'}</p>{/if}
+</form>
+<style>
+.editor-save{position:sticky;bottom:0;z-index:20;padding:16px 0;background:#f6f8fbf2;border-top:1px solid var(--border);backdrop-filter:blur(8px);margin-top:24px}.editor-save .save-status{color:var(--muted)}fieldset{border:0;padding:0;margin:0;min-width:0}.section-head h1{margin-top:12px}.section-head a{display:inline-flex;align-items:center;gap:7px;font-size:12px}.basics{display:grid;grid-template-columns:1.5fr 1fr .7fr .7fr;gap:18px;background:var(--surface);border:1px solid var(--border);border-radius:var(--radius);padding:20px}.basics.multiple{grid-template-columns:1.5fr 1fr .8fr .7fr .7fr}.basics.staged{grid-template-columns:1.5fr 1fr}.basics.staged.multiple{grid-template-columns:1.5fr 1fr .8fr}.shape{margin:20px 0 16px}.shape label{max-width:240px}.shape select{font-size:12px}.editor-section{margin:16px 0;background:var(--surface);border:1px solid var(--border);border-radius:var(--radius);padding:16px 20px}.flow-section{width:min(100%,820px)}.editor-section summary>span,.advanced summary>span{margin-left:auto;font-size:11px;font-weight:400;color:var(--muted);text-align:right}.editor-section :global(.mix){border:0;padding:0;margin:14px 0 0;box-shadow:none}.editor-section :global(.mix .section-head h2),.editor-section :global(.mix .section-head p){display:none}.editor-section :global(.mix .section-head){justify-content:flex-start;margin-bottom:10px}.editor-section :global(.mix .section-head button){margin-left:0}.advanced{margin-top:14px}.fault-settings>p{max-width:620px;margin:0 0 16px;font-size:12px}@media(max-width:1000px){.basics,.basics.multiple{grid-template-columns:1fr 1fr}}@media(max-width:480px){.basics,.basics.staged,.basics.multiple,.basics.staged.multiple{grid-template-columns:1fr;padding:18px}.editor-save{padding:12px 0}.editor-save .save-status{font-size:11px}.editor-section summary,.advanced summary{flex-wrap:wrap}.editor-section summary>span,.advanced summary>span{margin-left:20px;text-align:left}}
+</style>
diff --git a/loadtest/console/src/RampEditor.svelte b/loadtest/console/src/RampEditor.svelte
new file mode 100644
index 0000000000..6a06d4e637
--- /dev/null
+++ b/loadtest/console/src/RampEditor.svelte
@@ -0,0 +1,68 @@
+<script>
+import {faultTargetLabel} from './fault-types.mjs';
+import Icon from './Icon.svelte';
+import {flip} from 'svelte/animate';
+import {onMount} from 'svelte';
+import {decodeStages,encodeStages,rampPoints,stageRates} from './ramp-editor.mjs';
+import {loadShape} from './load-shape.mjs';
+export let startRps=0;export let stagesJson='[]';export let valid=true;export let targets=[];
+let sequence=0;
+const identify=row=>row._uiId?row:{...row,_uiId:`stage-${++sequence}`};
+let rows;try{rows=decodeStages(stagesJson,startRps).map(identify);}catch{rows=[];}
+let validation='',advanced='',importMessage='',dragged='',dragPointer=null,editor,dragBefore=null,undo=null,lastPointer=null,selectedStage='',editingStage='',dragCandidate=null,suppressStageClick=false,plotWidth=800;
+const durationLabel=value=>{const seconds=Number(value)||0;if(seconds<60)return `${seconds} sec`;const minutes=seconds/60;return `${Number.isInteger(minutes)?minutes:Number(minutes.toFixed(1))} ${minutes===1?'min':'mins'}`;};
+$: starts=rows.map((_,i)=>rows.slice(0,i).reduce((n,row)=>n+Number(row.duration||0),0));
+function sync(){try{for(const row of rows){if(row.kind==='fault'){const actions=targets.find(target=>target.id===row.fault?.targetId)?.actions;if(actions?.length===1)row.fault.action=actions[0];}}stagesJson=JSON.stringify(encodeStages(rows,startRps));validation='';valid=true;}catch(e){validation=e.message;valid=false;}}
+function move(i,offset){undo=structuredClone(rows);const next=[...rows];[next[i],next[i+offset]]=[next[i+offset],next[i]];rows=next;sync();}
+function add(kind){rows=[...rows,identify({kind,target:stageRates(rows,startRps).at(-1) ?? Number(startRps),duration:kind==='fault'?10:60,...(kind==='fault'?{fault:{targetId:targets[0]?.id||'',action:targets[0]?.actions[0]||'outage'}}:{})})];editingStage=rows.at(-1)._uiId;sync();}
+function dragStart(event,id){if(event.button!==0&&!(event.buttons&1))return;event.preventDefault();selectedStage=id;dragBefore=structuredClone(rows);dragged=id;dragPointer=event.pointerId;lastPointer={clientY:event.clientY,pointerId:event.pointerId,preventDefault:()=>{}};}
+function dragMove(event){if(dragCandidate&&event.pointerId===dragCandidate.pointerId&&Math.hypot(event.clientX-dragCandidate.x,event.clientY-dragCandidate.y)>6){const id=dragCandidate.id;dragCandidate=null;dragStart(event,id);suppressStageClick=true;}if(!dragged||event.pointerId!==dragPointer||!editor)return;event.preventDefault();lastPointer={clientY:event.clientY,pointerId:event.pointerId,preventDefault:()=>{}};const current=rows.findIndex(row=>row._uiId===dragged);const elements=[...editor.querySelectorAll('[data-stage-id]')];const target=elements.findIndex(element=>event.clientY<element.getBoundingClientRect().top+element.getBoundingClientRect().height/2);const insertion=target<0?rows.length:target,destination=Math.max(0,Math.min(rows.length-1,insertion-(current<insertion?1:0)));if(current<0||destination===current)return;const next=[...rows],item=next.splice(current,1)[0];next.splice(destination,0,item);rows=next;sync();}
+function dragEnd(event){dragCandidate=null;if(event?.pointerId!==undefined&&event.pointerId!==dragPointer)return;if(dragBefore)undo=dragBefore;dragBefore=null;dragged='';dragPointer=null;lastPointer=null;}
+function cancelDrag(event){if(event.key==='Escape'&&dragged){rows=dragBefore;dragBefore=null;dragEnd();sync();}}
+function prepareStageDrag(event,id){suppressStageClick=false;if(event.button===0)dragCandidate={id,x:event.clientX,y:event.clientY,pointerId:event.pointerId};}
+function toggleStage(id){if(suppressStageClick){suppressStageClick=false;return;}editingStage=editingStage===id?'':id;}
+function rowDrag(event,id){if(!event.target.closest('input,select,button,summary,a,label,details'))dragStart(event,id);}
+function keyboardMove(event,index){if(!event.altKey||!['ArrowUp','ArrowDown'].includes(event.key))return;event.preventDefault();const offset=event.key==='ArrowUp'?-1:1;if(index+offset>=0&&index+offset<rows.length)move(index,offset);}
+function importJson(){try{rows=decodeStages(advanced,startRps).map(identify);sync();if(validation)throw Error(validation);importMessage='Imported';}catch(e){validation=e.message;}}
+onMount(()=>{const observer=new ResizeObserver(entries=>plotWidth=Math.max(280,entries[0].contentRect.width));observer.observe(editor);const autoScroll=setInterval(()=>{if(!dragged||!lastPointer)return;const y=lastPointer.clientY,delta=y<155?-12:y>window.innerHeight-70?12:0;if(delta){window.scrollBy(0,delta);dragMove(lastPointer);}},16);window.addEventListener('keydown',cancelDrag);window.addEventListener('pointermove',dragMove,{passive:false});window.addEventListener('pointerup',dragEnd);window.addEventListener('pointercancel',dragEnd);window.addEventListener('blur',dragEnd);return()=>{observer.disconnect();clearInterval(autoScroll);window.removeEventListener('keydown',cancelDrag);window.removeEventListener('pointermove',dragMove);window.removeEventListener('pointerup',dragEnd);window.removeEventListener('pointercancel',dragEnd);window.removeEventListener('blur',dragEnd);};});
+$: startRps,targets,sync();
+$: rates=stageRates(rows,startRps);
+$: points=(()=>{try{return rampPoints(startRps,JSON.parse(stagesJson));}catch{return [];}})();
+$: shape=(()=>{try{return loadShape({start_rps:startRps,stages:JSON.parse(stagesJson)});}catch{return {duration:0,peak:0,average:0};}})();
+$: plotSpan=plotWidth-60;
+$: line=points.map(p=>`${30+(p.t/(shape.duration||1))*plotSpan},${130-(p.value/(shape.peak||1))*105}`).join(' ');
+</script>
+<section class="ramp-editor" bind:this={editor}>
+<div class="section-head"><div><h2>Timeline</h2><p>Offered flows per second · {shape.duration}s total · {shape.peak} TPS peak</p></div><label>Starting TPS<input type="number" min="0" bind:value={startRps}/></label></div>
+<svg viewBox={`0 0 ${plotWidth} 160`} role="img" aria-label="Offered TPS over active test time">{#each rows as row,i}{#if selectedStage===row._uiId}<rect x={30+starts[i]/(shape.duration||1)*plotSpan} y="20" width={Number(row.duration||0)/(shape.duration||1)*plotSpan} height="110" fill="#0561e212"/>{/if}{/each}<path d={`M30 20V130H${plotWidth-30}`} fill="none" stroke="#dfe3eb"/>{#each rows as row,i}{#if row.kind==='fault'}<line x1={30+(rows.slice(0,i).reduce((n,r)=>n+Number(r.duration),0)/(shape.duration||1))*plotSpan} x2={30+(rows.slice(0,i).reduce((n,r)=>n+Number(r.duration),0)/(shape.duration||1))*plotSpan} y1="20" y2="130" stroke="#bd5a20" stroke-dasharray="4 4"/>{/if}{/each}<polyline points={line} fill="none" stroke="#0066ff" stroke-width="2.5"/>{#each points as point}<circle cx={30+(point.t/(shape.duration||1))*plotSpan} cy={130-(point.value/(shape.peak||1))*105} r="3" fill="#0066ff"/>{/each}<text x="30" y="153">0s</text><text x={plotWidth-30} y="153" text-anchor="end">{shape.duration}s</text><text x="35" y="18">{shape.peak} TPS</text></svg>
+<div class="stage-list">
+{#each rows as row,i (row._uiId)}
+ <div animate:flip={{duration:180}} data-stage-id={row._uiId} role="group" aria-label={`Stage ${i+1}`} class="stage-row" onfocusin={()=>selectedStage=row._uiId} onpointerenter={()=>selectedStage=row._uiId} onpointerdown={event=>rowDrag(event,row._uiId)} class:expanded={editingStage===row._uiId} class:dragging={dragged===row._uiId}>
+ <button type="button" class="quiet drag-handle" aria-label={`Move stage ${i+1}. Drag or press Alt plus arrow keys.`} aria-pressed={dragged===row._uiId} onpointerdown={e=>dragStart(e,row._uiId)} onkeydown={e=>keyboardMove(e,i)}><Icon name="grip"/></button>
+ <span class="stage-number" aria-hidden="true">{i+1}</span>
+ <button type="button" class="quiet stage-summary" aria-expanded={editingStage===row._uiId} onpointerdown={e=>prepareStageDrag(e,row._uiId)} onclick={()=>toggleStage(row._uiId)}>
+ <span class="stage-symbol" class:fault={row.kind==='fault'}><Icon name={row.kind==='fault'?'bolt':row.kind==='ramp'?'performance':'clock'}/></span>
+ <span><strong>{row.kind==='fault'?`${targets.find(t=>t.id===row.fault?.targetId)?faultTargetLabel(targets.find(t=>t.id===row.fault?.targetId)): 'Choose fault target'} ${row.fault?.action==='failover'?'failover':'outage'}`:`${row.kind==='ramp'?'Ramp up to':'Hold'} ${rates[i]} TPS`}</strong><small>{durationLabel(row.duration)}</small></span>
+ <span class="edit-cue">{editingStage===row._uiId?'Close':'Edit'}</span>
+ </button>
+ <div class="row-actions"><button type="button" class="icon-button danger" aria-label={`Remove stage ${i+1}`} onclick={()=>{undo=structuredClone(rows);rows=rows.filter((_,n)=>n!==i);sync();}}><Icon name="close"/></button></div>
+ {#if editingStage===row._uiId}<div class="stage-fields">
+ <label>Stage<select bind:value={row.kind} onchange={()=>{if(row.kind==='fault')row.fault ||= {targetId:targets[0]?.id||'',action:targets[0]?.actions[0]||'outage'};sync();}}><option value="ramp">Ramp to</option><option value="hold">Hold</option><option value="fault">Fault</option></select></label>
+ {#if row.kind==='fault'}<label>Target<select bind:value={row.fault.targetId} onchange={()=>{row.fault.action=targets.find(t=>t.id===row.fault.targetId)?.actions[0]||'outage';sync();}}><option value="">Choose target</option>{#each targets as target}<option value={target.id}>{faultTargetLabel(target.target||target)}</option>{/each}</select></label><label>Action<select bind:value={row.fault.action} onchange={sync}>{#each targets.find(t=>t.id===row.fault.targetId)?.actions||[] as action}<option value={action}>{action==='failover'?'Failover':'Outage'}</option>{/each}</select></label>
+ {:else if row.kind==='ramp'}<label>Target TPS<input type="number" min="1" bind:value={row.target} oninput={sync}/></label>
+ {:else}<div class="hold-rate"><span>Hold TPS</span><strong>{rates[i]} TPS</strong><small>From {i===0?'starting TPS':'preceding stage'}</small></div>{/if}
+ <label>{row.kind==='fault'?(row.fault.action==='failover'?'Stage duration':'Downtime'):'Duration'} · seconds<input type="number" min="1" max={row.kind==='fault'?300:undefined} step="1" bind:value={row.duration} oninput={sync}/></label>
+ </div>{/if}
+ </div>
+{/each}
+</div>
+{#if validation}<p class="invalid" role="alert">{validation}</p>{/if}<div class="add-stages" role="group" aria-label="Add timeline stage"><button type="button" class="secondary" onclick={()=>add('ramp')}>+ Ramp</button><button type="button" class="secondary" onclick={()=>add('hold')}>+ Hold</button><button type="button" class="secondary" onclick={()=>add('fault')}>+ Fault</button></div>
+{#if undo}<button type="button" class="quiet" onclick={()=>{rows=undo;undo=null;sync();}}>Undo timeline change</button>{/if}<p class="timeline-hint">Faults keep traffic steady and recover automatically.</p>
+<details class="advanced"><summary>JSON import / export</summary><label>Current stages<textarea readonly rows="4" value={stagesJson}></textarea></label><label>Import stages<textarea rows="4" bind:value={advanced}></textarea></label><button type="button" class="secondary" onclick={importJson}>Import</button><span role="status">{importMessage}</span></details>
+</section>
+
+<style>
+.ramp-editor>svg{height:160px}.stage-list{margin-top:16px;border:1px solid var(--border);border-radius:8px;overflow:clip}.stage-row{display:grid;grid-template-columns:28px 24px minmax(0,1fr) auto;gap:10px;padding:10px 12px;border:0;border-bottom:1px solid var(--border);touch-action:pan-y;position:relative;cursor:grab;transition:background-color .14s}.stage-row:last-child{border-bottom:0}.stage-row.expanded{background:#f3f7fc}.stage-row.dragging{background:var(--accent-soft);box-shadow:0 4px 18px #18263b15;z-index:2;outline:1px solid var(--accent);opacity:.75}.drag-handle{width:28px;min-height:32px;padding:0;touch-action:none;user-select:none;cursor:grab}.drag-handle:active,.drag-handle[aria-pressed=true]{cursor:grabbing}.stage-number{align-self:center;color:var(--subtle);font-size:11px;font-weight:500;font-variant-numeric:tabular-nums;text-align:center}.stage-summary{touch-action:pan-y;user-select:none;justify-content:flex-start;text-align:left;padding:6px;min-width:0;white-space:normal}.stage-summary strong{display:block;font-size:12px;font-weight:550;color:var(--ink)}.stage-summary small{display:block;font-size:10px;font-weight:450;margin-top:4px;color:var(--muted)}.stage-symbol{display:flex;align-items:center;justify-content:center;background:var(--accent-soft);color:var(--accent);width:30px;height:30px;border-radius:6px;margin-right:4px;flex-shrink:0}.stage-symbol.fault{background:var(--warning-soft);color:var(--warning)}.edit-cue{margin-left:auto;font-size:11px;color:var(--muted);opacity:0}.stage-summary:hover .edit-cue,.stage-summary:focus-visible .edit-cue,.expanded .edit-cue{opacity:1}.row-actions{display:flex;align-items:center}.stage-fields{grid-column:3/-1;display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:14px;padding:8px 6px 12px;cursor:default}.hold-rate{font-size:11px;color:var(--muted)}.hold-rate strong{display:block;color:var(--ink);font-size:13px;margin:8px 0 3px}.hold-rate small{font-size:10px}.add-stages{display:flex;justify-content:flex-end;gap:8px;margin-top:14px}.add-stages button{min-height:34px;font-size:12px}.timeline-hint{font-size:11px;color:var(--muted);margin:14px 0 0}.advanced{border:0;border-top:1px solid var(--border);border-radius:0;padding:14px 0 0;margin-top:14px}.advanced label{margin-bottom:14px}.advanced span{font-size:12px;margin-left:10px}
+@media(hover:hover){.stage-row:not(.dragging):hover{background:#f7f9fc}.stage-row.expanded:not(.dragging):hover{background:#eef4fb}.stage-row:hover .stage-summary,.stage-row:focus-within .stage-summary{background:transparent;color:inherit;border-color:transparent}}
+@media(max-width:650px){.stage-row{grid-template-columns:24px 20px minmax(0,1fr) auto;gap:4px;padding:8px}.stage-symbol{display:none}.stage-fields{grid-column:2/-1;grid-template-columns:1fr}.stage-summary{gap:4px}.edit-cue{display:none}.ramp-editor{padding:14px}.section-head p{max-width:210px}.add-stages{justify-content:stretch}.add-stages button{flex:1;padding-left:8px;padding-right:8px}}
+</style>
diff --git a/loadtest/console/src/ReconciliationSummary.svelte b/loadtest/console/src/ReconciliationSummary.svelte
new file mode 100644
index 0000000000..84f9a597bd
--- /dev/null
+++ b/loadtest/console/src/ReconciliationSummary.svelte
@@ -0,0 +1,18 @@
+<script>
+/** @type {any} */ export let result=null;
+/** @type {any} */ export let job=null;
+export let running=false;
+$: failed=job?.status==='failed';
+$: current=running||failed?job?.progress||{}:result||{};
+$: compared=current.compared??current.total??0;
+$: expected=current.expected??compared;
+$: percent=expected?Math.min(100,compared/expected*100):0;
+const durationLabel=t=>t<1?`${Math.max(1,Math.round(t*1000))}ms`:`${t.toFixed(1)}s`;
+</script>
+<section class="recon-summary" aria-label="Reconciliation progress">
+{#if running||result||failed}<div class="summary-head"><strong class:failure={failed}>{running?'Comparing…':failed?'Comparison failed':'Reconciled'}</strong><span role="status">{#if running}{expected?`${compared.toLocaleString()} / ${expected.toLocaleString()} payment IDs compared`:'Preparing comparison…'}{:else if result}{(result.accounted??compared).toLocaleString()} outcomes{/if}{#if current.elapsedSeconds!=null} · {durationLabel(current.elapsedSeconds)}{/if}</span></div>{/if}
+{#if failed&&job?.error}<p class="failure" role="alert">{job.error}</p>{/if}
+{#if running}<progress aria-label="Payments compared" max="100" value={percent}></progress>{/if}
+<slot><p class="chart-caption">Reconcile recorded outcomes with the configured database.</p></slot>
+</section>
+<style>.failure{color:#c43b36;font-size:13px}.summary-head{display:flex;justify-content:space-between;gap:12px;flex-wrap:wrap;font-size:11px;margin-bottom:16px}.summary-head span{color:var(--muted);font-variant-numeric:tabular-nums}.summary-head strong{font-weight:500;color:var(--success)}.summary-head strong.failure{color:var(--danger)}progress{width:100%;height:7px;margin-bottom:16px;accent-color:#0561e2}.chart-caption{font-size:12px;color:var(--muted)}</style>
diff --git a/loadtest/console/src/ResponseBrowser.svelte b/loadtest/console/src/ResponseBrowser.svelte
new file mode 100644
index 0000000000..7f9293edda
--- /dev/null
+++ b/loadtest/console/src/ResponseBrowser.svelte
@@ -0,0 +1,17 @@
+<script>
+import {onMount} from 'svelte';
+import {api} from './api.js';
+import {setQuery} from './navigation.mjs';
+export let runId;export let payment='';export let merchant='';export let event='';export let initial={};
+let history=null,error='',busy=false,search=initial.search||'',operation=initial.operation||'',status=initial.status||'',stack=[0],request=0;
+$: options={search,operation,status,payment,merchant,event};
+$: exportUrl=`/api/runs/${encodeURIComponent(runId)}/export?${new URLSearchParams(options)}`;
+async function load(after=0){busy=true;error='';const token=++request;try{const result=await api.requests(runId,{...options,after});if(token===request)history=result;}catch(e){if(token===request)error=e.message;}finally{if(token===request)busy=false;}}
+function filter(){stack=[0];load();if(!payment&&!event)setQuery({search,operation,status});}
+onMount(()=>{load();return()=>request++;});
+</script>
+<div class="response-filters"><form onsubmit={e=>{e.preventDefault();filter();}}><input aria-label="Search responses" placeholder="Payment, merchant or message" bind:value={search}/><input aria-label="Operation" placeholder="Operation" bind:value={operation}/><select aria-label="HTTP status" bind:value={status} onchange={filter}><option value="">All HTTP outcomes</option><option value="transport">Transport failures</option><option value="errors">All errors</option><option value="200">200</option><option value="400">400</option><option value="404">404</option><option value="500">500</option></select><button class="secondary" disabled={busy}>Search</button></form><a class="quiet" href={exportUrl} download>Export filtered CSV</a></div>
+{#if error}<p class="invalid" role="alert">{error}<button class="quiet" onclick={()=>load(stack.at(-1))}>Retry</button></p>{/if}
+{#if busy}<p role="status">Loading responses…</p>{/if}
+{#if history}<div class="table-wrap"><table><thead><tr><th>Time</th><th>Operation / Payment</th><th>HTTP</th><th>Latency</th><th>Response</th></tr></thead><tbody>{#each history.rows as row}<tr><td>{new Date(row.observed_at).toLocaleTimeString()}</td><td>{row.operation}<small>{row.payment_id||'No payment ID'}</small></td><td>{row.api_status_code||'Transport failure'}</td><td>{Math.round(row.latency_ms)} ms</td><td><details><summary>{row.message||row.status||'Details'}</summary><pre>{row.error_body||row.status||'No response body'}</pre></details></td></tr>{:else}<tr><td colspan="5">No responses match these filters.</td></tr>{/each}</tbody></table></div><div class="pagination"><button class="secondary" disabled={busy||stack.length===1} onclick={()=>{stack=stack.slice(0,-1);load(stack.at(-1));}}>Previous</button><span>Page {stack.length}</span><button class="secondary" disabled={busy||!history.next} onclick={()=>{stack=[...stack,history.next];load(history.next);}}>Next</button></div>{/if}
+<style>.response-filters,.response-filters form{display:flex;gap:8px;align-items:center;flex-wrap:wrap}.response-filters{margin:16px 0}.response-filters form{flex:1}.response-filters input,.response-filters select{width:170px;margin:0;flex:1;min-width:120px;font-size:12px}.response-filters a,.pagination{font-size:12px}.pagination{display:flex;align-items:center;justify-content:flex-end;gap:12px;margin-top:12px}small{display:block;font-size:11px;color:#667085;overflow-wrap:anywhere}pre{white-space:pre-wrap;overflow-wrap:anywhere;max-height:220px;overflow:auto}td{font-size:12px;max-width:300px}</style>
diff --git a/loadtest/console/src/RunScreen.svelte b/loadtest/console/src/RunScreen.svelte
new file mode 100644
index 0000000000..af9944e040
--- /dev/null
+++ b/loadtest/console/src/RunScreen.svelte
@@ -0,0 +1,308 @@
+<script>
+import {environments,environmentLabel} from './environments.mjs';
+import {faultTargetLabel,faultTargetResource} from './fault-types.mjs';
+ import {faultNotice} from './fault-notice.mjs';
+ import {recordingFinished} from './run-lifecycle.mjs';
+import Icon from './Icon.svelte';
+ import { onMount, tick } from 'svelte';
+ import { api } from './api.js';
+ import StatCard from './StatCard.svelte';
+ import {loadShape,loadTimeline} from './load-shape.mjs';
+ import LiveChart from './LiveChart.svelte';
+ import {compactSamples,metricSeries,chartHorizon,pausedChartSamples} from './chart-timeline.mjs';
+ import FollowingLog from './FollowingLog.svelte';
+ import {page} from '$app/stores';
+ import {setQuery} from './navigation.mjs';
+ import {watchJobStream} from './job-stream.mjs';
+ import ConnectionStatus from './ConnectionStatus.svelte';
+ import PaymentChart from './PaymentChart.svelte';
+ import ResponseBrowser from './ResponseBrowser.svelte';
+ import ReconciliationSummary from './ReconciliationSummary.svelte';
+ import RunSummary from './RunSummary.svelte';
+ import MetricsView from './MetricsView.svelte';
+ import ConnectorResults from './ConnectorResults.svelte';
+ import {connectorSet} from './connector-config.mjs';
+ export let data;
+
+ const flowCatalog = [
+ ['cit_off_session', 'CIT off-session'], ['sdk_checkout', 'SDK checkout'],
+ ['guest', 'Guest payment'], ['cit_on_session', 'CIT on-session'],
+ ['ptv_on_session', 'Pay to vault · on-session'], ['ptv_off_session', 'Pay to vault · off-session'],
+ ['cit_metadata_changed', 'Card metadata update'], ['mit', 'Merchant-initiated payment'], ['saved_card_checkout', 'Saved-card checkout']
+ ];
+ import {goto} from '$app/navigation';
+ export let tab='performance';
+
+ let metricsSource=$page.url.searchParams.get('metrics')==='grafana'?'grafana':'native';
+ let pending = '';
+ let stopRequestedJobId = '';
+ $: stopping = activeJob && (job?.status === 'cancelling' || stopRequestedJobId === job?.id);
+ let notice = '';
+ let error = '';
+ let settings = structuredClone(data.settings);
+ let workers=[],execution='local',workerPlan=null,planError='',planKey='',connection='connecting',lastUpdate=0,smokeDialog;
+ $: if(execution==='distributed'&&executionProfile){const key=executionProfile.id+':'+executionProfile.version;if(key!==planKey){planKey=key;previewWorkers();}}
+ async function previewWorkers(){try{workerPlan=await api.workerPlan(executionProfile.id);planError='';}catch(e){workerPlan=null;planError=e.message;}}
+ let smokeRps=settings.smokeTest?.rps ?? 1,smokeDuration=settings.smokeTest?.durationSeconds ?? 10;
+ $: shapePreview=previewShape(executionProfile || settings);
+ function previewShape(s){try{return s.loadShape==='staged'?loadShape({start_rps:Number(s.startRps),stages:JSON.parse(s.stagesJson)}):{peak:s.totalRps,duration:s.durationSeconds};}catch{return {peak:'—',duration:'—'};}}
+ $: activeJob = ['starting','running','pausing','paused','cancelling'].includes(job?.status);
+ $: smokeActive=job?.command==='smoke' && activeJob;
+ let runs = data.runs;
+ let selectedRun = data.run || null;
+ let runTimeline = data.run?.timeline || [];
+ let job = data.job;
+ let events;
+ let finishedRecordingJobId='';
+ let faultDialog;
+ let faults={targets:[],active:null,blocked:false};
+ let faultDraft={targetId:'demo',action:'outage',durationSeconds:10,confirm:''};
+ let flowFilter=$page.url.searchParams.get('flow')||'all';
+ let chartMetric=$page.url.searchParams.get('metric')||'tps';
+ let urlReady=false;
+ $: if(urlReady)setQuery({flow:flowFilter==='all'?null:flowFilter,metric:chartMetric==='tps'?null:chartMetric,metrics:metricsSource,time:null});
+ $: if(['errors','backlog','connectorTps'].includes(chartMetric))flowFilter='all';
+ $: viewJob=job?.command==='load' && (!selectedRun || job.runId===selectedRun.id) ? job : null;
+ $: loadState=selectedRun?.live?viewJob?.loadState||selectedRun.loadState||'running':selectedRun?.loadState||viewJob?.loadState||'idle';
+ $: live=selectedRun?.live && activeJob && (job?.runId===selectedRun.id || (job?.command==='smoke'&&selectedRun.id===`smoke:${job.id}`));
+ $: chartPoints=pausedChartSamples(selectedRun?.telemetry || [],loadState);
+ $: faultTarget=faults.targets.find(t=>t.id===faultDraft.targetId);
+ $: activity=(live?job?.events:selectedRun?.activity) || viewJob?.events || [];
+
+ let reconciliationJob=data.reconciliationJob || null,reconciling=['starting','running','cancelling'].includes(data.reconciliationJob?.status),reconciliationEvents;
+ let reconciliation = selectedRun?.reconciliation || null;
+ let allowIncomplete = false,responsesOpen=false;
+
+
+ onMount(() => {
+ let disposed=false;
+ tick().then(()=>{if(disposed)return;setQuery({run:selectedRun?.id||null,profile:selectedRun?.profile?.id||selectedProfileId,fixtures:selectedRun?.fixtureSetId||selectedFixtureId});urlReady=true;});
+ if(['load','smoke'].includes(job?.command)) watchJob();
+ if(reconciling)watchReconciliation(selectedRun.id);
+ const connections=async()=>{try{[settings,workers]=await Promise.all([api.settings(),api.workers()]);faults=await api.faults();if(!faults.targets.some(t=>t.id===faultDraft.targetId)){faultDraft.targetId=faults.targets[0]?.id||'';faultDraft.action=faults.targets[0]?.actions[0]||'outage';}fixtureSets=await api.fixtures();error='';}catch(e){error=e.message;}};window.addEventListener('console-connections-saved',connections);connections();
+ const polling=setInterval(async()=>{try{faults=await api.faults();workers=await api.workers();const r=await fetch('/api/jobs');if(r.ok){const active=await r.json();generatorBusy=active!=null && active.command!=='reconcile';if(['load','smoke'].includes(active?.command)&&active.id!==job?.id){job=active;watchJob();}}}catch{}},3000);
+ api.faults().then(value=>{faults=value;faultDraft.targetId=value.targets[0]?.id || '';faultDraft.action=value.targets[0]?.actions[0] || 'outage';}).catch(e=>error=e.message);
+ return () => {disposed=true;urlReady=false;events?.close();reconciliationEvents?.close();clearInterval(polling);window.removeEventListener('console-connections-saved',connections);};
+ });
+
+ async function refreshRuns() { runs = await api.runs(); }
+
+ async function selectRun(run) {
+ error = ''; reconciliation = null;
+ flowFilter='all';
+ try { selectedRun = await api.run(run.id); runTimeline=selectedRun.timeline || []; reconciliation = selectedRun.reconciliation || null;if(tab==='results'){reconciliationEvents?.close();reconciliationJob=await api.reconciliationJob(run.id);reconciling=['starting','running','cancelling'].includes(reconciliationJob?.status);if(reconciling)watchReconciliation(run.id);}setQuery({run:run.id,profile:selectedRun.profile?.id||selectedProfileId,fixtures:selectedRun.fixtureSetId||selectedFixtureId});}
+ catch (e) { error = e.message; }
+ }
+
+ let generatorBusy=data.busy || false;
+ let profiles=data.profiles || [],fixtureSets=data.fixtures || [];
+ let selectedProfileId=data.profileId || profiles[0]?.id || '';
+ let selectedFixtureId=data.fixtureSetId || '';
+ $: if(profiles.length&&!profiles.some(p=>p.id===selectedProfileId))selectedProfileId=profiles[0].id;
+ $: executionProfile=profiles.find(p=>p.id===selectedProfileId);
+ const readyFixturesFor=profile=>fixtureSets.filter(f=>f.status==='ready'&&f.compatible&&f.mode===profile?.mode&&f.merchant_count===profile?.merchantCount&&JSON.stringify(f.connectors||['stripe_test'])===JSON.stringify(connectorSet(profile?.connectors)));
+ $: compatibleFixtureSets=readyFixturesFor(executionProfile);
+ $: if(!selectedRun&&!compatibleFixtureSets.some(f=>f.id===selectedFixtureId))selectedFixtureId=compatibleFixtureSets[0]?.id||'';
+ function faultAction(stage){return faults.targets.find(target=>target.id===stage.fault?.targetId)?.actions?.[0] || stage.fault?.action;}
+ function canonicalLoad(profile){const load=profile?.load || {};return {...load,stages:(load.stages || []).map(stage=>stage.fault?{...stage,fault:{...stage.fault,action:faultAction(stage)}}:stage)};}
+ function chooseProfile(){const first=readyFixturesFor(profiles.find(p=>p.id===selectedProfileId))[0];selectedFixtureId=first?.id||'';selectedRun=null;goto(`/performance?metrics=${metricsSource}&profile=${encodeURIComponent(selectedProfileId)}${selectedFixtureId?`&fixtures=${encodeURIComponent(selectedFixtureId)}`:''}`,{replaceState:true,noScroll:true});}
+ function newRun(){selectedRun=null;setQuery({run:null,profile:selectedProfileId});}
+ function runAgain(){if(selectedRun?.profile?.id)selectedProfileId=selectedRun.profile.id;if(selectedRun?.fixtureSetId)selectedFixtureId=selectedRun.fixtureSetId;newRun();}
+ $: startBlocker=generatorBusy||activeJob?'A job is already running.':!environments.find(e=>e.id===(settings.environment||'local'))?.supported?'Choose a supported environment in Settings.':!executionProfile?'Choose a saved scenario.':executionProfile.unavailableReason?executionProfile.unavailableReason:!selectedFixtureId?'Choose ready fixtures for this scenario.':execution==='distributed'&&planError?planError:'';
+ async function start(command) {
+ if(pending||startBlocker)return;
+ if(!executionProfile||!selectedFixtureId){error='Select a saved scenario and ready fixtures';return;}
+ pending=command;error='';smokeDialog?.close();
+ runTimeline=command==='smoke'?[{index:0,start:0,end:Number(smokeDuration),from:Number(smokeRps),target:Number(smokeRps),kind:'hold',fault:null}]:loadTimeline(canonicalLoad(executionProfile),(executionProfile.load.stages || []).map((s,index)=>({index,target:{label:faults.targets.find(t=>t.id===s.fault?.targetId)?.label}})));
+ try{
+ const selection={mode:executionProfile.mode,profileId:executionProfile.id,version:executionProfile.version,fixtureSetId:selectedFixtureId,execution};
+ job=await api.start(command,command==='smoke'?{...selection,rps:Number(smokeRps),durationSeconds:Number(smokeDuration)}:selection);
+ notice='';selectedRun=null;flowFilter='all';generatorBusy=true;watchJob();
+ if(command==='load')goto(`/performance?metrics=${metricsSource}&run=${encodeURIComponent(job.runId)}&profile=${encodeURIComponent(selectedProfileId)}`,{replaceState:true,noScroll:true});
+ }
+ catch(e){error=e.message;}finally{pending='';}
+ }
+
+ function watchJob() {
+ events?.close();
+ events = watchJobStream(job.id, async (value) => {
+ job = value;
+ if(job.faults){faults=job.faults;window.dispatchEvent(new Event('console-fault-state'));}
+ const profile=job.profile || settings;
+ const visualId=job.command==='smoke'?`smoke:${job.id}`:job.runId;
+ if(visualId && (!selectedRun || selectedRun.id === visualId)) {
+ const p=job.progress;
+ let telemetry=selectedRun?.telemetry || [];
+ if(p.trend && (!telemetry.length || p.trend.t>telemetry.at(-1).t)) {
+ const trend={...p.trend,serverP99:p.trend.serverP99 ?? p.server_p99_ms ?? null,flows:Object.fromEntries(Object.entries(p.trend.flows||{}).map(([name,f])=>[name,{...f,serverP99:f.serverP99 ?? p.flows?.[name]?.server_p99_ms ?? null}]))};
+ telemetry=compactSamples([...telemetry,trend]);
+ }
+ if(p.elapsed_seconds!=null&&!recordingFinished(job)) selectedRun={...(selectedRun || {}),id:visualId,kind:job.command,mode:job.mode,startedAt:job.startedAt,profile:job.profile,
+ telemetry,timeline:job.profile?.timeline || selectedRun?.timeline || runTimeline,
+ activity:job.events,activeSeconds:p.control?.active_seconds ?? p.elapsed_seconds,wallSeconds:p.control?.wall_seconds ?? p.elapsed_seconds,loadState:job.loadState,serverP99:p.server_p99_ms ?? null,confirmP99:p.p99_ms ?? null,
+ live:true,complete:false,recordingState:job.command==='smoke'?'disabled':'running',durationSeconds:profile.durationSeconds,
+ elapsedSeconds:Number((p.control?.active_seconds ?? p.elapsed_seconds).toFixed(1)),iterations:p.iterations,successfulTps:Number(p.successful_tps.toFixed(2)),
+ displayErrorRate:p.display_error_rate ?? (p.http_attempts?100*p.http_errors/p.http_attempts:0),
+ confirmErrorRate:p.confirm_http_attempts==null?null:p.confirm_http_attempts?Number((p.confirm_http_errors/p.confirm_http_attempts*100).toFixed(2)):0,
+ offeredTps:profile.totalRps,errorRate:p.http_attempts?Number((p.http_errors/p.http_attempts*100).toFixed(2)):0,
+ dropped:p.dropped,enqueued:p.recorder.enqueued,persisted:p.recorder.persisted,gaps:p.recorder.enqueued-p.recorder.persisted,
+ flows:profile.scenarios.map(f=>({name:f.name,label:flowCatalog.find(c=>c[0]===f.scenario)?.[1] || f.name,
+ offeredTps:profile.totalRps*f.weight/100,successes:p.flows[f.name]?.successes||0,successfulTps:Number((p.flows[f.name]?.tps || 0).toFixed(2)),
+ serverP99:p.flows[f.name]?.server_p99_ms ?? null,confirmP99:p.flows[f.name]?.p99_ms ?? null,confirmP90:p.flows[f.name]?.p90_ms ?? null,errors:p.flows[f.name]?.failures || 0}))};
+ }
+ if(recordingFinished(job)&&finishedRecordingJobId!==job.id){
+ finishedRecordingJobId=job.id;
+ try{
+ await refreshRuns();
+ const recorded=runs.find(r=>r.id===job.runId);
+ if(!recorded?.endedAt||recorded.recordingState==='running')finishedRecordingJobId='';
+ if(recorded?.endedAt&&recorded.recordingState!=='running'&&(!selectedRun||selectedRun.id===job.runId)){
+ const completed=await api.run(job.runId);
+ // Do not replace a newer selection or an already-started run.
+ if(recordingFinished(job)&&completed.id===job.runId&&(!selectedRun||selectedRun.id===completed.id)){
+ selectedRun=completed;runTimeline=completed.timeline||[];reconciliation=completed.reconciliation||reconciliation;
+ }
+ }
+ }catch(e){finishedRecordingJobId='';error=e.message;}
+ }
+ if (!['starting','running','pausing','paused','cancelling'].includes(job.status)) {
+ events.close();
+ generatorBusy=false;
+ if(job.command==='smoke'){
+ if(selectedRun?.id===`smoke:${job.id}`){const elapsed=job.progress.control?.active_seconds??job.progress.elapsed_seconds;const flows=selectedRun.flows.map(f=>({...f,successfulTps:Number(((job.progress.flows[f.name]?.successes||0)/Math.max(1,elapsed)).toFixed(2))}));selectedRun={...selectedRun,flows,successfulTps:Number(flows.reduce((sum,f)=>sum+f.successfulTps,0).toFixed(2)),live:false,complete:true,endedAt:job.endedAt,loadState:job.status==='complete'?'completed':job.status,recordingState:'disabled'};}
+ notice='';
+ }
+ else if(job.command==='reconcile') reconciliation=job.result;
+ else {await refreshRuns();if(!selectedRun || selectedRun.id===job.runId){const latest=runs.find(r=>r.id===job.runId) || runs[0];if(latest)await selectRun(latest);}}
+ if(job.error&&!/k6 thresholds failed/i.test(job.error))error=job.error;
+ }
+ },(state,at)=>{connection=state;lastUpdate=at;});
+ }
+
+ async function reconcile() {
+ if(!selectedRun||reconciling)return;
+ error='';reconciling=true;reconciliation=null;
+ const runId=selectedRun.id;
+ try{
+ reconciliationJob=await api.reconcile(runId,allowIncomplete);
+ watchReconciliation(runId);
+ }catch(e){error=e.message;reconciling=false;}
+ }
+ function watchReconciliation(runId){
+ reconciliationEvents?.close();
+ reconciliationEvents=watchJobStream(reconciliationJob.id,async value=>{
+ reconciliationJob=value;
+ if(!['starting','running','cancelling'].includes(reconciliationJob.status)){
+ reconciliationEvents.close();reconciling=false;
+ if(selectedRun?.id===runId){
+ reconciliation=reconciliationJob.result;
+ if(reconciliationJob.error)error=reconciliationJob.error;
+ else if(reconciliationJob.result){
+ try{
+ const refreshed=await api.run(runId);
+ if(selectedRun?.id===runId){selectedRun=refreshed;runTimeline=refreshed.timeline||[];}
+ }catch(e){if(selectedRun?.id===runId)error=e.message;}
+ }
+ }
+ }
+ },(state,at)=>{connection=state;lastUpdate=at;});
+ }
+
+ const modeLabel = (mode) => mode === 'tenancy' ? 'Tenancy' : 'Single';
+ const loadLabel = (mode,tps) => `${modeLabel(mode)} · ${tps ?? '—'} TPS`;
+ function formatDate(value) { return value ? new Intl.DateTimeFormat(undefined, { dateStyle: 'medium', timeStyle: 'short' }).format(new Date(value)) : 'Unknown'; }
+ const fixtureLabel = fixture => `${fixture.id.slice(0,8)} · ${new Intl.DateTimeFormat(undefined, {dateStyle:'medium'}).format(new Date(fixture.created_at))}`;
+ const formatLatency=value=>value==null?'—':Number(value.toFixed(1));
+ $: chartDuration=chartHorizon(chartPoints,selectedRun?.durationSeconds,selectedRun?.timeline||[],activity,selectedRun?.startedAt||0);
+ $: isSmoke=selectedRun?.kind==='smoke';
+ $: thresholdFailure=loadState==='failed'&&/k6 thresholds failed/i.test(viewJob?.error||job?.error||'');
+ $: timelineStopping=live&&stopping;
+ $: timelineStatus=selectedRun?{state:timelineStopping?'stopping':loadState,stopping:timelineStopping,stateLabel:timelineStopping?'Stopping…':isSmoke?(live?'Smoke':loadState==='completed'?'Smoke passed':'Smoke failed'):thresholdFailure?'Checks failed':null,reason:thresholdFailure?'HTTP failure threshold exceeded':null,live,smoke:isSmoke,label:isSmoke?`${selectedRun.offeredTps} TPS verification`:`${selectedRun.offeredTps} TPS`,clock:isSmoke?`${selectedRun.durationSeconds}s`:`${selectedRun.elapsedSeconds} / ${selectedRun.durationSeconds}s active · ${Math.round(selectedRun.wallSeconds)}s elapsed${live?` · ${job.progress?.control?.in_flight ?? 0} in flight`:''}`,pending:!!pending,faultActive:!!faults.active,cancel,pause:()=>control('pause'),resume:()=>control('resume'),runAgain,resultsUrl:`/results?metrics=${metricsSource}&run=${encodeURIComponent(selectedRun.id)}`} : null;
+ $: previewStatus={state:stopping?'stopping':smokeActive?'running':pending?'starting':'idle',stateLabel:stopping?'Stopping…':smokeActive?'Smoke':pending?'Starting…':'Ready',live:true,smoke:smokeActive,stopping,label:smokeActive?`${smokeRps} TPS verification`:'',clock:smokeActive?`${smokeDuration}s`:`${shapePreview.duration}s · up to ${shapePreview.peak} TPS`,pending:!!pending,startBlocked:!!startBlocker,cancel,startLoad:()=>start('load'),smokeTest:()=>smokeDialog.showModal()};
+ async function cancel() {
+ if(!job || stopping)return;
+ const id=job.id;
+ stopRequestedJobId=id;error='';
+ try{
+ const cancelled=await api.cancel(id);
+ // A late acknowledgement must not overwrite a newer terminal stream update.
+ if(job?.id===id && activeJob)job=cancelled;
+ }catch(e){if(stopRequestedJobId===id)stopRequestedJobId='';error=e.message;}
+ }
+
+ async function control(action){
+ if(pending)return;pending=action;error='';
+ try{job=await api.control(job.id,action);}catch(e){error=e.message;}finally{pending='';}
+ }
+ async function fireFault(){
+ if(pending)return;pending='fault';error='';
+ try{faults=await api.fireFault({...faultDraft,environment:faults.environment,expectedTarget:faultTarget?.target||faultTarget,jobId:job.id});window.dispatchEvent(new Event('console-fault-state'));faultDialog.close();faultDraft.confirm='';}catch(e){error=e.message;}finally{pending='';}
+ }
+ async function restoreFault(){try{faults=await api.restoreFault();window.dispatchEvent(new Event('console-fault-state'));}catch(e){error=e.message;}}
+
+</script>
+<svelte:head><title>{tab==='performance'?'Performance':'Results'} · Testbench</title></svelte:head>
+<dialog class="fault-dialog" bind:this={faultDialog} aria-labelledby="fault-title"><form onsubmit={e=>{e.preventDefault();fireFault();}}><div class="section-head"><h1 id="fault-title">Create fault · {environmentLabel(faults.environment)}</h1><button type="button" class="icon-button" aria-label="Close fault" onclick={()=>faultDialog.close()}><Icon name="close"/></button></div>{#if error}<div class="message error" role="alert">{error}</div>{/if}<label>Target<select bind:value={faultDraft.targetId} onchange={e=>{faultDraft.action=faults.targets.find(t=>t.id===e.currentTarget.value)?.actions[0] || 'outage';faultDraft.confirm='';}}>{#each faults.targets as target}<option value={target.id}>{faultTargetLabel(target.target||target)}</option>{/each}</select></label>{#if faultDraft.action==='outage'}<label>Downtime · seconds<input type="number" min="1" max="300" bind:value={faultDraft.durationSeconds}/></label>{/if}<p>{faultTarget?.adapter==='simulated'?'Simulation does not change infrastructure.':faultDraft.action==='failover'?'Triggers managed failover and verifies readiness.':'Stops the service, waits for the configured downtime, then restores it and verifies recovery.'}</p><p>{faultTargetResource(faultTarget?.target||faultTarget)}</p><label>Type “{faultDraft.action} {faultDraft.targetId}” to confirm<input autocomplete="off" bind:value={faultDraft.confirm}/></label><div class="actions"><button type="button" class="secondary" onclick={()=>faultDialog.close()}>Cancel</button><button disabled={!!pending || faultDraft.confirm!==`${faultDraft.action} ${faultDraft.targetId}`}>Apply fault</button></div></form></dialog>
+
+<dialog class="smoke-dialog" bind:this={smokeDialog} aria-labelledby="smoke-title"><form onsubmit={e=>{e.preventDefault();start('smoke');}}><div class="section-head"><div><p class="eyebrow">Quick verification</p><h2 id="smoke-title">Run smoke test</h2></div><button type="button" class="icon-button" aria-label="Close smoke test" onclick={()=>smokeDialog.close()}><Icon name="close"/></button></div><p class="smoke-intro">Confirm that the selected scenario can complete its flows before starting the full load.</p><div class="smoke-context"><Icon name="shield" size={18}/><div><strong>{executionProfile?.name || 'Selected scenario'}</strong><span>Uses ready fixtures · skips faults and response recording</span></div></div><div class="fields smoke-fields"><label>Traffic<div class="number-field"><input aria-label="Smoke test TPS" type="number" min="1" max="100" required bind:value={smokeRps}/><span>TPS</span></div></label><label>Duration<div class="number-field"><input aria-label="Smoke test duration" type="number" min="1" max="300" required bind:value={smokeDuration}/><span>sec</span></div></label></div><div class="actions"><button type="button" class="quiet" onclick={()=>smokeDialog.close()}>Cancel</button><button disabled={!!pending||!!startBlocker}><Icon name="performance"/> Run smoke test</button></div></form></dialog>
+<main>
+{#if error}<div class="message error" role="alert">{error}</div>{/if}
+{#if notice}<div class="message" role="status">{notice}</div>{/if}
+ {#if settings && tab === 'performance'}
+ <div class="section-head"><div><h1>Performance</h1>{#if selectedRun}<p>{selectedRun.profile?.name ? `${selectedRun.profile.name} · ` : ''}{formatDate(selectedRun.startedAt)}</p>{:else}<p>Run scenarios and watch your system respond.</p>{/if}</div><label class="run-select">Load run<select value={selectedRun?.id || ''} onchange={(e) => { const run = runs.find((item) => item.id === e.currentTarget.value); if (run) selectRun(run); else if(job?.command==='load' && job.runId===e.currentTarget.value)selectRun({id:job.runId}); else newRun(); }}><option value="">New run · selected scenario</option>{#if selectedRun?.kind==='smoke'}<option value={selectedRun.id}>Smoke · {formatDate(selectedRun.startedAt)}</option>{/if}{#if job?.command==='load' && activeJob && job.runId && !runs.some(r=>r.id===job.runId)}<option value={job.runId}>Live · {loadLabel(job.mode,job.profile?.totalRps)}</option>{/if}{#each runs as run}<option value={run.id}>{run.profile?.name||'Load test'} · {formatDate(run.startedAt)}</option>{/each}</select></label></div>
+ {#if !selectedRun}<div class="load-controls execution-inputs"><label>Scenario<select bind:value={selectedProfileId} onchange={chooseProfile} disabled={!profiles.length}>{#each profiles as profile}<option value={profile.id}>{profile.name} · {modeLabel(profile.mode)} · {profile.totalRps} TPS</option>{/each}</select></label><label>Fixture set<select bind:value={selectedFixtureId} onchange={()=>setQuery({fixtures:selectedFixtureId})} disabled={!compatibleFixtureSets.length}>{#each compatibleFixtureSets as fixture}<option value={fixture.id}>{fixtureLabel(fixture)}</option>{/each}</select></label><label>Execution<select bind:value={execution}><option value="local">Local worker</option><option value="distributed" >Distributed · auto</option></select>{#if execution==='distributed'}<small>{workers.filter(worker=>worker.id!=='local'&&worker.status==='idle').length} ready workers · {workers.filter(worker=>worker.id!=='local'&&worker.status==='idle').reduce((sum,worker)=>sum+worker.capacityTps,0)} TPS capacity</small>{/if}</label>{#if execution==='distributed'}<small>{#if planError}{planError} <button class="quiet" onclick={()=>window.dispatchEvent(new CustomEvent('console-settings',{detail:{section:'workers'}}))}>Connect workers</button>{:else if workerPlan}{workerPlan.map(w=>`${w.workerName}: ${w.offeredTps} TPS`).join(' · ')} <button class="quiet" onclick={previewWorkers}>Refresh allocation</button>{:else}Planning workers…{/if}</small>{/if}</div>{/if}
+ {#if !selectedRun&&startBlocker&&!activeJob}<p class="blocker" role="status">{startBlocker} {#if !selectedFixtureId}<a href={`/fixtures?profile=${selectedProfileId}`}>Open Fixtures</a>{/if}</p>{/if}
+ {#if viewJob?.workers?.length}<div class="worker-strip" aria-label="Distributed workers">{#each viewJob.workers as worker}<span><i class:complete={worker.status==='complete'} class:failed={worker.status==='failed'}></i>{worker.name} · {worker.offeredTps} TPS · {worker.status}</span>{/each}</div>{/if}
+ {#if selectedRun}
+ {@const filteredFlow=selectedRun.flows?.find(f=>f.name===flowFilter)}
+
+ <MetricsView bind:value={metricsSource} run={selectedRun} grafana={settings.grafana}>
+ <div class="stats">
+ <StatCard label="Successful TPS" value={filteredFlow?filteredFlow.successfulTps:selectedRun.successfulTps} caption={filteredFlow?`${filteredFlow.offeredTps} offered TPS`:`${selectedRun.flows.reduce((sum,f)=>sum+(f.successes||0),0)} successful flows`} series={metricSeries(chartPoints,'tps',flowFilter)} durationSeconds={chartDuration} color="#398453"/>
+ <StatCard label="Client-side latency" value={formatLatency(filteredFlow?filteredFlow.confirmP99:selectedRun.confirmP99)} unit="ms" caption="p99 request latency" series={metricSeries(chartPoints,'p99',flowFilter)} durationSeconds={chartDuration} color="#5277b8"/>
+ <StatCard label="Server-side latency" value={formatLatency(filteredFlow?filteredFlow.serverP99:selectedRun.serverP99)} unit="ms" caption="p99 request latency" series={metricSeries(chartPoints,'serverP99',flowFilter)} durationSeconds={chartDuration} color="#5277b8"/>
+ <StatCard label="HTTP errors · all flows" value={selectedRun.displayErrorRate ?? selectedRun.errorRate} unit="%" caption={`${selectedRun.dropped} dropped flows`} series={metricSeries(chartPoints,'errors')} durationSeconds={chartDuration} color={(selectedRun.displayErrorRate ?? selectedRun.errorRate) ? '#b67822' : '#398453'}/>
+ </div>
+ </MetricsView>
+ <LiveChart points={chartPoints} activity={activity} startedAt={selectedRun.startedAt} durationSeconds={selectedRun.durationSeconds} timeline={selectedRun.timeline || []} allPoints={chartPoints} flows={selectedRun.flows} runStatus={timelineStatus} bind:flow={flowFilter} bind:metric={chartMetric}>
+ {#if activeJob&&live&&connection!=='connected'}<ConnectionStatus state={connection} updatedAt={lastUpdate}/>{/if}
+ {#if faults.active||faults.blocked}<div class="fault-notice" class:background={faults.active?.databaseAvailability==='available'&&faults.active?.status==='restoring'&&!faults.blocked} role="status">{faultNotice(faults,{live,stopping,activity})}{#if faults.blocked}<button class="secondary" disabled={faults.recovering} onclick={restoreFault}>Retry recovery</button>{/if}</div>{/if}
+ </LiveChart>
+ {#if selectedRun.flows.length>1}<details class="detail-section"><summary>Flow breakdown · {selectedRun.flows.length} flows</summary><div class="table-wrap"><table><thead><tr><th>Flow</th><th>Offered TPS</th><th>Successful TPS</th><th>Client-side latency</th><th>Server-side latency</th><th>Errors</th></tr></thead><tbody>{#each selectedRun.flows.filter(f=>flowFilter==='all'||f.name===flowFilter) as flow}<tr><td>{flow.label}</td><td>{flow.offeredTps}</td><td>{flow.successfulTps}</td><td>{flow.confirmP99 == null ? '—' : `${Number(flow.confirmP99.toFixed(1))} ms`}</td><td>{flow.serverP99 == null ? '—' : `${Number(flow.serverP99.toFixed(1))} ms`}</td><td>{flow.errors}</td></tr>{/each}</tbody></table></div></details>{/if}
+ {:else}<LiveChart runStatus={previewStatus} durationSeconds={smokeActive?Number(smokeDuration):shapePreview.duration} timeline={smokeActive?runTimeline:loadTimeline(canonicalLoad(executionProfile),(executionProfile?.load?.stages || []).map((s,index)=>({index,target:{label:faults.targets.find(t=>t.id===s.fault?.targetId)?.label}})))} bind:metric={chartMetric}/>{/if}
+ {#if activity.length}<details class="activity detail-section"><summary>Activity · {activity.length} events</summary>{#if activity.length}<ol>{#each activity as event (event.id)}<li><time>{new Date(event.at).toLocaleTimeString()}</time><span>{event.message}</span></li>{/each}</ol>{:else}<p>Run events will appear here.</p>{/if}</details>{/if}
+ {#if viewJob || selectedRun?.diagnostics || (job && job.command!=='load')}<details class="diagnostics"><summary>Recording and diagnostics</summary>{#if selectedRun}<p>{selectedRun.persisted.toLocaleString()} responses persisted · {selectedRun.gaps} pending · recording {selectedRun.recordingState}</p>{/if}{#key viewJob?.id || selectedRun?.id || job?.id}<FollowingLog output={viewJob?.output ?? selectedRun?.diagnostics ?? job?.output ?? ''}/>{/key}</details>{/if}
+ {/if}
+
+ {#if tab === 'results'}
+ <div class="section-head results-header"><div><h1>Results</h1>{#if selectedRun}<p>{(selectedRun.payments+(selectedRun.failedCreates||0)).toLocaleString()} outcomes · recording {selectedRun.recordingState}</p>{/if}</div><label class="run-select">Run<select value={selectedRun?.id || ''} disabled={reconciling} onchange={e=>{const run=runs.find(r=>r.id===e.currentTarget.value);if(run)selectRun(run);}}>{#if !runs.length}<option value="">No runs yet</option>{/if}{#each runs as run}<option value={run.id}>{run.profile?.name || 'Load test'} · {formatDate(run.startedAt)}</option>{/each}</select></label></div>
+ {#if !runs.length}<section class="empty-state"><h2>No load-test runs yet</h2><p>Start a load test from Performance. Results and reconciliation will appear here when recording begins.</p><a class="button" href="/performance">Open Performance</a></section>{/if}
+ {#if selectedRun}<RunSummary run={selectedRun}/><ConnectorResults result={selectedRun.connectors}/><section class="reconcile results-comparison">
+ <div class="section-head"><h2>Reconciliation</h2><button disabled={reconciling || (!selectedRun.complete && !allowIncomplete)} onclick={reconcile}>{reconciling?'Comparing…':'Reconcile'}</button></div>
+ {#if selectedRun}
+ {#if !selectedRun.complete}<label><input type="checkbox" bind:checked={allowIncomplete}/> Allow incomplete recording</label>{/if}
+ <ReconciliationSummary result={reconciliation} job={reconciliationJob?.runId===selectedRun.id?reconciliationJob:null} running={reconciling}>
+ {#if reconciliation||reconciling}{#key selectedRun.id}<PaymentChart run={selectedRun} result={reconciliation} revision={reconciliation?.comparedAt||reconciliationJob?.progress?.compared||0} running={reconciling}/>{/key}{:else}<p>Check recorded outcomes against the configured database.</p>{/if}
+ </ReconciliationSummary>{#if reconciling&&connection!=='connected'}<ConnectionStatus state={connection} updatedAt={lastUpdate}/>{/if}
+ {#if reconciliation?.transport?.attempts&&reconciliation.accounted==null}
+ <details class="discrepancies"><summary>Transport failures · {reconciliation.transport.attempts} attempts · {reconciliation.transport.unresolved} unresolved</summary>
+ <p>{reconciliation.transport.found} payment IDs found · {reconciliation.transport.missing} not found. Found means the payment exists; its PostgreSQL status is shown below.</p>
+ {#if reconciliation.transport.unresolved}<p>No payment ID was received for {reconciliation.transport.unresolved} attempts. Their server outcome cannot be established from this recording.</p>{/if}
+ <div class="table-wrap"><table><thead><tr><th>Operation</th><th>Failed attempts</th><th>Without payment ID</th></tr></thead><tbody>{#each reconciliation.transport.byOperation as row}<tr><td>{row.operation}</td><td>{row.attempts}</td><td>{row.unresolved}</td></tr>{/each}</tbody></table></div>
+ {#if reconciliation.transport.details.length}<div class="table-wrap"><table><thead><tr><th>Merchant / Payment</th><th>Failed attempts</th><th>PostgreSQL status</th><th>Outcome</th></tr></thead><tbody>{#each reconciliation.transport.details as row}<tr><td><small>{row.merchantId}</small><br/>{row.paymentId}</td><td>{row.attempts}</td><td>{row.databaseStatus ?? '—'}</td><td>{row.outcome==='found'?'Found':'Not found'}</td></tr>{/each}</tbody></table></div>{/if}
+ {#if reconciliation.transport.truncated}<p>First 100 payment IDs shown. Full comparisons are saved in reconciliation.sqlite.</p>{/if}
+ </details>
+ {/if}
+
+ {/if}
+ </section>{/if}
+ {#if selectedRun}<details class="result-details" bind:open={responsesOpen}><summary>Recorded responses</summary>{#if responsesOpen}{#key selectedRun.id}<ResponseBrowser runId={selectedRun.id} initial={Object.fromEntries($page.url.searchParams)}/>{/key}{/if}</details>{/if}
+ {/if}
+</main>
+
+<style>
+.stats{grid-template-columns:repeat(4,minmax(0,1fr))}.fault-notice{font-size:12px;color:var(--warning);padding:8px 0}.fault-notice.background{color:var(--muted)}.fault-notice button{margin-left:12px}
+.blocker{font-size:12px;color:var(--warning);padding:0 2px}.blocker a{margin-left:8px}.worker-strip{display:flex;gap:8px;flex-wrap:wrap;margin:0 0 18px}.worker-strip span{display:flex;align-items:center;gap:6px;background:white;border:1px solid var(--border);border-radius:6px;padding:6px 10px;font-size:11px}.worker-strip i{width:6px;height:6px;border-radius:50%;background:var(--accent)}.worker-strip i.complete{background:var(--success)}.worker-strip i.failed{background:var(--danger)}.results-header .run-select{max-width:560px;width:48%}.results-comparison{padding:24px}.results-comparison>.section-head{margin-bottom:16px;padding-bottom:16px;border-bottom:1px solid var(--border)}.discrepancies{margin-top:20px;padding-top:18px;border-top:1px solid var(--border)}.discrepancies[open]>summary{margin-bottom:14px}.execution-inputs{gap:16px}.execution-inputs>small{grid-column:1/-1;font-size:11px}.activity ol{margin-top:14px}.smoke-dialog .section-head{align-items:flex-start;margin-bottom:12px}.smoke-dialog .eyebrow{margin:0 0 4px}.smoke-intro{margin:0 0 18px}.smoke-context{display:flex;align-items:flex-start;gap:12px;padding:14px;background:var(--accent-soft);border-radius:9px;color:var(--accent)}.smoke-context>div{display:flex;flex-direction:column;gap:3px;min-width:0}.smoke-context strong{font-size:13px;color:var(--ink);overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.smoke-context span{font-size:11px;color:var(--muted)}.smoke-fields{margin-top:20px}.number-field{position:relative}.number-field input{padding-right:48px}.number-field span{position:absolute;right:12px;top:50%;transform:translateY(-50%);font-size:11px;color:var(--muted);pointer-events:none}.smoke-dialog .actions{justify-content:space-between}
+@media(max-width:800px){.results-header .run-select{width:100%;max-width:none}.results-comparison>.section-head{align-items:flex-start;flex-wrap:wrap}.results-comparison{padding:16px}}
+@media(max-width:900px){.stats{grid-template-columns:repeat(2,minmax(0,1fr))}}
+</style>
diff --git a/loadtest/console/src/RunSummary.svelte b/loadtest/console/src/RunSummary.svelte
new file mode 100644
index 0000000000..7e1326eefb
--- /dev/null
+++ b/loadtest/console/src/RunSummary.svelte
@@ -0,0 +1,54 @@
+<script>
+import {environmentLabel} from './environments.mjs';
+ import ScenarioChecks from './ScenarioChecks.svelte';
+ import {resultTestCases} from './result-test-cases.mjs';
+ export let run;
+ const number=(value,digits=2)=>value==null||!Number.isFinite(Number(value))?'—':Number(value).toLocaleString(undefined,{maximumFractionDigits:digits});
+ const duration=value=>{
+ if(value==null||!Number.isFinite(Number(value)))return '—';
+ const total=Math.max(0,Math.round(Number(value))),hours=Math.floor(total/3600),minutes=Math.floor(total%3600/60),seconds=total%60;
+ return [hours?`${hours}h`:'',minutes?`${minutes}m`:'',seconds||(!hours&&!minutes)?`${seconds}s`:''].filter(Boolean).join(' ');
+ };
+ const formatStartedAt=value=>{
+ const date=new Date(value),day=date.getDate();
+ const suffix=day%100>=11&&day%100<=13?'th':({1:'st',2:'nd',3:'rd'}[day%10]||'th');
+ return `${day}${suffix} ${date.toLocaleString('en-GB',{month:'short'})}, ${date.getFullYear()} · ${date.toLocaleTimeString('en-US',{hour:'numeric',minute:'2-digit',second:'2-digit'})}`;
+ };
+ const labels={'HTTP errors (%)':'HTTP errors'};
+ const units={'Successful TPS':' TPS','HTTP errors (%)':'%'};
+ $: acceptance=run.acceptance;
+ $: faultLabels=[...new Set((run.timeline||[]).filter(stage=>stage.fault).map(stage=>`${stage.fault.target==='PostgreSQL'?'DB':stage.fault.target} ${stage.fault.action==='failover'?'failover':stage.fault.action==='restart'?'restart':'outage'}`))];
+ $: visibleChecks=run.scenarioChecks?resultTestCases(run.scenarioChecks).flatMap(s=>s.cases):[];
+ $: checked=visibleChecks.filter(c=>c.id.startsWith('TC-')||c.id==='completion');
+ $: passed=checked.filter(c=>c.outcome==='pass').length;
+ $: caseIncomplete=visibleChecks.some(c=>['not_measured','not_run','incomplete'].includes(c.outcome));
+ $: pending=run.live||!run.endedAt;
+ $: verdict=run.scenarioChecks?(run.scenarioChecks.verdict==='pass'&&caseIncomplete?'Incomplete':({pass:'Passed',fail:'Failed',incomplete:'Incomplete',recorded:'Recorded',in_progress:'In progress',not_run:'Not run'}[run.scenarioChecks.verdict]||'Recorded')):pending?'In progress':!run.savedSettings?.limitsSaved?'Recorded':({pass:'Passed',fail:'Failed',incomplete:'Incomplete',unmeasured:'Unmeasured'}[acceptance?.verdict]||'Recorded');
+ $: checks=(acceptance?.checks||[]).filter(check=>['Successful TPS','HTTP errors (%)'].includes(check.label)).map(check=>({...check,label:labels[check.label]||check.label,
+ observed:number(check.actual)+(check.actual==null?'':units[check.label]||''),
+ threshold:run.savedSettings?.limitsSaved?(check.label==='Successful TPS'?'≥ ':'≤ ')+number(check.limit)+(units[check.label]||''):'—',
+ outcome:pending?'unmeasured':!run.savedSettings?.limitsSaved?'recorded':check.outcome}));
+</script>
+
+<section class="run-summary" aria-labelledby="run-summary-title">
+ <div class="summary-head"><div><span class="summary-eyebrow">Run summary</span><h2 id="run-summary-title">{run.profile?.name||'Load test run'}</h2><p>{formatStartedAt(run.startedAt)} · {duration(run.activeSeconds??run.elapsedSeconds)} active · {duration(run.wallSeconds)} elapsed</p></div><div class="summary-status">{#if checked.length}<span class="check-count">{passed}/{checked.length} test cases passed</span>{/if}<span class="verdict" class:failed={verdict==='Failed'} class:passed={verdict==='Passed'}>{verdict}</span></div></div>
+ <div class="configuration"><div class="summary-labels">{#if run.environment}<span class="summary-label environment">{environmentLabel(run.environment)}</span>{/if}<span class="summary-label">{number(run.offeredTps)} TPS peak</span>{#each faultLabels as label}<span class="summary-label fault">{label}</span>{/each}</div></div>
+ {#if run.scenarioChecks}<ScenarioChecks summary={run.scenarioChecks} latencyPhases={run.serverLatencyPhases}/>{:else}
+ <div class="table-wrap"><table><thead><tr><th>Metric</th><th class="numeric">Limit</th><th class="numeric">Observed</th><th>Verdict</th></tr></thead><tbody>
+ {#each checks as check}<tr><td>{check.label}</td><td class="numeric muted">{check.threshold}</td><td class="numeric">{check.observed}</td><td><span class="check" class:failed={check.outcome==='fail'} class:passed={check.outcome==='pass'}>{check.outcome==='pass'?'Pass':check.outcome==='fail'?'Fail':'—'}</span></td></tr>{/each}
+ <tr><td>Completed flows</td><td class="numeric muted">—</td><td class="numeric">{number(run.iterations,0)}</td><td class="muted">—</td></tr>
+ </tbody></table></div>
+ <h3 class="latency-title">Server-side latency</h3>
+ <div class="table-wrap"><table class="latency-table"><thead><tr><th>State</th><th class="numeric">Samples</th><th class="numeric">p50 · ms</th><th class="numeric">p95 · ms</th><th class="numeric">p99 · ms</th></tr></thead><tbody>
+ {#each run.serverLatencyPhases||[] as phase}<tr><td title={phase.state==='normal'?'Requests outside recorded outage and recovery windows':phase.state==='outage'?'Requests overlapping a vault outage or observed database unavailability':`Requests overlapping the first ${run.recoveryLatencySeconds||10} seconds after recovery, excluding outage requests`}>{phase.state==='normal'?'Normal':phase.state==='outage'?'Outage':`After recovery · first ${run.recoveryLatencySeconds||10}s`}</td><td class="numeric muted">{number(phase.count,0)}</td><td class="numeric">{number(phase.p50,1)}</td><td class="numeric">{number(phase.p95,1)}</td><td class="numeric">{number(phase.p99,1)}</td></tr>{:else}<tr><td colspan="5" class="muted">No successful latency samples recorded</td></tr>{/each}
+ </tbody></table></div>
+ {/if}
+</section>
+
+<style>
+.summary-eyebrow{display:block;font-size:11px;color:var(--muted);margin-bottom:6px}.summary-head h2{font-weight:700}.configuration{display:flex;align-items:center;flex-wrap:wrap;gap:8px 16px}.summary-labels{display:flex;flex-wrap:wrap;gap:6px}.summary-label{display:inline-flex;align-items:center;background:var(--surface-muted);border-radius:5px;padding:3px 8px;font-weight:500}.summary-label.environment{color:var(--primary,#0668ff);background:var(--primary-soft,#edf4ff)}.summary-label.fault{color:#9b651b;background:#fff7e9}
+
+.latency-title{margin:20px 0 12px;font-size:12px}.latency-table td:last-child,.latency-table th:last-child{width:auto;padding-left:16px}
+.summary-status{display:flex;align-items:center;gap:12px}.check-count{font-size:11px;color:var(--muted);white-space:nowrap}@media(max-width:600px){.summary-status{align-items:flex-end;flex-direction:column;gap:6px}}
+.run-summary{background:var(--surface);border:1px solid var(--border);border-radius:var(--radius);padding:24px;margin-bottom:16px}.summary-head{display:flex;align-items:flex-start;justify-content:space-between;gap:16px}.summary-head p,.configuration{font-size:11px;color:var(--muted);line-height:1.6}.summary-head p{margin:6px 0 0}.configuration{margin:12px 0 16px}.verdict{font-size:11px;font-weight:500;border-radius:5px;padding:5px 9px;background:var(--surface-muted);color:var(--muted);white-space:nowrap}.verdict.failed{background:var(--danger-soft);color:var(--danger)}.verdict.passed{background:var(--success-soft);color:var(--success)}.numeric{text-align:right;font-variant-numeric:tabular-nums;white-space:nowrap}.muted{color:var(--muted)}.check{font-size:11px;color:var(--muted)}.check.failed{color:var(--danger);font-weight:500}.check.passed{color:var(--success)}.table-wrap{border-top:1px solid var(--border)}td,th{padding-top:10px;padding-bottom:10px}td:last-child,th:last-child{width:90px;padding-left:24px}@media(max-width:600px){.run-summary{padding:16px}.configuration{margin-top:10px}table{min-width:460px}}
+</style>
diff --git a/loadtest/console/src/ScenarioChecks.svelte b/loadtest/console/src/ScenarioChecks.svelte
new file mode 100644
index 0000000000..3524d6d732
--- /dev/null
+++ b/loadtest/console/src/ScenarioChecks.svelte
@@ -0,0 +1,61 @@
+<script>
+ import {resultTestCases,formatTestCaseValue,formatTestCaseLimit} from './result-test-cases.mjs';
+ export let summary;
+ export let latencyPhases=null;
+ $: sections=resultTestCases(summary);
+ $: states=(summary.states??latencyPhases??[]).filter(s=>s.count>0||s.windowExpected);
+ const latencyCheck=check=>/^p(50|95|99)$/.test(check.id);
+ const periodMetrics=new Set(['tps','errors','failed','completed']);
+ const periods=testCase=>(summary.groups||[]).filter(g=>['fault','recovery'].includes(g.kind)&&testCase.checks.some(c=>c.source===g.id));
+ const metric=(group,id)=>group.checks.find(c=>c.id===id);
+ const p99Limit=state=>state==='normal'?metric(summary.steady||{checks:[]},'p99')?.limit:state==='recovery'?(summary.groups||[]).filter(g=>g.kind==='recovery').flatMap(g=>g.checks).find(c=>c.id==='p99'&&c.limit!=null)?.limit:null;
+ const detailChecks=testCase=>testCase.checks.filter(c=>!latencyCheck(c)&&!(periods(testCase).length&&periodMetrics.has(c.id)));
+ const number=(value,digits=1)=>value==null||!Number.isFinite(value)?'—':value.toLocaleString(undefined,{maximumFractionDigits:digits});
+ const verdictLabel=check=>check.outcome==='not_measured'&&(check.id==='lost'||check.checks?.some(c=>c.id==='lost'&&c.outcome==='not_measured'))?'Reconciliation required':labels[check.outcome];
+ const labels={pass:'Pass',fail:'Fail',recorded:'—',not_measured:'Pending verification',not_run:'Not run',in_progress:'In progress',incomplete:'Incomplete'};
+</script>
+
+{#snippet caseRow(testCase)}
+ <span class="case-name">{testCase.title}</span><span class="muted">{testCase.expected}</span><span>{testCase.observed}{#if testCase.failureReason}<small class="failed">{testCase.failureReason}</small>{/if}</span><span class="outcome" class:passed={testCase.outcome==='pass'} class:failed={testCase.outcome==='fail'}>{verdictLabel(testCase)}</span>
+{/snippet}
+
+<div class="case-table">
+ <div class="case-row column-head" aria-hidden="true"><span>Test case</span><span>Expected</span><span>Observed</span><span>Verdict</span></div>
+ {#each sections as section (section.id)}
+ <section aria-labelledby={`case-section-${section.id}`}>
+ <h3 id={`case-section-${section.id}`}>{section.title}</h3>
+ {#each section.cases as testCase (testCase.id)}
+ {#if detailChecks(testCase).length>1||periods(testCase).length}
+ <details class="test-case">
+ <summary class="case-row">{@render caseRow(testCase)}</summary>
+ <div class="detail-table"><table><thead><tr><th>Check</th><th class="numeric">Limit</th><th class="numeric">Observed</th><th>Verdict</th></tr></thead><tbody>
+ {#each detailChecks(testCase) as check,index (`${check.source||''}:${check.id}:${index}`)}<tr><td>{check.label}</td><td class="numeric muted">{formatTestCaseLimit(check)}</td><td class="numeric">{formatTestCaseValue(check)}</td><td><span class="outcome" class:passed={check.outcome==='pass'} class:failed={check.outcome==='fail'}>{verdictLabel(check)}</span></td></tr>{:else}<tr><td colspan="4" class="muted">No execution evidence recorded for this test case.</td></tr>{/each}
+ </tbody></table></div>
+ {#if periods(testCase).length}
+ <div class="detail-table"><table aria-label="Outage and recovery measurements"><thead><tr><th>Period</th><th class="numeric">Successful TPS</th><th class="numeric">HTTP errors</th><th class="numeric">Completed flows</th></tr></thead><tbody>
+ {#each periods(testCase) as period}<tr><td>{period.kind==='fault'?'Outage':'After recovery'}</td><td class="numeric">{number(metric(period,'tps')?.actual)}</td><td class="numeric">{number(metric(period,'errors')?.actual)}%</td><td class="numeric">{number(metric(period,'completed')?.actual,0)}</td></tr>{/each}
+ </tbody></table></div>
+ {/if}
+ </details>
+ {:else}
+ <div class="test-case case-row">{@render caseRow(testCase)}</div>
+ {/if}
+ {/each}
+ </section>
+ {/each}
+</div>
+{#if states.length}
+ <h3 class="latency-title">Server-side latency</h3>
+ {#if summary.latencySettlingSeconds!=null}<p class="latency-note">Successful payment confirmations in settled periods · {summary.latencySettlingSeconds}s transition settling · restoration and cross-state flows excluded</p>{/if}
+ <div class="detail-table latency"><table><thead><tr><th>State</th><th class="numeric">p50 · ms</th><th class="numeric">p95 · ms</th><th class="numeric">p99 · ms</th></tr></thead><tbody>
+ {#each states as state}<tr><td>{state.state==='normal'?'Steady load':state.state==='outage'?'Outage':'After recovery'}</td><td class="numeric">{number(state.p50)}</td><td class="numeric">{number(state.p95)}</td><td class="numeric" class:failed={p99Limit(state.state)!=null&&state.p99>p99Limit(state.state)}>{number(state.p99)}{#if p99Limit(state.state)!=null&&state.p99>p99Limit(state.state)}<small>Limit ≤ {number(p99Limit(state.state))} ms</small>{/if}</td></tr>{/each}
+ </tbody></table></div>
+{/if}
+
+<style>
+
+
+ .latency-note{margin:-4px 0 10px;color:var(--muted);font-size:11px}
+ summary::before{display:none;content:none}summary{font-weight:400;line-height:1.45}
+ .case-table{min-width:0;border-top:1px solid var(--border)}.case-row{display:grid;grid-template-columns:minmax(0,1.25fr) minmax(0,1fr) minmax(0,1.4fr) minmax(0,.65fr);gap:16px;align-items:start;min-width:0;font-size:12px;padding:12px 8px}.case-row>span{min-width:0;overflow-wrap:anywhere}.column-head{background:var(--surface-muted);color:var(--muted);font-size:11px;font-weight:500}.case-table h3{margin:0;padding:14px 8px 8px;font-size:12px;font-weight:600}.test-case{border-bottom:1px solid var(--border)}summary{cursor:pointer;list-style:none}summary::-webkit-details-marker{display:none}.case-name{position:relative;padding-left:14px}summary .case-name::before{content:'›';position:absolute;left:0;transition:transform .1s}.test-case[open] summary .case-name::before{transform:rotate(90deg)}.detail-table{min-width:0}.test-case .detail-table{padding:0 8px 12px 22px}.latency-title{margin:20px 0 10px;font-size:12px;font-weight:600}.numeric{text-align:right;white-space:nowrap;font-variant-numeric:tabular-nums}.muted,.outcome{color:var(--muted)}.outcome{font-size:11px;white-space:normal;overflow-wrap:anywhere}.passed{color:var(--success)}.failed{color:var(--danger);font-weight:500}table{width:100%;table-layout:fixed}th,td{padding:9px 12px;font-size:12px;overflow-wrap:anywhere}th:first-child,td:first-child{padding-left:0;width:44%}th:last-child,td:last-child{padding-right:0;padding-left:16px;width:22%}small{display:block;color:var(--muted);font-size:10px;margin-top:3px}@media(max-width:600px){.case-row{grid-template-columns:minmax(0,1fr) minmax(0,1fr);gap:8px}.column-head{display:none}.case-name{grid-column:1/-1}.numeric{white-space:normal}th,td{padding:8px 4px}.test-case .detail-table{padding-left:8px}th:first-child,td:first-child{width:38%}th:last-child,td:last-child{padding-left:6px}}
+</style>
diff --git a/loadtest/console/src/ScenarioScreen.svelte b/loadtest/console/src/ScenarioScreen.svelte
new file mode 100644
index 0000000000..19598d648e
--- /dev/null
+++ b/loadtest/console/src/ScenarioScreen.svelte
@@ -0,0 +1,44 @@
+<script>
+import Icon from './Icon.svelte';
+import {formatDuration} from './duration.mjs';
+import {onMount} from 'svelte';
+import {loadTimeline} from './load-shape.mjs';
+import {api} from './api.js';import {invalidateAll} from '$app/navigation';import {setQuery} from './navigation.mjs';
+import {page} from '$app/stores';import ProfileEditor from './ProfileEditor.svelte';import {flowLabel} from './flow-catalog.mjs';
+export let data;
+let selectedId=data.profileId,search='',error='',deleteDialog,pendingDelete,deleting=false;
+$: search=$page.url.searchParams.get('q')||'';
+$: visible=profiles.filter(p=>p.name.toLowerCase().includes(search.toLowerCase()));
+$: profiles=data.profiles.filter(profile=>!profile.archived);
+$: view=$page.url.searchParams.get('view');
+$: source=profiles.find(p=>p.id===$page.url.searchParams.get('profile'));
+$: copying=source||profiles.find(p=>p.id===selectedId)||profiles[0]||data.profileTemplate;
+$: newScenarioHref=copying?.id?`/scenarios?view=new&profile=${encodeURIComponent(copying.id)}`:'/scenarios?view=new';
+onMount(()=>{const refresh=()=>invalidateAll();window.addEventListener('console-connections-saved',refresh);return()=>window.removeEventListener('console-connections-saved',refresh);});
+const hasRamp=profile=>loadTimeline(profile.load).some(stage=>stage.kind==='ramp');
+const faultCount=profile=>profile.load?.stages?.filter(stage=>stage.fault).length||0;
+const merchantLabel=profile=>profile.mode==='single'?'Single merchant':`Multiple · ${profile.merchantCount.toLocaleString()} merchants`;
+const readyFixture=profile=>data.fixtures.find(set=>set.status==='ready'&&set.compatible&&set.mode===profile.mode&&set.merchant_count===profile.merchantCount);
+function confirmDelete(profile){pendingDelete=profile;deleteDialog.showModal();}
+async function removeScenario(){if(!pendingDelete||deleting)return;deleting=true;error='';try{await api.deleteProfile(pendingDelete.id);deleteDialog.close();pendingDelete=null;await invalidateAll();}catch(e){error=e.message;}finally{deleting=false;}}
+</script>
+<svelte:head><title>Scenarios · Testbench</title></svelte:head>
+<main>
+{#if view==='new'||view==='edit'&&source}
+{#key `${view}:${copying.id}`}<ProfileEditor profile={view==='new'?copying:source} creating={view==='new'}/>{/key}
+{:else}
+<div class="section-head"><div><h1>Scenarios</h1><p>Build traffic patterns and resilience tests.</p></div><a class="button" href={newScenarioHref}><Icon name="plus"/> New scenario</a></div>
+{#if view==='edit'&&!source}<div class="message error">Scenario not found. Choose a saved scenario below.</div>{/if}
+<div class="library-filters"><div class="library-search"><Icon name="search"/><input type="search" aria-label="Search scenarios" placeholder="Search scenarios" bind:value={search} oninput={()=>setQuery({q:search})}/></div></div>{#if error}<p class="invalid" role="alert">{error}</p>{/if}<div class="profile-library">
+{#each visible as profile}
+{@const fixture=readyFixture(profile)}
+<article class="profile-card"><div class="profile-copy"><h2><a href={`/scenarios?view=edit&profile=${encodeURIComponent(profile.id)}`}>{profile.name}</a>{#if profile.isDefault}<span class="default-label">Default</span>{/if}</h2><div class="profile-metadata" aria-label="Scenario summary"><span>{merchantLabel(profile)}</span><span>{hasRamp(profile)?'Ramping':'Constant load'}</span><span><strong>{profile.totalRps.toLocaleString()}</strong> {hasRamp(profile)?'peak TPS':'TPS'}</span><span>{formatDuration(profile.durationSeconds)}</span>{#if faultCount(profile)>0}<span class="faults"><strong>{faultCount(profile)}</strong> {faultCount(profile)===1?'fault':'faults'}</span>{/if}</div><div class="flow-summary">{#each profile.scenarios as flow,index}<span>{index?' · ':''}{flowLabel(flow.scenario)} {flow.weight}%</span>{/each}</div></div><div class="profile-actions">{#if !profile.isDefault}<a class="button quiet" href={`/scenarios?view=edit&profile=${encodeURIComponent(profile.id)}`} onclick={()=>selectedId=profile.id}>Edit</a><button type="button" class="quiet delete-action" onclick={()=>confirmDelete(profile)}>Delete</button>{/if}<a class="button secondary" href={fixture?`/performance?profile=${encodeURIComponent(profile.id)}&fixtures=${encodeURIComponent(fixture.id)}`:`/fixtures?profile=${encodeURIComponent(profile.id)}`}>{fixture?'Test performance':'Create fixtures'}</a></div></article>
+{/each}{#if !visible.length}<div class="empty-library"><h2>{profiles.length?'No matching scenarios':'No scenarios yet'}</h2><p class="muted">{profiles.length?'Try a different search.':'Create a scenario to configure traffic, merchants, and faults.'}</p>{#if !profiles.length}<a class="button secondary" href={newScenarioHref}><Icon name="plus"/> New scenario</a>{/if}</div>{/if}
+</div>
+{/if}
+</main>
+<dialog bind:this={deleteDialog} oncancel={event=>{if(deleting)event.preventDefault();}} aria-labelledby="delete-scenario-title"><h2 id="delete-scenario-title">Delete scenario?</h2><p><strong>{pendingDelete?.name}</strong> will be deleted. Existing load-test runs keep their saved snapshots.</p><div class="actions"><button type="button" class="secondary" disabled={deleting} onclick={()=>deleteDialog.close()}>Cancel</button><button type="button" class="danger" disabled={deleting} onclick={removeScenario}>{deleting?'Deleting…':'Delete scenario'}</button></div></dialog>
+<style>
+.default-label{display:inline-block;vertical-align:middle;margin-left:10px;padding:3px 7px;border-radius:4px;background:var(--accent-soft);color:var(--accent);font-size:10px;font-weight:500}
+.library-filters{display:flex;align-items:center;gap:24px;margin:0 0 20px}.library-search{position:relative;flex:1;max-width:360px}.library-search :global(.ui-icon){position:absolute;left:12px;top:11px;color:var(--subtle)}.library-search input{margin:0;padding-left:36px;background:var(--surface)}.profile-library{background:var(--surface);border:1px solid var(--border);border-radius:var(--radius);box-shadow:var(--shadow)}.profile-card{display:flex;align-items:center;justify-content:space-between;gap:24px;padding:20px 22px;border-bottom:1px solid var(--border)}.profile-card:last-child{border-bottom:0}.profile-copy{min-width:0}.profile-card h2{font-size:15px;margin:0 0 9px}.profile-card h2 a{color:var(--ink);text-decoration:none}.profile-card h2 a:hover{color:var(--accent)}.profile-metadata{display:flex;align-items:center;gap:6px;flex-wrap:wrap;margin-bottom:8px}.profile-metadata span{display:inline-flex;align-items:center;min-height:24px;padding:4px 8px;border-radius:5px;background:var(--surface-muted);color:#536176;font-size:11px;line-height:1.2}.profile-metadata strong{font-weight:600;color:var(--ink);margin-right:3px}.profile-metadata .faults{background:var(--warning-soft);color:var(--warning)}.profile-metadata .faults strong{color:inherit}.flow-summary{color:var(--muted);font-size:11px;line-height:1.6}.profile-actions{display:flex;align-items:center;gap:6px;flex-shrink:0}.profile-actions a,.profile-actions button{font-size:12px}.profile-actions .delete-action{--button-fg:var(--danger);--button-hover-bg:var(--danger-soft);--button-hover-fg:var(--danger)}.empty-library{padding:44px 24px;text-align:center}.empty-library h2{margin-bottom:4px}.empty-library p{margin:0 0 16px}.section-head>div{min-width:0}@media(max-width:750px){.profile-card{align-items:flex-start;flex-direction:column;padding:18px;gap:16px}.profile-actions{width:100%;flex-wrap:wrap}.profile-actions a:last-child{margin-left:auto}.library-filters{gap:16px}.library-search{max-width:none}}@media(max-width:420px){.library-filters{flex-wrap:wrap}.library-search{flex-basis:100%}.profile-actions a:last-child{width:100%;margin-left:0}}
+</style>
diff --git a/loadtest/console/src/ServiceIndicators.svelte b/loadtest/console/src/ServiceIndicators.svelte
new file mode 100644
index 0000000000..b75fe8d866
--- /dev/null
+++ b/loadtest/console/src/ServiceIndicators.svelte
@@ -0,0 +1,74 @@
+<script>
+import {environments,environmentLabel} from './environments.mjs';
+import {onMount} from 'svelte';
+import {api} from './api.js';
+import {isDatabaseTarget,faultHealthOverride,pendingHealth} from './service-health.mjs';
+
+export let settings;
+let services=[],refreshing=false,refreshQueued=false,timer;
+
+const labelFor=target=>target.serviceType==='card-vault'?'Card vault':target.serviceType==='redis'?'Redis':target.label;
+// Database reachability is always defined by the saved Settings connection. Older
+// fault targets may lack serviceType, so recognize their legacy PostgreSQL labels too.
+function configuredServices(targets=[]){
+ const result=[
+ {id:'router',label:'Router',check:()=>api.testService('router',settings.router,undefined,settings.environment)},
+ {id:'pm',label:'PM service',check:()=>api.testService('modularPm',settings.modularPm,undefined,settings.environment)},
+ {id:'database',label:'DB',check:()=>api.testDatabase(settings.database,settings.environment)}
+ ];
+ if(settings.superposition?.endpoint)result.push({id:'superposition',label:'Superposition',check:()=>api.testService('superposition',settings.superposition.endpoint,settings.superposition,settings.environment)});
+ for(const target of targets){
+ if(target.adapter==='simulated'||isDatabaseTarget(target))continue;
+ const label=labelFor(target);
+ if(result.some(service=>service.label===label))continue;
+ result.push({id:`fault-${target.id}`,targetId:target.id,label,check:()=>api.checkFaultTarget(target)});
+ }
+ return result;
+}
+async function refresh(){
+ if(refreshing){refreshQueued=true;return;}
+ refreshing=true;
+ try{settings=await api.settings();}catch(error){services=services.map(service=>({...service,state:'offline',message:error.message}));refreshing=false;return;}
+ if(!environments.find(e=>e.id===settings.environment)?.supported){services=[{id:'environment',label:environmentLabel(settings.environment),state:'unconfigured',message:'Provider execution is not configured'}];refreshing=false;return;}
+ let targets=[],fault={};
+ try{fault=await api.faults();targets=(fault.targets||[]).map(item=>item.target||item);}catch{}
+ if(fault.environment&&fault.environment!==settings.environment){refreshing=false;return;}
+ const configured=configuredServices(targets),previous=new Map(services.map(service=>[service.id,service]));
+ services=configured.map(service=>pendingHealth(service,previous.get(service.id),faultHealthOverride(service,fault,targets)));
+ await Promise.all(configured.map(async service=>{
+ const override=faultHealthOverride(service,fault,targets);if(override)return;
+ try{const result=await service.check();services=services.map(item=>item.id===service.id?{...item,state:'online',message:result.message||'Available'}:item);}
+ catch(error){services=services.map(item=>item.id===service.id?{...item,state:'offline',message:error.message}:item);}
+ }));
+ refreshing=false;
+ if(refreshQueued){refreshQueued=false;refresh();}
+}
+onMount(()=>{
+ const saved=()=>refresh(),faultChanged=()=>refresh();
+ refresh();timer=setInterval(refresh,30000);
+ window.addEventListener('console-connections-saved',saved);
+ window.addEventListener('console-fault-state',faultChanged);
+ return()=>{clearInterval(timer);window.removeEventListener('console-connections-saved',saved);window.removeEventListener('console-fault-state',faultChanged);};
+});
+</script>
+
+<div class="service-indicators" aria-label="Configured service status" aria-live="polite">
+ {#each services as service}
+ <button type="button" class="service-indicator" class:online={service.state==='online'} class:offline={service.state==='offline'} class:checking={service.state==='checking'} class:recovering={service.state==='recovering'} onclick={refresh} title={`${service.label}: ${service.message}`} aria-label={`${service.label}: ${service.message}`}>
+ <span aria-hidden="true"></span><b>{service.label}</b>
+ </button>
+ {/each}
+</div>
+
+<style>
+.service-indicators{display:flex;flex-direction:column;align-items:stretch;gap:8px;width:100%}
+.service-indicator{--button-bg:transparent;--button-fg:#617087;--button-border:transparent;--button-hover-bg:var(--hover-bg);--button-hover-fg:var(--ink);--button-hover-border:transparent;width:100%;min-height:32px;justify-content:flex-start;gap:10px;padding:6px 8px;border-radius:6px;font-size:12px;font-weight:500;line-height:1.25;letter-spacing:-.01em;transition:color .14s ease,background-color .14s ease}
+.service-indicator span{width:6px;height:6px;border-radius:50%;background:var(--subtle);flex:0 0 auto;transition:background-color .16s ease}
+.service-indicator.online span{background:var(--success)}
+.service-indicator.recovering span{background:#b7791f}
+.service-indicator.offline{--button-fg:var(--danger);--button-hover-fg:var(--danger)}
+.service-indicator.offline span{background:var(--danger)}
+.service-indicator.checking{--button-fg:var(--subtle)}
+.service-indicator b{font:inherit;white-space:nowrap}
+@media(max-width:600px){.service-indicators{flex-direction:row;flex-wrap:wrap;justify-content:center;gap:2px 8px}.service-indicator{width:auto;min-height:32px;padding:6px 8px;gap:8px;font-size:11px}}
+</style>
diff --git a/loadtest/console/src/Shell.svelte b/loadtest/console/src/Shell.svelte
new file mode 100644
index 0000000000..b8738ab8fc
--- /dev/null
+++ b/loadtest/console/src/Shell.svelte
@@ -0,0 +1,153 @@
+<script>
+import InfoTooltip from './InfoTooltip.svelte';
+import {environmentAccessNote,environments,environmentLabel} from './environments.mjs';
+import {onMount} from 'svelte';
+import Icon from './Icon.svelte';
+import Brand from './Brand.svelte';
+import ServiceIndicators from './ServiceIndicators.svelte';
+import {page,navigating} from '$app/stores';
+import {api} from './api.js';
+export let data;
+import {beforeNavigate,afterNavigate,goto} from '$app/navigation';
+import UnsavedChanges from './UnsavedChanges.svelte';
+import {defaultResultsLimits,resultsLimitFields} from './results-limits.mjs';
+import {navigationContext,rememberPage,sectionHref} from './navigation.mjs';
+let settings=structuredClone(data.settings),savedSettings=JSON.stringify(settings),settingsDialog,pending='',error='',databaseCheck=null,serviceChecks={},certificates=[],workers=[],certificateFile,certificateName='';
+let section='connections',settingsPanel,loading=false,leaveDialog,allowLeave=false,copied=false;
+let restorePageScroll;
+$: loadingSection=$navigating?.to?.url.pathname!==$page.url.pathname&&['/scenarios','/fixtures','/performance','/results'].includes($navigating?.to?.url.pathname)?$navigating.to.url.pathname.slice(1):'';
+const sections=[['environment','Environment'],['connections','Connections'],['database','Database & TLS'],['load','Load generation'],['results','Results limits'],['workers','Workers']];
+$: dirty=JSON.stringify(settings)!==savedSettings;
+$: healthSettings=JSON.parse(savedSettings);
+$: databaseFingerprint=JSON.stringify(settings.database);
+$: if(databaseCheck&&databaseCheck.fingerprint!==databaseFingerprint)databaseCheck=null;
+$: activeCertificate=JSON.parse(savedSettings).database.caCertificateId;
+function selectSection(id){section=id;if(settingsPanel)settingsPanel.scrollTop=0;}
+function settingsKey(event,index){if(!['ArrowLeft','ArrowRight','ArrowUp','ArrowDown','Home','End'].includes(event.key))return;event.preventDefault();const next=event.key==='Home'?0:event.key==='End'?sections.length-1:(index+(['ArrowRight','ArrowDown'].includes(event.key)?1:-1)+sections.length)%sections.length;selectSection(sections[next][0]);event.currentTarget.parentElement.querySelectorAll('button')[next].focus();}
+function lockPageScroll(){
+ if(restorePageScroll)return;
+ const root=document.documentElement,body=document.body,scrollbar=Math.max(0,window.innerWidth-root.clientWidth);
+ const previous={rootOverflow:root.style.overflow,bodyOverflow:body.style.overflow,bodyPaddingRight:body.style.paddingRight};
+ root.style.overflow='hidden';body.style.overflow='hidden';
+ if(scrollbar)body.style.paddingRight=`${Number.parseFloat(getComputedStyle(body).paddingRight||'0')+scrollbar}px`;
+ restorePageScroll=()=>{root.style.overflow=previous.rootOverflow;body.style.overflow=previous.bodyOverflow;body.style.paddingRight=previous.bodyPaddingRight;restorePageScroll=null;};
+}
+async function openSettings(event){section=event?.detail?.section||'connections';if(settingsDialog.open)return;settingsDialog.showModal();lockPageScroll();loading=true;error='';try{settings=await api.settings();environmentDrafts={};savedSettings=JSON.stringify(settings);await Promise.all([api.certificates().then(x=>certificates=x),api.workers().then(x=>workers=x)]);}catch(e){error=e.message;}finally{loading=false;}}
+let environmentDrafts={};
+async function selectEnvironment(environment){environmentDrafts[settings.environment]=structuredClone(settings);pending='environment';error='';try{settings=environmentDrafts[environment]||await api.settings(environment);databaseCheck=null;serviceChecks={};}catch(e){error=e.message;}finally{pending='';}}
+async function closeSettings(){if(pending)return;if(!dirty||await leaveDialog.ask()){if(dirty)settings=JSON.parse(savedSettings);settingsDialog.close();}}
+async function saveSettings(){pending='save';error='';try{settings=await api.saveSettings(settings);savedSettings=JSON.stringify(settings);settingsDialog.close();window.dispatchEvent(new Event('console-connections-saved'));return true;}catch(e){error=e.message;return false;}finally{pending='';}}
+async function testDatabase(){pending='test';databaseCheck=null;const fingerprint=databaseFingerprint;try{const result=await api.testDatabase(settings.database,settings.environment);if(databaseFingerprint===fingerprint)databaseCheck={...result,fingerprint};}catch(e){if(databaseFingerprint===fingerprint)databaseCheck={ok:false,message:e.message,fingerprint};}finally{pending='';}}
+async function testService(kind,endpoint){pending=`test-${kind}`;serviceChecks={...serviceChecks,[kind]:null};try{serviceChecks={...serviceChecks,[kind]:{...await api.testService(kind,endpoint,kind==='superposition'?settings.superposition:undefined,settings.environment),endpoint}};}catch(e){serviceChecks={...serviceChecks,[kind]:{ok:false,message:e.message,endpoint}};}finally{pending='';}}
+async function importCertificate(){if(!certificateFile)return;pending='certificate';error='';try{const added=await api.importCertificate(certificateFile,certificateName);certificates=[...certificates,added];settings.database.caCertificateId=added.id;settings.database.caPath='';certificateFile=null;certificateName='';}catch(e){error=e.message;}finally{pending='';}}
+async function removeCertificate(id){pending='certificate';error='';try{await api.removeCertificate(id);certificates=certificates.filter(item=>item.id!==id);}catch(e){error=e.message;}finally{pending='';}}
+async function deleteWorker(id){pending='worker';error='';try{await api.removeWorker(id);workers=workers.filter(worker=>worker.id!==id);}catch(e){error=e.message;}finally{pending='';}}
+function workerCommand(){return `LOADTEST_CONTROL_PLANE_URL=${window.location.origin} LOADTEST_WORKER_NAME=worker-1 LOADTEST_WORKER_ENROLLMENT_TOKEN='<server enrollment token>' LOADTEST_WORKER_TPS=250 LOADTEST_WORKER_VUS=2500 npm run worker:agent`;}
+async function copyWorker(){try{await navigator.clipboard.writeText(workerCommand());copied=true;setTimeout(()=>copied=false,2000);}catch{error='Clipboard unavailable. Select and copy the command below.';}}
+afterNavigate(({to})=>{if(to)rememberPage(new URL(window.location.href));});
+beforeNavigate(({cancel,to,type})=>{if(allowLeave){allowLeave=false;return;}if(!settingsDialog?.open)return;if(pending){cancel();return;}if(dirty){cancel();leaveDialog.ask().then(ok=>{if(ok&&to){if(dirty)settings=JSON.parse(savedSettings);settingsDialog.close();allowLeave=true;goto(to.url,{replaceState:type==='popstate'});}});}else settingsDialog.close();});
+onMount(()=>{const open=e=>openSettings(e),unload=e=>{if(settingsDialog.open&&dirty){e.preventDefault();e.returnValue='';}},closed=()=>restorePageScroll?.();window.addEventListener('console-settings',open);window.addEventListener('beforeunload',unload);settingsDialog.addEventListener('close',closed);const poll=setInterval(()=>{if(settingsDialog.open&&section==='workers')api.workers().then(x=>workers=x).catch(e=>error=e.message);},5000);return()=>{clearInterval(poll);restorePageScroll?.();settingsDialog.removeEventListener('close',closed);window.removeEventListener('console-settings',open);window.removeEventListener('beforeunload',unload);};});
+</script>
+<header class="app-header">
+ <div class="brand-group"><a class="brand" href="/scenarios" aria-label="JUSPAY Hyperswitch · Testbench home"><img class="company-logo" src="/hyperswitch-logo.svg" alt="JUSPAY Hyperswitch"/><span class="product-brand"><Brand/></span></a><button type="button" class="environment-label" aria-label={`Change environment: ${environmentLabel(healthSettings.environment)}`} aria-haspopup="dialog" onclick={()=>openSettings({detail:{section:'environment'}})}>{environmentLabel(healthSettings.environment)}</button></div>
+ <div class="header-actions"><button class="header-button" onclick={openSettings}><Icon name="settings"/> Settings</button><form action="/logout" method="POST"><button class="header-button" aria-label="Sign out" title="Sign out"><span>Sign out</span><Icon name="logout"/></button></form></div>
+</header>
+<div class="console-frame">
+ <nav class="section-nav" aria-label="Console sections" aria-busy={!!$navigating}><div class="section-links">{#each ['scenarios','fixtures','performance','results'] as item}<a class:active={$page.url.pathname===`/${item}`||$page.url.pathname.startsWith(`/${item}/`)} class:opening={$navigating?.to?.url.pathname===`/${item}`} aria-current={$page.url.pathname===`/${item}`?'page':undefined} href={sectionHref(item,$page.url,$navigationContext)}><Icon name={item}/><span>{item[0].toUpperCase()+item.slice(1)}</span></a>{/each}</div></nav>
+ <aside class="service-sidebar" aria-labelledby="service-health-heading">
+ <div class="service-health">
+ <h2 id="service-health-heading">HEALTH</h2>
+ <ServiceIndicators settings={healthSettings}/>
+ </div>
+ </aside>
+ <div class="console-content" aria-busy={!!loadingSection}>
+ <div hidden={!!loadingSection}><slot/></div>
+ {#if loadingSection}<section class="section-loader" role="status" aria-live="polite"><span class="loading-spinner" aria-hidden="true"></span><p>Loading {loadingSection}…</p></section>{/if}
+ </div>
+</div>
+
+<UnsavedChanges bind:this={leaveDialog} save={saveSettings}/>
+<dialog oncancel={e=>{e.preventDefault();closeSettings();}} class="settings-dialog" bind:this={settingsDialog} aria-labelledby="settings-title">
+ <section class="settings">
+ <div class="section-head"><h1 id="settings-title">Settings</h1><button class="icon-button" aria-label="Close settings" onclick={closeSettings}><Icon name="close"/></button></div>
+ {#if error}<div class="message error" role="alert">{error}</div>{/if}
+ <div class="settings-body">
+ <div class="settings-tabs" role="tablist" aria-label="Settings sections">{#each sections as [id,label],index}<button class="quiet" role="tab" tabindex={section===id?0:-1} onkeydown={e=>settingsKey(e,index)} aria-selected={section===id} class:active={section===id} onclick={()=>selectSection(id)}>{label}</button>{/each}</div>
+ <div class="settings-grid" bind:this={settingsPanel}>
+ {#if loading}<p role="status">Loading settings…</p>{:else}
+ <div hidden={section!=='environment'}>
+ <h2>Environment <InfoTooltip id="environment-access-info" label="Environment access information" text={environmentAccessNote(settings.environment)}/></h2>
+ <p>Select where connections, load tests and faults run.</p>
+ <label>Provider<select value={settings.environment} disabled={!!pending} onchange={e=>selectEnvironment(e.currentTarget.value)}><option value="unassigned" disabled>Choose an environment</option>{#each environments as environment}<option value={environment.id}>{environment.label}</option>{/each}</select></label>
+ {#if settings.environment==='gcp'}<p class="environment-note" role="note"><Icon name="info" size={16}/><span>GCP fault tests require authenticated <code>gcloud</code> access on the console host and permissions for the configured resources. Kubernetes faults also require the correct context and workload permissions.</span></p>{/if}
+ </div>
+ <div hidden={section!=='connections'}>
+ <h2>Services</h2>
+ <div class="fields"><div class="service-field"><label for="service-router">Router</label><div class="service-input"><input id="service-router" bind:value={settings.router}/><button type="button" class="secondary" class:check-success={serviceChecks.router?.endpoint===settings.router&&serviceChecks.router?.ok} class:check-failed={serviceChecks.router?.endpoint===settings.router&&serviceChecks.router&&!serviceChecks.router.ok} disabled={!!pending||!environments.find(e=>e.id===settings.environment)?.supported} onclick={()=>testService('router',settings.router)}>{pending==='test-router'?'Checking…':serviceChecks.router?.endpoint===settings.router?serviceChecks.router.ok?'Succeeded':'Failed':'Test'}</button></div>{#if serviceChecks.router?.endpoint===settings.router}<small class:invalid={!serviceChecks.router.ok} role="status">{serviceChecks.router.message}</small>{/if}</div><div class="service-field"><label for="service-modularPm">Payment methods</label><div class="service-input"><input id="service-modularPm" bind:value={settings.modularPm}/><button type="button" class="secondary" class:check-success={serviceChecks.modularPm?.endpoint===settings.modularPm&&serviceChecks.modularPm?.ok} class:check-failed={serviceChecks.modularPm?.endpoint===settings.modularPm&&serviceChecks.modularPm&&!serviceChecks.modularPm.ok} disabled={!!pending||!environments.find(e=>e.id===settings.environment)?.supported} onclick={()=>testService('modularPm',settings.modularPm)}>{pending==='test-modularPm'?'Checking…':serviceChecks.modularPm?.endpoint===settings.modularPm?serviceChecks.modularPm.ok?'Succeeded':'Failed':'Test'}</button></div>{#if serviceChecks.modularPm?.endpoint===settings.modularPm}<small class:invalid={!serviceChecks.modularPm.ok} role="status">{serviceChecks.modularPm.message}</small>{/if}</div><label>Router admin key<input type="password" bind:value={settings.adminApiKey} placeholder={settings.hasAdminApiKey ? 'Configured · leave blank to keep' : 'Required'} /></label><label>Connector<input bind:value={settings.connector} /></label></div>
+ <h2>Superposition</h2>
+ <div class="fields"><div class="service-field"><label for="service-superposition">Endpoint</label><div class="service-input"><input id="service-superposition" bind:value={settings.superposition.endpoint}/><button type="button" class="secondary" class:check-success={serviceChecks.superposition?.endpoint===settings.superposition.endpoint&&serviceChecks.superposition?.ok} class:check-failed={serviceChecks.superposition?.endpoint===settings.superposition.endpoint&&serviceChecks.superposition&&!serviceChecks.superposition.ok} disabled={!!pending||!environments.find(e=>e.id===settings.environment)?.supported} onclick={()=>testService('superposition',settings.superposition.endpoint)}>{pending==='test-superposition'?'Checking…':serviceChecks.superposition?.endpoint===settings.superposition.endpoint?serviceChecks.superposition.ok?'Succeeded':'Failed':'Test'}</button></div>{#if serviceChecks.superposition?.endpoint===settings.superposition.endpoint}<small class:invalid={!serviceChecks.superposition.ok} role="status">{serviceChecks.superposition.message}</small>{/if}</div><label>Authentication<select bind:value={settings.superposition.accessHeader}><option value="x-superposition-access">x-superposition-access header</option><option value="authorization">Authorization bearer token</option></select></label><label>Token<input type="password" bind:value={settings.superposition.token} placeholder={settings.superposition.hasToken ? 'Configured · leave blank to keep' : 'Required'} /></label><label>Organization<input bind:value={settings.superposition.organizationId} /></label><label>Workspace<input bind:value={settings.superposition.workspaceId} /></label><label>Refresh timeout · seconds<input type="number" min="0" bind:value={settings.superposition.refreshSeconds}/></label><label>Poll every · seconds<input type="number" min="0.25" max="60" step="0.25" bind:value={settings.superposition.pollSeconds}/></label></div>
+ <label>Defaults<textarea rows="5" bind:value={settings.superposition.defaultsJson}></textarea></label>
+ </div><div hidden={section!=='load'}>
+ <h2>Load generator</h2>
+ <p>VU capacity applied when each load or smoke run starts.</p>
+ <div class="fields"><label>Preallocated VUs per TPS<input type="number" min="0.1" step="0.1" bind:value={settings.preAllocatedVusMultiplier}/></label><label>Maximum VUs per TPS<input type="number" min="0.1" step="0.1" bind:value={settings.maxVusMultiplier}/></label></div>
+ </div><div hidden={section!=='results'}>
+ <h2>Results limits</h2>
+ <p>Applied to future runs. Each run keeps its own copy of these limits.</p>
+ <div class="fields">{#each resultsLimitFields as [key,label,unit,max]}<label for={`results-${key}`}>{label} · {unit}<input id={`results-${key}`} type="number" min={key==='recoveryWindowSeconds'?0.1:0} {max} step={key==='maximumLostPayments'?1:'any'} bind:value={settings.resultsLimits[key]} required/></label>{/each}</div>
+ <button type="button" class="secondary" onclick={()=>settings.resultsLimits={...defaultResultsLimits}}>Reset to defaults</button>
+ </div><div hidden={section!=='workers'}>
+ <h2>Workers</h2><p>Load agents connect outbound and report their available TPS and VU capacity.</p>
+ {#if !settings.workerEnrollmentConfigured}<div class="message error" role="alert">Worker enrollment is disabled. Set <code>LOADTEST_WORKER_ENROLLMENT_TOKEN</code> in <code>loadtest/console/.env</code>, then restart the console.</div>{/if}
+ <details class="advanced"><summary>Connect a worker</summary><p>Run from loadtest/console on each load machine. Use a unique name and the enrollment token configured on the master.</p><pre class="onboarding">{typeof window!=='undefined'?workerCommand():''}</pre><button type="button" class="secondary" onclick={copyWorker}>{copied?'Copied':'Copy command'}</button><p>Fault commands run on the master. Workers generate load only. Health refreshes every 5 seconds.</p></details><div class="worker-list">{#each workers as worker}<div><span class:offline={worker.status==='offline'}></span><strong>{worker.name}</strong><small>{worker.status} · {worker.capacityTps} TPS · {worker.capacityVus} VUs</small>{#if worker.id!=='local'}<button class="icon-button danger" aria-label={`Remove ${worker.name}`} disabled={worker.status!=='offline'||!!pending} onclick={()=>deleteWorker(worker.id)}><Icon name="close"/></button>{/if}</div>{:else}<p>No workers registered.</p>{/each}</div>
+ </div>
+ <div hidden={section!=='database'}>
+ <h2 id="database-settings">Database</h2><p>Use an existing PostgreSQL account with read access to payment_intent.</p>
+ <div class="fields">
+ <label>Host<input bind:value={settings.database.host} /></label>
+ <label>Port<input type="number" bind:value={settings.database.port} /></label>
+ <label>Database<input bind:value={settings.database.database} /></label>
+ <label>Read-only user<input bind:value={settings.database.user} /></label>
+ <label>Password<input type="password" bind:value={settings.database.password} placeholder={settings.database.hasPassword ? 'Configured · leave blank to keep' : 'Required'} /></label>
+ <label>TLS<select bind:value={settings.database.tlsMode}><option value="disable">Disabled</option><option value="require">Required · encrypted</option><option value="verify">Verified certificate</option></select></label>
+ </div>
+ {#if settings.database.tlsMode==='verify'}
+ <details class="custom-ca">
+ <summary>Custom CA certificate <span>{settings.database.caCertificateId ? certificates.find(c=>c.id===settings.database.caCertificateId)?.name || 'Imported certificate' : settings.database.caPath ? 'Server-mounted certificate' : 'System trust store'}</span></summary>
+ <div class="ca-options">
+ {#if certificates.length}
+ <label>Certificate authority<select bind:value={settings.database.caCertificateId} onchange={()=>{if(settings.database.caCertificateId)settings.database.caPath='';}}><option value="">System trust store</option>{#each certificates as certificate}<option value={certificate.id}>{certificate.name} · {certificate.fingerprint?.slice(-17)}</option>{/each}</select></label>
+ {/if}
+ <div class="fields">
+ <label>Certificate name<input bind:value={certificateName} placeholder="Database CA" /></label>
+ <label>PEM or CRT file<input type="file" accept=".pem,.crt,application/x-pem-file,application/pem-certificate-chain" onchange={e=>certificateFile=e.currentTarget.files?.[0]}/></label>
+ </div>
+ <button type="button" class="secondary" disabled={!certificateFile||!!pending} onclick={importCertificate}>{pending==='certificate'?'Importing…':'Import certificate'}</button>
+ {#if certificates.length}
+ <div class="certificate-list">{#each certificates as certificate}<div><span><strong>{certificate.name}</strong><small>{certificate.subject} · expires {new Date(certificate.validTo).toLocaleDateString()}</small></span><button type="button" class="icon-button danger" aria-label={`Delete ${certificate.name}`} disabled={settings.database.caCertificateId===certificate.id||activeCertificate===certificate.id||!!pending} onclick={()=>removeCertificate(certificate.id)}><Icon name="close"/></button></div>{/each}</div>
+ {/if}
+ </div>
+ </details>
+ {/if}
+ <button type="button" class="secondary database-test" class:check-success={databaseCheck?.ok} class:check-failed={databaseCheck&&!databaseCheck.ok} disabled={!!pending||!environments.find(e=>e.id===settings.environment)?.supported} onclick={testDatabase}>{pending==='test'?'Checking…':databaseCheck?databaseCheck.ok?'Succeeded':'Failed':'Test connection'}</button>
+ {#if databaseCheck}<p role="status" class:invalid={!databaseCheck.ok}>{databaseCheck.message}</p>{/if}
+ </div>
+ {/if}
+ </div>
+ </div>
+ <div class="actions settings-save"><small>{dirty?'Unsaved changes':'All changes saved'}</small><button type="button" class="secondary" onclick={closeSettings}>Close</button><button type="button" disabled={!!pending || loading || !dirty} onclick={saveSettings}>{pending === 'save' ? 'Saving…' : 'Save settings'}</button></div>
+ </section>
+</dialog>
+
+<style>
+.environment-note{display:flex;align-items:flex-start;gap:10px;margin:16px 0 0;padding:12px 14px;border:1px solid var(--border);border-radius:6px;background:var(--accent-soft);color:var(--ink);font-size:12px;line-height:1.6}.environment-note :global(svg){flex-shrink:0;margin-top:2px;color:var(--accent)}
+
+.section-nav a.opening{color:var(--accent);background:var(--accent-soft)}.section-loader{min-height:calc(100dvh - var(--header-height) - var(--nav-height));display:flex;align-items:center;justify-content:center;flex-direction:column;gap:14px;padding:32px;color:var(--muted)}.section-loader p{margin:0;font-size:14px}.loading-spinner{width:28px;height:28px;border:3px solid var(--border);border-top-color:var(--accent);border-radius:50%;animation:section-spin .8s linear infinite}@keyframes section-spin{to{transform:rotate(360deg)}}@media(prefers-reduced-motion:reduce){.loading-spinner{animation:none}}
+.brand-group{display:flex;align-items:center;gap:14px;flex-shrink:0}.environment-label{--button-hover-bg:var(--accent-soft);--button-hover-fg:var(--accent);--button-hover-border:var(--accent);min-height:0;font-size:11px;font-weight:400;line-height:1.2;color:var(--accent);background:var(--accent-soft);border:1px solid transparent;border-radius:5px;padding:4px 8px;white-space:nowrap}.brand{gap:14px}.company-logo{display:block;width:175px;height:auto}.product-brand{display:flex;align-items:center;padding-left:14px;border-left:1px solid var(--border)}
+@media(max-width:900px){.company-logo{width:150px}.product-brand{padding-left:12px}}
+@media(max-width:600px){.company-logo{width:138px}.product-brand{display:none}}
+.custom-ca{border-top:1px solid var(--border);padding-top:14px}.custom-ca summary{flex-wrap:wrap}.custom-ca summary>span{margin-left:auto;font-size:12px;font-weight:400;color:var(--muted)}.ca-options{display:grid;gap:14px;padding-top:16px}.ca-options>button{justify-self:start}.ca-options .certificate-list{margin-top:0}
+.service-input{display:flex;align-items:center;gap:8px;margin-top:6px}.service-input input{margin:0;min-width:0}.service-input button{flex-shrink:0}.database-test{margin-top:16px}.service-field small{display:block;margin-top:6px;font-size:11px}
+.settings{display:flex;flex-direction:column;height:100%;gap:20px;overflow:hidden}.settings>.section-head,.settings>.message,.settings>.settings-save{flex-shrink:0}.settings>.message{margin:0;max-height:90px;overflow:auto}.settings-body{display:grid;grid-template-columns:156px minmax(0,1fr);gap:24px;min-height:0;flex:1}.settings>.section-head{margin:0;padding-bottom:20px;border-bottom:1px solid var(--border);align-items:flex-start}.settings-tabs{display:flex;flex-direction:column;align-items:stretch;gap:5px;overflow-y:auto;padding:4px}.settings-tabs button{justify-content:flex-start;text-align:left;white-space:normal;font-size:12px;padding:10px 12px}.settings-tabs button.active{--button-bg:var(--accent-soft);--button-fg:var(--accent);--button-hover-bg:var(--selected-hover);--button-hover-fg:var(--accent)}.settings-grid{display:block;min-height:0;overflow-y:auto;overscroll-behavior:contain;scrollbar-gutter:stable;padding:4px 8px 8px 24px;border-left:1px solid var(--border)}.settings-save{background:var(--surface);padding:16px 0 0;margin:0;border-top:1px solid var(--border)}.settings-save small{margin-right:auto;color:var(--muted);font-size:12px}.onboarding{white-space:pre-wrap;overflow-wrap:anywhere;font-size:12px;background:var(--surface-muted);padding:14px;border-radius:8px}[hidden]{display:none!important}.certificate-list,.worker-list{display:grid;gap:8px;margin-top:12px}.certificate-list>div,.worker-list>div{display:flex;align-items:center;gap:10px;border:1px solid var(--border);border-radius:7px;padding:10px 12px}.certificate-list>div{justify-content:space-between}.certificate-list span{display:grid;gap:3px;min-width:0}.certificate-list small{overflow-wrap:anywhere}.worker-list span{width:7px;height:7px;border-radius:50%;background:var(--success);flex-shrink:0}.worker-list span.offline{background:var(--subtle)}.worker-list small{margin-left:auto;color:var(--muted)}
+@media(max-width:650px){.settings{gap:16px}.settings-body{display:flex;flex-direction:column;gap:12px}.settings-tabs{flex-direction:row;flex-wrap:wrap;flex-shrink:0;gap:4px}.settings-tabs button{padding:8px 10px}.settings-grid{border:0;padding:4px 4px 8px;flex:1}.settings-save{flex-wrap:wrap}.settings-save small{flex-basis:100%}.worker-list>div{flex-wrap:wrap}}
+</style>
diff --git a/loadtest/console/src/StatCard.svelte b/loadtest/console/src/StatCard.svelte
new file mode 100644
index 0000000000..61cd72f77a
--- /dev/null
+++ b/loadtest/console/src/StatCard.svelte
@@ -0,0 +1,34 @@
+<script>
+ import {rateIntervals} from './chart-timeline.mjs';
+ export let rate=false;
+ export let durationSeconds=0;
+ export let tooltip='';
+ export let label;
+ export let value;
+ export let unit = '';
+ export let caption;
+ export let series = [];
+ export let color = '#5277b8';
+
+ $: points = series.filter(p => Number.isFinite(p.t) && Number.isFinite(p.value));
+ $: maximum = Math.max(1, ...points.map(p => p.value));
+ $: duration = Math.max(1,durationSeconds,points.at(-1)?.t||0);
+ $: values=rate?rateIntervals(points):points;
+ $: line = values.map(p => `${(p.t/duration*300).toFixed(2)},${(69-Math.max(0,p.value)/maximum*63).toFixed(2)}`).join(' ');
+ $: firstX=(values[0]?.t||0)/duration*300;
+ $: lastX=(values.at(-1)?.t||0)/duration*300;
+</script>
+
+<article title={tooltip || undefined} style:--trend-color={color}>
+ {#if points.length > 1}
+ <svg viewBox="0 0 300 70" preserveAspectRatio="none" aria-hidden="true">
+ <polygon points={`${firstX},70 ${line} ${lastX},70`} />
+ <polyline points={line} />
+ </svg>
+ {/if}
+ <span>{label}</span><strong>{value}<small>{unit}</small></strong><em>{caption}</em>
+</article>
+
+<style>
+article{position:relative;overflow:hidden;isolation:isolate;background:var(--surface);padding:18px 20px 40px;min-height:134px;border-right:1px solid var(--border)}article:last-child{border-right:0}span,em{position:relative;display:block;color:var(--muted);font-size:11px;font-style:normal;line-height:1.5}span{font-weight:500}strong{position:relative;display:block;font-size:29px;line-height:1.15;margin:8px 0 5px;color:var(--ink);font-weight:550;letter-spacing:-.8px;font-variant-numeric:tabular-nums}small{font-size:12px;font-weight:400;margin-left:5px;letter-spacing:0;color:var(--muted)}svg{position:absolute;z-index:-1;inset:auto 0 0;width:100%;height:26px;overflow:hidden}polygon{fill:var(--trend-color);opacity:.04}polyline{fill:none;stroke:var(--trend-color);opacity:.55;stroke-width:1.2;vector-effect:non-scaling-stroke}@media(max-width:900px){article:nth-child(2){border-right:0}article:nth-child(-n+2){border-bottom:1px solid var(--border)}}@media(max-width:480px){article{padding:16px 14px 36px}strong{font-size:26px}}
+</style>
diff --git a/loadtest/console/src/UnsavedChanges.svelte b/loadtest/console/src/UnsavedChanges.svelte
new file mode 100644
index 0000000000..83168ca4af
--- /dev/null
+++ b/loadtest/console/src/UnsavedChanges.svelte
@@ -0,0 +1,13 @@
+<script>
+export let save=async()=>false;
+let dialog,resolve,pending=false,error='';
+export function ask(){error='';dialog.showModal();return new Promise(done=>resolve=done);}
+function answer(value){dialog.close();resolve?.(value);resolve=null;}
+async function saveAndLeave(){pending=true;error='';try{if(await save())answer(true);else error='Could not save. Review the highlighted fields.';}catch(e){error=e.message;}finally{pending=false;}}
+</script>
+<dialog class="unsaved-dialog" bind:this={dialog} aria-label="Unsaved changes" oncancel={e=>{e.preventDefault();if(!pending)answer(false);}}>
+<div class="unsaved-copy"><h2>Save your changes?</h2><p>Your edits haven’t been saved yet.</p></div>
+{#if error}<p class="invalid" role="alert">{error}</p>{/if}
+<div class="actions"><button type="button" class="quiet" disabled={pending} onclick={()=>answer(false)}>Continue editing</button><button type="button" class="secondary danger" disabled={pending} onclick={()=>answer(true)}>Discard</button><button type="button" disabled={pending} onclick={saveAndLeave}>{pending?'Saving…':'Save changes'}</button></div>
+</dialog>
+<style>.unsaved-dialog{width:min(520px,calc(100vw - 32px));padding:24px}.unsaved-copy h2{font-size:20px;margin:0 0 8px;letter-spacing:-.3px}.unsaved-copy p{margin:0;color:var(--muted);font-size:13px}.actions{gap:8px;flex-wrap:wrap;justify-content:flex-end}.actions .quiet{margin-right:auto}@media(max-width:460px){.actions .quiet{width:100%;order:3;margin:4px 0 0}.actions>button:not(.quiet){flex:1}}</style>
diff --git a/loadtest/console/src/api.js b/loadtest/console/src/api.js
new file mode 100644
index 0000000000..6395d004de
--- /dev/null
+++ b/loadtest/console/src/api.js
@@ -0,0 +1,52 @@
+async function request(path, options = {}) {
+ const form=typeof FormData!=='undefined'&&options.body instanceof FormData;
+ const response = await fetch(`/api${path}`, {
+ ...options,
+ headers: { ...(form?{}:{'content-type':'application/json'}), ...(options.headers || {}) }
+ });
+ const body = await response.json().catch(() => ({}));
+ if (!response.ok) throw new Error(body.error || `Request failed (${response.status})`);
+ return body;
+}
+
+export const api = {
+ importFixtures:input=>request('/fixtures/import',{method:'POST',body:JSON.stringify(input)}),
+ profiles:()=>request('/profiles'),
+ archiveProfile:(id,archived)=>request(`/profiles/${encodeURIComponent(id)}/archive`,{method:'PUT',body:JSON.stringify({archived})}),
+ deleteProfile:id=>request(`/profiles/${encodeURIComponent(id)}`,{method:'DELETE'}),
+ saveScenario:input=>request('/scenarios/save',{method:'POST',body:JSON.stringify(input)}),
+ saveProfile:(profile)=>request(profile.id?`/profiles/${encodeURIComponent(profile.id)}`:'/profiles',{method:profile.id?'PUT':'POST',body:JSON.stringify(profile)}),
+ fixtures:()=>request('/fixtures'),
+ deleteFixtures:id=>request(`/fixtures/${encodeURIComponent(id)}`,{method:'DELETE'}),
+ testDatabase:(database,environment)=>request('/settings/database/test',{method:'POST',body:JSON.stringify({...database,environment})}),
+ testService:(kind,endpoint,superposition,environment)=>request('/settings/services/test',{method:'POST',body:JSON.stringify({kind,endpoint,superposition,environment})}),
+ settings: (environment) => request('/settings'+(environment?`?environment=${encodeURIComponent(environment)}`:'')),
+ certificates:()=>request('/settings/certificates'),
+ importCertificate:(file,name='')=>{const form=new FormData();form.append('certificate',file);form.append('name',name);return request('/settings/certificates',{method:'POST',body:form});},
+ removeCertificate:id=>request(`/settings/certificates/${encodeURIComponent(id)}`,{method:'DELETE'}),
+ workers:()=>request('/workers'),
+ workerPlan:id=>request(`/workers/plan?profile=${encodeURIComponent(id)}`),
+ removeWorker:id=>request(`/workers/${encodeURIComponent(id)}`,{method:'DELETE'}),
+ saveSettings: (settings) => request('/settings', { method: 'PUT', body: JSON.stringify(settings) }),
+ runs: () => request('/runs'),
+ run: (id) => request(`/runs/${encodeURIComponent(id)}`),
+ start: (command, selection) => request(command === 'fixtures' ? '/fixtures' : command === 'smoke' ? '/smoke' : '/runs', { method: 'POST', body: JSON.stringify(typeof selection==='string'?{mode:selection}:selection) }),
+ job: (id) => request(`/jobs/${encodeURIComponent(id)}`),
+ cancel: (id) => request(`/jobs/${encodeURIComponent(id)}/cancel`, { method: 'POST' }),
+ control: (id,action) => request(`/jobs/${encodeURIComponent(id)}/${action}`, {method:'POST'}),
+ faultTargets:()=>request('/faults/targets'),
+ saveFaultTargets:targets=>request('/faults/targets',{method:'PUT',body:JSON.stringify(targets)}),
+ checkFaultTarget:target=>request('/faults/check',{method:'POST',body:JSON.stringify(target)}),
+ testFault:input=>request('/faults/test',{method:'POST',body:JSON.stringify(input)}),
+ faults: () => request('/faults'),
+ fireFault: (input) => request('/faults', {method:'POST',body:JSON.stringify(input)}),
+ restoreFault: () => request('/faults/restore', {method:'POST'}),
+ panels: (panels) => request('/grafana/panels', { method: 'PUT', body: JSON.stringify(panels) }),
+ requests: (id, options = {}) => request(`/runs/${encodeURIComponent(id)}/requests?${new URLSearchParams(typeof options==='number'?{after:options}:options)}`),
+ paymentBars:(id,options={})=>request(`/runs/${encodeURIComponent(id)}/payment-bars?${new URLSearchParams(options)}`),
+ paymentPage:(id,options={})=>request(`/runs/${encodeURIComponent(id)}/payment-page?${new URLSearchParams(options)}`),
+ paymentDetail:(id,options={})=>request(`/runs/${encodeURIComponent(id)}/payment-detail?${new URLSearchParams(options)}`),
+ nextDiscrepancy:(id,after)=>request(`/runs/${encodeURIComponent(id)}/next-discrepancy?after=${after}`),
+ reconciliationJob:(id)=>request(`/runs/${encodeURIComponent(id)}/reconcile`),
+ reconcile: (id, allowIncomplete = false) => request(`/runs/${encodeURIComponent(id)}/reconcile`, { method: 'POST', body: JSON.stringify({ allowIncomplete }) })
+};
diff --git a/loadtest/console/src/app.html b/loadtest/console/src/app.html
new file mode 100644
index 0000000000..2acd2d9f15
--- /dev/null
+++ b/loadtest/console/src/app.html
@@ -0,0 +1,5 @@
+<!doctype html>
+<html lang="en">
+ <head><meta charset="utf-8" /><meta name="viewport" content="width=device-width, initial-scale=1" /><link rel="icon" type="image/svg+xml" href="/favicon.svg"/>%sveltekit.head%</head>
+ <body data-sveltekit-preload-data="hover"><div style="display:contents">%sveltekit.body%</div></body>
+</html>
diff --git a/loadtest/console/src/chart-timeline.mjs b/loadtest/console/src/chart-timeline.mjs
new file mode 100644
index 0000000000..a9971669c2
--- /dev/null
+++ b/loadtest/console/src/chart-timeline.mjs
@@ -0,0 +1,118 @@
+export const activeTime=p=>Number.isFinite(p.activeSeconds)?p.activeSeconds:p.t;
+// Keep wall-clock recording intact, but stop extending the visible graph once
+// the current pause has drained and its first zero-throughput sample arrives.
+export function pausedChartSamples(points,state){
+ if(state!=='paused'||!points.length)return points;
+ let start=points.length-1;
+ while(start>0&&points[start-1].state==='paused')start--;
+ if(points[start].state!=='paused')return points;
+ const zero=points.findIndex((p,i)=>i>=start&&p.successfulTps===0&&(p.inFlight??0)===0);
+ return points.slice(0,(zero<0?start:zero)+1);
+}
+export function activeSamples(points){const result=[];for(const p of points){const t=activeTime(p);if(!Number.isFinite(t))continue;const row={...p,t};if(result.at(-1)?.t===t)result[result.length-1]=row;else result.push(row);}return result;}
+export function eventActiveTime(event,startedAt,points){
+ const wall=Math.max(0,(event.at-startedAt)/1000);
+ if(!points.length)return wall;
+ const next=points.findIndex(p=>p.t>=wall);
+ if(next===0)return Math.min(wall,activeTime(points[0]));
+ if(next<0)return activeTime(points.at(-1));
+ const a=points[next-1],b=points[next],fraction=(wall-a.t)/(b.t-a.t||1);
+ return activeTime(a)+(activeTime(b)-activeTime(a))*fraction;
+}
+export function activeToWall(seconds,points,edge='start'){
+ const samples=(points || []).filter(point=>Number.isFinite(point?.t)&&Number.isFinite(activeTime(point)));
+ if(!samples.length)return seconds;
+ const exact=samples.filter(point=>Math.abs(activeTime(point)-seconds)<.01);
+ if(exact.length)return edge==='end'?exact.at(-1).t:exact[0].t;
+ const next=samples.find(point=>activeTime(point)>seconds);
+ if(!next){const last=samples.at(-1);return last.t+Math.max(0,seconds-activeTime(last));}
+ const index=samples.indexOf(next),previous=samples[index-1];
+ if(!previous)return Math.max(0,next.t-(activeTime(next)-seconds));
+ const fraction=(seconds-activeTime(previous))/(activeTime(next)-activeTime(previous));
+ return previous.t+(next.t-previous.t)*fraction;
+}
+export function wallToActive(seconds,points){
+ const samples=(points || []).filter(point=>Number.isFinite(point?.t)&&Number.isFinite(activeTime(point)));
+ if(!samples.length)return seconds;
+ const next=samples.find(point=>point.t>=seconds);
+ if(!next)return activeTime(samples.at(-1));
+ const index=samples.indexOf(next),previous=samples[index-1];
+ if(!previous)return activeTime(next);
+ const fraction=(seconds-previous.t)/(next.t-previous.t||1);
+ return activeTime(previous)+(activeTime(next)-activeTime(previous))*fraction;
+}
+export function plannedEvents(timeline){return timeline.flatMap((s,index)=>[
+ {t:s.start,edge:index>0&&timeline[index-1].fault?'end':'start',label:s.fault?`${s.fault.target} · fault planned`:s.kind==='ramp'?`Ramp ${s.from} → ${s.target} TPS`:`Hold ${s.target} TPS`,kind:s.kind},
+ ...(s.fault?.action==='outage'?[{t:s.end,edge:'start',label:`${s.fault.target} · recovery planned`,kind:'recovery'}]:[])
+]);}
+function eventTarget(event){
+ const parts=(event.message||'').split(' · ');
+ while(parts.length>1&&['SIMULATED','Local','GCP','AWS','Azure','Custom'].includes(parts[0]))parts.shift();
+ return event.target||parts[0]||'Service';
+}
+function failoverTargets(timeline,activity){
+ return new Set([...timeline.filter(s=>s.fault?.action==='failover').map(s=>s.fault.target),...activity.filter(e=>/ · failover(?: requested)?$/.test(e.message||'')).map(eventTarget)]);
+}
+export function availabilityGraphEvents(activity,timeline=[]){
+ const failovers=failoverTargets(timeline,activity);
+ return activity.flatMap(e=>{
+ const failover=failovers.has(eventTarget(e));
+ if(failover&&e.kind==='fault_requested')return [{...e,kind:'failover_requested'}];
+ return ['pause','resume','database_unavailable','database_available'].includes(e.kind)||(['fault_requested','fault_started','fault_restore','fault_restored'].includes(e.kind)&&!failover)?[e]:[];
+ });
+}
+// Fault recovery pauses the active clock. The following stage therefore starts
+// at the verified-recovery event, rather than at the recovery request or its
+// nominal active-time boundary.
+export function stageWallTimes(timeline,points,activity=[],startedAt=0){
+ const recovered=activity.filter(event=>['fault_restored','fault_skipped'].includes(event.kind)&&Number.isFinite(event?.at)).sort((a,b)=>a.at-b.at),stages=[];
+ let recoveryIndex=0;
+ for(const [index,stage] of timeline.entries()){
+ const previous=timeline[index-1];
+ const verified=previous?.fault?recovered[recoveryIndex++]:null;
+ const start=verified?Math.max(0,(verified.at-startedAt)/1000):activeToWall(stage.start,points,index>0&&previous?.fault?'end':'start');
+ stages.push({...stage,wallStart:start});
+ }
+ return stages.map((stage,index)=>({...stage,wallEnd:stage.fault?(stages[index+1]?.wallStart??activeToWall(stage.end,points,'end')):activeToWall(stage.end,points,'start')}));
+}
+// Execution phases use wall time. An outage spans verified interruption through
+// verified recovery, including the time spent restoring the service.
+export function executionPhases(timeline,points,activity=[],startedAt=0,elapsedSeconds=0){
+ const stages=stageWallTimes(timeline,points,activity,startedAt),end=Math.max(elapsedSeconds,points.at(-1)?.t||0,stages.at(-1)?.wallEnd||0);
+ const outages=[],open=new Map(),target=eventTarget;
+ const failovers=failoverTargets(timeline,activity);
+ for(const event of [...activity].sort((a,b)=>a.at-b.at)){
+ if(event.kind==='database_unavailable'||(event.kind==='fault_started'&&!failovers.has(target(event))))open.set(target(event),{start:Math.max(0,(event.at-startedAt)/1000),target:target(event)});
+ if((event.kind==='database_available'||(event.kind==='fault_restored'&&!failovers.has(target(event))))&&open.has(target(event))){const fault=open.get(target(event));outages.push({...fault,end:Math.max(fault.start,(event.at-startedAt)/1000)});open.delete(target(event));}
+ }
+ for(const fault of open.values())outages.push({...fault,end});
+ const boundaries=[...new Set([0,end,...stages.flatMap(s=>[s.wallStart,s.wallEnd]),...outages.flatMap(f=>[f.start,f.end])])].filter(t=>t>=0&&t<=end).sort((a,b)=>a-b),phases=[];
+ for(let i=1;i<boundaries.length;i++){
+ const start=boundaries[i-1],finish=boundaries[i],mid=(start+finish)/2,fault=outages.find(f=>mid>=f.start&&mid<f.end),stage=stages.find(s=>mid>=s.wallStart&&mid<s.wallEnd)||stages.at(-1);
+ if(!stage&&!fault)continue;
+ const kind=fault?'outage':stage?.kind==='ramp'?'ramp':'hold',label=fault?`${fault.target==='PostgreSQL'?'DB':fault.target} outage`:kind==='ramp'?'Ramp':'Hold';
+ const previous=phases.at(-1);if(previous?.label===label&&previous.end===start)previous.end=finish;else phases.push({start,end:finish,kind,label});
+ }
+ return phases;
+}
+export function targetAt(t,timeline){const stage=timeline.find(s=>t>=s.start&&t<s.end)||timeline.at(-1);if(!stage)return null;return stage.kind==='ramp'?stage.from+(stage.target-stage.from)*Math.max(0,Math.min(1,(t-stage.start)/(stage.end-stage.start||1))):stage.target;}
+export function compactSamples(points,limit=1800){return points.length>limit?points.filter((_,i)=>i%2===0||i===points.length-1):points;}
+
+// Cards and the main chart share metric selection, interval edges and wall time.
+export function metricValue(point,metric,flow='all'){
+ const key=metric==='tps'?'successfulTps':metric;
+ const source=flow==='all'||['errors','backlog'].includes(metric)?point:point?.flows?.[flow];
+ // Empty observed latency intervals are zero on charts; never bridge them.
+ if(['p99','serverP99'].includes(metric)&&(source?.successfulTps===0||source?.[key]===null))return 0;
+ return source?.[key];
+}
+export function metricSeries(points,metric,flow='all'){
+ return (points||[]).filter(p=>Number.isFinite(p?.t)).map(p=>({t:p.t,intervalStart:p.intervalStart,value:metricValue(p,metric,flow)}));
+}
+export function rateIntervals(points){
+ return points.flatMap((point,index)=>[{t:Number.isFinite(point.intervalStart)?point.intervalStart:index?points[index-1].t:0,value:point.value},point]);
+}
+export function chartHorizon(points,durationSeconds,timeline=[],activity=[],startedAt=0){
+ const wall=stageWallTimes(timeline,points,activity,startedAt),planned=plannedEvents(timeline);
+ return Math.max(1,Number(durationSeconds)||0,points.at(-1)?.t||0,wall.at(-1)?.wallEnd||0,planned.at(-1)?.t||0);
+}
diff --git a/loadtest/console/src/connector-catalog.json b/loadtest/console/src/connector-catalog.json
new file mode 100644
index 0000000000..39f7a7b0a7
--- /dev/null
+++ b/loadtest/console/src/connector-catalog.json
@@ -0,0 +1,3677 @@
+[
+ {
+ "id": "absa_sanlam",
+ "label": "Absa Sanlam",
+ "dummy": false,
+ "card": false,
+ "networks": [],
+ "authType": "BodyKey",
+ "fields": [
+ {
+ "name": "api_key",
+ "label": "API Key"
+ },
+ {
+ "name": "key1",
+ "label": "Merchant Id"
+ }
+ ]
+ },
+ {
+ "id": "authipay",
+ "label": "Authipay",
+ "dummy": false,
+ "card": true,
+ "networks": [
+ "Mastercard",
+ "Visa"
+ ],
+ "authType": "BodyKey",
+ "fields": [
+ {
+ "name": "api_key",
+ "label": "API Key"
+ },
+ {
+ "name": "key1",
+ "label": "API Secret"
+ }
+ ]
+ },
+ {
+ "id": "adyenplatform",
+ "label": "Adyenplatform",
+ "dummy": false,
+ "card": false,
+ "networks": [],
+ "authType": null,
+ "fields": []
+ },
+ {
+ "id": "stripe_billing_test",
+ "label": "Stripe Billing Test",
+ "dummy": true,
+ "card": true,
+ "networks": [],
+ "authType": "HeaderKey",
+ "fields": [
+ {
+ "name": "api_key",
+ "label": "Test key"
+ }
+ ]
+ },
+ {
+ "id": "phonypay",
+ "label": "Phonypay",
+ "dummy": true,
+ "card": true,
+ "networks": [],
+ "authType": "HeaderKey",
+ "fields": [
+ {
+ "name": "api_key",
+ "label": "Test key"
+ }
+ ]
+ },
+ {
+ "id": "fauxpay",
+ "label": "Fauxpay",
+ "dummy": true,
+ "card": true,
+ "networks": [],
+ "authType": "HeaderKey",
+ "fields": [
+ {
+ "name": "api_key",
+ "label": "Test key"
+ }
+ ]
+ },
+ {
+ "id": "pretendpay",
+ "label": "Pretendpay",
+ "dummy": true,
+ "card": true,
+ "networks": [],
+ "authType": "HeaderKey",
+ "fields": [
+ {
+ "name": "api_key",
+ "label": "Test key"
+ }
+ ]
+ },
+ {
+ "id": "stripe_test",
+ "label": "Stripe Test",
+ "dummy": true,
+ "card": true,
+ "networks": [
+ "Mastercard",
+ "Visa",
+ "Interac",
+ "AmericanExpress",
+ "JCB",
+ "DinersClub",
+ "Discover",
+ "CartesBancaires",
+ "UnionPay"
+ ],
+ "authType": "HeaderKey",
+ "fields": [
+ {
+ "name": "api_key",
+ "label": "Api Key"
+ }
+ ]
+ },
+ {
+ "id": "adyen_test",
+ "label": "Adyen Test",
+ "dummy": true,
+ "card": true,
+ "networks": [],
+ "authType": "HeaderKey",
+ "fields": [
+ {
+ "name": "api_key",
+ "label": "Test key"
+ }
+ ]
+ },
+ {
+ "id": "checkout_test",
+ "label": "Checkout Test",
+ "dummy": true,
+ "card": true,
+ "networks": [],
+ "authType": "HeaderKey",
+ "fields": [
+ {
+ "name": "api_key",
+ "label": "Test key"
+ }
+ ]
+ },
+ {
+ "id": "paypal_test",
+ "label": "Paypal Test",
+ "dummy": true,
+ "card": true,
+ "networks": [
+ "Mastercard",
+ "Visa",
+ "Interac",
+ "AmericanExpress",
+ "JCB",
+ "DinersClub",
+ "Discover",
+ "CartesBancaires",
+ "UnionPay"
+ ],
+ "authType": "HeaderKey",
+ "fields": [
+ {
+ "name": "api_key",
+ "label": "Api Key"
+ }
+ ]
+ },
+ {
+ "id": "aci",
+ "label": "Aci",
+ "dummy": false,
+ "card": true,
+ "networks": [
+ "Mastercard",
+ "Visa",
+ "Interac",
+ "AmericanExpress",
+ "JCB",
+ "DinersClub",
+ "Discover",
+ "CartesBancaires",
+ "UnionPay"
+ ],
+ "authType": "BodyKey",
+ "fields": [
+ {
+ "name": "api_key",
+ "label": "API Key"
+ },
+ {
+ "name": "key1",
+ "label": "Entity ID"
+ }
+ ]
+ },
+ {
+ "id": "adyen",
+ "label": "Adyen",
+ "dummy": false,
+ "card": true,
+ "networks": [
+ "Mastercard",
+ "Visa",
+ "Interac",
+ "AmericanExpress",
+ "JCB",
+ "DinersClub",
+ "Discover",
+ "CartesBancaires",
+ "UnionPay"
+ ],
+ "authType": "BodyKey",
+ "fields": [
+ {
+ "name": "api_key",
+ "label": "Adyen API Key"
+ },
+ {
+ "name": "key1",
+ "label": "Adyen Account Id"
+ }
+ ]
+ },
+ {
+ "id": "affirm",
+ "label": "Affirm",
+ "dummy": false,
+ "card": false,
+ "networks": [],
+ "authType": "BodyKey",
+ "fields": [
+ {
+ "name": "api_key",
+ "label": "Public Key"
+ },
+ {
+ "name": "key1",
+ "label": "Private Key"
+ }
+ ]
+ },
+ {
+ "id": "airwallex",
+ "label": "Airwallex",
+ "dummy": false,
+ "card": true,
+ "networks": [
+ "Mastercard",
+ "Visa",
+ "Interac",
+ "AmericanExpress",
+ "JCB",
+ "DinersClub",
+ "Discover",
+ "CartesBancaires",
+ "UnionPay"
+ ],
+ "authType": "BodyKey",
+ "fields": [
+ {
+ "name": "api_key",
+ "label": "API Key"
+ },
+ {
+ "name": "key1",
+ "label": "Client ID"
+ }
+ ]
+ },
+ {
+ "id": "amazonpay",
+ "label": "Amazonpay",
+ "dummy": false,
+ "card": false,
+ "networks": [],
+ "authType": "BodyKey",
+ "fields": [
+ {
+ "name": "api_key",
+ "label": "Public Key"
+ },
+ {
+ "name": "key1",
+ "label": "Private Key"
+ }
+ ]
+ },
+ {
+ "id": "archipel",
+ "label": "Archipel",
+ "dummy": false,
+ "card": true,
+ "networks": [
+ "Mastercard",
+ "Visa",
+ "AmericanExpress",
+ "DinersClub",
+ "Discover",
+ "CartesBancaires"
+ ],
+ "authType": "HeaderKey",
+ "fields": [
+ {
+ "name": "api_key",
+ "label": "Enter CA Certificate PEM"
+ }
+ ]
+ },
+ {
+ "id": "authorizedotnet",
+ "label": "Authorizedotnet",
+ "dummy": false,
+ "card": true,
+ "networks": [
+ "Mastercard",
+ "Visa",
+ "Interac",
+ "AmericanExpress",
+ "JCB",
+ "DinersClub",
+ "Discover",
+ "CartesBancaires",
+ "UnionPay"
+ ],
+ "authType": "BodyKey",
+ "fields": [
+ {
+ "name": "api_key",
+ "label": "API Login ID"
+ },
+ {
+ "name": "key1",
+ "label": "Transaction Key"
+ }
+ ]
+ },
+ {
+ "id": "bankofamerica",
+ "label": "Bankofamerica",
+ "dummy": false,
+ "card": true,
+ "networks": [
+ "Mastercard",
+ "Visa",
+ "Interac",
+ "AmericanExpress",
+ "JCB",
+ "DinersClub",
+ "Discover",
+ "CartesBancaires",
+ "UnionPay"
+ ],
+ "authType": "SignatureKey",
+ "fields": [
+ {
+ "name": "api_key",
+ "label": "Key"
+ },
+ {
+ "name": "key1",
+ "label": "Merchant ID"
+ },
+ {
+ "name": "api_secret",
+ "label": "Shared Secret"
+ }
+ ]
+ },
+ {
+ "id": "barclaycard",
+ "label": "Barclaycard",
+ "dummy": false,
+ "card": true,
+ "networks": [
+ "Mastercard",
+ "Visa",
+ "AmericanExpress",
+ "JCB",
+ "Discover",
+ "Maestro",
+ "Interac",
+ "DinersClub",
+ "CartesBancaires",
+ "UnionPay"
+ ],
+ "authType": "SignatureKey",
+ "fields": [
+ {
+ "name": "api_key",
+ "label": "Key"
+ },
+ {
+ "name": "key1",
+ "label": "Merchant ID"
+ },
+ {
+ "name": "api_secret",
+ "label": "Shared Secret"
+ }
+ ]
+ },
+ {
+ "id": "betterpayment",
+ "label": "Betterpayment",
+ "dummy": false,
+ "card": false,
+ "networks": [],
+ "authType": "BodyKey",
+ "fields": [
+ {
+ "name": "api_key",
+ "label": "API Key"
+ },
+ {
+ "name": "key1",
+ "label": "API Password"
+ }
+ ]
+ },
+ {
+ "id": "billwerk",
+ "label": "Billwerk",
+ "dummy": false,
+ "card": true,
+ "networks": [
+ "Mastercard",
+ "Visa",
+ "Interac",
+ "AmericanExpress",
+ "JCB",
+ "DinersClub",
+ "Discover",
+ "CartesBancaires",
+ "UnionPay"
+ ],
+ "authType": "BodyKey",
+ "fields": [
+ {
+ "name": "api_key",
+ "label": "Private Api Key"
+ },
+ {
+ "name": "key1",
+ "label": "Public Api Key"
+ }
+ ]
+ },
+ {
+ "id": "bitpay",
+ "label": "Bitpay",
+ "dummy": false,
+ "card": false,
+ "networks": [],
+ "authType": "HeaderKey",
+ "fields": [
+ {
+ "name": "api_key",
+ "label": "API Key"
+ }
+ ]
+ },
+ {
+ "id": "bambora",
+ "label": "Bambora",
+ "dummy": false,
+ "card": true,
+ "networks": [
+ "Mastercard",
+ "Visa",
+ "Interac",
+ "AmericanExpress",
+ "JCB",
+ "DinersClub",
+ "Discover",
+ "CartesBancaires",
+ "UnionPay"
+ ],
+ "authType": "BodyKey",
+ "fields": [
+ {
+ "name": "api_key",
+ "label": "Passcode"
+ },
+ {
+ "name": "key1",
+ "label": "Merchant Id"
+ }
+ ]
+ },
+ {
+ "id": "blackhawknetwork",
+ "label": "Blackhawknetwork",
+ "dummy": false,
+ "card": false,
+ "networks": [],
+ "authType": "SignatureKey",
+ "fields": [
+ {
+ "name": "api_key",
+ "label": "Client Id"
+ },
+ {
+ "name": "api_secret",
+ "label": "Client Secret"
+ },
+ {
+ "name": "key1",
+ "label": "Product Line Id"
+ }
+ ]
+ },
+ {
+ "id": "bamboraapac",
+ "label": "Bamboraapac",
+ "dummy": false,
+ "card": true,
+ "networks": [
+ "Mastercard",
+ "Visa",
+ "Interac",
+ "AmericanExpress",
+ "JCB",
+ "DinersClub",
+ "Discover",
+ "CartesBancaires",
+ "UnionPay"
+ ],
+ "authType": "SignatureKey",
+ "fields": [
+ {
+ "name": "api_key",
+ "label": "Username"
+ },
+ {
+ "name": "key1",
+ "label": "Account Number"
+ },
+ {
+ "name": "api_secret",
+ "label": "Password"
+ }
+ ]
+ },
+ {
+ "id": "bluesnap",
+ "label": "Bluesnap",
+ "dummy": false,
+ "card": true,
+ "networks": [
+ "Mastercard",
+ "Visa",
+ "Interac",
+ "AmericanExpress",
+ "JCB",
+ "DinersClub",
+ "Discover",
+ "CartesBancaires",
+ "UnionPay"
+ ],
+ "authType": "BodyKey",
+ "fields": [
+ {
+ "name": "api_key",
+ "label": "Password"
+ },
+ {
+ "name": "key1",
+ "label": "Username"
+ }
+ ]
+ },
+ {
+ "id": "calida",
+ "label": "Calida",
+ "dummy": false,
+ "card": false,
+ "networks": [],
+ "authType": "HeaderKey",
+ "fields": [
+ {
+ "name": "api_key",
+ "label": "E-Order Token"
+ }
+ ]
+ },
+ {
+ "id": "boku",
+ "label": "Boku",
+ "dummy": false,
+ "card": false,
+ "networks": [],
+ "authType": "BodyKey",
+ "fields": [
+ {
+ "name": "api_key",
+ "label": "API KEY"
+ },
+ {
+ "name": "key1",
+ "label": "MERCHANT ID"
+ }
+ ]
+ },
+ {
+ "id": "braintree",
+ "label": "Braintree",
+ "dummy": false,
+ "card": true,
+ "networks": [
+ "Mastercard",
+ "Visa",
+ "Interac",
+ "AmericanExpress",
+ "JCB",
+ "DinersClub",
+ "Discover",
+ "CartesBancaires",
+ "UnionPay"
+ ],
+ "authType": "SignatureKey",
+ "fields": [
+ {
+ "name": "api_key",
+ "label": "Public Key"
+ },
+ {
+ "name": "key1",
+ "label": "Merchant Id"
+ },
+ {
+ "name": "api_secret",
+ "label": "Private Key"
+ }
+ ]
+ },
+ {
+ "id": "breadpay",
+ "label": "Breadpay",
+ "dummy": false,
+ "card": false,
+ "networks": [],
+ "authType": "BodyKey",
+ "fields": [
+ {
+ "name": "api_key",
+ "label": "API Key"
+ },
+ {
+ "name": "key1",
+ "label": "API Secret"
+ }
+ ]
+ },
+ {
+ "id": "cashtocode",
+ "label": "Cashtocode",
+ "dummy": false,
+ "card": false,
+ "networks": [],
+ "authType": "CurrencyAuthKey",
+ "fields": [
+ {
+ "name": "auth_key_map",
+ "label": "Auth Key Map"
+ }
+ ]
+ },
+ {
+ "id": "celero",
+ "label": "Celero",
+ "dummy": false,
+ "card": true,
+ "networks": [
+ "AmericanExpress",
+ "Discover",
+ "DinersClub",
+ "JCB",
+ "Mastercard",
+ "Visa"
+ ],
+ "authType": "HeaderKey",
+ "fields": [
+ {
+ "name": "api_key",
+ "label": "Celero API Key"
+ }
+ ]
+ },
+ {
+ "id": "chargebee",
+ "label": "Chargebee",
+ "dummy": false,
+ "card": false,
+ "networks": [],
+ "authType": "HeaderKey",
+ "fields": [
+ {
+ "name": "api_key",
+ "label": "Chargebee API Key"
+ }
+ ]
+ },
+ {
+ "id": "custombilling",
+ "label": "Custombilling",
+ "dummy": false,
+ "card": false,
+ "networks": [],
+ "authType": null,
+ "fields": []
+ },
+ {
+ "id": "checkbook",
+ "label": "Checkbook",
+ "dummy": false,
+ "card": false,
+ "networks": [],
+ "authType": "BodyKey",
+ "fields": [
+ {
+ "name": "key1",
+ "label": "Checkbook Publishable key"
+ },
+ {
+ "name": "api_key",
+ "label": "Checkbook API Secret key"
+ }
+ ]
+ },
+ {
+ "id": "checkout",
+ "label": "Checkout",
+ "dummy": false,
+ "card": true,
+ "networks": [
+ "Mastercard",
+ "Visa",
+ "Interac",
+ "AmericanExpress",
+ "JCB",
+ "DinersClub",
+ "Discover",
+ "CartesBancaires",
+ "UnionPay"
+ ],
+ "authType": "SignatureKey",
+ "fields": [
+ {
+ "name": "api_key",
+ "label": "Checkout API Public Key"
+ },
+ {
+ "name": "key1",
+ "label": "Processing Channel ID"
+ },
+ {
+ "name": "api_secret",
+ "label": "Checkout API Secret Key"
+ }
+ ]
+ },
+ {
+ "id": "citigate",
+ "label": "Citigate",
+ "dummy": false,
+ "card": true,
+ "networks": [
+ "Visa",
+ "Mastercard",
+ "AmericanExpress",
+ "DinersClub",
+ "Maestro"
+ ],
+ "authType": "BodyKey",
+ "fields": [
+ {
+ "name": "api_key",
+ "label": "Merchant Name"
+ },
+ {
+ "name": "key1",
+ "label": "Merchant Password"
+ }
+ ]
+ },
+ {
+ "id": "coinbase",
+ "label": "Coinbase",
+ "dummy": false,
+ "card": false,
+ "networks": [],
+ "authType": "HeaderKey",
+ "fields": [
+ {
+ "name": "api_key",
+ "label": "API Key"
+ }
+ ]
+ },
+ {
+ "id": "coingate",
+ "label": "Coingate",
+ "dummy": false,
+ "card": false,
+ "networks": [],
+ "authType": "BodyKey",
+ "fields": [
+ {
+ "name": "api_key",
+ "label": "API Key"
+ },
+ {
+ "name": "key1",
+ "label": "Merchant Token"
+ }
+ ]
+ },
+ {
+ "id": "cryptopay",
+ "label": "Cryptopay",
+ "dummy": false,
+ "card": false,
+ "networks": [],
+ "authType": "BodyKey",
+ "fields": [
+ {
+ "name": "api_key",
+ "label": "API Key"
+ },
+ {
+ "name": "key1",
+ "label": "Secret Key"
+ }
+ ]
+ },
+ {
+ "id": "cybersource",
+ "label": "Cybersource",
+ "dummy": false,
+ "card": true,
+ "networks": [
+ "Mastercard",
+ "Visa",
+ "Interac",
+ "AmericanExpress",
+ "JCB",
+ "DinersClub",
+ "Discover",
+ "CartesBancaires",
+ "UnionPay"
+ ],
+ "authType": "SignatureKey",
+ "fields": [
+ {
+ "name": "api_key",
+ "label": "Key"
+ },
+ {
+ "name": "key1",
+ "label": "Merchant ID"
+ },
+ {
+ "name": "api_secret",
+ "label": "Shared Secret"
+ }
+ ]
+ },
+ {
+ "id": "cybersourcedecisionmanager",
+ "label": "Cybersourcedecisionmanager",
+ "dummy": false,
+ "card": false,
+ "networks": [],
+ "authType": null,
+ "fields": []
+ },
+ {
+ "id": "d24",
+ "label": "D24",
+ "dummy": false,
+ "card": false,
+ "networks": [],
+ "authType": "SignatureKey",
+ "fields": [
+ {
+ "name": "api_key",
+ "label": "API Key"
+ },
+ {
+ "name": "key1",
+ "label": "Read-only API Key"
+ },
+ {
+ "name": "api_secret",
+ "label": "API Signature"
+ }
+ ]
+ },
+ {
+ "id": "datatrans",
+ "label": "Datatrans",
+ "dummy": false,
+ "card": true,
+ "networks": [
+ "Mastercard",
+ "Visa",
+ "Interac",
+ "AmericanExpress",
+ "JCB",
+ "DinersClub",
+ "Discover",
+ "CartesBancaires",
+ "UnionPay"
+ ],
+ "authType": "BodyKey",
+ "fields": [
+ {
+ "name": "api_key",
+ "label": "Passcode"
+ },
+ {
+ "name": "key1",
+ "label": "datatrans MerchantId"
+ }
+ ]
+ },
+ {
+ "id": "deutschebank",
+ "label": "Deutschebank",
+ "dummy": false,
+ "card": true,
+ "networks": [
+ "Visa",
+ "Mastercard"
+ ],
+ "authType": "SignatureKey",
+ "fields": [
+ {
+ "name": "api_key",
+ "label": "Client ID"
+ },
+ {
+ "name": "key1",
+ "label": "Merchant ID"
+ },
+ {
+ "name": "api_secret",
+ "label": "Client Key"
+ }
+ ]
+ },
+ {
+ "id": "digitalvirgo",
+ "label": "Digitalvirgo",
+ "dummy": false,
+ "card": false,
+ "networks": [],
+ "authType": "BodyKey",
+ "fields": [
+ {
+ "name": "api_key",
+ "label": "Password"
+ },
+ {
+ "name": "key1",
+ "label": "Username"
+ }
+ ]
+ },
+ {
+ "id": "dlocal",
+ "label": "Dlocal",
+ "dummy": false,
+ "card": true,
+ "networks": [
+ "Mastercard",
+ "Visa",
+ "Interac",
+ "AmericanExpress",
+ "JCB",
+ "DinersClub",
+ "Discover",
+ "CartesBancaires",
+ "UnionPay"
+ ],
+ "authType": "SignatureKey",
+ "fields": [
+ {
+ "name": "api_key",
+ "label": "X Login"
+ },
+ {
+ "name": "key1",
+ "label": "X Trans Key"
+ },
+ {
+ "name": "api_secret",
+ "label": "Secret Key"
+ }
+ ]
+ },
+ {
+ "id": "dwolla",
+ "label": "Dwolla",
+ "dummy": false,
+ "card": false,
+ "networks": [],
+ "authType": "BodyKey",
+ "fields": [
+ {
+ "name": "api_key",
+ "label": "Client ID"
+ },
+ {
+ "name": "key1",
+ "label": "Client Secret"
+ }
+ ]
+ },
+ {
+ "id": "ebanx",
+ "label": "Ebanx",
+ "dummy": false,
+ "card": false,
+ "networks": [],
+ "authType": null,
+ "fields": []
+ },
+ {
+ "id": "ecommpay",
+ "label": "Ecommpay",
+ "dummy": false,
+ "card": true,
+ "networks": [
+ "Mastercard",
+ "Visa",
+ "AmericanExpress",
+ "JCB",
+ "Discover",
+ "DinersClub",
+ "UnionPay"
+ ],
+ "authType": "BodyKey",
+ "fields": [
+ {
+ "name": "api_key",
+ "label": "Secret key"
+ },
+ {
+ "name": "key1",
+ "label": "Project ID"
+ }
+ ]
+ },
+ {
+ "id": "elavon",
+ "label": "Elavon",
+ "dummy": false,
+ "card": true,
+ "networks": [
+ "Mastercard",
+ "Visa",
+ "Interac",
+ "AmericanExpress",
+ "JCB",
+ "DinersClub",
+ "Discover",
+ "CartesBancaires",
+ "UnionPay"
+ ],
+ "authType": "SignatureKey",
+ "fields": [
+ {
+ "name": "api_key",
+ "label": "Account Id"
+ },
+ {
+ "name": "key1",
+ "label": "User ID"
+ },
+ {
+ "name": "api_secret",
+ "label": "Pin"
+ }
+ ]
+ },
+ {
+ "id": "elavon_pg",
+ "label": "Elavon Pg",
+ "dummy": false,
+ "card": true,
+ "networks": [
+ "Mastercard",
+ "Visa",
+ "AmericanExpress",
+ "JCB",
+ "Discover",
+ "DinersClub",
+ "UnionPay"
+ ],
+ "authType": "BodyKey",
+ "fields": [
+ {
+ "name": "api_key",
+ "label": "Merchant Alias"
+ },
+ {
+ "name": "key1",
+ "label": "Secret API Key"
+ }
+ ]
+ },
+ {
+ "id": "envoy",
+ "label": "Envoy",
+ "dummy": false,
+ "card": false,
+ "networks": [],
+ "authType": null,
+ "fields": []
+ },
+ {
+ "id": "etisalat",
+ "label": "Etisalat",
+ "dummy": false,
+ "card": true,
+ "networks": [
+ "Visa",
+ "Mastercard",
+ "AmericanExpress",
+ "JCB",
+ "DinersClub"
+ ],
+ "authType": "SignatureKey",
+ "fields": [
+ {
+ "name": "api_key",
+ "label": "EPG Password"
+ },
+ {
+ "name": "key1",
+ "label": "EPG UserName"
+ },
+ {
+ "name": "api_secret",
+ "label": "EPG Customer"
+ }
+ ]
+ },
+ {
+ "id": "facilitapay",
+ "label": "Facilitapay",
+ "dummy": false,
+ "card": false,
+ "networks": [],
+ "authType": "BodyKey",
+ "fields": [
+ {
+ "name": "api_key",
+ "label": "Password"
+ },
+ {
+ "name": "key1",
+ "label": "Username"
+ }
+ ]
+ },
+ {
+ "id": "finix",
+ "label": "Finix",
+ "dummy": false,
+ "card": true,
+ "networks": [
+ "Mastercard",
+ "Visa",
+ "AmericanExpress",
+ "Discover",
+ "JCB",
+ "DinersClub",
+ "UnionPay",
+ "Interac",
+ "Maestro"
+ ],
+ "authType": "MultiAuthKey",
+ "fields": [
+ {
+ "name": "api_key",
+ "label": "Username"
+ },
+ {
+ "name": "api_secret",
+ "label": "Password"
+ },
+ {
+ "name": "key1",
+ "label": "Merchant Id"
+ },
+ {
+ "name": "key2",
+ "label": "Merchant Identity Id"
+ }
+ ]
+ },
+ {
+ "id": "fiserv",
+ "label": "Fiserv",
+ "dummy": false,
+ "card": true,
+ "networks": [
+ "Mastercard",
+ "Visa",
+ "Interac",
+ "AmericanExpress",
+ "JCB",
+ "DinersClub",
+ "Discover",
+ "CartesBancaires",
+ "UnionPay"
+ ],
+ "authType": "SignatureKey",
+ "fields": [
+ {
+ "name": "api_key",
+ "label": "API Key"
+ },
+ {
+ "name": "key1",
+ "label": "Merchant ID"
+ },
+ {
+ "name": "api_secret",
+ "label": "API Secret"
+ }
+ ]
+ },
+ {
+ "id": "fiservemea",
+ "label": "Fiservemea",
+ "dummy": false,
+ "card": true,
+ "networks": [
+ "Mastercard",
+ "Visa",
+ "Interac",
+ "AmericanExpress",
+ "JCB",
+ "DinersClub",
+ "Discover",
+ "CartesBancaires",
+ "UnionPay"
+ ],
+ "authType": "BodyKey",
+ "fields": [
+ {
+ "name": "api_key",
+ "label": "API Key"
+ },
+ {
+ "name": "key1",
+ "label": "Secret Key"
+ }
+ ]
+ },
+ {
+ "id": "fiservcommercehub",
+ "label": "Fiservcommercehub",
+ "dummy": false,
+ "card": true,
+ "networks": [
+ "Mastercard",
+ "Visa",
+ "Interac",
+ "AmericanExpress",
+ "JCB",
+ "DinersClub",
+ "Discover",
+ "CartesBancaires",
+ "UnionPay"
+ ],
+ "authType": "MultiAuthKey",
+ "fields": [
+ {
+ "name": "api_key",
+ "label": "API Key"
+ },
+ {
+ "name": "key1",
+ "label": "Merchant ID"
+ },
+ {
+ "name": "api_secret",
+ "label": "API Secret"
+ },
+ {
+ "name": "key2",
+ "label": "Terminal ID"
+ }
+ ]
+ },
+ {
+ "id": "fiuu",
+ "label": "Fiuu",
+ "dummy": false,
+ "card": true,
+ "networks": [
+ "Mastercard",
+ "Visa",
+ "Interac",
+ "AmericanExpress",
+ "JCB",
+ "DinersClub",
+ "Discover",
+ "CartesBancaires",
+ "UnionPay"
+ ],
+ "authType": "SignatureKey",
+ "fields": [
+ {
+ "name": "api_key",
+ "label": "Verify Key"
+ },
+ {
+ "name": "key1",
+ "label": "Merchant ID"
+ },
+ {
+ "name": "api_secret",
+ "label": "Secret Key"
+ }
+ ]
+ },
+ {
+ "id": "flexiti",
+ "label": "Flexiti",
+ "dummy": false,
+ "card": false,
+ "networks": [],
+ "authType": "BodyKey",
+ "fields": [
+ {
+ "name": "api_key",
+ "label": "Client id"
+ },
+ {
+ "name": "key1",
+ "label": "Client secret"
+ }
+ ]
+ },
+ {
+ "id": "forte",
+ "label": "Forte",
+ "dummy": false,
+ "card": true,
+ "networks": [
+ "Mastercard",
+ "Visa",
+ "Interac",
+ "AmericanExpress",
+ "JCB",
+ "DinersClub",
+ "Discover",
+ "CartesBancaires",
+ "UnionPay"
+ ],
+ "authType": "MultiAuthKey",
+ "fields": [
+ {
+ "name": "api_key",
+ "label": "API Access ID"
+ },
+ {
+ "name": "key1",
+ "label": "Organization ID"
+ },
+ {
+ "name": "api_secret",
+ "label": "API Secure Key"
+ },
+ {
+ "name": "key2",
+ "label": "Location ID"
+ }
+ ]
+ },
+ {
+ "id": "getnet",
+ "label": "Getnet",
+ "dummy": false,
+ "card": true,
+ "networks": [
+ "Mastercard",
+ "Visa",
+ "Interac",
+ "AmericanExpress",
+ "JCB",
+ "DinersClub",
+ "Discover",
+ "CartesBancaires",
+ "UnionPay",
+ "RuPay",
+ "Maestro"
+ ],
+ "authType": null,
+ "fields": []
+ },
+ {
+ "id": "gigadat",
+ "label": "Gigadat",
+ "dummy": false,
+ "card": false,
+ "networks": [],
+ "authType": "SignatureKey",
+ "fields": [
+ {
+ "name": "api_key",
+ "label": "Access Token"
+ },
+ {
+ "name": "api_secret",
+ "label": "Security Token"
+ },
+ {
+ "name": "key1",
+ "label": "Campaign ID"
+ }
+ ]
+ },
+ {
+ "id": "givepayments",
+ "label": "Givepayments",
+ "dummy": false,
+ "card": true,
+ "networks": [
+ "Mastercard",
+ "Visa",
+ "AmericanExpress",
+ "JCB",
+ "Discover",
+ "DinersClub",
+ "UnionPay"
+ ],
+ "authType": "HeaderKey",
+ "fields": [
+ {
+ "name": "api_key",
+ "label": "API Key"
+ }
+ ]
+ },
+ {
+ "id": "globalpay",
+ "label": "Globalpay",
+ "dummy": false,
+ "card": true,
+ "networks": [
+ "Mastercard",
+ "Visa",
+ "Interac",
+ "AmericanExpress",
+ "JCB",
+ "DinersClub",
+ "Discover",
+ "CartesBancaires",
+ "UnionPay"
+ ],
+ "authType": "BodyKey",
+ "fields": [
+ {
+ "name": "api_key",
+ "label": "Global App Key"
+ },
+ {
+ "name": "key1",
+ "label": "Global App ID"
+ }
+ ]
+ },
+ {
+ "id": "globalpayments_heartland",
+ "label": "Globalpayments Heartland",
+ "dummy": false,
+ "card": true,
+ "networks": [
+ "Mastercard",
+ "Visa",
+ "AmericanExpress",
+ "JCB",
+ "Discover",
+ "DinersClub"
+ ],
+ "authType": "HeaderKey",
+ "fields": [
+ {
+ "name": "api_key",
+ "label": "Secret API Key"
+ }
+ ]
+ },
+ {
+ "id": "globalpayments_realex",
+ "label": "Globalpayments Realex",
+ "dummy": false,
+ "card": true,
+ "networks": [
+ "Mastercard",
+ "Visa",
+ "AmericanExpress",
+ "JCB",
+ "Discover",
+ "DinersClub",
+ "UnionPay"
+ ],
+ "authType": "MultiAuthKey",
+ "fields": [
+ {
+ "name": "api_key",
+ "label": "Shared Secret"
+ },
+ {
+ "name": "key1",
+ "label": "Merchant Id"
+ },
+ {
+ "name": "key2",
+ "label": "Account"
+ },
+ {
+ "name": "api_secret",
+ "label": "Refund Password"
+ }
+ ]
+ },
+ {
+ "id": "globepay",
+ "label": "Globepay",
+ "dummy": false,
+ "card": false,
+ "networks": [],
+ "authType": "BodyKey",
+ "fields": [
+ {
+ "name": "api_key",
+ "label": "Partner Code"
+ },
+ {
+ "name": "key1",
+ "label": "Credential Code"
+ }
+ ]
+ },
+ {
+ "id": "gocardless",
+ "label": "Gocardless",
+ "dummy": false,
+ "card": false,
+ "networks": [],
+ "authType": "HeaderKey",
+ "fields": [
+ {
+ "name": "api_key",
+ "label": "Access Token"
+ }
+ ]
+ },
+ {
+ "id": "gotyme_sanlam",
+ "label": "Gotyme Sanlam",
+ "dummy": false,
+ "card": false,
+ "networks": [],
+ "authType": null,
+ "fields": []
+ },
+ {
+ "id": "hipay",
+ "label": "Hipay",
+ "dummy": false,
+ "card": true,
+ "networks": [
+ "Mastercard",
+ "Visa",
+ "Interac",
+ "AmericanExpress",
+ "JCB",
+ "DinersClub",
+ "Discover",
+ "CartesBancaires",
+ "UnionPay"
+ ],
+ "authType": "BodyKey",
+ "fields": [
+ {
+ "name": "api_key",
+ "label": "API Login ID"
+ },
+ {
+ "name": "key1",
+ "label": "API password"
+ }
+ ]
+ },
+ {
+ "id": "helcim",
+ "label": "Helcim",
+ "dummy": false,
+ "card": true,
+ "networks": [
+ "Mastercard",
+ "Visa",
+ "Interac",
+ "AmericanExpress",
+ "JCB",
+ "DinersClub",
+ "Discover",
+ "CartesBancaires",
+ "UnionPay"
+ ],
+ "authType": "HeaderKey",
+ "fields": [
+ {
+ "name": "api_key",
+ "label": "Api Key"
+ }
+ ]
+ },
+ {
+ "id": "hyperpg",
+ "label": "Hyperpg",
+ "dummy": false,
+ "card": true,
+ "networks": [
+ "Mastercard",
+ "Visa",
+ "Interac",
+ "AmericanExpress",
+ "JCB",
+ "DinersClub",
+ "Discover",
+ "CartesBancaires",
+ "UnionPay"
+ ],
+ "authType": "BodyKey",
+ "fields": [
+ {
+ "name": "api_key",
+ "label": "Username"
+ },
+ {
+ "name": "key1",
+ "label": "Password"
+ }
+ ]
+ },
+ {
+ "id": "iatapay",
+ "label": "Iatapay",
+ "dummy": false,
+ "card": false,
+ "networks": [],
+ "authType": "SignatureKey",
+ "fields": [
+ {
+ "name": "api_key",
+ "label": "Client ID"
+ },
+ {
+ "name": "key1",
+ "label": "Airline ID"
+ },
+ {
+ "name": "api_secret",
+ "label": "Client Secret"
+ }
+ ]
+ },
+ {
+ "id": "ilixium",
+ "label": "Ilixium",
+ "dummy": false,
+ "card": true,
+ "networks": [
+ "Mastercard",
+ "Visa",
+ "AmericanExpress",
+ "JCB",
+ "Discover",
+ "DinersClub",
+ "UnionPay"
+ ],
+ "authType": "SignatureKey",
+ "fields": [
+ {
+ "name": "api_key",
+ "label": "Digest Calculation Password"
+ },
+ {
+ "name": "key1",
+ "label": "Merchant Id"
+ },
+ {
+ "name": "api_secret",
+ "label": "Account Id"
+ }
+ ]
+ },
+ {
+ "id": "imerchantsolutions",
+ "label": "Imerchantsolutions",
+ "dummy": false,
+ "card": true,
+ "networks": [
+ "Mastercard",
+ "Visa",
+ "AmericanExpress",
+ "JCB",
+ "Discover",
+ "UnionPay"
+ ],
+ "authType": "HeaderKey",
+ "fields": [
+ {
+ "name": "api_key",
+ "label": "API Key"
+ }
+ ]
+ },
+ {
+ "id": "inespay",
+ "label": "Inespay",
+ "dummy": false,
+ "card": false,
+ "networks": [],
+ "authType": "BodyKey",
+ "fields": [
+ {
+ "name": "api_key",
+ "label": "API Key"
+ },
+ {
+ "name": "key1",
+ "label": "API Token"
+ }
+ ]
+ },
+ {
+ "id": "interpayments",
+ "label": "Interpayments",
+ "dummy": false,
+ "card": false,
+ "networks": [],
+ "authType": "HeaderKey",
+ "fields": [
+ {
+ "name": "api_key",
+ "label": "API Key"
+ }
+ ]
+ },
+ {
+ "id": "itaubank",
+ "label": "Itaubank",
+ "dummy": false,
+ "card": false,
+ "networks": [],
+ "authType": "MultiAuthKey",
+ "fields": [
+ {
+ "name": "key1",
+ "label": "Client Id"
+ },
+ {
+ "name": "api_key",
+ "label": "Client Secret"
+ },
+ {
+ "name": "api_secret",
+ "label": "Certificates"
+ },
+ {
+ "name": "key2",
+ "label": "Certificate Key"
+ }
+ ]
+ },
+ {
+ "id": "jpmorgan",
+ "label": "Jpmorgan",
+ "dummy": false,
+ "card": true,
+ "networks": [
+ "AmericanExpress",
+ "DinersClub",
+ "Discover",
+ "JCB",
+ "Mastercard",
+ "Discover",
+ "UnionPay",
+ "Visa"
+ ],
+ "authType": "MultiAuthKey",
+ "fields": [
+ {
+ "name": "api_key",
+ "label": "Client ID"
+ },
+ {
+ "name": "key1",
+ "label": "Certificate Thumbprint"
+ },
+ {
+ "name": "api_secret",
+ "label": "Private Key (Base64 encoded)"
+ },
+ {
+ "name": "key2",
+ "label": "Resource ID"
+ }
+ ]
+ },
+ {
+ "id": "jpmorgan_orbital",
+ "label": "Jpmorgan Orbital",
+ "dummy": false,
+ "card": true,
+ "networks": [
+ "Mastercard",
+ "Visa",
+ "AmericanExpress",
+ "JCB",
+ "Discover",
+ "DinersClub",
+ "UnionPay"
+ ],
+ "authType": "SignatureKey",
+ "fields": [
+ {
+ "name": "api_key",
+ "label": "Orbital Connection Username"
+ },
+ {
+ "name": "key1",
+ "label": "Merchant ID"
+ },
+ {
+ "name": "api_secret",
+ "label": "Orbital Connection Password"
+ }
+ ]
+ },
+ {
+ "id": "klarna",
+ "label": "Klarna",
+ "dummy": false,
+ "card": false,
+ "networks": [],
+ "authType": "BodyKey",
+ "fields": [
+ {
+ "name": "key1",
+ "label": "Klarna Merchant Username"
+ },
+ {
+ "name": "api_key",
+ "label": "Klarna Merchant ID Password"
+ }
+ ]
+ },
+ {
+ "id": "loonio",
+ "label": "Loonio",
+ "dummy": false,
+ "card": false,
+ "networks": [],
+ "authType": "BodyKey",
+ "fields": [
+ {
+ "name": "api_key",
+ "label": "Merchant ID"
+ },
+ {
+ "name": "key1",
+ "label": "Merchant Token"
+ }
+ ]
+ },
+ {
+ "id": "merchante",
+ "label": "Merchante",
+ "dummy": false,
+ "card": true,
+ "networks": [
+ "Visa",
+ "Mastercard",
+ "AmericanExpress",
+ "Discover",
+ "JCB",
+ "DinersClub"
+ ],
+ "authType": "BodyKey",
+ "fields": [
+ {
+ "name": "api_key",
+ "label": "Profile Key"
+ },
+ {
+ "name": "key1",
+ "label": "Profile ID"
+ }
+ ]
+ },
+ {
+ "id": "mifinity",
+ "label": "Mifinity",
+ "dummy": false,
+ "card": false,
+ "networks": [],
+ "authType": "HeaderKey",
+ "fields": [
+ {
+ "name": "api_key",
+ "label": "key"
+ }
+ ]
+ },
+ {
+ "id": "mollie",
+ "label": "Mollie",
+ "dummy": false,
+ "card": true,
+ "networks": [
+ "Mastercard",
+ "Visa",
+ "Interac",
+ "AmericanExpress",
+ "JCB",
+ "DinersClub",
+ "Discover",
+ "CartesBancaires",
+ "UnionPay"
+ ],
+ "authType": "BodyKey",
+ "fields": [
+ {
+ "name": "api_key",
+ "label": "API Key"
+ },
+ {
+ "name": "key1",
+ "label": "Profile Token"
+ }
+ ]
+ },
+ {
+ "id": "moneris",
+ "label": "Moneris",
+ "dummy": false,
+ "card": true,
+ "networks": [
+ "Mastercard",
+ "Visa",
+ "Interac",
+ "AmericanExpress",
+ "JCB",
+ "DinersClub",
+ "Discover",
+ "CartesBancaires",
+ "UnionPay"
+ ],
+ "authType": "SignatureKey",
+ "fields": [
+ {
+ "name": "api_key",
+ "label": "Client Secret"
+ },
+ {
+ "name": "key1",
+ "label": "Client Id"
+ },
+ {
+ "name": "api_secret",
+ "label": "Merchant Id"
+ }
+ ]
+ },
+ {
+ "id": "multisafepay",
+ "label": "Multisafepay",
+ "dummy": false,
+ "card": true,
+ "networks": [
+ "Mastercard",
+ "Visa",
+ "Interac",
+ "AmericanExpress",
+ "JCB",
+ "DinersClub",
+ "Discover",
+ "CartesBancaires",
+ "UnionPay"
+ ],
+ "authType": "HeaderKey",
+ "fields": [
+ {
+ "name": "api_key",
+ "label": "Enter API Key"
+ }
+ ]
+ },
+ {
+ "id": "nexinets",
+ "label": "Nexinets",
+ "dummy": false,
+ "card": true,
+ "networks": [
+ "Mastercard",
+ "Visa",
+ "Interac",
+ "AmericanExpress",
+ "JCB",
+ "DinersClub",
+ "Discover",
+ "CartesBancaires",
+ "UnionPay"
+ ],
+ "authType": "BodyKey",
+ "fields": [
+ {
+ "name": "api_key",
+ "label": "API Key"
+ },
+ {
+ "name": "key1",
+ "label": "Merchant ID"
+ }
+ ]
+ },
+ {
+ "id": "nexixpay",
+ "label": "Nexixpay",
+ "dummy": false,
+ "card": true,
+ "networks": [
+ "Mastercard",
+ "Visa",
+ "AmericanExpress",
+ "JCB"
+ ],
+ "authType": "HeaderKey",
+ "fields": [
+ {
+ "name": "api_key",
+ "label": "API Key"
+ }
+ ]
+ },
+ {
+ "id": "nmi",
+ "label": "Nmi",
+ "dummy": false,
+ "card": true,
+ "networks": [
+ "Mastercard",
+ "Visa",
+ "Interac",
+ "AmericanExpress",
+ "JCB",
+ "DinersClub",
+ "Discover",
+ "CartesBancaires",
+ "UnionPay"
+ ],
+ "authType": "BodyKey",
+ "fields": [
+ {
+ "name": "api_key",
+ "label": "API Key"
+ },
+ {
+ "name": "key1",
+ "label": "Public Key"
+ }
+ ]
+ },
+ {
+ "id": "nomupay",
+ "label": "Nomupay",
+ "dummy": false,
+ "card": false,
+ "networks": [],
+ "authType": null,
+ "fields": []
+ },
+ {
+ "id": "noon",
+ "label": "Noon",
+ "dummy": false,
+ "card": true,
+ "networks": [
+ "Mastercard",
+ "Visa",
+ "Interac",
+ "AmericanExpress",
+ "JCB",
+ "DinersClub",
+ "Discover",
+ "CartesBancaires",
+ "UnionPay"
+ ],
+ "authType": "SignatureKey",
+ "fields": [
+ {
+ "name": "api_key",
+ "label": "API Key"
+ },
+ {
+ "name": "key1",
+ "label": "Business Identifier"
+ },
+ {
+ "name": "api_secret",
+ "label": "Application Identifier"
+ }
+ ]
+ },
+ {
+ "id": "nordea",
+ "label": "Nordea",
+ "dummy": false,
+ "card": false,
+ "networks": [],
+ "authType": "SignatureKey",
+ "fields": [
+ {
+ "name": "api_key",
+ "label": "Client Secret"
+ },
+ {
+ "name": "key1",
+ "label": "Client ID"
+ },
+ {
+ "name": "api_secret",
+ "label": "eIDAS Private Key"
+ }
+ ]
+ },
+ {
+ "id": "novalnet",
+ "label": "Novalnet",
+ "dummy": false,
+ "card": true,
+ "networks": [
+ "Mastercard",
+ "Visa",
+ "Interac",
+ "AmericanExpress",
+ "JCB",
+ "DinersClub",
+ "Discover",
+ "CartesBancaires",
+ "UnionPay"
+ ],
+ "authType": "SignatureKey",
+ "fields": [
+ {
+ "name": "api_key",
+ "label": "Product Activation Key"
+ },
+ {
+ "name": "key1",
+ "label": "Payment Access Key"
+ },
+ {
+ "name": "api_secret",
+ "label": "Tariff ID"
+ }
+ ]
+ },
+ {
+ "id": "nuvei",
+ "label": "Nuvei",
+ "dummy": false,
+ "card": true,
+ "networks": [
+ "Mastercard",
+ "Visa",
+ "Interac",
+ "AmericanExpress",
+ "JCB",
+ "DinersClub",
+ "Discover",
+ "CartesBancaires",
+ "UnionPay"
+ ],
+ "authType": "SignatureKey",
+ "fields": [
+ {
+ "name": "api_key",
+ "label": "Merchant ID"
+ },
+ {
+ "name": "key1",
+ "label": "Merchant Site ID"
+ },
+ {
+ "name": "api_secret",
+ "label": "Merchant Secret"
+ }
+ ]
+ },
+ {
+ "id": "opennode",
+ "label": "Opennode",
+ "dummy": false,
+ "card": false,
+ "networks": [],
+ "authType": "HeaderKey",
+ "fields": [
+ {
+ "name": "api_key",
+ "label": "API Key"
+ }
+ ]
+ },
+ {
+ "id": "paybox",
+ "label": "Paybox",
+ "dummy": false,
+ "card": true,
+ "networks": [
+ "Mastercard",
+ "Visa",
+ "Interac",
+ "AmericanExpress",
+ "JCB",
+ "DinersClub",
+ "Discover",
+ "CartesBancaires",
+ "UnionPay"
+ ],
+ "authType": "MultiAuthKey",
+ "fields": [
+ {
+ "name": "api_key",
+ "label": "SITE Key"
+ },
+ {
+ "name": "key1",
+ "label": "Rang Identifier"
+ },
+ {
+ "name": "api_secret",
+ "label": "CLE Secret"
+ },
+ {
+ "name": "key2",
+ "label": "Merchant Id"
+ }
+ ]
+ },
+ {
+ "id": "paydotcom",
+ "label": "Paydotcom",
+ "dummy": false,
+ "card": true,
+ "networks": [
+ "Visa",
+ "Mastercard",
+ "AmericanExpress",
+ "Discover",
+ "DinersClub",
+ "JCB",
+ "UnionPay"
+ ],
+ "authType": "HeaderKey",
+ "fields": [
+ {
+ "name": "api_key",
+ "label": "API Key"
+ }
+ ]
+ },
+ {
+ "id": "payme",
+ "label": "Payme",
+ "dummy": false,
+ "card": true,
+ "networks": [
+ "Mastercard",
+ "Visa",
+ "Interac",
+ "AmericanExpress",
+ "JCB",
+ "DinersClub",
+ "Discover",
+ "CartesBancaires",
+ "UnionPay"
+ ],
+ "authType": "BodyKey",
+ "fields": [
+ {
+ "name": "api_key",
+ "label": "Seller Payme Id"
+ },
+ {
+ "name": "key1",
+ "label": "Payme Public Key"
+ }
+ ]
+ },
+ {
+ "id": "paynearme",
+ "label": "Paynearme",
+ "dummy": false,
+ "card": true,
+ "networks": [
+ "Visa",
+ "Mastercard",
+ "AmericanExpress",
+ "Discover"
+ ],
+ "authType": "BodyKey",
+ "fields": [
+ {
+ "name": "api_key",
+ "label": "PayNearMe API Secret Key"
+ },
+ {
+ "name": "key1",
+ "label": "PayNearMe Site Identifier"
+ }
+ ]
+ },
+ {
+ "id": "payload",
+ "label": "Payload",
+ "dummy": false,
+ "card": true,
+ "networks": [
+ "AmericanExpress",
+ "Discover",
+ "Mastercard",
+ "Visa"
+ ],
+ "authType": "CurrencyAuthKey",
+ "fields": [
+ {
+ "name": "auth_key_map",
+ "label": "Auth Key Map"
+ }
+ ]
+ },
+ {
+ "id": "payone",
+ "label": "Payone",
+ "dummy": false,
+ "card": false,
+ "networks": [],
+ "authType": null,
+ "fields": []
+ },
+ {
+ "id": "paypal",
+ "label": "Paypal",
+ "dummy": false,
+ "card": true,
+ "networks": [
+ "Mastercard",
+ "Visa",
+ "Interac",
+ "AmericanExpress",
+ "JCB",
+ "DinersClub",
+ "Discover",
+ "CartesBancaires",
+ "UnionPay"
+ ],
+ "authType": "BodyKey",
+ "fields": [
+ {
+ "name": "api_key",
+ "label": "Client Secret"
+ },
+ {
+ "name": "key1",
+ "label": "Client ID"
+ }
+ ]
+ },
+ {
+ "id": "paysafe",
+ "label": "Paysafe",
+ "dummy": false,
+ "card": true,
+ "networks": [
+ "Mastercard",
+ "Visa",
+ "Interac",
+ "AmericanExpress",
+ "JCB",
+ "DinersClub",
+ "Discover",
+ "CartesBancaires",
+ "UnionPay"
+ ],
+ "authType": "BodyKey",
+ "fields": [
+ {
+ "name": "api_key",
+ "label": "Username"
+ },
+ {
+ "name": "key1",
+ "label": "Password"
+ }
+ ]
+ },
+ {
+ "id": "paystack",
+ "label": "Paystack",
+ "dummy": false,
+ "card": false,
+ "networks": [],
+ "authType": "HeaderKey",
+ "fields": [
+ {
+ "name": "api_key",
+ "label": "API Key"
+ }
+ ]
+ },
+ {
+ "id": "paytm",
+ "label": "Paytm",
+ "dummy": false,
+ "card": false,
+ "networks": [],
+ "authType": "SignatureKey",
+ "fields": [
+ {
+ "name": "api_key",
+ "label": "Signing key"
+ },
+ {
+ "name": "api_secret",
+ "label": "website name"
+ },
+ {
+ "name": "key1",
+ "label": "merchant_id"
+ }
+ ]
+ },
+ {
+ "id": "payconex",
+ "label": "Payconex",
+ "dummy": false,
+ "card": true,
+ "networks": [
+ "Visa",
+ "Mastercard",
+ "AmericanExpress",
+ "Discover"
+ ],
+ "authType": "BodyKey",
+ "fields": [
+ {
+ "name": "api_key",
+ "label": "API Key"
+ },
+ {
+ "name": "key1",
+ "label": "Account Id"
+ }
+ ]
+ },
+ {
+ "id": "payu",
+ "label": "Payu",
+ "dummy": false,
+ "card": true,
+ "networks": [
+ "Mastercard",
+ "Visa",
+ "Interac",
+ "AmericanExpress",
+ "JCB",
+ "DinersClub",
+ "Discover",
+ "CartesBancaires",
+ "UnionPay"
+ ],
+ "authType": "BodyKey",
+ "fields": [
+ {
+ "name": "api_key",
+ "label": "API Key"
+ },
+ {
+ "name": "key1",
+ "label": "Merchant POS ID"
+ }
+ ]
+ },
+ {
+ "id": "peachpayments",
+ "label": "Peachpayments",
+ "dummy": false,
+ "card": true,
+ "networks": [
+ "Mastercard",
+ "Visa",
+ "AmericanExpress"
+ ],
+ "authType": "BodyKey",
+ "fields": [
+ {
+ "name": "api_key",
+ "label": "API Key"
+ },
+ {
+ "name": "key1",
+ "label": "Tenant ID"
+ }
+ ]
+ },
+ {
+ "id": "payjustnow",
+ "label": "Payjustnow",
+ "dummy": false,
+ "card": false,
+ "networks": [],
+ "authType": "BodyKey",
+ "fields": [
+ {
+ "name": "api_key",
+ "label": "Signing Key"
+ },
+ {
+ "name": "key1",
+ "label": "Merchant Account Id"
+ }
+ ]
+ },
+ {
+ "id": "payjustnowinstore",
+ "label": "Payjustnowinstore",
+ "dummy": false,
+ "card": false,
+ "networks": [],
+ "authType": "BodyKey",
+ "fields": [
+ {
+ "name": "api_key",
+ "label": "Merchant API Key"
+ },
+ {
+ "name": "key1",
+ "label": "Merchant Terminal Id"
+ }
+ ]
+ },
+ {
+ "id": "phonepe",
+ "label": "Phonepe",
+ "dummy": false,
+ "card": false,
+ "networks": [],
+ "authType": "SignatureKey",
+ "fields": [
+ {
+ "name": "api_key",
+ "label": "merchant_id"
+ },
+ {
+ "name": "api_secret",
+ "label": "key_index"
+ },
+ {
+ "name": "key1",
+ "label": "salt_key"
+ }
+ ]
+ },
+ {
+ "id": "placetopay",
+ "label": "Placetopay",
+ "dummy": false,
+ "card": true,
+ "networks": [
+ "Mastercard",
+ "Visa",
+ "Interac",
+ "AmericanExpress",
+ "JCB",
+ "DinersClub",
+ "Discover",
+ "CartesBancaires",
+ "UnionPay"
+ ],
+ "authType": "BodyKey",
+ "fields": [
+ {
+ "name": "api_key",
+ "label": "Login"
+ },
+ {
+ "name": "key1",
+ "label": "Trankey"
+ }
+ ]
+ },
+ {
+ "id": "powertranz",
+ "label": "Powertranz",
+ "dummy": false,
+ "card": true,
+ "networks": [
+ "Mastercard",
+ "Visa",
+ "Interac",
+ "AmericanExpress",
+ "JCB",
+ "DinersClub",
+ "Discover",
+ "CartesBancaires",
+ "UnionPay"
+ ],
+ "authType": "BodyKey",
+ "fields": [
+ {
+ "name": "key1",
+ "label": "PowerTranz Id"
+ },
+ {
+ "name": "api_key",
+ "label": "PowerTranz Password"
+ }
+ ]
+ },
+ {
+ "id": "prophetpay",
+ "label": "Prophetpay",
+ "dummy": false,
+ "card": false,
+ "networks": [],
+ "authType": "SignatureKey",
+ "fields": [
+ {
+ "name": "api_key",
+ "label": "Username"
+ },
+ {
+ "name": "key1",
+ "label": "Token"
+ },
+ {
+ "name": "api_secret",
+ "label": "Profile"
+ }
+ ]
+ },
+ {
+ "id": "rapyd",
+ "label": "Rapyd",
+ "dummy": false,
+ "card": true,
+ "networks": [
+ "Mastercard",
+ "Visa",
+ "Interac",
+ "AmericanExpress",
+ "JCB",
+ "DinersClub",
+ "Discover",
+ "CartesBancaires",
+ "UnionPay"
+ ],
+ "authType": "BodyKey",
+ "fields": [
+ {
+ "name": "api_key",
+ "label": "Access Key"
+ },
+ {
+ "name": "key1",
+ "label": "API Secret"
+ }
+ ]
+ },
+ {
+ "id": "razorpay",
+ "label": "Razorpay",
+ "dummy": false,
+ "card": false,
+ "networks": [],
+ "authType": "BodyKey",
+ "fields": [
+ {
+ "name": "api_key",
+ "label": "Razorpay Id"
+ },
+ {
+ "name": "key1",
+ "label": "Razorpay Secret"
+ }
+ ]
+ },
+ {
+ "id": "recurly",
+ "label": "Recurly",
+ "dummy": false,
+ "card": false,
+ "networks": [],
+ "authType": null,
+ "fields": []
+ },
+ {
+ "id": "redsys",
+ "label": "Redsys",
+ "dummy": false,
+ "card": true,
+ "networks": [
+ "Mastercard",
+ "Visa",
+ "AmericanExpress",
+ "JCB",
+ "DinersClub",
+ "UnionPay"
+ ],
+ "authType": "SignatureKey",
+ "fields": [
+ {
+ "name": "api_key",
+ "label": "Merchant ID"
+ },
+ {
+ "name": "key1",
+ "label": "Terminal ID"
+ },
+ {
+ "name": "api_secret",
+ "label": "Secret Key"
+ }
+ ]
+ },
+ {
+ "id": "revolv3",
+ "label": "Revolv3",
+ "dummy": false,
+ "card": true,
+ "networks": [
+ "Mastercard",
+ "Visa",
+ "Interac",
+ "AmericanExpress",
+ "JCB",
+ "DinersClub",
+ "Discover",
+ "CartesBancaires",
+ "UnionPay"
+ ],
+ "authType": "HeaderKey",
+ "fields": [
+ {
+ "name": "api_key",
+ "label": "Static Tokens"
+ }
+ ]
+ },
+ {
+ "id": "riskified",
+ "label": "Riskified",
+ "dummy": false,
+ "card": false,
+ "networks": [],
+ "authType": null,
+ "fields": []
+ },
+ {
+ "id": "saferpay",
+ "label": "Saferpay",
+ "dummy": false,
+ "card": true,
+ "networks": [
+ "Mastercard",
+ "Visa",
+ "AmericanExpress",
+ "JCB",
+ "Discover",
+ "DinersClub",
+ "UnionPay"
+ ],
+ "authType": "MultiAuthKey",
+ "fields": [
+ {
+ "name": "api_key",
+ "label": "API Username"
+ },
+ {
+ "name": "key1",
+ "label": "API Password"
+ },
+ {
+ "name": "api_secret",
+ "label": "Customer Id"
+ },
+ {
+ "name": "key2",
+ "label": "Terminal Id"
+ }
+ ]
+ },
+ {
+ "id": "sanlam_payshield",
+ "label": "Sanlam Payshield",
+ "dummy": false,
+ "card": false,
+ "networks": [],
+ "authType": null,
+ "fields": []
+ },
+ {
+ "id": "santander",
+ "label": "Santander",
+ "dummy": false,
+ "card": false,
+ "networks": [],
+ "authType": "CertificateAuth",
+ "fields": [
+ {
+ "name": "certificate",
+ "label": "Base64 encoded PEM formatted certificate chain"
+ },
+ {
+ "name": "private_key",
+ "label": "Base64 encoded PEM formatted private key"
+ }
+ ]
+ },
+ {
+ "id": "shift4",
+ "label": "Shift4",
+ "dummy": false,
+ "card": true,
+ "networks": [
+ "Mastercard",
+ "Visa",
+ "Interac",
+ "AmericanExpress",
+ "JCB",
+ "DinersClub",
+ "Discover",
+ "CartesBancaires",
+ "UnionPay"
+ ],
+ "authType": "HeaderKey",
+ "fields": [
+ {
+ "name": "api_key",
+ "label": "API Key"
+ }
+ ]
+ },
+ {
+ "id": "signifyd",
+ "label": "Signifyd",
+ "dummy": false,
+ "card": false,
+ "networks": [],
+ "authType": null,
+ "fields": []
+ },
+ {
+ "id": "nsure",
+ "label": "Nsure",
+ "dummy": false,
+ "card": false,
+ "networks": [],
+ "authType": null,
+ "fields": []
+ },
+ {
+ "id": "silverflow",
+ "label": "Silverflow",
+ "dummy": false,
+ "card": true,
+ "networks": [
+ "Mastercard",
+ "Visa"
+ ],
+ "authType": "SignatureKey",
+ "fields": [
+ {
+ "name": "api_key",
+ "label": "API Key"
+ },
+ {
+ "name": "api_secret",
+ "label": "API Secret"
+ },
+ {
+ "name": "key1",
+ "label": "Merchant Acceptor Key"
+ }
+ ]
+ },
+ {
+ "id": "square",
+ "label": "Square",
+ "dummy": false,
+ "card": true,
+ "networks": [
+ "Mastercard",
+ "Visa",
+ "Interac",
+ "AmericanExpress",
+ "JCB",
+ "DinersClub",
+ "Discover",
+ "CartesBancaires",
+ "UnionPay"
+ ],
+ "authType": "BodyKey",
+ "fields": [
+ {
+ "name": "api_key",
+ "label": "Square API Key"
+ },
+ {
+ "name": "key1",
+ "label": "Square Client Id"
+ }
+ ]
+ },
+ {
+ "id": "stax",
+ "label": "Stax",
+ "dummy": false,
+ "card": true,
+ "networks": [
+ "Mastercard",
+ "Visa",
+ "Interac",
+ "AmericanExpress",
+ "JCB",
+ "DinersClub",
+ "Discover",
+ "CartesBancaires",
+ "UnionPay"
+ ],
+ "authType": "HeaderKey",
+ "fields": [
+ {
+ "name": "api_key",
+ "label": "Api Key"
+ }
+ ]
+ },
+ {
+ "id": "stripe",
+ "label": "Stripe",
+ "dummy": false,
+ "card": true,
+ "networks": [
+ "Mastercard",
+ "Visa",
+ "Interac",
+ "AmericanExpress",
+ "JCB",
+ "DinersClub",
+ "Discover",
+ "CartesBancaires",
+ "UnionPay"
+ ],
+ "authType": "HeaderKey",
+ "fields": [
+ {
+ "name": "api_key",
+ "label": "Secret Key"
+ }
+ ]
+ },
+ {
+ "id": "stripebilling",
+ "label": "Stripebilling",
+ "dummy": false,
+ "card": false,
+ "networks": [],
+ "authType": null,
+ "fields": []
+ },
+ {
+ "id": "tesouro",
+ "label": "Tesouro",
+ "dummy": false,
+ "card": true,
+ "networks": [
+ "Mastercard",
+ "Visa",
+ "AmericanExpress",
+ "Discover",
+ "DinersClub",
+ "JCB",
+ "Maestro",
+ "UnionPay"
+ ],
+ "authType": "SignatureKey",
+ "fields": [
+ {
+ "name": "api_key",
+ "label": "Client ID"
+ },
+ {
+ "name": "api_secret",
+ "label": "Client Secret"
+ },
+ {
+ "name": "key1",
+ "label": "Acceptor ID"
+ }
+ ]
+ },
+ {
+ "id": "truelayer",
+ "label": "Truelayer",
+ "dummy": false,
+ "card": false,
+ "networks": [],
+ "authType": "BodyKey",
+ "fields": [
+ {
+ "name": "api_key",
+ "label": "Client ID"
+ },
+ {
+ "name": "key1",
+ "label": "Client Secret"
+ }
+ ]
+ },
+ {
+ "id": "trustly",
+ "label": "Trustly",
+ "dummy": false,
+ "card": false,
+ "networks": [],
+ "authType": "SignatureKey",
+ "fields": [
+ {
+ "name": "api_key",
+ "label": "Username"
+ },
+ {
+ "name": "key1",
+ "label": "Password"
+ },
+ {
+ "name": "api_secret",
+ "label": "Private Key(Base64 encoded)"
+ }
+ ]
+ },
+ {
+ "id": "trustpay",
+ "label": "Trustpay",
+ "dummy": false,
+ "card": true,
+ "networks": [
+ "Mastercard",
+ "Visa",
+ "Interac",
+ "AmericanExpress",
+ "JCB",
+ "DinersClub",
+ "Discover",
+ "CartesBancaires",
+ "UnionPay"
+ ],
+ "authType": "SignatureKey",
+ "fields": [
+ {
+ "name": "api_key",
+ "label": "API Key"
+ },
+ {
+ "name": "key1",
+ "label": "Project ID"
+ },
+ {
+ "name": "api_secret",
+ "label": "Secret Key"
+ }
+ ]
+ },
+ {
+ "id": "trustpayments",
+ "label": "Trustpayments",
+ "dummy": false,
+ "card": true,
+ "networks": [
+ "Mastercard",
+ "Visa"
+ ],
+ "authType": "HeaderKey",
+ "fields": [
+ {
+ "name": "api_key",
+ "label": "API Key"
+ }
+ ]
+ },
+ {
+ "id": "tokenio",
+ "label": "Tokenio",
+ "dummy": false,
+ "card": false,
+ "networks": [],
+ "authType": "MultiAuthKey",
+ "fields": [
+ {
+ "name": "api_key",
+ "label": "Key Id"
+ },
+ {
+ "name": "api_secret",
+ "label": "Private Key"
+ },
+ {
+ "name": "key1",
+ "label": "Merchant Id"
+ },
+ {
+ "name": "key2",
+ "label": "Key Algorithm"
+ }
+ ]
+ },
+ {
+ "id": "tsys",
+ "label": "Tsys",
+ "dummy": false,
+ "card": true,
+ "networks": [
+ "Mastercard",
+ "Visa",
+ "Interac",
+ "AmericanExpress",
+ "JCB",
+ "DinersClub",
+ "Discover",
+ "CartesBancaires",
+ "UnionPay"
+ ],
+ "authType": "SignatureKey",
+ "fields": [
+ {
+ "name": "api_key",
+ "label": "Device Id"
+ },
+ {
+ "name": "key1",
+ "label": "Transaction Key"
+ },
+ {
+ "name": "api_secret",
+ "label": "Developer Id"
+ }
+ ]
+ },
+ {
+ "id": "tsys_transit",
+ "label": "Tsys Transit",
+ "dummy": false,
+ "card": true,
+ "networks": [
+ "Mastercard",
+ "Visa",
+ "AmericanExpress",
+ "JCB",
+ "DinersClub",
+ "Discover",
+ "UnionPay"
+ ],
+ "authType": "SignatureKey",
+ "fields": [
+ {
+ "name": "api_key",
+ "label": "Device Id"
+ },
+ {
+ "name": "key1",
+ "label": "Transaction Key"
+ },
+ {
+ "name": "api_secret",
+ "label": "Developer Id"
+ }
+ ]
+ },
+ {
+ "id": "volt",
+ "label": "Volt",
+ "dummy": false,
+ "card": false,
+ "networks": [],
+ "authType": "MultiAuthKey",
+ "fields": [
+ {
+ "name": "api_key",
+ "label": "Username"
+ },
+ {
+ "name": "api_secret",
+ "label": "Password"
+ },
+ {
+ "name": "key1",
+ "label": "Client ID"
+ },
+ {
+ "name": "key2",
+ "label": "Client Secret"
+ }
+ ]
+ },
+ {
+ "id": "wellsfargo",
+ "label": "Wellsfargo",
+ "dummy": false,
+ "card": true,
+ "networks": [
+ "Mastercard",
+ "Visa",
+ "Interac",
+ "AmericanExpress",
+ "JCB",
+ "DinersClub",
+ "Discover",
+ "CartesBancaires",
+ "UnionPay"
+ ],
+ "authType": "SignatureKey",
+ "fields": [
+ {
+ "name": "api_key",
+ "label": "Key"
+ },
+ {
+ "name": "key1",
+ "label": "Merchant ID"
+ },
+ {
+ "name": "api_secret",
+ "label": "Shared Secret"
+ }
+ ]
+ },
+ {
+ "id": "wise",
+ "label": "Wise",
+ "dummy": false,
+ "card": false,
+ "networks": [],
+ "authType": null,
+ "fields": []
+ },
+ {
+ "id": "worldline",
+ "label": "Worldline",
+ "dummy": false,
+ "card": true,
+ "networks": [
+ "Mastercard",
+ "Visa",
+ "Interac",
+ "AmericanExpress",
+ "JCB",
+ "DinersClub",
+ "Discover",
+ "CartesBancaires",
+ "UnionPay"
+ ],
+ "authType": "SignatureKey",
+ "fields": [
+ {
+ "name": "api_key",
+ "label": "API Key ID"
+ },
+ {
+ "name": "key1",
+ "label": "Merchant ID"
+ },
+ {
+ "name": "api_secret",
+ "label": "Secret API Key"
+ }
+ ]
+ },
+ {
+ "id": "worldpay",
+ "label": "Worldpay",
+ "dummy": false,
+ "card": true,
+ "networks": [
+ "Mastercard",
+ "Visa",
+ "Interac",
+ "AmericanExpress",
+ "JCB",
+ "DinersClub",
+ "Discover",
+ "CartesBancaires",
+ "UnionPay"
+ ],
+ "authType": "SignatureKey",
+ "fields": [
+ {
+ "name": "key1",
+ "label": "Username"
+ },
+ {
+ "name": "api_key",
+ "label": "Password"
+ },
+ {
+ "name": "api_secret",
+ "label": "Merchant Identifier"
+ }
+ ]
+ },
+ {
+ "id": "worldpaymodular",
+ "label": "Worldpaymodular",
+ "dummy": false,
+ "card": false,
+ "networks": [],
+ "authType": "SignatureKey",
+ "fields": [
+ {
+ "name": "key1",
+ "label": "Username"
+ },
+ {
+ "name": "api_key",
+ "label": "Password"
+ },
+ {
+ "name": "api_secret",
+ "label": "Merchant Identifier"
+ }
+ ]
+ },
+ {
+ "id": "worldpayraft",
+ "label": "Worldpayraft",
+ "dummy": false,
+ "card": true,
+ "networks": [
+ "Visa",
+ "Mastercard",
+ "AmericanExpress",
+ "DinersClub"
+ ],
+ "authType": "BodyKey",
+ "fields": [
+ {
+ "name": "api_key",
+ "label": "Worldpay License"
+ },
+ {
+ "name": "key1",
+ "label": "Worldpay Merchant ID"
+ }
+ ]
+ },
+ {
+ "id": "worldpayvantiv",
+ "label": "Worldpayvantiv",
+ "dummy": false,
+ "card": true,
+ "networks": [
+ "Mastercard",
+ "Visa",
+ "AmericanExpress",
+ "JCB",
+ "DinersClub",
+ "Discover"
+ ],
+ "authType": "SignatureKey",
+ "fields": [
+ {
+ "name": "api_key",
+ "label": "Username"
+ },
+ {
+ "name": "api_secret",
+ "label": "Password"
+ },
+ {
+ "name": "key1",
+ "label": "Merchant ID"
+ }
+ ]
+ },
+ {
+ "id": "worldpayxml",
+ "label": "Worldpayxml",
+ "dummy": false,
+ "card": true,
+ "networks": [
+ "Mastercard",
+ "Visa",
+ "Interac",
+ "AmericanExpress",
+ "JCB",
+ "DinersClub",
+ "Discover",
+ "CartesBancaires",
+ "UnionPay"
+ ],
+ "authType": "SignatureKey",
+ "fields": [
+ {
+ "name": "api_secret",
+ "label": "Merchant Code"
+ },
+ {
+ "name": "api_key",
+ "label": "API Username"
+ },
+ {
+ "name": "key1",
+ "label": "API Password"
+ }
+ ]
+ },
+ {
+ "id": "xendit",
+ "label": "Xendit",
+ "dummy": false,
+ "card": true,
+ "networks": [
+ "Mastercard",
+ "Visa",
+ "Interac",
+ "AmericanExpress",
+ "JCB",
+ "DinersClub",
+ "Discover",
+ "CartesBancaires",
+ "UnionPay"
+ ],
+ "authType": "HeaderKey",
+ "fields": [
+ {
+ "name": "api_key",
+ "label": "API Key"
+ }
+ ]
+ },
+ {
+ "id": "zen",
+ "label": "Zen",
+ "dummy": false,
+ "card": true,
+ "networks": [
+ "Mastercard",
+ "Visa",
+ "Interac",
+ "AmericanExpress",
+ "JCB",
+ "DinersClub",
+ "Discover",
+ "CartesBancaires",
+ "UnionPay"
+ ],
+ "authType": "HeaderKey",
+ "fields": [
+ {
+ "name": "api_key",
+ "label": "API Key"
+ }
+ ]
+ },
+ {
+ "id": "zift",
+ "label": "Zift",
+ "dummy": false,
+ "card": true,
+ "networks": [
+ "Mastercard",
+ "Visa",
+ "Interac",
+ "AmericanExpress",
+ "JCB",
+ "DinersClub",
+ "Discover",
+ "CartesBancaires",
+ "UnionPay"
+ ],
+ "authType": "SignatureKey",
+ "fields": [
+ {
+ "name": "api_key",
+ "label": "Username"
+ },
+ {
+ "name": "api_secret",
+ "label": "Password"
+ },
+ {
+ "name": "key1",
+ "label": "Account ID"
+ }
+ ]
+ },
+ {
+ "id": "plaid",
+ "label": "Plaid",
+ "dummy": false,
+ "card": false,
+ "networks": [],
+ "authType": "BodyKey",
+ "fields": [
+ {
+ "name": "api_key",
+ "label": "client_id"
+ },
+ {
+ "name": "key1",
+ "label": "secret"
+ }
+ ]
+ },
+ {
+ "id": "zsl",
+ "label": "Zsl",
+ "dummy": false,
+ "card": false,
+ "networks": [],
+ "authType": "BodyKey",
+ "fields": [
+ {
+ "name": "api_key",
+ "label": "Key"
+ },
+ {
+ "name": "key1",
+ "label": "Merchant ID"
+ }
+ ]
+ },
+ {
+ "id": "juspaythreedsserver",
+ "label": "Juspaythreedsserver",
+ "dummy": false,
+ "card": false,
+ "networks": [],
+ "authType": "NoKey",
+ "fields": []
+ },
+ {
+ "id": "ctp_mastercard",
+ "label": "Ctp Mastercard",
+ "dummy": false,
+ "card": false,
+ "networks": [],
+ "authType": "HeaderKey",
+ "fields": [
+ {
+ "name": "api_key",
+ "label": "API Key"
+ }
+ ]
+ },
+ {
+ "id": "ctp_visa",
+ "label": "Ctp Visa",
+ "dummy": false,
+ "card": false,
+ "networks": [],
+ "authType": "NoKey",
+ "fields": []
+ },
+ {
+ "id": "netcetera",
+ "label": "Netcetera",
+ "dummy": false,
+ "card": false,
+ "networks": [],
+ "authType": "CertificateAuth",
+ "fields": [
+ {
+ "name": "certificate",
+ "label": "Base64 encoded PEM formatted certificate chain"
+ },
+ {
+ "name": "private_key",
+ "label": "Base64 encoded PEM formatted private key"
+ }
+ ]
+ },
+ {
+ "id": "vgs",
+ "label": "Vgs",
+ "dummy": false,
+ "card": false,
+ "networks": [],
+ "authType": "SignatureKey",
+ "fields": [
+ {
+ "name": "api_key",
+ "label": "Client Id"
+ },
+ {
+ "name": "key1",
+ "label": "Client Secret"
+ },
+ {
+ "name": "api_secret",
+ "label": "Vault Id"
+ }
+ ]
+ },
+ {
+ "id": "cardinal",
+ "label": "Cardinal",
+ "dummy": false,
+ "card": false,
+ "networks": [],
+ "authType": "SignatureKey",
+ "fields": [
+ {
+ "name": "api_key",
+ "label": "API Key"
+ },
+ {
+ "name": "api_secret",
+ "label": "API ID"
+ },
+ {
+ "name": "key1",
+ "label": "Organization Unit ID"
+ }
+ ]
+ },
+ {
+ "id": "threedsecureio",
+ "label": "Threedsecureio",
+ "dummy": false,
+ "card": false,
+ "networks": [],
+ "authType": "HeaderKey",
+ "fields": [
+ {
+ "name": "api_key",
+ "label": "Api Key"
+ }
+ ]
+ }
+]
diff --git a/loadtest/console/src/connector-config.mjs b/loadtest/console/src/connector-config.mjs
new file mode 100644
index 0000000000..351013902c
--- /dev/null
+++ b/loadtest/console/src/connector-config.mjs
@@ -0,0 +1,20 @@
+import catalog from './connector-catalog.json' with {type:'json'};
+export {catalog as connectorCatalog};
+export const supportedConnectorAuth=new Set(['HeaderKey','BodyKey','SignatureKey','MultiAuthKey','NoKey']);
+export const defaultConnectorPlan=()=>({mode:'dummy',mix:[{connector:'stripe_test',weight:100}]});
+export function normalizeConnectorPlan(value){
+ if(value==null)return defaultConnectorPlan();
+ if(!['dummy','real'].includes(value.mode))throw new Error('Choose Dummy or Real connectors');
+ if(!Array.isArray(value.mix)||!value.mix.length||value.mix.length>20)throw new Error('Choose between 1 and 20 connectors');
+ const seen=new Set();const mix=value.mix.map(row=>{
+ const definition=catalog.find(c=>c.id===row.connector),weight=Number(row.weight);
+ if(!definition||definition.dummy!==(value.mode==='dummy')||!definition.card||!supportedConnectorAuth.has(definition.authType))throw new Error('Choose a configured card connector for this mode');
+ if(seen.has(row.connector))throw new Error('Each connector can only appear once');seen.add(row.connector);
+ if(!Number.isInteger(weight)||weight<1||weight>100)throw new Error('Connector weights must be whole percentages between 1 and 100');
+ return {connector:row.connector,weight};
+ });
+ if(mix.reduce((s,r)=>s+r.weight,0)!==100)throw new Error('Connector weights must total 100%');
+ return {mode:value.mode,mix};
+}
+export const connectorSet=plan=>normalizeConnectorPlan(plan).mix.map(r=>r.connector).sort();
+export function connectorPlanError(value){try{normalizeConnectorPlan(value);return '';}catch(e){return e.message;}}
diff --git a/loadtest/console/src/dismissible-menu.mjs b/loadtest/console/src/dismissible-menu.mjs
new file mode 100644
index 0000000000..1b539338c1
--- /dev/null
+++ b/loadtest/console/src/dismissible-menu.mjs
@@ -0,0 +1,52 @@
+import {tick} from 'svelte';
+
+/** Light-dismiss behavior for native details used as action menus. */
+/** @param {HTMLDetailsElement} node */
+export function dismissibleMenu(node) {
+ const document = node.ownerDocument;
+ const summary = node.querySelector('summary');
+
+ /** @param {Event} event */
+ function dismissOutside(event) {
+ if (node.open && !event.composedPath().includes(node)) node.open = false;
+ }
+
+ /** @param {KeyboardEvent} event */
+ function onKeydown(event) {
+ if (!node.open || event.key !== 'Escape') return;
+ event.preventDefault();
+ event.stopPropagation();
+ node.open = false;
+ summary?.focus();
+ }
+
+ /** @param {MouseEvent} event */
+ function onClick(event) {
+ dismissOutside(event);
+ if (!node.open || !(event.target instanceof Element)) return;
+ const action = event.target.closest('button, a[href]');
+ if (!action || !node.contains(action) || action.matches(':disabled, [aria-disabled="true"]')) return;
+ const hadFocus = node.contains(document.activeElement);
+ // Let the action finish (including keyed row moves) before hiding its focused button.
+ queueMicrotask(async () => {
+ await tick();
+ if (!node.isConnected) return;
+ const restoreFocus = hadFocus && (document.activeElement === document.body || node.contains(document.activeElement));
+ node.open = false;
+ if (restoreFocus) summary?.focus();
+ });
+ }
+
+ document.addEventListener('pointerdown', dismissOutside, true);
+ document.addEventListener('focusin', dismissOutside, true);
+ document.addEventListener('click', onClick, true);
+ document.addEventListener('keydown', onKeydown, true);
+ return {
+ destroy() {
+ document.removeEventListener('pointerdown', dismissOutside, true);
+ document.removeEventListener('focusin', dismissOutside, true);
+ document.removeEventListener('click', onClick, true);
+ document.removeEventListener('keydown', onKeydown, true);
+ }
+ };
+}
diff --git a/loadtest/console/src/duration.mjs b/loadtest/console/src/duration.mjs
new file mode 100644
index 0000000000..d51a3ab470
--- /dev/null
+++ b/loadtest/console/src/duration.mjs
@@ -0,0 +1,5 @@
+export function formatDuration(seconds) {
+ if(!Number.isFinite(Number(seconds))||Number(seconds)<0)return '—';
+ const total=Math.round(Number(seconds)),hours=Math.floor(total/3600),minutes=Math.floor(total%3600/60),remaining=total%60;
+ return [hours?`${hours} hr`:'',minutes?`${minutes} min`:'',remaining||!total?`${remaining} sec`:''].filter(Boolean).join(' ');
+}
diff --git a/loadtest/console/src/environments.mjs b/loadtest/console/src/environments.mjs
new file mode 100644
index 0000000000..b31248fc85
--- /dev/null
+++ b/loadtest/console/src/environments.mjs
@@ -0,0 +1,38 @@
+export const environments=[
+ {id:'local',label:'Local',supported:true},
+ {id:'gcp',label:'GCP',supported:true},
+ {id:'aws',label:'AWS',supported:false},
+ {id:'azure',label:'Azure',supported:false}
+];
+export const environmentLabel=id=>environments.find(e=>e.id===id)?.label||'Unassigned';
+export function validateEnvironment(id){if(!environments.some(e=>e.id===id))throw new Error('Choose Local, GCP, AWS or Azure');return id;}
+export function requireSupportedEnvironment(id){validateEnvironment(id);if(!environments.find(e=>e.id===id).supported)throw new Error(`${environmentLabel(id)} execution is not supported; select Local or GCP to execute tests`);}
+// Kubernetes alone does not identify a cloud provider. Explicit legacy Cloud
+// targets were GCP in the previous editor; unclassified custom targets stay inert.
+export function targetEnvironment(target){
+ if(environments.some(e=>e.id===target.environment))return target.environment;
+ if(target.environment==='cloud'||target.adapter?.startsWith('gcp-'))return 'gcp';
+ if(['local-vault','process-compose'].includes(target.adapter))return 'local';
+ return null;
+}
+export const faultCapabilities={
+ local:{'card-vault':{adapter:'local-vault',actions:['outage']},postgres:{adapter:'process-compose',actions:['outage']},redis:{adapter:'process-compose',actions:['outage']}},
+ gcp:{'card-vault':{adapter:'kubernetes',actions:['outage']},postgres:{adapter:'gcp-alloydb',actions:['failover']},redis:{adapter:'gcp-redis',actions:['failover']}},
+ aws:{},azure:{}
+};
+export function validateTargetProvider(target,type){
+ const environment=targetEnvironment(target);
+ if(target.adapter==='simulated')return environment;
+ if(target.adapter==='command'){requireSupportedEnvironment(environment);if(!['card-vault','postgres','redis'].includes(type))throw new Error('Choose a custom fault service type');return environment;}
+ if(!environment)throw new Error('Assign a provider to this legacy fault target before using it');
+ requireSupportedEnvironment(environment);
+ const capability=faultCapabilities[environment][type];
+ if(!capability||capability.adapter!==target.adapter)throw new Error(`${environmentLabel(environment)} does not support this fault adapter for ${type}`);
+ return environment;
+}
+
+export function environmentAccessNote(environment){
+ if(environment==='gcp')return 'GCP actions run on the console supervisor. Authenticate gcloud there and grant access to inspect and fail over the selected resources. Kubernetes actions also need the correct context and workload permissions. A successful read-only check does not prove permission to trigger a failover.';
+ if(environment==='local')return 'Local commands run on the console supervisor, not in your browser. Service paths and process controllers must be accessible from that machine.';
+ return 'Execution is not supported for this environment yet.';
+}
diff --git a/loadtest/console/src/fault-notice.mjs b/loadtest/console/src/fault-notice.mjs
new file mode 100644
index 0000000000..5fb37f3dc8
--- /dev/null
+++ b/loadtest/console/src/fault-notice.mjs
@@ -0,0 +1,11 @@
+export function faultNotice(faults,{live=false,stopping=false,activity=[]}={}) {
+ const active=faults?.active;
+ if(!active&&!faults?.blocked)return '';
+ const label=active?.target||'Fault recovery';
+ const databaseAvailability=active?.databaseAvailability??[...activity].reverse().find(e=>['database_available','database_unavailable'].includes(e.kind)&&e.at>=(active?.recoveryAt||Infinity)-10000)?.kind?.replace('database_','');
+ if(databaseAvailability==='available'&&['restoring','recovery_failed'].includes(active.status)) {
+ return active.status==='recovery_failed'?`${label} · DB available · failover completion not verified`:`${label} · recovered · cloud operation finishing in background`;
+ }
+ const status=active?.status==='recovery_failed'?'recovery not verified':active?.status||'pending';
+ return `${label} · ${status}${live&&!stopping?' · next stage waits for recovery':''}`;
+}
diff --git a/loadtest/console/src/fault-types.mjs b/loadtest/console/src/fault-types.mjs
new file mode 100644
index 0000000000..74d3e5d314
--- /dev/null
+++ b/loadtest/console/src/fault-types.mjs
@@ -0,0 +1,63 @@
+import {targetEnvironment,faultCapabilities,environmentLabel} from './environments.mjs';
+export const faultTypes=[{type:'card-vault',label:'Card vault',adapter:'local-vault',port:3001},{type:'postgres',label:'PostgreSQL',adapter:'process-compose',port:5432},{type:'redis',label:'Redis',adapter:'process-compose',port:6379}];
+// Older targets did not store a service type. Keep their IDs and connection settings.
+export function faultType(target){
+ if(target.serviceType)return target.serviceType;
+ if(target.adapter==='gcp-alloydb')return 'postgres';
+ if(target.adapter==='gcp-redis')return 'redis';
+ if(target.adapter==='local-vault')return 'card-vault';
+ if(target.adapter!=='process-compose')return null;
+ return /redis/i.test(target.label||'')||[6378,6379].includes(target.port)||/^r\d+$/.test(target.process||'')?'redis':'postgres';
+}
+
+export function faultEnvironment(target){return targetEnvironment(target)||'unassigned';}
+export function configureFaultTarget(target,environment){
+ environment=environment==='cloud'?'gcp':environment;
+ const type=faultType(target),spec=faultTypes.find(t=>t.type===type),capability=faultCapabilities[environment]?.[type];
+ return {...target,environment,adapter:capability?.adapter||'placeholder',actions:capability?.actions||[],port:target.port??spec?.port,repository:target.repository??'',binary:target.binary??'process-compose',controllerPort:target.controllerPort??8090,process:target.process??(type==='redis'?'r1':'p1'),project:target.project||'',region:target.region||'',cluster:target.cluster||'',instance:target.instance||'',context:target.context??'',namespace:target.namespace||'',deployment:target.deployment||'',recoveryReplicas:target.recoveryReplicas??1,container:target.container??''};
+}
+export const faultTargetLabel=target=>`${target.label} · ${environmentLabel(faultEnvironment(target))}`;
+
+// Describe the actual execution adapter rather than assuming every provider uses a CLI.
+export function faultAccessNote(target){
+ const location='on the console supervisor host';
+ switch(target.adapter){
+ case 'gcp-alloydb':
+ case 'gcp-redis':return `Requires gcloud installed and authenticated ${location}, with access to the configured project and permissions to inspect the target and trigger failover. Check target is read-only; it does not prove failover permission.`;
+ case 'kubernetes':return `Requires kubectl and any cluster credential plugin ${location}, the correct kubeconfig context, and permissions to inspect, scale and delete pods for the configured workload.`;
+ case 'docker':return `Requires the Docker CLI ${location}, access to the Docker daemon, and permissions to inspect, stop and start the configured container.`;
+ case 'process-compose':return `Requires access to the configured process-compose controller and process ${location}. The process-compose CLI must also be available for target checks. Stop/start permissions are required.`;
+ case 'local-vault':return `Requires lsof and ps ${location}, access to the vault repository, and permission to stop and restart its process. Nix/Cargo must be available for a Nix-based repository, or provide a prebuilt locker binary.`;
+ case 'command':return `Custom commands run through /bin/sh as the console supervisor's OS user. Install and authenticate any CLI they invoke (such as gcloud, aws or az) on that host, with permissions for the intended resources. Verification commands must be read-only.`;
+ case 'placeholder':return `${environmentLabel(faultEnvironment(target))} fault execution is not supported yet.`;
+ default:return '';
+ }
+}
+
+export function faultCommandPreview(target){
+ if(target.adapter==='command')return `Scheduled trigger: ${target.triggerCommand||'Not configured'}\nRecovery: ${target.recoveryMode==='self-recovering'?'Self-recovering':target.restoreCommand||'Not configured'}`;
+ if(target.adapter==='gcp-alloydb')return `gcloud alloydb instances failover ${target.instance} --cluster=${target.cluster} --region=${target.region} --project=${target.project} --quiet`;
+ if(target.adapter==='kubernetes'){
+ const prefix=`kubectl${target.context?` --context=${target.context}`:''} -n ${target.namespace}`;
+ const hard=(target.outageMode??(faultType(target)==='card-vault'?'hard':'graceful'))==='hard';
+ return `Interruption: ${prefix} scale deploy ${target.deployment} --replicas=0${hard?`\n${prefix} delete pod <captured vault pod> --grace-period=0 --force --wait=false\nVerify: captured vault pods absent from kubelet runtime before starting outage duration`:''}\nRecovery: ${prefix} scale deploy ${target.deployment} --replicas=${target.recoveryReplicas ?? 'original'}`;
+ }
+ return '';
+}
+
+export function switchFaultEnvironment(target,environment){
+ const {presets={},...current}=target;
+ environment=environment==='cloud'?'gcp':environment;
+ const saved={...presets,...(presets.cloud?{gcp:presets.cloud}:{}),[faultEnvironment(target)]:current};
+ const next=configureFaultTarget({...saved[environment],id:target.id,label:target.label,serviceType:faultType(target)},environment);
+ return {...next,presets:saved};
+}
+
+export function faultTargetResource(target){
+ if(!target)return '';
+ if(target.adapter==='local-vault')return `${target.repository} · port ${target.port}`;
+ if(target.adapter==='process-compose')return `${target.process} · controller 127.0.0.1:${target.controllerPort} · service port ${target.port}`;
+ if(target.adapter==='kubernetes')return [target.context||'Current Kubernetes context',`${target.namespace}/${target.deployment}`].join(' · ');
+ if(target.adapter?.startsWith('gcp-'))return [target.project,target.region,target.cluster,target.instance].filter(Boolean).join(' · ');
+ return target.container||target.resourceId||'';
+}
diff --git a/loadtest/console/src/fixture-steps.mjs b/loadtest/console/src/fixture-steps.mjs
new file mode 100644
index 0000000000..e888342b2f
--- /dev/null
+++ b/loadtest/console/src/fixture-steps.mjs
@@ -0,0 +1,17 @@
+export function fixtureSteps(job){
+ const progress=job?.progress||{},setup=progress.setup||{},sp=setup.superposition||{};
+ const done=job?.status==='complete'||setup.stage==='ready',terminal=['failed','cancelled','interrupted'].includes(job?.status);
+ let phase=sp.status||'pending',remaining=sp.remainingSeconds;
+ // Older generators have no structured setup status; their labelled output still
+ // identifies the refresh wait without treating a full merchant bar as readiness.
+ if(!progress.setup){const output=job?.output||'';if(output.includes('Verify refreshed flags'))phase='verifying';else if(output.includes('Service refresh')){phase='waiting';const matches=[...output.matchAll(/Service refresh[^\n]*\|\s*(\d+)s remaining/g)];remaining=Number(matches.at(-1)?.[1]??0);}else if(output.includes('Resolve flags'))phase='resolving';}
+ const merchantsDone=done||Number(progress.fixtures?.completed)>=Number(progress.fixtures?.total)&&Number(progress.fixtures?.total)>0;
+ const rank={pending:0,applying:1,resolving:1,waiting:2,verifying:3,complete:4,skipped:4}[phase]??0;
+ const status=(step)=>{if(done)return phase==='skipped'&&step>0?'skipped':'complete';if(phase==='skipped'&&step>0)return 'skipped';let value=step===0?(merchantsDone?'complete':'running'):rank>step?'complete':rank===step?'running':'pending';if(terminal||setup.stage==='failed')value=value==='running'?'failed':value;return value;};
+ return [
+ {label:'Merchants',status:status(0),detail:`${progress.fixtures?.completed??0} / ${progress.fixtures?.total??0} provisioned`},
+ {label:'Superposition defaults',status:status(1),detail:phase==='resolving'?'Checking resolved flags':phase==='applying'?'Applying configured flags':''},
+ {label:'Service refresh',status:status(2),detail:phase==='waiting'?`${remaining??0}s remaining`:'',remaining,total:sp.totalSeconds},
+ {label:'Readiness',status:status(3),detail:phase==='verifying'?'Verifying refreshed flags':''}
+ ];
+}
diff --git a/loadtest/console/src/flow-catalog.mjs b/loadtest/console/src/flow-catalog.mjs
new file mode 100644
index 0000000000..a3864ed66b
--- /dev/null
+++ b/loadtest/console/src/flow-catalog.mjs
@@ -0,0 +1,19 @@
+import {formatDuration} from './duration.mjs';
+import {unavailableFlows} from './payment-flows.mjs';
+export const flowCatalog=[['cit_off_session','CIT off-session'],['sdk_checkout','SDK checkout'],['guest','Guest payment'],['cit_on_session','CIT on-session'],['ptv_on_session','Pay to vault · on-session'],['ptv_off_session','Pay to vault · off-session'],['cit_metadata_changed','Card metadata update'],['mit','Merchant-initiated payment'],['saved_card_checkout','Saved-card checkout']];
+export const flowLabel=type=>flowCatalog.find(([key])=>key===type)?.[1] || type;
+export function newFlow(type,flows){const names=new Set(flows.map(flow=>flow.name));let name=type,index=2;while(names.has(name))name=`${type}_${index++}`;return {name,scenario:type,merchant_path:'modular',weight:0};}
+export function profileSummary(profile){return `${profile.mode==='tenancy'?'Tenancy':'Single'} · ${profile.merchantCount} ${profile.merchantCount===1?'merchant':'merchants'} · ${profile.totalRps} ${profile.loadShape==='staged'?'peak TPS':'TPS'} · ${formatDuration(profile.durationSeconds)}`;}
+
+export function balanceWeights(flows,normalize=false){
+ if(!flows.length)return flows;
+ const total=flows.reduce((sum,flow)=>sum+Number(flow.weight||0),0),remaining=Math.max(0,100-total);
+ const empty=flows.filter(flow=>!flow.weight).length;
+ const values=flows.map(flow=>normalize?(total?Number(flow.weight||0)/total*100:100/flows.length):Number(flow.weight||0)+(!empty||!flow.weight?remaining/(empty||flows.length):0));
+ const rounded=values.map(Math.floor);let extra=Math.round(values.reduce((a,b)=>a+b,0))-rounded.reduce((a,b)=>a+b,0);
+ const order=values.map((v,i)=>({i,remainder:v-rounded[i]})).sort((a,b)=>b.remainder-a.remainder);
+ for(let n=0;n<extra;n++)rounded[order[n%order.length].i]++;
+ return flows.map((flow,i)=>({...flow,weight:rounded[i]}));
+}
+
+export const flowAvailable=type=>!unavailableFlows.has(type);
diff --git a/loadtest/console/src/grafana-panels.mjs b/loadtest/console/src/grafana-panels.mjs
new file mode 100644
index 0000000000..6b74edc2d1
--- /dev/null
+++ b/loadtest/console/src/grafana-panels.mjs
@@ -0,0 +1,16 @@
+import {pausedChartSamples} from './chart-timeline.mjs';
+const dashboard='/d-solo/loadtest-unified-perf/load-test-e28094-unified-performance';
+export function unifiedPerformancePanels(run){
+ if(!run?.startedAt)return [];
+ const paused=run.loadState==='paused';
+ const frozen=pausedChartSamples(run.telemetry||[],run.loadState).at(-1);
+ const end=run.endedAt||(paused&&frozen?run.startedAt+frozen.t*1000:paused?run.startedAt+Math.max(0,run.wallSeconds||run.activeSeconds||0)*1000:'now');
+ return [[4,'Payment Confirm p99 Latency'],[2,'RPS (for router service)'],[3,'Error Rate % (5xx)']].map(([id,title])=>{
+ const query=new URLSearchParams({panelId:String(id),from:String(run.startedAt),to:String(end),timezone:'browser',theme:'light',
+ 'var-datasource':'prometheus','var-namespace':'hyperswitch','var-app':'hyperswitch-router-hyperswitch-server',
+ 'var-path':'$__all','var-status_code':'$__all','var-table':'$__all','var-operation':'$__all','var-pod':'$__all',
+ 'var-alloydb_cluster':'.*','var-alloydb_instance':'.*','var-redis_instance':'.*'});
+ if(!run.endedAt&&!paused)query.set('refresh','1s');
+ return {title,url:`/grafana${dashboard}?${query}`};
+ });
+}
diff --git a/loadtest/console/src/hooks.server.js b/loadtest/console/src/hooks.server.js
new file mode 100644
index 0000000000..409f7e8569
--- /dev/null
+++ b/loadtest/console/src/hooks.server.js
@@ -0,0 +1,29 @@
+import { redirect, json } from '@sveltejs/kit';
+import { authenticated, sessionCookie, sameOrigin } from '../server/auth.mjs';
+import { initializeConfig } from '../server/state.mjs';
+import { building } from '$app/environment';
+import {boundedRequest} from '../server/request-body.mjs';
+
+export async function handle({ event, resolve }) {
+ if(building)return resolve(event);
+ initializeConfig();
+ const path=event.url.pathname;
+ if(path==='/health')return resolve(event);
+ // Worker agents authenticate with their own bearer credentials and connect
+ // outbound, so they do not have a browser session or Origin header.
+ if(path.startsWith('/api/worker/v1/'))return resolve(event);
+ if(!['GET','HEAD','OPTIONS'].includes(event.request.method) && !sameOrigin(event.request,event.url)) return json({error:'Invalid request origin'},{status:403});
+ const isAuthenticated=authenticated(event.cookies.get(sessionCookie));
+ if(!['GET','HEAD','OPTIONS'].includes(event.request.method)){
+ try{event.request=await boundedRequest(event.request);}catch(e){return json({error:e.message},{status:e.status||400,headers:{connection:'close'}});}
+ }
+ if(path==='/login') {if(isAuthenticated && event.request.method==='GET')redirect(303,'/');return resolve(event);}
+ if(!isAuthenticated) {
+ if(path.startsWith('/api/')||path.startsWith('/grafana/'))return json({error:'Authentication required'},{status:401});
+ redirect(303,'/login');
+ }
+ const response=await resolve(event);
+ response.headers.set('cache-control','no-store');
+ response.headers.set('x-content-type-options','nosniff');
+ return response;
+}
diff --git a/loadtest/console/src/import-state.mjs b/loadtest/console/src/import-state.mjs
new file mode 100644
index 0000000000..c2ed8dde85
--- /dev/null
+++ b/loadtest/console/src/import-state.mjs
@@ -0,0 +1,27 @@
+export const importBusy=job=>['starting','running','cancelling'].includes(job?.status);
+export function matchesImport(job,profileId){const id=job?.progress?.verification?.profileId;return Boolean(job?.progress?.verification)&&(!id||id===profileId);}
+// A slower fallback poll or an old EventSource must not overwrite newer progress.
+export function acceptImportUpdate(current,incoming,profileId){
+ if(!current||current.id!==incoming?.id||!matchesImport(incoming,profileId))return false;
+ if(!importBusy(current))return false;
+ const rank={credentials:0,setup:1,saving:2};
+ if(importBusy(incoming)&&(rank[incoming.progress.verification.phase]??0)<(rank[current.progress.verification.phase]??0))return false;
+ const count=job=>job.progress?.verification?.checked??job.progress?.verification?.checks?.length??0;
+ return !importBusy(incoming)||count(incoming)>=count(current);
+}
+export function importView(job){
+ const verification=job?.progress?.verification;if(!verification)return null;
+ const busy=importBusy(job),checks=verification.checks||[],failures=checks.filter(c=>!c.ok);
+ const phase=busy?(verification.phase||'credentials'):job.status==='complete'&&verification.ok!==false?'ready':['cancelled','interrupted'].includes(job.status)?'cancelled':'failed';
+ const phases=['credentials','setup'];
+ const stages=phases.map((id,index)=>{
+ const saved=verification.stages?.[id],rows=checks.filter(c=>c.stage===id);
+ let status=saved?.status;
+ if(!status){status=rows.some(c=>!c.ok)?'failed':phase==='ready'?'passed':phase==='cancelled'?'blocked':phase==='failed'?(index===0&&failures[0]?.stage==='setup'?'passed':'blocked'):phase===id?'running':index===0&&phase!=='credentials'?'passed':'pending';}
+ return {id,label:index===0?'Credentials':'Connector setup',status,completed:saved?.completed??rows.length,total:saved?.total??null};
+ });
+ stages.push({id:'ready',label:'Ready',status:phase==='ready'?'passed':phase==='saving'?'running':['failed','cancelled'].includes(phase)?'blocked':'pending',completed:0,total:null});
+ const first=failures[0],title=phase==='ready'?'Verified':phase==='cancelled'?'Verification cancelled':phase==='failed'?(first?.stage==='setup'?'Setup verification failed':first?'Credential verification failed':'Verification failed'):job.status==='cancelling'?'Cancelling…':phase==='setup'?'Verifying connectors…':phase==='saving'?'Preparing fixture…':phase==='failed'?'Finishing verification…':'Verifying credentials…';
+ const detail=phase==='failed'?(first?`${first.merchant} · ${first.label} — ${first.message}`:job.error||'Verification could not complete'):phase==='cancelled'?'Edit the inputs and try again.':'';
+ return {phase,busy,title,detail,checks,failures,stages,fixtureSetId:verification.fixtureSetId||job.fixtureSetId,profileId:verification.profileId};
+}
diff --git a/loadtest/console/src/job-stream.mjs b/loadtest/console/src/job-stream.mjs
new file mode 100644
index 0000000000..33eaf5ba29
--- /dev/null
+++ b/loadtest/console/src/job-stream.mjs
@@ -0,0 +1,12 @@
+// The server owns jobs. Reconnecting only restores observation; it never stops work.
+export function watchJobStream(id,onProgress,onConnection=(_state,_last)=>{}){
+ let closed=false,busy=false,last=0;
+ const connection=state=>onConnection(state,last);
+ const receive=value=>{if(closed)return;last=Date.now();connection('connected');Promise.resolve(onProgress(value)).catch(()=>connection('reconnecting'));};
+ const stream=new EventSource(`/api/jobs/${encodeURIComponent(id)}/events`);
+ connection('connecting');stream.onopen=()=>connection('connected');
+ stream.addEventListener('progress',event=>{try{receive(JSON.parse(event.data));}catch{connection('reconnecting');}});
+ stream.onerror=()=>connection('reconnecting');
+ const poll=setInterval(async()=>{if(closed||busy||Date.now()-last<10000)return;busy=true;try{const response=await fetch(`/api/jobs/${encodeURIComponent(id)}`);if(!response.ok)throw Error();receive(await response.json());}catch{connection('reconnecting');}finally{busy=false;}},5000);
+ return {close(){closed=true;clearInterval(poll);stream.close();}};
+}
diff --git a/loadtest/console/src/k6-output.mjs b/loadtest/console/src/k6-output.mjs
new file mode 100644
index 0000000000..af9adb3837
--- /dev/null
+++ b/loadtest/console/src/k6-output.mjs
@@ -0,0 +1,32 @@
+export function k6Output(output = '') {
+ const lines = output.replace(/\x1b\[[0-9;?]*[A-Za-z]/g, '').replace(/\r\n/g, '\n').replace(/\r/g, '\n').split('\n');
+ const history = [], fixtureRows = new Map();
+ let frame = [], inFrame = false, framePosition = 0;
+ for (const line of lines) {
+ const fixture=line.match(/^\s*(.+?)\s+\[[=\- ]+\]\s+\d+%\s+\d+(?:\.\d+)?\/\d+(?:\.\d+)?(?:\s|$)/);
+ if(fixture){
+ const label=fixture[1].trim();
+ if(fixtureRows.has(label))history[fixtureRows.get(label)]=line.trimEnd();
+ else{fixtureRows.set(label,history.length);history.push(line.trimEnd());}
+ inFrame=false;
+ } else if (/^\s*running \(/.test(line)) {
+ frame = [line.trimEnd()];
+ framePosition = history.length;
+ inFrame = true;
+ } else if (/^\s*\S+\s+\[\s*\d+%\s*\].*(?:VUs|iters\/s)/.test(line)) {
+ // A progress row may survive truncation of the stored output buffer.
+ const name = line.trim().split(/\s/)[0];
+ const index = frame.findIndex(row => row.trim().startsWith(name + ' '));
+ if (index < 0) frame.push(line.trimEnd()); else frame[index] = line.trimEnd();
+ inFrame = true;
+ } else if (line.trim()) {
+ history.push(line);
+ inFrame = false;
+ } else if (!inFrame && history.length && history.at(-1) !== '') {
+ history.push('');
+ }
+ }
+ return {progress: frame.join('\n'), history: history.join('\n').trim(),
+ before: history.slice(0,framePosition).join('\n').trimEnd(),
+ after: history.slice(framePosition).join('\n').trim()};
+}
diff --git a/loadtest/console/src/load-shape.mjs b/loadtest/console/src/load-shape.mjs
new file mode 100644
index 0000000000..4322d151ee
--- /dev/null
+++ b/loadtest/console/src/load-shape.mjs
@@ -0,0 +1,20 @@
+// Shared, credential-free summary for saved load plans and the editor.
+export function loadShape(load={}){
+ if(Array.isArray(load.stages)&&load.stages.length){
+ let duration=0,area=0,start=load.start_rps ?? load.stages[0].target_rps,peak=start;
+ for(const stage of load.stages){duration+=stage.duration_seconds;area+=(start+stage.target_rps)/2*stage.duration_seconds;peak=Math.max(peak,stage.target_rps);start=stage.target_rps;}
+ return {duration,peak,average:duration?area/duration:0};
+ }
+ return {duration:load.duration_seconds || 0,peak:load.total_rps || 0,average:load.total_rps || 0};
+}
+
+// Only display fields leave the server; connector/controller credentials stay private.
+export function loadTimeline(load={},faultPlan=[]){
+ let at=0,from=load.start_rps ?? load.stages?.[0]?.target_rps ?? load.total_rps ?? 0;
+ const stages=load.stages?.length?load.stages:[{target_rps:load.total_rps||0,duration_seconds:load.duration_seconds||0}];
+ return stages.map((stage,index)=>{
+ const end=at+stage.duration_seconds,target=stage.target_rps;
+ const fault=stage.fault?{action:stage.fault.action,target:faultPlan.find(p=>p.index===index)?.target?.label||stage.fault.targetId}:null;
+ const row={index,start:at,end,from,target,kind:fault?'fault':from===target?'hold':'ramp',fault};at=end;from=target;return row;
+ });
+}
diff --git a/loadtest/console/src/navigation.mjs b/loadtest/console/src/navigation.mjs
new file mode 100644
index 0000000000..6544b25eb5
--- /dev/null
+++ b/loadtest/console/src/navigation.mjs
@@ -0,0 +1,26 @@
+import {writable} from 'svelte/store';
+import {replaceState} from '$app/navigation';
+export const navigationContext=writable({});
+/** @type {Record<string,string>} */
+let memory={};
+export function rememberPage(url){
+ if(typeof window==='undefined')return;
+ const next={...memory};
+ for(const key of ['profile','fixtures','run','metrics'])if(url.searchParams.has(key))next[key]=url.searchParams.get(key);
+ if(['/performance','/results'].includes(url.pathname)&&!url.searchParams.has('run'))delete next.run;
+ next[url.pathname]=url.pathname+url.search;memory=next;navigationContext.set(next);
+}
+export function sectionHref(section,url,context={}){
+ const path=`/${section}`,next=new URL(context[path]||path,url.origin);
+ for(const key of ['profile','fixtures','run','metrics']){
+ const value=url.searchParams.get(key)||context[key];
+ if(value&&(['profile','fixtures'].includes(key)||['performance','results'].includes(section)))next.searchParams.set(key,value);
+ }
+ if(!['performance','results'].includes(section)||!context.run&&!url.searchParams.has('run'))next.searchParams.delete('run');
+ return next.pathname+next.search;
+}
+export function setQuery(values){
+ const url=new URL(window.location.href);
+ for(const [key,value] of Object.entries(values))if(value===null||value===undefined||value==='')url.searchParams.delete(key);else url.searchParams.set(key,String(value));
+ replaceState(url,{});rememberPage(url);
+}
diff --git a/loadtest/console/src/payment-flows.mjs b/loadtest/console/src/payment-flows.mjs
new file mode 100644
index 0000000000..9297b172a0
--- /dev/null
+++ b/loadtest/console/src/payment-flows.mjs
@@ -0,0 +1,11 @@
+export const unavailableFlows=new Set(['cit_metadata_changed','mit','saved_card_checkout']);
+export function normalizePaymentFlows(flows=[]){
+ const used=new Set();return flows.map(flow=>{
+ let name=flow.name?.replace(/^(?:nomod|mod)_/,'')||flow.scenario,base=name,index=2;
+ while(used.has(name))name=`${base}_${index++}`;used.add(name);
+ return {...flow,name,merchant_path:'modular'};
+ });
+}
+export function assertSupportedPaymentFlows(flows){
+ for(const flow of flows)if(Number(flow.weight)>0&&unavailableFlows.has(flow.scenario))throw new Error(`${flow.scenario.replaceAll('_',' ')} is not yet supported by the payment-method service; remove it from the traffic mix`);
+}
diff --git a/loadtest/console/src/ramp-editor.mjs b/loadtest/console/src/ramp-editor.mjs
new file mode 100644
index 0000000000..a453854464
--- /dev/null
+++ b/loadtest/console/src/ramp-editor.mjs
@@ -0,0 +1,6 @@
+export function stageRates(rows,start=0){let previous=Number(start);return rows.map(row=>{if(row.kind==='ramp')previous=Number(row.target);return previous;});}
+export function decodeStages(json,start=0){let previous=Number(start);const stages=JSON.parse(json);if(!Array.isArray(stages))throw Error('Stages must be an array');return stages.map(s=>{const row={kind:s.fault?'fault':s.target_rps===previous?'hold':'ramp',target:Number(s.target_rps),duration:Number(s.duration_seconds),...(s.fault?{fault:{...s.fault}}:{})};previous=row.target;return row;});}
+export function encodeStages(rows,start=0){let previous=Number(start);if(!rows.length||rows.length>50)throw Error('Choose 1–50 stages');return rows.map(row=>{if(!['hold','ramp','fault'].includes(row.kind))throw Error('Choose Ramp, Hold or Fault');const target=row.kind==='ramp'?Number(row.target):previous,duration=Number(row.duration);if(!Number.isFinite(target)||target<=0||!Number.isInteger(duration)||duration<1)throw Error('Stages need positive TPS and whole-second durations');previous=target;
+let fault;if(row.kind==='fault'){const f=row.fault;if(!f?.targetId||!['outage','restart','failover'].includes(f.action)||duration>300)throw Error('Choose a fault target, action and duration of 1–300 seconds');fault={targetId:f.targetId,action:f.action};}
+return {target_rps:target,duration_seconds:duration,...(fault?{fault}:{})};});}
+export function rampPoints(start,stages){let time=0;const points=[{t:0,value:Number(start)}];for(const s of stages){time+=s.duration_seconds;points.push({t:time,value:s.target_rps});}return points;}
diff --git a/loadtest/console/src/result-test-cases.mjs b/loadtest/console/src/result-test-cases.mjs
new file mode 100644
index 0000000000..8f22ec7213
--- /dev/null
+++ b/loadtest/console/src/result-test-cases.mjs
@@ -0,0 +1,112 @@
+// Test-case presentation only. Recorded measurements and acceptance calculations
+// remain in scenario-checks; repeated executions retain all of their evidence.
+export const testCaseCatalog=[
+ {id:'TC-01',title:'Calibration',section:'load'},
+ {id:'TC-02',title:'Steady-load performance',section:'load'},
+ {id:'TC-03',title:'Burst-load performance',section:'load'},
+ {id:'TC-04',title:'Database failover',section:'faults'},
+ {id:'TC-05',title:'Application reconnection',section:'faults'},
+ {id:'TC-06',title:'Cache failover',section:'faults'},
+ {id:'TC-07',title:'Cluster zone loss',section:'faults'},
+ {id:'TC-08',title:'Cluster + database zone loss',section:'faults'},
+ {id:'TC-09',title:'Multi-merchant load',section:'load'},
+ {id:'TC-10',title:'Card vault restart',section:'faults'}
+];
+const byId=new Map(testCaseCatalog.map(tc=>[tc.id,tc]));
+const intents={calibration:'TC-01',steady:'TC-02',burst:'TC-03'};
+export function testCasePlan(config,groups){
+ const plan=new Map();
+ const add=(id,groupIds=[])=>{if(!byId.has(id))return;if(!plan.has(id))plan.set(id,{id,groupIds:[]});const entry=plan.get(id);entry.groupIds=[...new Set([...entry.groupIds,...groupIds])];};
+ for(const group of groups){
+ const stage=config.load?.stages?.[group.stageIndex]||{};
+ if(['hold','ramp'].includes(group.kind)){
+ const explicit=stage.testCase||intents[stage.intent];
+ if(['TC-01','TC-02','TC-03'].includes(explicit)&&(explicit!=='TC-03'||group.kind==='hold'))add(explicit,[group.id]);
+ else if(group.kind==='hold')add('TC-02',[group.id]);
+ }
+ if(group.kind==='fault'){
+ const target=config.faultPlan?.find(f=>f.index===group.stageIndex)?.target||{};
+ const action=config.faultPlan?.find(f=>f.index===group.stageIndex)?.action||stage.fault?.action;
+ const type=target.serviceType||target.id||stage.fault?.targetId;
+ const ids=(type==='postgres'&&action==='failover')||target.adapter==='gcp-alloydb'?['TC-04','TC-05']:(type==='redis'&&action==='failover')||target.adapter==='gcp-redis'?['TC-06']:type==='card-vault'?['TC-10']:type==='zone'?['TC-07']:type==='zone-and-database'?['TC-08']:[];
+ for(const id of ids)add(id,[group.id,`recovery-${group.stageIndex}`,'integrity'].filter(key=>groups.some(g=>g.id===key)));
+ }
+ }
+ const merchants=Number(config.fixtureSet?.merchantCount||0);
+ if(config.mode==='tenancy'||merchants>1)add('TC-09',groups.filter(g=>['hold','ramp'].includes(g.kind)).map(g=>g.id));
+ // Explicit selections without execution evidence remain Not run. In
+ // particular, a ramp is never inferred to be a sustained burst or a zone loss.
+ for(const id of config.load?.testCases||[])add(id);
+ return [...plan.values()].map(entry=>({...entry,...(entry.id==='TC-09'?{merchantCount:merchants||null}:{})}));
+}
+const number=value=>Number(value).toLocaleString(undefined,{maximumFractionDigits:2});
+const value=check=>check?.actual==null?'—':`${check.lowerBound?'≥ ':''}${number(check.actual)}${check.unit==='%'?'%':` ${check.unit||''}`}`;
+const threshold=check=>check?.limit==null?'—':`${check.comparison} ${number(check.limit)}${check.unit==='%'?'%':` ${check.unit||''}`}`;
+const missing=(id,label,limit=null,unit='')=>({id,label,actual:null,limit,unit,comparison:'≤',outcome:'not_measured'});
+const status=checks=>checks.some(c=>c.outcome==='fail')?'fail':checks.some(c=>c.outcome==='in_progress')?'in_progress':checks.every(c=>c.outcome==='not_run')?'not_run':checks.some(c=>['not_measured','not_run'].includes(c.outcome))?'not_measured':checks.some(c=>c.outcome==='pass')?'pass':'recorded';
+function extreme(checks,id,minimum=false){return checks.filter(c=>c.id===id&&c.actual!=null).reduce((a,b)=>!a||(minimum?b.actual<a.actual:b.actual>a.actual)?b:a,null);}
+export function resultTestCases(summary){
+ const groups=summary.groups||[];
+ // Older cached payloads can still render without changing any measurements.
+ const plan=summary.testCasePlan||testCasePlan({load:{},faultPlan:groups.filter(g=>g.kind==='fault').map(g=>({index:g.stageIndex,target:{id:/vault/i.test(g.target||g.title)?'card-vault':/postgres|database|\bdb\b/i.test(g.target||g.title)?'postgres':'unknown'}}))},groups);
+ const rows=plan.map(entry=>{
+ const catalog=byId.get(entry.id);if(!catalog)return null;
+ const parts=entry.groupIds.flatMap(id=>groups.find(g=>g.id===id)||[]);
+ const checks=entry.id==='TC-02'&&summary.steady?summary.steady.checks.map(c=>({...c,source:'steady',sourceLabel:'Steady load'})):parts.flatMap(g=>g.checks.map(c=>({...c,source:g.id,sourceLabel:g.title})));
+ let expected='Saved limits',observed='Pending verification';
+ const loadChecks=entry.id==='TC-02'&&summary.steady?checks:parts.filter(g=>['hold','ramp'].includes(g.kind)).flatMap(g=>g.checks);
+ const faultChecks=parts.filter(g=>g.kind==='fault').flatMap(g=>g.checks);
+ if(['TC-02','TC-03'].includes(entry.id)){
+ const throughput=extreme(loadChecks,'throughput',true),errors=extreme(loadChecks,'errors');
+ expected=throughput?.limit!=null?`Throughput ${threshold(throughput)}`:'Record throughput';
+ observed=[throughput?`${value(throughput)} window throughput`:null,errors?`${value(errors)} HTTP errors`:null].filter(Boolean).join(' · ')||'Pending verification';
+ }else if(entry.id==='TC-01'){
+ checks.push(missing('calls-per-payment','API calls per payment'));
+ expected='Record API calls per payment';observed='Call-counting evidence not available';
+ }else if(entry.id==='TC-09'){
+ checks.push(missing('merchant-coverage','Verified merchant traffic coverage'));
+ expected='Traffic across all configured merchants';observed=entry.merchantCount?`${number(entry.merchantCount)} merchants configured`:'Merchant coverage pending verification';
+ }else{
+ const recovery=extreme(faultChecks,'recovery'),failureCounts=faultChecks.filter(c=>c.id==='failed');
+ expected=recovery?.limit!=null?`Recovery ${threshold(recovery)}`:'Record recovery time';
+ observed=recovery?`${value(recovery)} recovery`:'Pending verification';
+ if(failureCounts.length){
+ for(let i=checks.length-1;i>=0;i--)if(checks[i].id==='failed')checks.splice(i,1);
+ checks.push({id:'total-failed',label:'Total failed requests',actual:failureCounts.every(c=>c.actual!=null)?failureCounts.reduce((sum,c)=>sum+c.actual,0):null,limit:null,unit:'requests',comparison:'≤',outcome:'recorded'});
+ }
+ if(entry.id==='TC-05'){
+ // A successful payment confirmation after DB recovery proves that
+ // application payment traffic resumed; it makes no claim about pods.
+ const recoveries=parts.filter(g=>g.kind==='recovery');
+ const reconnect=recoveries.map(g=>{
+ const actual=g.checks.find(c=>c.id==='completed')?.actual??null;
+ return {id:'application-reconnection',label:'Successful payment confirmations after recovery',actual,limit:1,unit:'confirmations',comparison:'≥',source:g.id,sourceLabel:g.title,
+ outcome:g.state==='not_run'?'not_run':actual==null?'not_measured':actual>0?'pass':g.state==='complete'?'fail':'in_progress'};
+ });
+ checks.splice(0,checks.length,...(reconnect.length?reconnect:[missing('application-reconnection','Successful payment confirmations after recovery',1,'confirmations')]));
+ expected='Payment confirmations resume after failover';
+ observed=reconnect.length&&reconnect.every(c=>c.actual!=null)?`${number(reconnect.reduce((sum,c)=>sum+c.actual,0))} successful confirmations after recovery`:'Pending verification';
+ }
+ }
+ const failedLatency=checks.find(c=>/^p(50|95|99)$/.test(c.id)&&c.outcome==='fail');
+ const failureReason=failedLatency?`${failedLatency.source?.startsWith('recovery-')?'Recovery':entry.id==='TC-02'?'Steady':''} ${failedLatency.id} exceeds ${number(failedLatency.limit)} ms`.trim():null;
+ const executed=parts.some(g=>['hold','ramp','fault'].includes(g.kind)&&g.state!=='not_run');
+ return {...catalog,expected,failureReason,observed:executed?observed:'Not run',checks,outcome:executed?status(checks):'not_run',occurrences:parts.filter(g=>g.kind==='fault'||['hold','ramp'].includes(g.kind)).length};
+ }).filter(Boolean);
+ // Preserve ramp/unknown-adapter measurements without incorrectly assigning
+ // them an original TC whose prerequisite is absent.
+ const assigned=new Set(plan.flatMap(p=>p.groupIds));
+ for(const [kind,title,section] of [['ramp','Ramp observations','load'],['fault','Fault observations','faults']]){
+ const parts=groups.filter(g=>g.kind===kind&&!assigned.has(g.id));
+ if(parts.length){const checks=parts.flatMap(g=>g.checks.map(c=>({...c,source:g.id,sourceLabel:g.title})));rows.push({id:`observations-${kind}`,title,section,expected:'Saved limits',observed:`${parts.length} ${kind==='ramp'?'ramp':'fault'} period${parts.length===1?'':'s'}`,checks,outcome:status(checks)});}
+ }
+ rows.sort((a,b)=>(testCaseCatalog.findIndex(tc=>tc.id===a.id)+1||100)-(testCaseCatalog.findIndex(tc=>tc.id===b.id)+1||100));
+ if(summary.completion){
+ const {expected,successful,check}=summary.completion;
+ rows.unshift({id:'completion',title:summary.completion.scope?'Payment confirmations':'Flow completion',section:'load',expected:check.limit==null?'Recorded target':`${number(check.limit)}% ${summary.completion.scope?'outside outage':'of target flows'}`,
+ observed:check.actual==null?'—':`${number(successful)} / ${number(expected)} ${summary.completion.scope?'confirmations':'flows'} · ${value(check)}${summary.completion.outageFailures?` · ${number(summary.completion.outageFailures)} failed during outage`:''}`,
+ checks:[check],outcome:check.outcome});
+ }
+ return [{id:'load',title:'Load & performance'},{id:'faults',title:'Faults & recovery'}].map(section=>({...section,cases:rows.filter(row=>row.section===section.id)})).filter(section=>section.cases.length);
+}
+export {value as formatTestCaseValue,threshold as formatTestCaseLimit};
diff --git a/loadtest/console/src/results-limits.mjs b/loadtest/console/src/results-limits.mjs
new file mode 100644
index 0000000000..dfdeaeb887
--- /dev/null
+++ b/loadtest/console/src/results-limits.mjs
@@ -0,0 +1,26 @@
+// Shared by Settings and the run evaluator; values are copied into each new run.
+export const defaultResultsLimits={
+ minimumThroughputPercent:97,maximumHttpErrorPercent:.1,
+ maximumHoldP99Ms:160,maximumRampP99Ms:500,maximumRecoveryP99Ms:300,maximumLatencyDriftPercent:10,
+ maximumRecoverySeconds:60,recoveryWindowSeconds:10,maximumLostPayments:0
+};
+export const resultsLimitFields=[
+ ['minimumThroughputPercent','Achieved throughput','% of offered',100],
+ ['maximumHttpErrorPercent','Normal-stage HTTP errors','%',100],
+ ['maximumHoldP99Ms','Hold server-side p99','ms'],
+ ['maximumRampP99Ms','Ramp server-side p99','ms'],
+ ['maximumRecoveryP99Ms','After recovery payment-confirm p99','ms'],
+ ['maximumLatencyDriftPercent','Hold latency drift','%'],
+ ['maximumRecoverySeconds','Recovery after restoration starts','s'],
+ ['recoveryWindowSeconds','Transition settling time','s'],
+ ['maximumLostPayments','Acknowledged payments lost','payments']
+];
+export function validateResultsLimits(input={}){
+ if(!input||typeof input!=='object'||Array.isArray(input))throw new Error('Invalid Results limits');
+ return Object.fromEntries(resultsLimitFields.map(([key,label,,max])=>{
+ const raw=input[key]??defaultResultsLimits[key],value=Number(raw);
+ if(raw===''||!['number','string'].includes(typeof raw)||!Number.isFinite(value)||value<0||(max!==undefined&&value>Number(max))||
+ (key==='recoveryWindowSeconds'&&(value<=0||value>3600))||(key==='maximumLostPayments'&&!Number.isSafeInteger(value)))throw new Error(`Invalid Results limit: ${label}`);
+ return [key,value];
+ }));
+}
diff --git a/loadtest/console/src/routes/(console)/+layout.server.js b/loadtest/console/src/routes/(console)/+layout.server.js
new file mode 100644
index 0000000000..b6ca6a35a0
--- /dev/null
+++ b/loadtest/console/src/routes/(console)/+layout.server.js
@@ -0,0 +1,2 @@
+import {publicSettings} from '../../../server/state.mjs';
+export function load(){return {settings:publicSettings()};}
diff --git a/loadtest/console/src/routes/(console)/+layout.svelte b/loadtest/console/src/routes/(console)/+layout.svelte
new file mode 100644
index 0000000000..be029b7371
--- /dev/null
+++ b/loadtest/console/src/routes/(console)/+layout.svelte
@@ -0,0 +1,2 @@
+<script>import Shell from '../../Shell.svelte'; let {data,children}=$props();</script>
+<Shell {data}>{@render children()}</Shell>
diff --git a/loadtest/console/src/routes/(console)/fixtures/+page.server.js b/loadtest/console/src/routes/(console)/fixtures/+page.server.js
new file mode 100644
index 0000000000..e181e91248
--- /dev/null
+++ b/loadtest/console/src/routes/(console)/fixtures/+page.server.js
@@ -0,0 +1,2 @@
+import {screenData} from '../../../../server/screens.mjs';
+export function load({url}){return screenData(url,'fixtures');}
diff --git a/loadtest/console/src/routes/(console)/fixtures/+page.svelte b/loadtest/console/src/routes/(console)/fixtures/+page.svelte
new file mode 100644
index 0000000000..9fa55e4403
--- /dev/null
+++ b/loadtest/console/src/routes/(console)/fixtures/+page.svelte
@@ -0,0 +1,2 @@
+<script>import FixtureScreen from '../../../FixtureScreen.svelte';let {data}=$props();</script>
+<FixtureScreen {data}/>
diff --git a/loadtest/console/src/routes/(console)/performance/+page.server.js b/loadtest/console/src/routes/(console)/performance/+page.server.js
new file mode 100644
index 0000000000..9ffc754fab
--- /dev/null
+++ b/loadtest/console/src/routes/(console)/performance/+page.server.js
@@ -0,0 +1,2 @@
+import {screenData} from '../../../../server/screens.mjs';
+export function load({url}){return screenData(url,'performance');}
diff --git a/loadtest/console/src/routes/(console)/performance/+page.svelte b/loadtest/console/src/routes/(console)/performance/+page.svelte
new file mode 100644
index 0000000000..cf262d3d1c
--- /dev/null
+++ b/loadtest/console/src/routes/(console)/performance/+page.svelte
@@ -0,0 +1,2 @@
+<script>import RunScreen from '../../../RunScreen.svelte'; let {data}=$props();</script>
+{#key data.run?.id || data.profileId}<RunScreen {data} tab="performance"/>{/key}
diff --git a/loadtest/console/src/routes/(console)/results/+page.server.js b/loadtest/console/src/routes/(console)/results/+page.server.js
new file mode 100644
index 0000000000..b0d3da392c
--- /dev/null
+++ b/loadtest/console/src/routes/(console)/results/+page.server.js
@@ -0,0 +1,2 @@
+import {screenData} from '../../../../server/screens.mjs';
+export function load({url}){return screenData(url,'results');}
diff --git a/loadtest/console/src/routes/(console)/results/+page.svelte b/loadtest/console/src/routes/(console)/results/+page.svelte
new file mode 100644
index 0000000000..a0e4067d25
--- /dev/null
+++ b/loadtest/console/src/routes/(console)/results/+page.svelte
@@ -0,0 +1,2 @@
+<script>import RunScreen from '../../../RunScreen.svelte'; let {data}=$props();</script>
+<RunScreen {data} tab="results"/>
diff --git a/loadtest/console/src/routes/(console)/scenarios/+page.server.js b/loadtest/console/src/routes/(console)/scenarios/+page.server.js
new file mode 100644
index 0000000000..069dd1216e
--- /dev/null
+++ b/loadtest/console/src/routes/(console)/scenarios/+page.server.js
@@ -0,0 +1,2 @@
+import {screenData} from '../../../../server/screens.mjs';
+export function load({url}){return screenData(url,'scenarios');}
diff --git a/loadtest/console/src/routes/(console)/scenarios/+page.svelte b/loadtest/console/src/routes/(console)/scenarios/+page.svelte
new file mode 100644
index 0000000000..95eb4e6e1a
--- /dev/null
+++ b/loadtest/console/src/routes/(console)/scenarios/+page.svelte
@@ -0,0 +1,2 @@
+<script>import ScenarioScreen from '../../../ScenarioScreen.svelte';let {data}=$props();</script>
+<ScenarioScreen {data}/>
diff --git a/loadtest/console/src/routes/+layout.svelte b/loadtest/console/src/routes/+layout.svelte
new file mode 100644
index 0000000000..65f3a7f606
--- /dev/null
+++ b/loadtest/console/src/routes/+layout.svelte
@@ -0,0 +1,2 @@
+<script>import '../styles.css'; let { children } = $props();</script>
+{@render children()}
diff --git a/loadtest/console/src/routes/+page.server.js b/loadtest/console/src/routes/+page.server.js
new file mode 100644
index 0000000000..c29caaa7e4
--- /dev/null
+++ b/loadtest/console/src/routes/+page.server.js
@@ -0,0 +1,2 @@
+import {redirect} from '@sveltejs/kit';
+export function load(){redirect(303,'/scenarios');}
diff --git a/loadtest/console/src/routes/+page.svelte b/loadtest/console/src/routes/+page.svelte
new file mode 100644
index 0000000000..88da6c5a5f
--- /dev/null
+++ b/loadtest/console/src/routes/+page.svelte
@@ -0,0 +1,2 @@
+<script>import Console from '../App.svelte'; let { data } = $props();</script>
+<Console {data}/>
diff --git a/loadtest/console/src/routes/api/[...path]/+server.js b/loadtest/console/src/routes/api/[...path]/+server.js
new file mode 100644
index 0000000000..177abb4f0b
--- /dev/null
+++ b/loadtest/console/src/routes/api/[...path]/+server.js
@@ -0,0 +1,137 @@
+import {requireSupportedEnvironment} from '../../../environments.mjs';
+import {csvStream} from '../../../../server/csv-stream.mjs';
+import { json } from '@sveltejs/kit';
+import { publicSettings,saveSettings,saveConnections,localSettings,localPath,atomicJson,panelPath,redact,runDirectory,dataRoot,superpositionConnection,activeEnvironment,environmentDatabase } from '../../../../server/state.mjs';
+import { queryWorker } from '../../../../server/workers.mjs';
+import {workerCommand,jobEvents} from '../../../../server/supervisor.mjs';
+import {listProfiles,getProfile,saveProfile,listFixtureSets,deleteFixtureSet,archiveProfile,deleteProfile} from '../../../../server/profiles.mjs';
+import {testServiceEndpoint,testSuperpositionEndpoint} from '../../../../server/service-checks.mjs';
+import {listCertificates,importCertificate,removeCertificate} from '../../../../server/certificates.mjs';
+import {listWorkers,enrollWorker,heartbeatWorker,pendingWorkerCommands,acknowledgeWorkerCommand,removeWorker} from '../../../../server/worker-registry.mjs';
+import {readWorkerBundle,storeWorkerArtifact} from '../../../../server/worker-artifacts.mjs';
+import {databaseTestConnection} from '../../../../server/connection-secrets.mjs';
+import {boundedRequest} from '../../../../server/request-body.mjs';
+import {createGrafanaEmbed} from '../../../../server/grafana-embed.mjs';
+import {sessionCookie} from '../../../../server/auth.mjs';
+
+async function dispatch(event) {
+ const method=event.request.method,segments=(event.params.path || '').split('/');
+ const input=async()=>{
+ const text=await (await boundedRequest(event.request)).text();return text?JSON.parse(text):{};
+ };
+ try {
+ if(segments.join('/')==='grafana/embed'&&method==='GET')return json(createGrafanaEmbed(event.cookies.get(sessionCookie),event.url.searchParams.get('panel')));
+ if(segments[0]==='worker'&&segments[1]==='v1'){
+ const bearer=(event.request.headers.get('authorization')||'').replace(/^Bearer\s+/i,'');
+ if(segments[2]==='enroll'&&segments.length===3&&method==='POST')return json(enrollWorker(await input(),bearer),{status:201});
+ const id=segments[3];
+ if(segments[2]==='workers'&&segments[4]==='heartbeat'&&segments.length===5&&method==='POST')return json(heartbeatWorker(id,bearer,await input()));
+ if(segments[2]==='workers'&&segments[4]==='commands'&&segments.length===5&&method==='GET')return json(pendingWorkerCommands(id,bearer,Number(event.url.searchParams.get('after')||0)));
+ if(segments[2]==='workers'&&segments[4]==='commands'&&segments[6]==='ack'&&segments.length===7&&method==='POST')return json(acknowledgeWorkerCommand(id,bearer,segments[5],await input()));
+ if(segments[2]==='workers'&&segments[4]==='bundles'&&segments.length===6&&method==='GET'){
+ const {authenticateWorker}=await import('../../../../server/worker-registry.mjs');authenticateWorker(id,bearer);const bundle=await readWorkerBundle(segments[5],id);return new Response(bundle.body,{headers:{'content-type':'application/json','x-content-sha256':bundle.sha256}});
+ }
+ if(segments[2]==='workers'&&segments[4]==='runs'&&segments[6]==='artifacts'&&segments.length===8&&method==='PUT'){
+ const {authenticateWorker}=await import('../../../../server/worker-registry.mjs');authenticateWorker(id,bearer);if(!event.request.body)throw new Error('Artifact body is required');
+ return json(await storeWorkerArtifact({workerId:id,runId:segments[5],name:segments[7],body:event.request.body,contentLength:Number(event.request.headers.get('content-length')||0)}),{status:201});
+ }
+ throw new Error('Unknown worker protocol operation');
+ }
+ if(segments.join('/')==='workers/plan'&&method==='GET'){const {planWorkerShards}=await import('../../../../server/distributed.mjs');const {loadShape}=await import('../../../load-shape.mjs');const profile=getProfile(event.url.searchParams.get('profile')),settings=publicSettings(),peak=loadShape(profile.load).peak;return json(planWorkerShards(peak,Math.ceil(peak*settings.maxVusMultiplier),listWorkers().filter(w=>w.id!=='local')));}
+ if(segments[0]==='workers'&&segments.length===1&&method==='GET')return json(listWorkers());
+ if(segments[0]==='workers'&&segments.length===2&&method==='DELETE')return json(removeWorker(segments[1]));
+ if(segments.join('/')==='settings/certificates') {
+ if(method==='GET')return json(listCertificates(dataRoot));
+ if(method==='POST'){
+ const length=Number(event.request.headers.get('content-length')||0);if(length>1100000)throw new Error('Certificate upload exceeds 1 MiB');
+ const form=await event.request.formData(),file=form.get('certificate');
+ if(!file||typeof file.arrayBuffer!=='function'||file.size>1024*1024)throw new Error('Choose a certificate up to 1 MiB');
+ const entry=await importCertificate(dataRoot,{name:form.get('name')||file.name,pem:Buffer.from(await file.arrayBuffer()).toString('utf8')});
+ return json(entry,{status:201});
+ }
+ }
+ if(segments[0]==='settings'&&segments[1]==='certificates'&&segments.length===3&&method==='DELETE'){
+ const settings=localSettings();if(settings.database.caCertificateId===segments[2]||Object.values(settings.environmentProfiles||{}).some(profile=>profile.database?.caCertificateId===segments[2]))throw new Error('Remove this certificate from the database settings before deleting it');
+ await removeCertificate(dataRoot,segments[2]);return json({deleted:true});
+ }
+ if(segments[0]==='settings' && segments.length===1) {
+ if(method==='GET')return json(publicSettings(event.url.searchParams.get('environment')));
+ if(method==='PUT')return json(await saveConnections(await input()));
+ }
+ if(segments[0]==='profiles') {
+ if(segments.length===1&&method==='GET')return json(listProfiles({includeArchived:event.url.searchParams.get('archived')==='true'}));
+ if(segments.length===3&&segments[2]==='archive'&&method==='PUT')return json(archiveProfile(segments[1],(await input()).archived===true));
+ if(segments.length===1&&method==='POST')return json(saveProfile(await input()),{status:201});
+ if(segments.length===2&&method==='GET')return json(getProfile(segments[1]));
+ if(segments.length===2&&method==='PUT')return json(saveProfile(await input(),segments[1]));
+ if(segments.length===2&&method==='DELETE')return json(deleteProfile(segments[1]));
+ }
+ if(segments.join('/')==='scenarios/save'&&method==='POST')return json(await workerCommand('save-scenario',await input()));
+ if(segments.join('/')==='settings/database/test'&&method==='POST') {
+ const draft=await input();requireSupportedEnvironment(draft.environment||activeEnvironment());const saved=environmentDatabase(draft.environment);
+ const database=databaseTestConnection(saved,draft);
+ return json(await queryWorker('database-test',{database}));
+ }
+ if(segments.join('/')==='settings/services/test'&&method==='POST') {
+ const body=await input();requireSupportedEnvironment(body.environment||activeEnvironment());
+ return json(body.kind==='superposition'
+ ? await testSuperpositionEndpoint(superpositionConnection(body.superposition,body.environment))
+ : await testServiceEndpoint(body.kind,body.endpoint));
+ }
+ if(segments.join('/')==='fixtures/import'&&method==='POST')return json(await workerCommand('import-fixtures',await input()),{status:202});
+ if(segments[0]==='fixtures'&&segments.length===1&&method==='GET')return json(listFixtureSets());
+ if(segments[0]==='fixtures'&&segments.length===2&&method==='DELETE')return json(deleteFixtureSet(segments[1]));
+ if(segments[0]==='fixtures' && segments.length===1 && method==='POST')return json(await workerCommand('start',{...await input(),kind:'fixtures'}),{status:202});
+ if(segments[0]==='smoke' && segments.length===1 && method==='POST')return json(await workerCommand('start',{...await input(),kind:'smoke'}),{status:202});
+ if(segments[0]==='faults') {
+ if(segments[1]==='targets'&&segments.length===2&&method==='GET')return json(await workerCommand('fault-targets'));
+ if(segments[1]==='targets'&&segments.length===2&&method==='PUT')return json(await workerCommand('save-fault-targets',{targets:await input()}));
+ if(segments[1]==='test'&&segments.length===2&&method==='POST')return json(await workerCommand('test-fault',await input()),{status:202});
+ if(segments[1]==='check'&&segments.length===2&&method==='POST')return json(await workerCommand('check-fault-target',await input()));
+ if(segments.length===1&&method==='GET')return json(await workerCommand('faults'));
+ if(segments[1]==='restore'&&segments.length===2&&method==='POST')return json(await workerCommand('restore'));
+ if(segments.length===1&&method==='POST'){const body=await input();return json(await workerCommand('fault',body),{status:202});}
+ }
+ if(segments[0]==='jobs') {
+ if(segments.length===1 && method==='GET')return json(await workerCommand('active'));
+ if(segments.length===2 && method==='GET')return json(await workerCommand('job',{id:segments[1]}));
+ if(segments[2]==='events' && segments.length===3 && method==='GET')return jobEvents(segments[1],event.request);
+ if(segments[2]==='cancel' && segments.length===3 && method==='POST')return json(await workerCommand('cancel',{id:segments[1]}));
+ if(['pause','resume'].includes(segments[2]) && segments.length===3 && method==='POST')return json(await workerCommand('control',{id:segments[1],action:segments[2]}));
+ }
+ if(segments[0]==='runs') {
+ const args={...Object.fromEntries(event.url.searchParams),id:segments[1]};
+ if(segments.length===3&&method==='GET'&&['payment-bars','payment-page','payment-detail','next-discrepancy'].includes(segments[2]))return json(await queryWorker(segments[2],args));
+ if(segments.length===3&&method==='GET'&&segments[2]==='export'){
+ const payments=event.url.searchParams.get('kind')==='payments',columns=payments?['elapsed_ms','merchant_id','payment_id','recorded_status','database_status','outcome','failure_category','event_id','operation','api_status_code','message']:['event_id','observed_at','operation','merchant_id','payment_id','api_status_code','status','latency_ms','message'];
+ // Validate run ownership/path before beginning the response stream.
+ runDirectory(segments[1]);
+ return new Response(csvStream(payments?'payment-page':'requests',args,columns),{headers:{'content-type':'text/csv; charset=utf-8','content-disposition':`attachment; filename="${payments?'payments':'responses'}.csv"`}});
+ }
+ if(segments.length===1 && method==='POST')return json(await workerCommand('start',{...await input(),kind:'load'}),{status:202});
+ if(segments.length===1 && method==='GET')return json(await queryWorker('list'));
+ if(segments.length===2 && method==='GET')return json(await queryWorker('run',{id:segments[1]}));
+ if(segments.length===3 && segments[2]==='requests' && method==='GET') {
+ const after=Number(event.url.searchParams.get('after') || 0),limit=Number(event.url.searchParams.get('limit') || 100);
+ if(!Number.isSafeInteger(after)||after<0||!Number.isInteger(limit)||limit<1||limit>200)throw new Error('Invalid pagination');
+ return json(await queryWorker('requests',{...args,after,limit}));
+ }
+ if(segments.length===3 && segments[2]==='reconcile' && method==='GET')return json(await workerCommand('latest-reconciliation',{path:runDirectory(segments[1]).path}));
+ if(segments.length===3 && segments[2]==='reconcile' && method==='POST') {
+ const body=await input();if(body.allowIncomplete!==undefined && typeof body.allowIncomplete!=='boolean')throw new Error('allowIncomplete must be a boolean');
+ return json(await workerCommand('reconcile',{id:segments[1],allowIncomplete:body.allowIncomplete===true}),{status:202});
+ }
+ }
+ if(segments.join('/')==='grafana/panels') {
+ const local=localSettings();
+ if(method==='GET')return json(local.grafana.panels || []);
+ if(method==='PUT') {
+ const panels=await input();if(!Array.isArray(panels)||panels.length>20)throw new Error('Choose at most 20 panels');
+ local.grafana.panels=panels.map(p=>({title:String(p.title).slice(0,100),url:panelPath(p.url,local.grafana.baseUrl)}));
+ await atomicJson(localPath,local);return json(local.grafana.panels);
+ }
+ }
+ return json({error:'Not found'},{status:404});
+ }catch(e){return json({error:redact(e.message)},{status:e.status || 400,...(e.status===413?{headers:{connection:'close'}}:{})});}
+}
+export const GET=dispatch,POST=dispatch,PUT=dispatch,DELETE=dispatch;
diff --git a/loadtest/console/src/routes/grafana/[...path]/+server.js b/loadtest/console/src/routes/grafana/[...path]/+server.js
new file mode 100644
index 0000000000..c6aa7887b0
--- /dev/null
+++ b/loadtest/console/src/routes/grafana/[...path]/+server.js
@@ -0,0 +1,3 @@
+// Active Grafana content must never be served on the console origin.
+const isolated=()=>Response.json({error:'Grafana panels use the isolated embed origin'},{status:403});
+export const GET=isolated,HEAD=isolated,POST=isolated;
diff --git a/loadtest/console/src/routes/health/+server.js b/loadtest/console/src/routes/health/+server.js
new file mode 100644
index 0000000000..7c0b9b4168
--- /dev/null
+++ b/loadtest/console/src/routes/health/+server.js
@@ -0,0 +1,3 @@
+import { json } from '@sveltejs/kit';
+import { controlDb } from '../../../server/state.mjs';
+export function GET(){controlDb().prepare('SELECT 1').get();return json({status:'ok'});}
diff --git a/loadtest/console/src/routes/login/+page.server.js b/loadtest/console/src/routes/login/+page.server.js
new file mode 100644
index 0000000000..dc8035cf4d
--- /dev/null
+++ b/loadtest/console/src/routes/login/+page.server.js
@@ -0,0 +1,13 @@
+import { fail,redirect } from '@sveltejs/kit';
+import { login,sessionCookie } from '../../../server/auth.mjs';
+export const actions={
+ default:async({request,cookies,getClientAddress,url})=>{
+ const form=await request.formData();
+ try {
+ const token=await login(String(form.get('username') || ''),String(form.get('password') || ''),getClientAddress());
+ if(!token)return fail(401,{error:'Invalid username or password'});
+ cookies.set(sessionCookie,token,{path:'/',httpOnly:true,secure:url.protocol==='https:',sameSite:'strict',maxAge:8*3600});
+ } catch(e) {return fail(e.status || 500,{error:e.status===429?e.message:'Login unavailable'});}
+ redirect(303,'/');
+ }
+};
diff --git a/loadtest/console/src/routes/login/+page.svelte b/loadtest/console/src/routes/login/+page.svelte
new file mode 100644
index 0000000000..61c7327a71
--- /dev/null
+++ b/loadtest/console/src/routes/login/+page.svelte
@@ -0,0 +1,9 @@
+<script>let {form}=$props();</script>
+<svelte:head><title>Sign in · Testbench</title></svelte:head>
+<main class="login"><div class="login-brand"><img class="login-logo" src="/hyperswitch-logo.svg" alt="JUSPAY Hyperswitch"/></div><div class="login-heading"><p class="eyebrow">Performance & reliability console</p></div>
+ <form method="POST"><label>Username<input name="username" autocomplete="username" required /></label>
+ <label>Password<input name="password" type="password" autocomplete="current-password" required /></label>
+ {#if form?.error}<p role="alert" class="invalid">{form.error}</p>{/if}<button>Sign in</button>
+ </form>
+</main>
+<style>.login{width:min(420px,calc(100% - 32px));margin:12vh auto 40px;padding:32px;background:var(--surface);border:1px solid var(--border);border-radius:14px;box-shadow:0 10px 40px #18263b06}.login-brand{margin-bottom:10px}.login-logo{display:block;width:205px;max-width:100%;height:auto}.login-heading{margin-bottom:28px}.login label{margin:18px 0}.login button{width:100%;margin-top:8px}.login .invalid{font-size:12px}.login .eyebrow{font-size:10px;margin:0}@media(max-width:480px){.login{padding:24px;margin-top:8vh}}</style>
diff --git a/loadtest/console/src/routes/logout/+server.js b/loadtest/console/src/routes/logout/+server.js
new file mode 100644
index 0000000000..c7b057ed37
--- /dev/null
+++ b/loadtest/console/src/routes/logout/+server.js
@@ -0,0 +1,3 @@
+import { redirect } from '@sveltejs/kit';
+import { logout,sessionCookie } from '../../../server/auth.mjs';
+export function POST({cookies}){logout(cookies.get(sessionCookie));cookies.delete(sessionCookie,{path:'/'});redirect(303,'/login');}
diff --git a/loadtest/console/src/run-lifecycle.mjs b/loadtest/console/src/run-lifecycle.mjs
new file mode 100644
index 0000000000..8c30799245
--- /dev/null
+++ b/loadtest/console/src/run-lifecycle.mjs
@@ -0,0 +1,8 @@
+const activeStatuses=['starting','running','pausing','paused','cancelling'];
+export function recordingFinished(job) {
+ return job?.command==='load'&&job.progress?.control?.state==='completed';
+}
+export function runJobPresentation(jobStatus,recording) {
+ const cleanupPending=activeStatuses.includes(jobStatus)&&recording?.recording_state==='complete'&&Boolean(recording?.ended_at);
+ return {jobStatus:cleanupPending?'complete':jobStatus,cleanupPending};
+}
diff --git a/loadtest/console/src/service-health.mjs b/loadtest/console/src/service-health.mjs
new file mode 100644
index 0000000000..de1261e629
--- /dev/null
+++ b/loadtest/console/src/service-health.mjs
@@ -0,0 +1,22 @@
+export const isDatabaseTarget=target=>target.serviceType==='postgres'||target.adapter==='gcp-alloydb'||/^(postgres(?:ql)?|db)$/i.test(String(target.label||'').trim());
+
+export function faultHealthOverride(service,fault,targets=[]){
+ const active=fault?.active;
+ if(!active||active.simulated)return null;
+ const target=targets.find(target=>target.id===active.targetId);
+ const matches=service.id==='database'?(target&&isDatabaseTarget(target)):service.targetId&&service.targetId===active.targetId;
+ if(!matches)return null;
+ if(service.id==='database'&&['available','unavailable'].includes(active.databaseAvailability))return {state:active.databaseAvailability==='available'?'online':'offline',message:`DB · ${active.databaseAvailability} · SQL connection probe`};
+ // A failed rollout verification is not evidence that a service is still down.
+ // Let the regular readiness probe measure non-DB services again.
+ if(active.status==='recovery_failed'&&service.id!=='database')return null;
+ if(active.status==='recovery_failed')return {state:'offline',message:`${active.target} · recovery not verified`};
+ if(active.status==='restoring')return {state:'recovering',message:`${active.target} · verifying recovery`};
+ if(active.action==='failover')return {state:'recovering',message:`${active.target} · failover in progress`};
+ if(active.occurred)return {state:'offline',message:`${active.target} · interruption verified`};
+ return {state:'recovering',message:`${active.target} · verifying interruption`};
+}
+
+export function pendingHealth(service,previous,override){
+ return {...service,state:previous?.state||'checking',message:previous?.message||'Checking…',...override};
+}
diff --git a/loadtest/console/src/styles.css b/loadtest/console/src/styles.css
new file mode 100644
index 0000000000..d72da73b62
--- /dev/null
+++ b/loadtest/console/src/styles.css
@@ -0,0 +1,41 @@
+@font-face{font-family:Inter;font-style:normal;font-weight:100 900;font-display:swap;src:url("/fonts/InterVariable.woff2") format("woff2")}
+/* Console design system. Controls own their states; layouts never restyle them. */
+:root{font-family:Inter,ui-sans-serif,-apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif;font-synthesis:none;color:#263247;background:#f6f8fb;--accent:#0967e8;--accent-hover:#0555c4;--accent-soft:#edf4ff;--hover-bg:#f2f6fd;--hover-fg:#165cb5;--hover-border:#b8cdec;--selected-hover:#e3edfc;--ink:#18263b;--muted:#68768a;--subtle:#8a97a8;--border:#e2e7ef;--border-strong:#cbd4e1;--surface:#fff;--surface-muted:#f6f8fb;--success:#24764d;--success-soft:#eef9f2;--danger:#bb3434;--danger-soft:#fff1f0;--warning:#9d651b;--warning-soft:#fff7e9;--radius:10px;--shadow:0 2px 8px #18263b05;--header-height:64px;--nav-height:45px}
+*{box-sizing:border-box}body{margin:0}button,input,select,textarea{font:inherit}button,a,input,select,textarea,summary{-webkit-tap-highlight-color:transparent}button,a.button{--button-bg:var(--accent);--button-fg:#fff;--button-border:var(--accent);--button-hover-bg:var(--accent-hover);--button-hover-fg:#fff;--button-hover-border:var(--accent-hover);display:inline-flex;align-items:center;justify-content:center;gap:7px;min-height:36px;padding:8px 13px;border:1px solid var(--button-border);border-radius:7px;background:var(--button-bg);color:var(--button-fg);font-size:13px;line-height:1.25;font-weight:550;text-decoration:none;cursor:pointer;transition:background-color .14s,color .14s,border-color .14s,box-shadow .14s;white-space:nowrap}
+button.secondary,a.button.secondary{--button-bg:var(--surface);--button-fg:var(--ink);--button-border:var(--border-strong);--button-hover-bg:var(--hover-bg);--button-hover-fg:var(--hover-fg);--button-hover-border:var(--hover-border)}
+button.quiet,a.button.quiet,button.icon-button,button.header-button{--button-bg:transparent;--button-fg:#536176;--button-border:transparent;--button-hover-bg:var(--hover-bg);--button-hover-fg:var(--hover-fg);--button-hover-border:transparent}
+button.danger{--button-bg:var(--surface);--button-fg:var(--danger);--button-border:#efc5c3;--button-hover-bg:var(--danger-soft);--button-hover-fg:#992222;--button-hover-border:#e2aaa7}
+button.icon-button.danger{--button-bg:transparent;--button-fg:var(--subtle);--button-border:transparent;--button-hover-border:transparent}
+button.check-success{--button-bg:var(--success-soft);--button-fg:var(--success);--button-border:#b5d9c4;--button-hover-bg:#e0f3e7;--button-hover-fg:#1b5e3c;--button-hover-border:#99c7ac}
+button.check-failed{--button-bg:var(--danger-soft);--button-fg:var(--danger);--button-border:#efc5c3;--button-hover-bg:#ffe4e1;--button-hover-fg:#992222;--button-hover-border:#e2aaa7}
+@media(hover:hover){button:not(:disabled):hover,a.button:hover{background:var(--button-hover-bg);color:var(--button-hover-fg);border-color:var(--button-hover-border)}}
+button:not(:disabled):active,a.button:active{box-shadow:inset 0 1px 2px #18263b18}button:disabled{background:#edf0f5;color:#919cad;border-color:#e4e8ee;cursor:not-allowed;box-shadow:none}button.quiet:disabled,button.icon-button:disabled{background:transparent;border-color:transparent;color:#a0abb9}
+:focus-visible{outline:2px solid var(--accent);outline-offset:3px}button:focus:not(:focus-visible),a:focus:not(:focus-visible){outline:none}.icon-button{min-width:32px;min-height:32px;width:32px;padding:0;font-size:20px;font-weight:400}.header-button{font-size:12px;min-height:34px}.ui-icon{width:16px;height:16px;flex-shrink:0;vertical-align:middle}
+a{color:var(--accent);text-underline-offset:3px}a.quiet{color:#536176;font-size:12px;text-decoration:none}a.quiet:hover{color:var(--accent);text-decoration:underline}
+label{display:block;font-size:12px;font-weight:500;color:#536176}input,select,textarea{width:100%;min-height:38px;margin-top:6px;padding:8px 11px;border:1px solid var(--border-strong);border-radius:7px;background:var(--surface);color:var(--ink);font-size:13px;line-height:1.4;transition:border-color .14s,box-shadow .14s}input::placeholder,textarea::placeholder{color:#8a96a7}input:not(:disabled):hover,select:not(:disabled):hover,textarea:not(:disabled):hover{border-color:var(--hover-border)}input:focus-visible,select:focus-visible,textarea:focus-visible{border-color:var(--accent);outline:2px solid #0967e82b;outline-offset:1px;box-shadow:none}input:disabled,select:disabled,textarea:disabled{background:#f4f6f9;color:#8592a4;border-color:var(--border);cursor:not-allowed}input[readonly]{background:var(--surface-muted)}textarea{font-family:ui-monospace,SFMono-Regular,Menlo,monospace;font-size:12px;resize:vertical}select{appearance:none;background-image:url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='16' height='16' fill='none' stroke='%2368768a' stroke-width='1.5' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpath d='m4 6 4 4 4-4'/%3E%3C/svg%3E");background-repeat:no-repeat;background-position:right 11px center;padding-right:32px}input[type=checkbox]{appearance:auto;width:16px;height:16px;min-height:0;margin:0;accent-color:var(--accent);vertical-align:middle}input[type=range]{min-height:24px;padding:0;border:0;accent-color:var(--accent);box-shadow:none}input[type=file]{padding:6px;font-size:12px}input[type=file]::file-selector-button{cursor:pointer;border:0;padding:6px 10px;border-radius:4px;background:#edf1f7;color:var(--ink);margin-right:8px}input[type=number]{appearance:textfield;-moz-appearance:textfield}input::-webkit-inner-spin-button,input::-webkit-outer-spin-button{appearance:none;margin:0}.checkbox{display:flex;align-items:center;gap:8px;font-weight:400}.fields{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:18px}.fields small{display:block;margin-top:6px;font-weight:400;line-height:1.5}
+h1,h2,h3{color:var(--ink)}h1{font-size:25px;line-height:1.25;letter-spacing:-.65px;font-weight:600;margin:0}h2{font-size:15px;line-height:1.4;font-weight:600;margin:0}h3{font-size:13px;font-weight:600}.eyebrow{font-size:11px;letter-spacing:.08em;text-transform:uppercase;color:var(--muted);margin:0 0 7px;font-weight:550}p{line-height:1.6}.muted,small{color:var(--muted)}p.muted{font-size:12px}.invalid{color:var(--danger)}.sr-only{position:absolute;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip:rect(0,0,0,0);white-space:nowrap;border:0}
+.app-header{height:var(--header-height);display:flex;align-items:center;justify-content:space-between;gap:24px;padding:0 32px;background:var(--surface);border-bottom:1px solid var(--border);position:sticky;top:0;z-index:50}.brand{display:flex;align-items:center;gap:20px;text-decoration:none;color:var(--ink);flex-shrink:0}.header-actions{display:flex;align-items:center;gap:6px;flex-shrink:0}.header-actions form{margin:0}.console-frame{--service-column:184px;--content-gutter:32px;display:grid;grid-template-columns:var(--service-column) minmax(0,1fr);grid-template-rows:var(--nav-height) auto;align-items:start}.section-nav{grid-column:1 / -1;grid-row:1;height:var(--nav-height);display:grid;grid-template-columns:var(--service-column) minmax(0,1fr);background:var(--surface);border-bottom:1px solid var(--border);position:sticky;top:var(--header-height);z-index:49}.section-links{grid-column:2;display:flex;align-items:stretch;gap:4px;width:100%;max-width:1320px;margin:0 auto;padding:0 calc(var(--content-gutter) - 13px);overflow-x:auto;scrollbar-width:none}.section-links::-webkit-scrollbar{display:none}.section-nav a{display:flex;align-items:center;gap:8px;padding:0 13px;border-bottom:2px solid transparent;color:var(--muted);text-decoration:none;font-size:12px;font-weight:550;transition:color .14s,border-color .14s,background-color .14s}.section-nav a:hover{color:var(--hover-fg);background:var(--hover-bg)}.section-nav a.active{color:var(--accent);border-bottom-color:var(--accent)}.service-sidebar{grid-column:1;grid-row:2;position:sticky;top:calc(var(--header-height) + var(--nav-height));height:calc(100dvh - var(--header-height) - var(--nav-height));display:flex;align-items:safe flex-end;justify-content:center;padding:32px 24px;background:transparent;overflow-y:auto;overscroll-behavior:contain}.service-health{width:max-content;max-width:100%;flex-shrink:0}.service-sidebar h2{margin:0 0 12px 9px;font-size:14px;line-height:22px;color:var(--muted);font-weight:400;letter-spacing:.06em;text-align:left}.console-content{grid-column:2;grid-row:2;min-width:0}
+main{padding:32px;max-width:1320px;margin:auto;min-width:0}.section-head{display:flex;align-items:center;justify-content:space-between;gap:20px;margin-bottom:24px}.section-head h1,.section-head h2{margin:0}.section-head p{margin:6px 0 0;color:var(--muted);font-size:12px}.section-head>div{min-width:0}.actions{display:flex;align-items:center;justify-content:flex-end;gap:8px;margin-top:20px;flex-wrap:wrap}.flow-footer{display:flex;align-items:center;justify-content:space-between;gap:16px;margin-top:20px}.flow-footer .actions{margin:0}.save-status{font-size:12px}.surface{background:var(--surface);border:1px solid var(--border);border-radius:var(--radius);box-shadow:var(--shadow)}
+.load-controls{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:20px;background:var(--surface);border:1px solid var(--border);border-radius:var(--radius);padding:20px;margin-bottom:20px}.execution-inputs{grid-template-columns:1.4fr 1fr .8fr;align-items:end}.load-controls input,.load-controls select{font-size:13px;font-weight:400}.fixture-summary{align-self:center}.fixture-summary strong{font-size:14px;font-weight:550}.fixture-summary p{font-size:12px;color:var(--muted);margin:4px 0}.run-select{min-width:240px;max-width:480px}.run-select select{font-size:12px}
+.table-wrap{overflow-x:auto;max-width:100%}table{width:100%;border-collapse:collapse;font-size:12px}th,td{text-align:left;padding:13px 16px;border-bottom:1px solid var(--border);vertical-align:middle}th{color:var(--muted);font-size:11px;font-weight:500;background:#f9fafc;white-space:nowrap}td{color:#344257}td:first-child,th:first-child{padding-left:12px}td:last-child,th:last-child{padding-right:12px}tbody tr:last-child td{border-bottom:0}tbody tr:hover{background:var(--hover-bg)}td input,td select{margin:0;min-width:100px}td small{font-size:11px}details pre{max-width:100%;max-height:240px;overflow:auto;white-space:pre-wrap;overflow-wrap:anywhere;font:12px/1.55 ui-monospace,SFMono-Regular,Menlo,monospace;background:#f6f8fb;border-radius:6px;padding:12px}
+summary{cursor:pointer;color:#46556b;list-style:none;display:flex;align-items:center;gap:8px;font-size:13px;font-weight:500;border-radius:4px}summary::-webkit-details-marker{display:none}summary:before{content:'';width:6px;height:6px;flex-shrink:0;border-right:1.5px solid currentColor;border-bottom:1.5px solid currentColor;transform:rotate(-45deg);transition:transform .16s;margin:0 4px 0 2px}details[open]>summary:before{transform:rotate(45deg)}summary:hover{color:var(--hover-fg)}details>summary:focus-visible{outline-offset:5px}.advanced{margin-top:16px;padding:16px 18px;border:1px solid var(--border);border-radius:var(--radius);background:var(--surface)}.advanced[open]>summary{margin-bottom:18px}
+.message{display:flex;align-items:center;gap:12px;flex-wrap:wrap;padding:12px 14px;background:var(--accent-soft);color:#285790;border:1px solid #dbe8fc;border-radius:8px;margin-bottom:18px;font-size:12px}.message.error{background:var(--danger-soft);color:#a6322a;border-color:#f2d5d2}.message button{margin-left:auto}.empty{padding:64px 20px;text-align:center;color:var(--muted)}.empty-state{padding:60px 24px;text-align:center;background:var(--surface);border:1px dashed var(--border-strong);border-radius:12px}.empty-state h2{font-size:17px}.empty-state p{max-width:420px;margin:10px auto 20px;font-size:13px;color:var(--muted)}
+.run-toolbar{display:flex;align-items:center;justify-content:space-between;gap:20px;padding:16px 20px;background:var(--surface);border:1px solid var(--border);border-radius:var(--radius);margin-bottom:20px}.run-toolbar>div:first-child{display:flex;align-items:center;gap:14px;flex-wrap:wrap}.run-toolbar strong{font-size:13px;font-weight:550}.run-toolbar .actions{margin:0}.run-clock{font-size:12px;color:var(--muted);font-variant-numeric:tabular-nums}.state-badge{font-size:11px;font-weight:500;background:#eef1f5;color:#65738a;border-radius:5px;padding:4px 7px;display:inline-flex;align-items:center;gap:5px}.state-badge.running{background:var(--success-soft);color:var(--success)}.state-badge.paused{background:var(--warning-soft);color:var(--warning)}.stats{display:grid;grid-template-columns:repeat(4,minmax(0,1fr));gap:0;background:var(--surface);border:1px solid var(--border);border-radius:var(--radius);margin-bottom:20px;overflow:hidden}.chart-controls{display:flex;align-items:center;justify-content:flex-end;gap:12px;margin:12px 0}.chart-controls select{width:200px;margin:0}.activity,.acceptance,.diagnostics,.result-details,.detail-section{border:1px solid var(--border);background:var(--surface);border-radius:var(--radius);padding:16px 20px;margin-top:14px}.activity h2{margin:0 0 16px}.activity ol{list-style:none;padding:0;margin:0;max-height:240px;overflow:auto}.activity li{display:flex;gap:20px;padding:10px 0;font-size:12px;border-top:1px solid var(--border)}.activity time{font-variant-numeric:tabular-nums;color:var(--muted);min-width:80px}.activity p,.acceptance p{font-size:12px;color:var(--muted)}.diagnostics[open]>summary,.detail-section[open]>summary,.result-details[open]>summary{margin-bottom:16px}.run-profile-label{display:block;font-size:11px;font-weight:400;margin-top:5px;color:var(--muted)}
+.panels-head{margin-top:28px;margin-bottom:14px}.panel-grid{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:16px}.grafana-panel{background:var(--surface);border:1px solid var(--border);border-radius:var(--radius);overflow:hidden}.grafana-panel>div{display:flex;align-items:center;justify-content:space-between;padding:12px 16px;border-bottom:1px solid var(--border)}.grafana-panel h3{font-size:13px;margin:0}.grafana-panel iframe{display:block;width:100%;height:250px;border:0;background:var(--surface)}.panel-form,.job,.reconcile{background:var(--surface);border:1px solid var(--border);border-radius:var(--radius);padding:20px;margin-bottom:16px}.reconcile p{font-size:12px;color:var(--muted)}.job pre{background:#172033;color:#e4ebf5;padding:16px;border-radius:8px}.panel-form{display:grid;grid-template-columns:1fr 2fr auto;gap:12px;align-items:end}.panel-form .actions{margin:0}
+progress{display:block;width:100%;height:5px;appearance:none;border:0;border-radius:4px;overflow:hidden;accent-color:var(--accent);margin:12px 0 20px}progress::-webkit-progress-bar{background:#edf1f6}progress::-webkit-progress-value{background:var(--accent);border-radius:4px}progress::-moz-progress-bar{background:var(--accent)}
+dialog{width:min(480px,calc(100vw - 32px));max-height:calc(100dvh - 48px);padding:24px;border:1px solid var(--border);border-radius:14px;color:var(--ink);background:var(--surface);box-shadow:0 16px 70px #172b4d24;overflow:auto}dialog::backdrop{background:#14233c55;backdrop-filter:blur(2px)}dialog h1{font-size:21px}dialog h2{font-size:18px}dialog p{font-size:13px;color:var(--muted)}dialog .section-head{margin-bottom:20px}dialog .section-head h2{font-size:18px}dialog .actions{padding-top:20px;margin-top:24px;border-top:1px solid var(--border)}.fault-dialog label{margin-bottom:16px}.fault-dialog .actions button{flex-shrink:0}.settings-dialog{padding:0;width:min(940px,calc(100vw - 48px));height:min(720px,calc(100dvh - 64px));max-height:calc(100dvh - 64px);overflow:hidden}.settings{padding:24px}.settings h2{font-size:14px;margin:0 0 18px}.settings .fields+h2{margin-top:28px}.settings p{font-size:12px;color:var(--muted)}.settings-grid{min-width:0}.settings-grid>div>.fields{margin-bottom:20px}
+.ramp-editor{padding:20px;background:var(--surface);border:1px solid var(--border);border-radius:var(--radius);margin-bottom:20px;position:relative}.ramp-editor .section-head{margin-bottom:8px}.ramp-editor .section-head>label{width:112px}.ramp-editor>svg{display:block;width:100%;height:125px;margin:12px 0}.ramp-editor svg text{font-size:12px;fill:var(--muted)}.stage-row{display:grid;grid-template-columns:28px 1.1fr 1.4fr .8fr auto;gap:14px;align-items:center;padding:12px 0;border-top:1px solid var(--border)}.stage-row input,.stage-row select{min-height:36px}.stage-row label{font-size:11px}.stage-row .icon-button{width:30px;min-width:30px}.stage-number{color:var(--muted);font-size:12px}
+@media(max-width:900px){.app-header{padding-left:24px;padding-right:24px}.console-frame{--service-column:150px;--content-gutter:24px}.service-sidebar{padding:24px 16px}main{padding:24px}.execution-inputs{grid-template-columns:1fr 1fr}.stats{grid-template-columns:repeat(2,minmax(0,1fr))}.panel-grid{grid-template-columns:1fr}.section-head{align-items:flex-start}.run-toolbar{flex-wrap:wrap}.stage-row{gap:10px}}
+@media(max-width:600px){:root{--header-height:58px}.app-header{padding:0 16px;gap:8px}.console-frame{grid-template-columns:minmax(0,1fr);grid-template-rows:var(--nav-height) auto auto}.section-nav{grid-template-columns:minmax(0,1fr)}.section-links{grid-column:1;padding:0 8px;gap:0}.section-nav a{padding:0 8px}.header-actions{gap:0}.header-button{padding:7px 8px;font-size:11px}.header-button>span{display:none}.service-sidebar{position:static;grid-column:1;grid-row:2;height:auto;display:block;padding:16px 16px 0}.service-health{width:100%}.service-sidebar h2{margin:0 0 6px;text-align:center}.console-content{grid-column:1;grid-row:3}main{padding:22px 16px}.section-head{gap:14px;flex-wrap:wrap;margin-bottom:20px}h1{font-size:23px}.fields,.load-controls,.execution-inputs{grid-template-columns:1fr}.run-select{min-width:0;width:100%;max-width:none}.run-toolbar{padding:14px}.run-toolbar>div:first-child{gap:10px}.run-toolbar .actions{justify-content:flex-start}.activity,.diagnostics,.result-details,.detail-section,.reconcile{padding:16px}.settings-dialog{width:calc(100vw - 24px);height:calc(100dvh - 32px);max-height:calc(100dvh - 32px)}.settings{padding:20px}.stage-row{grid-template-columns:26px 1fr 1fr}.panel-form{grid-template-columns:1fr}.panel-grid{grid-template-columns:1fr}.actions{gap:8px}.flow-footer{flex-wrap:wrap}.fault-dialog .actions{flex-wrap:wrap}}
+@media(pointer:coarse){button,a.button{min-height:44px}.icon-button{min-width:40px;min-height:40px}.section-nav a{min-height:44px}input,select,textarea{font-size:16px;min-height:42px}.stage-row input,.stage-row select{min-height:42px}.header-button{min-height:40px}summary{min-height:32px}}
+
+@media(prefers-reduced-motion:reduce){*,*::before,*::after{scroll-behavior:auto!important;transition:none!important;animation:none!important}}
+
+/* All overflow actions share one trigger, popover, and hover treatment. */
+.action-menu{position:relative;flex-shrink:0}
+.action-menu>summary{display:flex;align-items:center;justify-content:center;width:32px;min-height:32px;padding:7px;border-radius:7px;color:var(--muted);transition:background-color .14s,color .14s}
+.action-menu>summary:before{display:none}
+.action-menu[open]>summary{background:var(--accent-soft);color:var(--accent)}
+.action-menu .menu-popover{position:absolute;right:0;top:calc(100% + 4px);z-index:10;min-width:160px;padding:4px;border:1px solid var(--border);border-radius:9px;background:var(--surface);box-shadow:0 8px 24px #18263b16}
+.action-menu .menu-popover button{display:flex;justify-content:flex-start;width:100%;min-height:34px;text-align:left;font-size:12px}
+@media(hover:hover){.action-menu>summary:hover{background:var(--hover-bg);color:var(--hover-fg)}.action-menu[open]>summary:hover{background:var(--selected-hover)}}
diff --git a/loadtest/console/start.mjs b/loadtest/console/start.mjs
new file mode 100644
index 0000000000..23f62ee658
--- /dev/null
+++ b/loadtest/console/start.mjs
@@ -0,0 +1,13 @@
+// The SSR process does not own or stop worker jobs.
+// Artifact uploads are streamed and bounded by their route. Other request bodies
+// retain a 1 MiB limit in hooks, including chunked requests and login forms.
+process.env.BODY_SIZE_LIMIT ??= '2000000000';
+import {initializeSupervisor} from './server/supervisor.mjs';
+import {startGrafanaProxy} from './server/grafana-embed.mjs';
+if(!process.env.ADMIN_PASSWORD_HASH)throw new Error('ADMIN_PASSWORD_HASH is required; run npm run password to generate it');
+await initializeSupervisor();
+const grafanaProxy=await startGrafanaProxy();
+const closeGrafana=()=>{grafanaProxy.closeAllConnections();grafanaProxy.close();};
+process.once('SIGTERM',closeGrafana);
+process.once('SIGINT',closeGrafana);
+await import('./build/index.js');
diff --git a/loadtest/console/static/favicon.svg b/loadtest/console/static/favicon.svg
new file mode 100644
index 0000000000..600962d70e
--- /dev/null
+++ b/loadtest/console/static/favicon.svg
@@ -0,0 +1 @@
+<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 55 58"><path fill-rule="evenodd" clip-rule="evenodd" d="M27.0673 54.3079C25.7664 54.3441 24.5016 54.2355 23.2006 54.0545C19.6953 53.5477 16.4068 52.4255 13.3713 50.5792C6.6497 46.5246 2.34935 40.6238 0.578616 32.8766C0.181104 31.139 0.000416954 29.3651 0.000416954 27.5912C-0.0357205 20.4957 2.27707 14.2691 6.97494 8.98363C11.0585 4.42224 16.1177 1.63472 22.0804 0.476271C23.7427 0.150457 25.405 -0.0305508 27.0673 0.0418522C27.0673 2.75697 27.0673 5.43588 27.0673 8.15099C26.9951 8.18719 26.9228 8.2234 26.8505 8.2958C25.8748 8.98363 24.8991 9.70766 23.9595 10.4679C21.8274 12.2056 19.8037 14.0518 18.1053 16.2601C15.8286 19.1925 14.3108 22.4144 14.094 26.2156C13.9856 28.0256 14.2024 29.7995 14.7806 31.501C16.19 35.7366 20.5626 40.1169 26.706 40.2255C27.0673 40.2255 27.1396 40.298 27.1396 40.6962C27.1035 42.5424 27.1035 46.235 27.1035 46.235C27.1035 46.235 27.1035 46.4522 27.1035 46.5608C27.0673 49.1311 27.0673 51.7014 27.0673 54.3079Z" fill="#0099FF"/><path fill-rule="evenodd" clip-rule="evenodd" d="M27.0666 8.11469C27.0666 8.11469 27.0666 2.72066 27.0666 0.00554404C28.5483 -0.0306575 29.9938 0.114149 31.4393 0.331358C34.1496 0.765776 36.7515 1.56221 39.2088 2.82926C44.3042 5.47197 48.3154 9.23693 51.0257 14.3775C52.5796 17.3461 53.5915 20.4956 53.989 23.7899C54.4588 27.6635 54.0974 31.5009 52.941 35.2296C51.6039 39.4652 49.3634 43.194 46.2195 46.3435C42.3889 50.1447 37.8356 52.6064 32.5595 53.7286C30.7526 54.0906 28.9096 54.3078 27.0666 54.2716C27.0666 51.6651 27.0666 49.0948 27.0666 46.4883C27.0666 46.3797 27.0666 46.1987 27.0666 46.1987C27.0666 46.1987 27.175 46.1263 27.2112 46.0901C30.0299 44.099 32.7041 41.9269 35.0169 39.3204C36.5346 37.6189 37.8356 35.8088 38.739 33.7092C40.0038 30.7406 40.5097 27.6997 39.8593 24.4778C38.7029 18.6131 33.463 14.2327 27.428 14.0879C27.0305 14.0879 27.0666 13.7621 27.0666 13.7621V8.11469Z" fill="#0561E2"/></svg>
diff --git a/loadtest/console/static/fonts/Inter-LICENSE.txt b/loadtest/console/static/fonts/Inter-LICENSE.txt
new file mode 100644
index 0000000000..9b2ca37b3f
--- /dev/null
+++ b/loadtest/console/static/fonts/Inter-LICENSE.txt
@@ -0,0 +1,92 @@
+Copyright (c) 2016 The Inter Project Authors (https://github.com/rsms/inter)
+
+This Font Software is licensed under the SIL Open Font License, Version 1.1.
+This license is copied below, and is also available with a FAQ at:
+http://scripts.sil.org/OFL
+
+-----------------------------------------------------------
+SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
+-----------------------------------------------------------
+
+PREAMBLE
+The goals of the Open Font License (OFL) are to stimulate worldwide
+development of collaborative font projects, to support the font creation
+efforts of academic and linguistic communities, and to provide a free and
+open framework in which fonts may be shared and improved in partnership
+with others.
+
+The OFL allows the licensed fonts to be used, studied, modified and
+redistributed freely as long as they are not sold by themselves. The
+fonts, including any derivative works, can be bundled, embedded,
+redistributed and/or sold with any software provided that any reserved
+names are not used by derivative works. The fonts and derivatives,
+however, cannot be released under any other type of license. The
+requirement for fonts to remain under this license does not apply
+to any document created using the fonts or their derivatives.
+
+DEFINITIONS
+"Font Software" refers to the set of files released by the Copyright
+Holder(s) under this license and clearly marked as such. This may
+include source files, build scripts and documentation.
+
+"Reserved Font Name" refers to any names specified as such after the
+copyright statement(s).
+
+"Original Version" refers to the collection of Font Software components as
+distributed by the Copyright Holder(s).
+
+"Modified Version" refers to any derivative made by adding to, deleting,
+or substituting -- in part or in whole -- any of the components of the
+Original Version, by changing formats or by porting the Font Software to a
+new environment.
+
+"Author" refers to any designer, engineer, programmer, technical
+writer or other person who contributed to the Font Software.
+
+PERMISSION AND CONDITIONS
+Permission is hereby granted, free of charge, to any person obtaining
+a copy of the Font Software, to use, study, copy, merge, embed, modify,
+redistribute, and sell modified and unmodified copies of the Font
+Software, subject to the following conditions:
+
+1) Neither the Font Software nor any of its individual components,
+in Original or Modified Versions, may be sold by itself.
+
+2) Original or Modified Versions of the Font Software may be bundled,
+redistributed and/or sold with any software, provided that each copy
+contains the above copyright notice and this license. These can be
+included either as stand-alone text files, human-readable headers or
+in the appropriate machine-readable metadata fields within text or
+binary files as long as those fields can be easily viewed by the user.
+
+3) No Modified Version of the Font Software may use the Reserved Font
+Name(s) unless explicit written permission is granted by the corresponding
+Copyright Holder. This restriction only applies to the primary font name as
+presented to the users.
+
+4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
+Software shall not be used to promote, endorse or advertise any
+Modified Version, except to acknowledge the contribution(s) of the
+Copyright Holder(s) and the Author(s) or with their explicit written
+permission.
+
+5) The Font Software, modified or unmodified, in part or in whole,
+must be distributed entirely under this license, and must not be
+distributed under any other license. The requirement for fonts to
+remain under this license does not apply to any document created
+using the Font Software.
+
+TERMINATION
+This license becomes null and void if any of the above conditions are
+not met.
+
+DISCLAIMER
+THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
+OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
+COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
+INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
+DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
+OTHER DEALINGS IN THE FONT SOFTWARE.
diff --git a/loadtest/console/static/fonts/InterVariable.woff2 b/loadtest/console/static/fonts/InterVariable.woff2
new file mode 100644
index 0000000000..5a8d3e72ad
Binary files /dev/null and b/loadtest/console/static/fonts/InterVariable.woff2 differ
diff --git a/loadtest/console/static/hyperswitch-logo.svg b/loadtest/console/static/hyperswitch-logo.svg
new file mode 100644
index 0000000000..66b2c279d0
--- /dev/null
+++ b/loadtest/console/static/hyperswitch-logo.svg
@@ -0,0 +1,21 @@
+<svg width="545" height="58" viewBox="0 0 545 58" fill="none" xmlns="http://www.w3.org/2000/svg">
+<path fill-rule="evenodd" clip-rule="evenodd" d="M27.0673 54.3079C25.7664 54.3441 24.5016 54.2355 23.2006 54.0545C19.6953 53.5477 16.4068 52.4255 13.3713 50.5792C6.6497 46.5246 2.34935 40.6238 0.578616 32.8766C0.181104 31.139 0.000416954 29.3651 0.000416954 27.5912C-0.0357205 20.4957 2.27707 14.2691 6.97494 8.98363C11.0585 4.42224 16.1177 1.63472 22.0804 0.476271C23.7427 0.150457 25.405 -0.0305508 27.0673 0.0418522C27.0673 2.75697 27.0673 5.43588 27.0673 8.15099C26.9951 8.18719 26.9228 8.2234 26.8505 8.2958C25.8748 8.98363 24.8991 9.70766 23.9595 10.4679C21.8274 12.2056 19.8037 14.0518 18.1053 16.2601C15.8286 19.1925 14.3108 22.4144 14.094 26.2156C13.9856 28.0256 14.2024 29.7995 14.7806 31.501C16.19 35.7366 20.5626 40.1169 26.706 40.2255C27.0673 40.2255 27.1396 40.298 27.1396 40.6962C27.1035 42.5424 27.1035 46.235 27.1035 46.235C27.1035 46.235 27.1035 46.4522 27.1035 46.5608C27.0673 49.1311 27.0673 51.7014 27.0673 54.3079Z" fill="#0099FF"/>
+<path fill-rule="evenodd" clip-rule="evenodd" d="M27.0666 8.11469C27.0666 8.11469 27.0666 2.72066 27.0666 0.00554404C28.5483 -0.0306575 29.9938 0.114149 31.4393 0.331358C34.1496 0.765776 36.7515 1.56221 39.2088 2.82926C44.3042 5.47197 48.3154 9.23693 51.0257 14.3775C52.5796 17.3461 53.5915 20.4956 53.989 23.7899C54.4588 27.6635 54.0974 31.5009 52.941 35.2296C51.6039 39.4652 49.3634 43.194 46.2195 46.3435C42.3889 50.1447 37.8356 52.6064 32.5595 53.7286C30.7526 54.0906 28.9096 54.3078 27.0666 54.2716C27.0666 51.6651 27.0666 49.0948 27.0666 46.4883C27.0666 46.3797 27.0666 46.1987 27.0666 46.1987C27.0666 46.1987 27.175 46.1263 27.2112 46.0901C30.0299 44.099 32.7041 41.9269 35.0169 39.3204C36.5346 37.6189 37.8356 35.8088 38.739 33.7092C40.0038 30.7406 40.5097 27.6997 39.8593 24.4778C38.7029 18.6131 33.463 14.2327 27.428 14.0879C27.0305 14.0879 27.0666 13.7621 27.0666 13.7621V8.11469Z" fill="#0561E2"/>
+<path d="M89.0807 35.5966C89.0807 37.0921 88.8354 38.5164 88.3798 39.9051C87.9243 41.2937 87.1884 42.5044 86.2773 43.5726C85.3311 44.6408 84.1748 45.4598 82.7731 46.1007C81.3714 46.7061 79.7244 47.0265 77.9022 47.0265C74.9586 47.0265 72.5407 46.3144 70.6835 44.9257C68.7912 43.537 67.5647 41.3293 66.969 38.3027L73.1715 36.8072C73.3817 38.0535 73.8723 39.0505 74.6783 39.7982C75.4492 40.546 76.4304 40.9021 77.5868 40.9021C79.4791 40.9021 80.7757 40.2611 81.4415 38.9437C82.1073 37.6618 82.4577 35.8458 82.4577 33.5669V8.25005H89.0807V35.5966Z" fill="#1C1C1C"/>
+<path d="M125.593 32.1782C125.593 34.4571 125.208 36.5223 124.437 38.3383C123.666 40.1899 122.615 41.721 121.283 43.0029C119.952 44.2848 118.375 45.2818 116.553 45.9583C114.73 46.6705 112.733 46.9909 110.595 46.9909C108.458 46.9909 106.46 46.6349 104.673 45.9583C102.851 45.2818 101.274 44.2848 99.9075 43.0029C98.5408 41.721 97.4895 40.1543 96.7536 38.3383C95.9827 36.5223 95.6323 34.4571 95.6323 32.1782V8.25005H102.255V31.9646C102.255 32.8904 102.395 33.8518 102.676 34.8844C102.956 35.8814 103.412 36.8428 104.077 37.6974C104.708 38.552 105.584 39.2641 106.671 39.7982C107.722 40.3679 109.053 40.6172 110.63 40.6172C112.207 40.6172 113.539 40.3323 114.59 39.7982C115.641 39.2641 116.518 38.552 117.183 37.6974C117.814 36.8428 118.305 35.917 118.585 34.8844C118.865 33.8518 119.006 32.8904 119.006 31.9646V8.25005H125.629V32.1782H125.593Z" fill="#1C1C1C"/>
+<path d="M150.684 16.3685C149.983 15.3358 149.037 14.5881 147.881 14.0896C146.689 13.5911 145.463 13.3774 144.166 13.3774C143.395 13.3774 142.659 13.4843 141.924 13.6623C141.188 13.8403 140.557 14.1252 139.996 14.5169C139.4 14.9086 138.945 15.4071 138.595 16.048C138.244 16.6889 138.069 17.4011 138.069 18.2557C138.069 19.5375 138.489 20.5345 139.4 21.1755C140.277 21.852 141.363 22.4573 142.659 22.9202C143.956 23.4187 145.358 23.9172 146.9 24.3801C148.441 24.843 149.843 25.484 151.175 26.3029C152.471 27.1219 153.558 28.2257 154.434 29.5432C155.31 30.8963 155.765 32.7123 155.765 34.9199C155.765 36.9496 155.415 38.7299 154.679 40.2254C153.943 41.7566 152.962 43.0028 151.7 43.9998C150.439 44.9968 149.002 45.7446 147.355 46.2431C145.708 46.7416 143.956 46.9908 142.169 46.9908C139.856 46.9908 137.613 46.5992 135.511 45.8158C133.373 45.0324 131.516 43.715 129.974 41.8634L134.985 36.9496C135.791 38.1958 136.842 39.1572 138.174 39.8694C139.506 40.5815 140.872 40.902 142.344 40.902C143.115 40.902 143.886 40.7952 144.657 40.5815C145.428 40.3679 146.129 40.0474 146.759 39.6201C147.39 39.1928 147.881 38.6587 148.266 37.9822C148.652 37.3412 148.862 36.5579 148.862 35.7033C148.862 34.3146 148.406 33.2464 147.53 32.4986C146.654 31.7509 145.568 31.1099 144.271 30.6114C142.975 30.1129 141.538 29.6144 139.996 29.1515C138.454 28.6886 137.018 28.0477 135.756 27.2643C134.46 26.481 133.373 25.4127 132.497 24.0597C131.621 22.7066 131.166 20.9262 131.166 18.6829C131.166 16.7245 131.551 15.051 132.357 13.6267C133.128 12.2024 134.179 11.0273 135.476 10.0659C136.737 9.14016 138.209 8.42801 139.856 7.96511C141.503 7.50222 143.185 7.28857 144.902 7.28857C146.865 7.28857 148.757 7.60904 150.614 8.17876C152.436 8.78408 154.118 9.78109 155.59 11.1698L150.684 16.3685Z" fill="#1C1C1C"/>
+<path d="M173.813 8.25005C175.6 8.25005 177.317 8.42809 178.999 8.78416C180.646 9.14024 182.118 9.74556 183.379 10.5645C184.641 11.4191 185.657 12.5229 186.393 13.9116C187.129 15.3359 187.514 17.0807 187.514 19.1815C187.514 21.5672 187.094 23.49 186.288 24.9499C185.482 26.4098 184.396 27.5493 183.029 28.3326C181.662 29.116 180.085 29.6857 178.263 29.9706C176.441 30.2554 174.584 30.3979 172.621 30.3979H167.891V46.0651H161.268V8.25005H173.813ZM171.92 24.6651C172.867 24.6651 173.848 24.6295 174.864 24.5583C175.88 24.487 176.826 24.2734 177.667 23.9173C178.508 23.5612 179.209 23.0271 179.77 22.315C180.296 21.6028 180.576 20.6058 180.576 19.324C180.576 18.1489 180.331 17.2231 179.84 16.511C179.349 15.7988 178.719 15.2647 177.948 14.9086C177.177 14.517 176.301 14.3033 175.355 14.1965C174.408 14.0897 173.497 14.0185 172.621 14.0185H167.891V24.6651H171.92Z" fill="#1C1C1C"/>
+<path d="M200.234 8.25005H205.946L221.995 46.0651H214.426L210.957 37.4125H194.838L191.474 46.0651H184.045L200.234 8.25005ZM208.644 31.6441L202.897 16.2617L197.08 31.6441H208.644Z" fill="#1C1C1C"/>
+<path d="M230.055 29.8994L216.073 8.25005H224.378L233.524 23.312L242.775 8.25005H250.66L236.678 29.8994V46.1007H230.055V29.8994Z" fill="#1C1C1C"/>
+<path d="M266.655 46.6572V8.06836H271.396V24.5336L270.53 24.0748C271.209 22.3417 272.297 20.9993 273.792 20.0477C275.321 19.0622 277.106 18.5694 279.145 18.5694C281.116 18.5694 282.866 19.0112 284.395 19.8948C285.958 20.7784 287.182 22.0018 288.065 23.5651C288.983 25.1283 289.442 26.8955 289.442 28.8666V46.6572H284.65V30.3959C284.65 28.8666 284.361 27.5752 283.783 26.5217C283.24 25.4682 282.475 24.6526 281.489 24.0748C280.504 23.4631 279.365 23.1573 278.074 23.1573C276.817 23.1573 275.678 23.4631 274.659 24.0748C273.639 24.6526 272.841 25.4852 272.263 26.5727C271.685 27.6262 271.396 28.9006 271.396 30.3959V46.6572H266.655Z" fill="#7D7B86"/>
+<path d="M295.677 57.872C295.065 57.872 294.453 57.821 293.842 57.719C293.23 57.6171 292.652 57.4472 292.108 57.2093V52.9783C292.482 53.0462 292.941 53.1142 293.485 53.1822C294.063 53.2841 294.623 53.3351 295.167 53.3351C296.764 53.3351 297.971 52.9783 298.786 52.2646C299.636 51.5849 300.435 50.3955 301.182 48.6963L302.915 44.5672L302.813 48.6963L291.089 19.1811H296.237L305.362 42.6301H303.833L312.907 19.1811H318.157L305.77 49.9197C305.192 51.381 304.445 52.7064 303.527 53.8958C302.643 55.1193 301.556 56.0878 300.265 56.8015C298.973 57.5151 297.444 57.872 295.677 57.872Z" fill="#7D7B86"/>
+<path d="M320.845 56.8525V19.1811H325.484V25.0944L324.873 23.9219C325.892 22.2907 327.285 20.9993 329.053 20.0477C330.82 19.0622 332.842 18.5694 335.119 18.5694C337.701 18.5694 340.012 19.1981 342.051 20.4555C344.124 21.713 345.756 23.4291 346.945 25.6041C348.135 27.7451 348.729 30.192 348.729 32.9447C348.729 35.6294 348.135 38.0593 346.945 40.2343C345.756 42.4092 344.124 44.1254 342.051 45.3828C340.012 46.6402 337.684 47.269 335.068 47.269C332.859 47.269 330.837 46.7762 329.002 45.7906C327.2 44.8051 325.807 43.4118 324.822 41.6106L325.586 40.795V56.8525H320.845ZM334.711 42.6811C336.444 42.6811 337.99 42.2563 339.35 41.4067C340.709 40.5571 341.763 39.4016 342.51 37.9403C343.292 36.445 343.683 34.7798 343.683 32.9447C343.683 31.0416 343.292 29.3764 342.51 27.949C341.763 26.4877 340.709 25.3323 339.35 24.4827C337.99 23.5991 336.444 23.1573 334.711 23.1573C332.978 23.1573 331.414 23.5821 330.021 24.4317C328.662 25.2813 327.574 26.4537 326.759 27.949C325.977 29.4103 325.586 31.0756 325.586 32.9447C325.586 34.7798 325.977 36.445 326.759 37.9403C327.574 39.4016 328.662 40.5571 330.021 41.4067C331.414 42.2563 332.978 42.6811 334.711 42.6811Z" fill="#7D7B86"/>
+<path d="M366.058 47.269C363.408 47.269 361.046 46.6402 358.973 45.3828C356.9 44.1254 355.268 42.4092 354.079 40.2343C352.89 38.0253 352.295 35.5614 352.295 32.8427C352.295 30.09 352.873 27.6432 354.028 25.5022C355.217 23.3612 356.815 21.679 358.82 20.4555C360.859 19.1981 363.136 18.5694 365.651 18.5694C367.69 18.5694 369.491 18.9433 371.054 19.6909C372.651 20.4046 373.994 21.3901 375.081 22.6475C376.203 23.8709 377.052 25.2813 377.63 26.8785C378.242 28.4418 378.548 30.073 378.548 31.7722C378.548 32.1461 378.514 32.5709 378.446 33.0466C378.412 33.4884 378.361 33.9132 378.293 34.321H355.761V30.2429H375.54L373.297 32.0781C373.603 30.3109 373.433 28.7307 372.787 27.3373C372.142 25.944 371.19 24.8395 369.933 24.0239C368.675 23.2082 367.248 22.8004 365.651 22.8004C364.053 22.8004 362.592 23.2082 361.267 24.0239C359.941 24.8395 358.905 26.0119 358.157 27.5412C357.443 29.0365 357.155 30.8207 357.29 32.8937C357.155 34.8988 357.46 36.6659 358.208 38.1952C358.99 39.6905 360.077 40.863 361.471 41.7126C362.898 42.5282 364.444 42.936 366.109 42.936C367.944 42.936 369.491 42.5112 370.748 41.6616C372.006 40.812 373.025 39.7245 373.807 38.3991L377.783 40.4382C377.239 41.6956 376.39 42.851 375.234 43.9045C374.113 44.924 372.77 45.7397 371.207 46.3514C369.678 46.9631 367.961 47.269 366.058 47.269Z" fill="#7D7B86"/>
+<path d="M383.199 46.6572V19.1811H387.838V24.2278L387.329 23.5141C387.974 21.9508 388.96 20.7954 390.285 20.0477C391.611 19.2661 393.225 18.8753 395.128 18.8753H396.81V23.3612H394.414C392.477 23.3612 390.914 23.9729 389.724 25.1963C388.535 26.3858 387.94 28.085 387.94 30.2939V46.6572H383.199Z" fill="#7D7B86"/>
+<path d="M409.33 47.269C406.578 47.269 404.182 46.5893 402.143 45.2299C400.104 43.8705 398.659 42.0354 397.81 39.7245L401.582 37.8894C402.364 39.5206 403.434 40.812 404.793 41.7635C406.153 42.7151 407.665 43.1909 409.33 43.1909C410.826 43.1909 412.066 42.834 413.052 42.1204C414.037 41.4067 414.53 40.4721 414.53 39.3167C414.53 38.5011 414.292 37.8554 413.816 37.3796C413.374 36.8698 412.831 36.479 412.185 36.2071C411.539 35.9013 410.945 35.6804 410.401 35.5445L406.272 34.372C403.791 33.6583 401.973 32.6388 400.817 31.3134C399.696 29.9881 399.135 28.4418 399.135 26.6746C399.135 25.0434 399.543 23.633 400.358 22.4436C401.208 21.2202 402.347 20.2686 403.774 19.5889C405.235 18.9093 406.866 18.5694 408.668 18.5694C411.08 18.5694 413.238 19.1811 415.142 20.4046C417.079 21.628 418.455 23.3442 419.271 25.5531L415.396 27.3373C414.785 25.91 413.867 24.7885 412.644 23.9729C411.42 23.1233 410.044 22.6985 408.515 22.6985C407.121 22.6985 406.017 23.0553 405.201 23.769C404.386 24.4487 403.978 25.3153 403.978 26.3688C403.978 27.1504 404.182 27.7961 404.59 28.3059C404.997 28.7816 405.49 29.1555 406.068 29.4273C406.646 29.6652 407.206 29.8691 407.75 30.039L412.236 31.3644C414.479 32.0101 416.212 33.0126 417.435 34.372C418.693 35.7314 419.322 37.3626 419.322 39.2657C419.322 40.795 418.897 42.1713 418.047 43.3948C417.198 44.6182 416.025 45.5697 414.53 46.2494C413.035 46.9291 411.301 47.269 409.33 47.269Z" fill="#7D7B86"/>
+<path d="M429.821 46.6572L420.391 19.1811H425.641L433.135 42.1713L431.3 42.1204L438.64 19.1811H443.126L450.467 42.1204L448.632 42.1713L456.176 19.1811H461.376L451.945 46.6572H447.408L440.17 23.718H441.597L434.358 46.6572H429.821Z" fill="#7D7B86"/>
+<path d="M464.086 46.6572V19.1811H468.827V46.6572H464.086ZM464.086 14.7972V8.68007H468.827V14.7972H464.086Z" fill="#7D7B86"/>
+<path d="M485.817 46.9631C483.133 46.9631 481.06 46.1985 479.598 44.6692C478.171 43.1399 477.457 40.9819 477.457 38.1952V23.718H472.462V19.1811H473.481C474.705 19.1811 475.673 18.8073 476.387 18.0597C477.101 17.312 477.457 16.3265 477.457 15.1031V12.8601H482.198V19.1811H488.366V23.718H482.198V38.0423C482.198 38.9599 482.334 39.7585 482.606 40.4382C482.912 41.1178 483.405 41.6616 484.084 42.0694C484.764 42.4432 485.665 42.6301 486.786 42.6301C487.024 42.6301 487.313 42.6131 487.653 42.5792C488.026 42.5452 488.366 42.5112 488.672 42.4772V46.6572C488.23 46.7592 487.738 46.8272 487.194 46.8611C486.65 46.9291 486.191 46.9631 485.817 46.9631Z" fill="#7D7B86"/>
+<path d="M505.333 47.269C502.648 47.269 500.252 46.6402 498.145 45.3828C496.072 44.1254 494.441 42.4092 493.252 40.2343C492.062 38.0593 491.467 35.6124 491.467 32.8937C491.467 30.141 492.062 27.6941 493.252 25.5531C494.441 23.4122 496.072 21.713 498.145 20.4555C500.252 19.1981 502.648 18.5694 505.333 18.5694C507.134 18.5694 508.816 18.8923 510.38 19.538C511.943 20.1837 513.319 21.0503 514.509 22.1378C515.698 23.2252 516.565 24.4996 517.108 25.961L512.877 28C512.232 26.5727 511.246 25.4172 509.921 24.5336C508.595 23.6161 507.066 23.1573 505.333 23.1573C503.668 23.1573 502.155 23.5821 500.796 24.4317C499.471 25.2813 498.417 26.4367 497.636 27.898C496.854 29.3594 496.463 31.0416 496.463 32.9447C496.463 34.7798 496.854 36.445 497.636 37.9403C498.417 39.4016 499.471 40.5571 500.796 41.4067C502.155 42.2563 503.668 42.6811 505.333 42.6811C507.066 42.6811 508.595 42.2393 509.921 41.3557C511.246 40.4382 512.232 39.2317 512.877 37.7364L517.108 39.8774C516.565 41.3048 515.698 42.5792 514.509 43.7006C513.319 44.7881 511.943 45.6547 510.38 46.3004C508.816 46.9461 507.134 47.269 505.333 47.269Z" fill="#7D7B86"/>
+<path d="M521.775 46.6572V8.06836H526.515V24.5336L525.649 24.0748C526.329 22.3417 527.416 20.9993 528.911 20.0477C530.441 19.0622 532.225 18.5694 534.264 18.5694C536.235 18.5694 537.985 19.0112 539.514 19.8948C541.078 20.7784 542.301 22.0018 543.185 23.5651C544.102 25.1283 544.561 26.8955 544.561 28.8666V46.6572H539.769V30.3959C539.769 28.8666 539.48 27.5752 538.903 26.5217C538.359 25.4682 537.594 24.6526 536.609 24.0748C535.623 23.4631 534.485 23.1573 533.193 23.1573C531.936 23.1573 530.797 23.4631 529.778 24.0748C528.758 24.6526 527.96 25.4852 527.382 26.5727C526.804 27.6262 526.515 28.9006 526.515 30.3959V46.6572H521.775Z" fill="#7D7B86"/>
+</svg>
diff --git a/loadtest/console/svelte.config.js b/loadtest/console/svelte.config.js
new file mode 100644
index 0000000000..059dd08233
--- /dev/null
+++ b/loadtest/console/svelte.config.js
@@ -0,0 +1,2 @@
+import adapter from '@sveltejs/adapter-node';
+export default { kit: { adapter: adapter({ out:'build' }) } };
diff --git a/loadtest/console/test/alloydb-failover.test.mjs b/loadtest/console/test/alloydb-failover.test.mjs
new file mode 100644
index 0000000000..efe7ad5c91
--- /dev/null
+++ b/loadtest/console/test/alloydb-failover.test.mjs
@@ -0,0 +1,63 @@
+import test from 'node:test';
+import assert from 'node:assert/strict';
+import {mkdtemp} from 'node:fs/promises';
+import os from 'node:os';
+import path from 'node:path';
+process.env.LOADTEST_DATA_DIR=await mkdtemp(path.join(os.tmpdir(),'alloydb-failover-'));
+const {makeFaultAdapter}=await import('../server/faults.mjs');
+const target={adapter:'gcp-alloydb',project:'test',region:'asia-south1',cluster:'payments',instance:'primary'};
+const instanceName='projects/test/locations/asia-south1/clusters/payments/instances/primary';
+const operationName='projects/test/locations/asia-south1/operations/operation-123';
+function fixture(){
+ const info={createTime:'original',state:'READY',availabilityType:'REGIONAL',instanceType:'PRIMARY'};
+ const operation={name:operationName,done:false,metadata:{verb:'failover',target:instanceName}};
+ const calls=[];let reads=0,reachable=true,submissionError=null;
+ const adapter=makeFaultAdapter(target,async(binary,args)=>{
+ calls.push(args);
+ if(args.includes('failover')){if(submissionError)throw submissionError;return JSON.stringify({name:operationName});}
+ return JSON.stringify(args.includes('operations')?operation:info);
+ },{databaseCheck:async()=>{reads++;if(!reachable)throw new Error('connection refused');return {ok:true};}});
+ return {adapter,operation,info,calls,get reads(){return reads;},set reachable(value){reachable=value;},set submissionError(value){submissionError=value;}};
+}
+test('READY during a long failover cannot release the next stage',async()=>{
+ const f=fixture(),before=await f.adapter.probe(),saved=[];
+ await f.adapter.apply('failover',before,async()=>saved.push(structuredClone(before)));
+ assert.equal(saved[0].failoverRequested,true);assert.equal(saved[0].operation,undefined);
+ assert.equal(saved[1].operation,operationName);
+ assert.ok(f.calls.find(args=>args.includes('failover')).includes('--async'));
+ // Model the observed 148-second operation, exceeding the old 120-second CLI deadline.
+ for(let seconds=0;seconds<=145;seconds+=5)assert.equal(await f.adapter.verify(before),false);
+ assert.equal(f.reads,0);assert.ok(f.adapter.recoveryTimeoutMs>148000);
+ f.operation.done=true;assert.equal(await f.adapter.verify(before),true);assert.equal(f.reads,1);
+});
+test('successful operation still waits for DB connectivity and original instance identity',async()=>{
+ const f=fixture(),before=await f.adapter.probe();await f.adapter.apply('failover',before);f.operation.done=true;
+ f.reachable=false;assert.equal(await f.adapter.verify(before),false);
+ f.reachable=true;f.info.state='MAINTENANCE';assert.equal(await f.adapter.verify(before),false);
+ f.info.state='READY';f.info.createTime='replacement';assert.equal(await f.adapter.verify(before),false);
+ f.info.createTime='original';assert.equal(await f.adapter.verify(before),true);
+});
+test('terminal failed operation releases the stage without reporting recovery',async()=>{
+ const f=fixture(),before=await f.adapter.probe();
+ await assert.rejects(f.adapter.verify(before),/operation ID is missing/);
+ await f.adapter.apply('failover',before);f.operation.done=true;f.operation.error={message:'failover rejected'};
+ assert.equal(await f.adapter.verify(before),true);assert.match(before.failoverFailed,/failover rejected/);assert.equal(f.reads,0);
+ delete f.operation.error;f.operation.metadata.target=instanceName+'-other';
+ await assert.rejects(f.adapter.verify(before),/identity changed/);
+});
+test('lost submission response remains unverified; persisted operation resumes without retriggering',async()=>{
+ const f=fixture(),before=await f.adapter.probe();f.submissionError=new Error('CLI timeout');
+ let saved;await assert.rejects(f.adapter.apply('failover',before,async()=>saved=structuredClone(before)),/CLI timeout/);
+ assert.equal(saved.failoverRequested,true);await assert.rejects(f.adapter.verify(saved),/operation ID is missing/);
+ assert.equal(saved.failoverRejected,undefined);
+ f.submissionError=null;await f.adapter.apply('failover',before,async()=>saved=structuredClone(before));
+ const resumed=fixture();resumed.operation.done=true;
+ assert.equal(await resumed.adapter.verify(saved),true);
+ assert.equal(resumed.calls.some(args=>args.includes('failover')),false);
+});
+test('explicit API rejection is persisted so it cannot enter recovery',async()=>{
+ const f=fixture(),before=await f.adapter.probe();
+ f.submissionError=new Error('ERROR: (gcloud.alloydb.instances.failover) ABORTED: another failover operation was recently executed');
+ let saved;await assert.rejects(f.adapter.apply('failover',before,async()=>saved=structuredClone(before)),/ABORTED/);
+ assert.match(saved.failoverRejected,/another failover/);assert.equal(saved.operation,undefined);
+});
diff --git a/loadtest/console/test/chart-timeline.test.mjs b/loadtest/console/test/chart-timeline.test.mjs
new file mode 100644
index 0000000000..1fcd01a450
--- /dev/null
+++ b/loadtest/console/test/chart-timeline.test.mjs
@@ -0,0 +1,83 @@
+import test from 'node:test';import assert from 'node:assert/strict';
+import {loadTimeline} from '../src/load-shape.mjs';
+import {activeSamples,activeToWall,eventActiveTime,plannedEvents,stageWallTimes,executionPhases,targetAt,wallToActive} from '../src/chart-timeline.mjs';
+test('provider-prefixed fault bands identify the affected service, not the cloud',()=>{
+ const timeline=[{start:0,end:30,from:5,target:5,kind:'hold'}];
+ const points=[{t:0,activeSeconds:0},{t:30,activeSeconds:30}];
+ for(const prefix of ['GCP · ','Local · ','AWS · ','Azure · ','SIMULATED · GCP · ','']){
+ const events=[{at:5000,kind:'fault_started',message:`${prefix}Card vault · outage`},{at:15000,kind:'fault_restored',message:`${prefix}Card vault · recovery verified`}];
+ assert.deepEqual(executionPhases(timeline,points,events,0).filter(p=>p.kind==='outage'),[{start:5,end:15,kind:'outage',label:'Card vault outage'}]);
+ }
+});
+test('timeline preserves full plan and exposes only display-safe fault fields',()=>{
+ const plan=loadTimeline({start_rps:0,stages:[{duration_seconds:10,target_rps:10},{duration_seconds:5,target_rps:10,fault:{targetId:'pg',action:'outage'}},{duration_seconds:10,target_rps:20}]},[{index:1,target:{label:'PostgreSQL',secret:'private'}}]);
+ assert.equal(plan.at(-1).end,25);assert.equal(targetAt(5,plan),5);assert.equal(targetAt(12,plan),10);assert.equal(targetAt(20,plan),15);
+ assert.deepEqual(plannedEvents(plan).map(e=>e.t),[0,10,15,15]);assert.match(plannedEvents(plan)[2].label,/recovery planned/);assert.doesNotMatch(JSON.stringify(plan),/private|secret/);
+ const restart=loadTimeline({start_rps:10,stages:[{duration_seconds:5,target_rps:10,fault:{targetId:'vault',action:'restart'}}]});assert.equal(plannedEvents(restart).length,1);
+});
+test('paused samples and wall-time events align to active time without shifting future stages',()=>{
+ const points=[{t:5,activeSeconds:5},{t:10,activeSeconds:10},{t:20,activeSeconds:10},{t:25,activeSeconds:15}];
+ assert.deepEqual(activeSamples(points).map(p=>p.t),[5,10,15]);
+ assert.equal(eventActiveTime({at:17000},0,points),10);assert.equal(eventActiveTime({at:22000},0,points),12);assert.equal(eventActiveTime({at:30000},0,points),15);
+ assert.equal(activeToWall(10,points),10);assert.equal(activeToWall(10,points,'end'),20);assert.equal(activeToWall(12,points),22);assert.equal(wallToActive(17,points),10);
+ assert.equal(loadTimeline({total_rps:10,duration_seconds:60})[0].end,60);
+});
+test('the stage after an outage begins only after recovery verification',()=>{
+ const timeline=[{start:0,end:10,from:1,target:1,kind:'hold'},{start:10,end:20,from:1,target:1,kind:'fault',fault:{target:'Card vault',action:'outage'}},{start:20,end:25,from:1,target:5,kind:'ramp'}];
+ const points=[{t:0,activeSeconds:0},{t:10,activeSeconds:10},{t:20,activeSeconds:20},{t:30,activeSeconds:20},{t:35,activeSeconds:25}];
+ const stages=stageWallTimes(timeline,points,[{kind:'fault_restored',at:32_000}],0);
+ assert.equal(stages[1].wallEnd,32);assert.equal(stages[2].wallStart,32);assert.equal(stages[2].wallEnd,35);
+});
+test('future stages include accumulated fault delays instead of collapsing at the latest sample',()=>{
+ const timeline=[{start:0,end:20,from:1,target:1,kind:'hold'},{start:20,end:40,from:1,target:1,kind:'fault',fault:{target:'Card vault',action:'outage'}},{start:40,end:45,from:1,target:5,kind:'ramp'},{start:45,end:65,from:5,target:5,kind:'hold'}];
+ const points=[{t:0,activeSeconds:0},{t:20,activeSeconds:20},{t:30,activeSeconds:20},{t:50,activeSeconds:40},{t:60,activeSeconds:40}];
+ const stages=stageWallTimes(timeline,points,[{kind:'fault_restored',at:60_000}],0);
+ assert.equal(stages[2].wallStart,60);assert.equal(stages[2].wallEnd,65);assert.equal(stages[3].wallEnd,85);
+ assert.equal(activeToWall(65,points),85);
+});
+import {compactSamples} from '../src/chart-timeline.mjs';
+import {availabilityGraphEvents} from '../src/chart-timeline.mjs';
+test('DB shading and markers use observed availability rather than provider completion',()=>{
+ const timeline=[{start:0,end:10,kind:'hold',target:5},{start:10,end:11,kind:'fault',target:5,fault:{target:'PostgreSQL',action:'failover'}},{start:11,end:21,kind:'hold',target:5}];
+ const points=[{t:0,activeSeconds:0},{t:10,activeSeconds:10},{t:11,activeSeconds:11},{t:100,activeSeconds:11},{t:110,activeSeconds:21}];
+ const events=[{at:10000,kind:'fault_requested',message:'PostgreSQL · failover requested'},{at:11000,kind:'fault_started',message:'PostgreSQL · failover'},{at:15000,kind:'database_unavailable',message:'DB · unavailable'},{at:30000,kind:'database_available',message:'DB · available'},{at:100000,kind:'fault_restored',message:'PostgreSQL · recovery verified'}];
+ assert.deepEqual(availabilityGraphEvents(events,timeline).map(e=>e.kind),['failover_requested','database_unavailable','database_available']);
+ assert.deepEqual(executionPhases(timeline,points,events,0,110).filter(p=>p.kind==='outage'),[{start:15,end:30,kind:'outage',label:'DB outage'}]);
+ assert.equal(executionPhases(timeline,points,events.filter(e=>!e.kind.startsWith('database_')),0,110).some(p=>p.kind==='outage'),false);
+ assert.equal(stageWallTimes(timeline,points,events,0)[2].wallStart,100);
+});
+test('a rejected failover advances the following stage without a DB outage band',()=>{
+ const timeline=[{start:0,end:10,kind:'hold',target:5},{start:10,end:70,kind:'fault',target:5,fault:{target:'PostgreSQL',action:'failover'}},{start:70,end:80,kind:'hold',target:5}];
+ const points=[{t:0,activeSeconds:0},{t:10,activeSeconds:10},{t:12,activeSeconds:70},{t:22,activeSeconds:80}];
+ const events=[{at:10000,kind:'fault_requested',message:'PostgreSQL · failover requested'},{at:12000,kind:'fault_error',message:'ABORTED'},{at:12000,kind:'fault_skipped',message:'PostgreSQL · failover rejected · continuing'}];
+ assert.equal(stageWallTimes(timeline,points,events,0)[2].wallStart,12);
+ assert.equal(executionPhases(timeline,points,events,0,22).some(p=>p.kind==='outage'),false);
+ assert.deepEqual(availabilityGraphEvents(events,timeline).map(e=>e.kind),['failover_requested']);
+});
+test('execution bands start at verified outage and keep recovery delay out of the ramp',()=>{
+ const timeline=[{start:0,end:20,from:1,target:1,kind:'hold'},{start:20,end:40,from:1,target:1,kind:'fault',fault:{target:'Card vault',action:'outage'}},{start:40,end:45,from:1,target:5,kind:'ramp'},{start:45,end:65,from:5,target:5,kind:'hold'}];
+ const points=[{t:0,activeSeconds:0},{t:20,activeSeconds:20},{t:22,activeSeconds:20},{t:42,activeSeconds:40},{t:50,activeSeconds:40},{t:55,activeSeconds:45},{t:75,activeSeconds:65}];
+ const activity=[{kind:'fault_requested',at:20_000,message:'Card vault · requested'},{kind:'fault_started',at:22_000,message:'Card vault · outage'},{kind:'fault_restore',at:42_000,message:'Card vault · restoring'},{kind:'fault_restored',at:50_000,message:'Card vault · recovery verified'}];
+ assert.deepEqual(executionPhases(timeline,points,activity,0),[{start:0,end:22,kind:'hold',label:'Hold'},{start:22,end:50,kind:'outage',label:'Card vault outage'},{start:50,end:55,kind:'ramp',label:'Ramp'},{start:55,end:75,kind:'hold',label:'Hold'}]);
+ const unrecovered=executionPhases(timeline,points.slice(0,4),activity.slice(0,3),0,80);assert.equal(unrecovered.at(-1).kind,'outage');assert.equal(unrecovered.at(-1).end,80);
+});
+test('bounded history keeps the beginning and latest sample',()=>{const points=Array.from({length:1801},(_,t)=>({t}));const compact=compactSamples(points);assert.equal(compact[0].t,0);assert.equal(compact.at(-1).t,1800);assert.ok(compact.length<1800);});
+
+import {metricSeries,rateIntervals,chartHorizon} from '../src/chart-timeline.mjs';
+test('cards and charts use successful completion intervals and a shared wall-time horizon',()=>{
+ const points=[{t:2,intervalStart:0,tps:5,successfulTps:0,flows:{guest:{tps:3,successfulTps:0}}},{t:4,intervalStart:2,tps:5,successfulTps:8,flows:{guest:{tps:3,successfulTps:4}}}];
+ assert.deepEqual(metricSeries(points,'tps').map(p=>p.value),[0,8]);
+ assert.deepEqual(metricSeries(points,'tps','guest').map(p=>p.value),[0,4]);
+ assert.equal(metricSeries([{t:1,tps:5}],'tps')[0].value,undefined);
+ assert.deepEqual(rateIntervals(metricSeries(points,'tps')).map(p=>[p.t,p.value]),[[0,0],[2,0],[2,8],[4,8]]);
+ assert.equal(chartHorizon(points,10),10);
+ assert.deepEqual(metricSeries([{t:1,errors:2,flows:{guest:{}}}],'errors','guest').map(p=>p.value),[2]);
+});
+
+test('latency intervals show zero without successful flows instead of stale or missing latency',()=>{
+ const points=[{t:1,successfulTps:5,p99:80,serverP99:60},{t:2,successfulTps:0,p99:900,serverP99:null,flows:{guest:{successfulTps:0,p99:null,serverP99:700}}},{t:3,successfulTps:5,p99:1200,serverP99:1000}];
+ assert.deepEqual(metricSeries(points,'serverP99').map(p=>p.value),[60,0,1000]);
+ assert.deepEqual(metricSeries(points,'p99').map(p=>p.value),[80,0,1200]);
+ assert.equal(metricSeries(points,'serverP99','guest')[1].value,0);
+ assert.equal(metricSeries([{t:1}],'serverP99')[0].value,undefined);
+});
diff --git a/loadtest/console/test/command-fault-lifecycle.test.mjs b/loadtest/console/test/command-fault-lifecycle.test.mjs
new file mode 100644
index 0000000000..116081522c
--- /dev/null
+++ b/loadtest/console/test/command-fault-lifecycle.test.mjs
@@ -0,0 +1,12 @@
+import test from 'node:test';import assert from 'node:assert/strict';import {mkdtemp,readFile,writeFile,access} from 'node:fs/promises';import path from 'node:path';import os from 'node:os';
+const temporary=await mkdtemp(path.join(os.tmpdir(),'scheduled-command-fault-')),down=path.join(temporary,'down');
+process.env.LOADTEST_DATA_DIR=temporary;process.env.LOADTEST_ALLOW_CUSTOM_COMMANDS='true';
+const seed=JSON.parse(await readFile('../loadtest.config.example.json','utf8'));seed.environment='local';seed.output=path.join(temporary,'artifacts');process.env.LOADTEST_CONFIG_FILE=path.join(temporary,'seed.json');await writeFile(process.env.LOADTEST_CONFIG_FILE,JSON.stringify(seed));
+const target={id:'custom-test',label:'Disposable test state',environment:'local',serviceType:'redis',adapter:'command',commandAction:'outage',recoveryMode:'restore',workingDirectory:temporary,timeoutSeconds:1,triggerCommand:`touch '${down}'`,restoreCommand:`rm -f '${down}'`,readyCommand:`test ! -f '${down}'`,faultCheckCommand:`test -f '${down}'`,actions:['outage']};process.env.LOADTEST_FAULT_TARGETS=path.join(temporary,'targets.json');await writeFile(process.env.LOADTEST_FAULT_TARGETS,JSON.stringify([target]));
+const {fireFault,restoreFaults,initializeFaults,faultStatus,testFault}=await import('../server/faults.mjs');
+const job={id:'load-test',command:'load',status:'running',loadState:'running'},input={targetId:target.id,action:'outage',durationSeconds:1,confirm:`outage ${target.id}`};
+async function restored(){await assert.rejects(access(down));assert.equal(faultStatus().blocked,false);}
+test('custom faults reject direct and standalone manual execution',async()=>{await assert.rejects(fireFault(job,input),/schedule/);await assert.rejects(testFault({...job,command:'fault-test'},input),/schedule/);});
+test('scheduled custom outage restores and records verified recovery',async()=>{const events=[];let activated;const started=new Promise(r=>activated=r);await fireFault(job,input,(_,kind)=>{events.push(kind);if(kind==='fault_started')activated();},()=>job,target);await started;await restoreFaults();await restored();assert.ok(events.includes('fault_restored'));});
+test('ambiguous trigger failure still restores infrastructure',async()=>{const failing={...target,triggerCommand:`touch '${down}'; exit 7`};const events=[];let failed;const observed=new Promise(r=>failed=r);await fireFault(job,input,(_,kind)=>{events.push(kind);if(kind==='fault_error')failed();},()=>job,failing);await observed;await restoreFaults();await restored();assert.ok(events.includes('fault_error'));assert.ok(events.includes('fault_restored'));});
+test('interrupted persisted custom outage is restored on supervisor startup',async()=>{await writeFile(down,'');await writeFile(path.join(temporary,'fault-ledger.json'),JSON.stringify({id:'interrupted',jobId:'load-test',target,action:'outage',status:'active',before:{ready:true},seconds:1,at:Date.now()}));await initializeFaults(()=>{});await restored();});
diff --git a/loadtest/console/test/command-faults.test.mjs b/loadtest/console/test/command-faults.test.mjs
new file mode 100644
index 0000000000..fb069aba44
--- /dev/null
+++ b/loadtest/console/test/command-faults.test.mjs
@@ -0,0 +1,9 @@
+import test from 'node:test';import assert from 'node:assert/strict';
+import {commandFaultAdapter,validateCommandTarget,executeFaultCommand} from '../server/command-faults.mjs';
+const target={adapter:'command',environment:'local',serviceType:'redis',commandAction:'outage',recoveryMode:'restore',workingDirectory:'/tmp',timeoutSeconds:1,triggerCommand:'true',restoreCommand:'true',readyCommand:'true',faultCheckCommand:'true'};
+test('custom commands require explicit supervisor opt-in and complete restoration configuration',()=>{delete process.env.LOADTEST_ALLOW_CUSTOM_COMMANDS;assert.throws(()=>validateCommandTarget(target),/disabled/);process.env.LOADTEST_ALLOW_CUSTOM_COMMANDS='true';assert.throws(()=>validateCommandTarget({...target,restoreCommand:''}),/restoreCommand/);assert.throws(()=>validateCommandTarget({...target,workingDirectory:'relative'}),/absolute/);assert.ok(validateCommandTarget({...target,recoveryMode:'self-recovering',restoreCommand:''}));});
+test('adapter independently checks initial health, activation and restoration',async()=>{process.env.LOADTEST_ALLOW_CUSTOM_COMMANDS='true';const calls=[];const adapter=commandFaultAdapter(target,{execute:async(_,field)=>{calls.push(field);if(field==='faultCheckCommand')throw new Error('not down');}});const before=await adapter.probe();await adapter.apply();assert.equal(await adapter.isDown(),false);await adapter.restore(before);assert.equal(await adapter.verify(before),true);assert.deepEqual(calls,['readyCommand','triggerCommand','faultCheckCommand','restoreCommand','readyCommand']);});
+test('self-recovering targets do not execute a restore command',async()=>{const calls=[];const adapter=commandFaultAdapter({...target,recoveryMode:'self-recovering'},{execute:async(_,f)=>calls.push(f)});await adapter.restore();assert.deepEqual(calls,[]);});
+test('shell command failures and timeouts omit raw output and terminate process groups',async()=>{await assert.rejects(executeFaultCommand({...target,triggerCommand:'echo private-output; exit 7'},'triggerCommand'),/exit 7/);const started=Date.now();await assert.rejects(executeFaultCommand({...target,triggerCommand:'sleep 30 & wait'},'triggerCommand'),/timed out/);assert.ok(Date.now()-started<3000);});
+
+test('disabling command execution preserves readable saved configuration',()=>{delete process.env.LOADTEST_ALLOW_CUSTOM_COMMANDS;assert.ok(validateCommandTarget(target,{requireEnabled:false}));assert.throws(()=>commandFaultAdapter(target),/disabled/);process.env.LOADTEST_ALLOW_CUSTOM_COMMANDS='true';});
diff --git a/loadtest/console/test/connectors.test.mjs b/loadtest/console/test/connectors.test.mjs
new file mode 100644
index 0000000000..99c6e9e4a4
--- /dev/null
+++ b/loadtest/console/test/connectors.test.mjs
@@ -0,0 +1,38 @@
+import test from 'node:test';import assert from 'node:assert/strict';
+import {mkdtemp,readFile,readdir} from 'node:fs/promises';import path from 'node:path';import os from 'node:os';
+import {connectorCatalog,normalizeConnectorPlan} from '../src/connector-config.mjs';
+import {connectorSecretStore,provisionConnectorAccounts,resolveConnectorAccounts} from '../server/connector-fixtures.mjs';
+import {connectorSchedule,selectedConnector,connectorRouting,connectorTestCard,connectorBrowserInfo} from '../../k6/scenario-mix/connectors.mjs';
+import {DatabaseSync} from 'node:sqlite';import {connectorResults} from '../server/connector-results.mjs';
+const plan={mode:'real',mix:[{connector:'stripe',weight:70},{connector:'adyen',weight:30}]};
+test('catalog canonical names and strict mode, weights and identities',()=>{
+ assert.ok(connectorCatalog.some(c=>c.id==='stripe_test'&&c.dummy));assert.ok(connectorCatalog.some(c=>c.id==='stripe'&&!c.dummy));assert.deepEqual(normalizeConnectorPlan(plan),plan);
+ for(const invalid of [{...plan,mode:'dummy'},{...plan,mix:[{connector:'not-real',weight:100}]},{...plan,mix:[{connector:'stripe',weight:60}]},{...plan,mix:[{connector:'stripe',weight:50},{connector:'stripe',weight:50}]}])assert.throws(()=>normalizeConnectorPlan(invalid));
+ assert.deepEqual(normalizeConnectorPlan({...plan,mix:plan.mix.map(r=>({...r,password:'must-not-save'}))}),plan);
+});
+test('weighted schedules preserve mix per cycle and merchant-specific account selection',()=>{
+ const slots=connectorSchedule(plan);assert.equal(slots.filter(c=>c==='stripe').length,70);const merchant={connector_accounts:{stripe:'mca-s',adyen:'mca-a'}};
+ for(let cycle=0;cycle<5;cycle++)assert.equal(Array.from({length:100},(_,i)=>selectedConnector(slots,cycle*100+i,merchant)).filter(c=>c.connector==='stripe').length,70);
+ assert.throws(()=>selectedConnector(slots,0,{merchant_connector_id:'wrong-mca'}));
+ assert.deepEqual(connectorRouting(selectedConnector(slots,0,merchant)),{routing:{type:'single',data:{connector:'stripe',merchant_connector_id:'mca-s'}}});
+});
+test('sandbox cards and browser context support provider requirements and explicit negative tests',()=>{
+ const stripe={card_number:'4242424242424242'};
+ assert.equal(connectorTestCard('stripe',stripe),stripe);
+ assert.equal(connectorTestCard('adyen',stripe).card_number,'4111111111111111');
+ assert.equal(connectorTestCard('adyen',stripe,{adyen:stripe}),stripe);
+ assert.equal(connectorBrowserInfo({language:'fr-FR'}).language,'fr-FR');
+ assert.ok(connectorBrowserInfo().accept_header);assert.equal(connectorBrowserInfo().java_enabled,false);
+});
+test('encrypted credentials never appear in references or plaintext files',async()=>{
+ const root=await mkdtemp(path.join(os.tmpdir(),'connector-vault-'));const sentinel='sandbox-secret-should-never-be-saved-plaintext';
+ const refs=provisionConnectorAccounts({mode:'real',mix:[{connector:'stripe',weight:100}]},{stripe:{credentials:{api_key:sentinel}}},root);
+ assert.ok(!JSON.stringify(refs).includes(sentinel));for(const file of await readdir(path.join(root,'connector-secrets')))assert.ok(!(await readFile(path.join(root,'connector-secrets',file))).includes(Buffer.from(sentinel)));
+ assert.equal(resolveConnectorAccounts(refs,root)[0].connector_account_details.api_key,sentinel);assert.throws(()=>connectorSecretStore(root).get('../key'));assert.throws(()=>provisionConnectorAccounts(plan,{stripe:{credentials:{api_key:sentinel}}},root),/Enter Adyen/);
+});
+test('Results separate assignments and reported routing, with HS-only and full latency',async()=>{
+ const directory=await mkdtemp(path.join(os.tmpdir(),'connector-results-'));const db=new DatabaseSync(path.join(directory,'results.sqlite'));db.exec(await readFile(new URL('../../k6/scenario-mix/recorder/schema.sql',import.meta.url),'utf8'));
+ const insert=db.prepare("INSERT INTO request_events(run_id,attempt_id,flow_id,operation,role,observed_at,method,url,api_status_code,status,latency_ms,server_latency_ms,requested_connector,connector) VALUES('r',1,?,'payment_confirm','measured',1,'POST','/confirm',?,?,?,?,?,?)");
+ insert.run('a',200,'succeeded',100,30,'stripe','stripe');insert.run('b',500,'failed',90,null,'adyen',null);insert.run('c',200,'succeeded',120,40,'stripe','adyen');db.close();
+ const result=connectorResults(directory,plan);assert.equal(result.unattributedConfirmations,1);const stripe=result.rows.find(r=>r.connector==='stripe');assert.equal(stripe.assigned,2);assert.equal(stripe.confirmations,1);assert.equal(stripe.observedPercent,50);assert.equal(stripe.hsP99,30);assert.equal(stripe.fullP99,100);assert.equal(result.rows.find(r=>r.connector==='adyen').successes,1);
+});
diff --git a/loadtest/console/test/core.test.mjs b/loadtest/console/test/core.test.mjs
new file mode 100644
index 0000000000..1930e245e2
--- /dev/null
+++ b/loadtest/console/test/core.test.mjs
@@ -0,0 +1,222 @@
+import test from 'node:test';
+import assert from 'node:assert/strict';
+import { mkdtemp,readFile,writeFile,mkdir } from 'node:fs/promises';
+import os from 'node:os';
+import path from 'node:path';
+import { DatabaseSync } from 'node:sqlite';
+
+const temporary=await mkdtemp(path.join(os.tmpdir(),'loadtest-console-core-'));
+process.env.LOADTEST_DATA_DIR=temporary;
+process.env.LOADTEST_CONSOLE_ROOT=path.resolve('.');
+process.env.LOADTEST_ROOT=path.resolve('..');
+const config=JSON.parse(await readFile('../loadtest.config.example.json','utf8'));
+config.output=path.join(temporary,'artifacts');config.fixtures.admin_api_key='private-admin-test';config.fixtures.superposition.token='private-sp-test';
+process.env.LOADTEST_CONFIG_FILE=path.join(temporary,'seed.json');await writeFile(process.env.LOADTEST_CONFIG_FILE,JSON.stringify(config));
+const state=await import('../server/state.mjs');state.initializeConfig();
+const auth=await import('../server/auth.mjs');
+const {comparePayments,describeRun,listRuns,requestHistory}=await import('../server/queries.mjs');
+const {telemetryPoint}=await import('../server/telemetry.mjs');
+const registry=await import('../server/worker-registry.mjs');
+
+test('successful TPS uses success counters rather than a shutdown rate spike',()=>{
+ const point=telemetryPoint({elapsed_seconds:10,successful_tps:10000,http_attempts:400,http_errors:0,recorder:{persisted:400},flows:{guest:{successes:100}}},{t:9,successes:90});
+ assert.equal(point.successfulTps,10);assert.equal(point.recorded,400);
+});
+test('flow rate counts admissions while requests are waiting for responses',()=>{
+ const point=telemetryPoint({elapsed_seconds:10,control:{started_flows:50,flow_starts:{guest:50},in_flight:50},http_attempts:0,http_errors:0,recorder:{persisted:0,enqueued:0},flows:{guest:{successes:0,failures:0}}},{t:9,started:45,successes:0,flows:{guest:{started:45,successes:0}}});
+ assert.equal(point.tps,5);assert.equal(point.flows.guest.tps,5);assert.equal(point.successfulTps,0);
+ const drain=telemetryPoint({elapsed_seconds:11,control:{started_flows:50,flow_starts:{guest:50},in_flight:0},http_attempts:50,http_errors:50,recorder:{persisted:50,enqueued:50},flows:{guest:{successes:0,failures:50}}},point);
+ assert.equal(drain.tps,0);assert.equal(drain.flows.guest.tps,0);
+});
+test('error trend shows recovery rather than carrying prior failures into every sample',()=>{
+ const sample=(elapsed_seconds,http_attempts,http_errors)=>({elapsed_seconds,http_attempts,http_errors,confirm_http_attempts:http_attempts,confirm_http_errors:http_errors,recorder:{persisted:http_attempts,enqueued:http_attempts},flows:{}});
+ const outage=telemetryPoint(sample(10,100,80));assert.equal(outage.errors,80);
+ const recovered=telemetryPoint(sample(11,110,80),outage);assert.equal(recovered.errors,0);
+ const noTraffic=telemetryPoint(sample(12,110,80),recovered);assert.equal(noTraffic.errors,0);
+});
+
+test('scrypt login, hashed persistent sessions, expiry and logout',async()=>{
+ process.env.ADMIN_PASSWORD_HASH=await auth.passwordHash('long test password');
+ assert.equal(await auth.verifyPassword('wrong',process.env.ADMIN_PASSWORD_HASH),false);
+ const token=await auth.login('admin','long test password','login-ok');
+ assert.ok(auth.authenticated(token));
+ const onDisk=state.controlDb().prepare('SELECT token FROM sessions').get().token;assert.notEqual(onDisk,token);
+ auth.logout(token);assert.equal(auth.authenticated(token),false);
+ const expired=await auth.login('admin','long test password','login-expired');state.controlDb().exec('UPDATE sessions SET expires=1');assert.equal(auth.authenticated(expired),false);
+});
+test('persistent login limiting and strict origin checks',async()=>{
+ for(let n=0;n<5;n++)assert.equal(await auth.login('admin','bad','blocked-ip'),null);
+ await assert.rejects(auth.login('admin','long test password','blocked-ip'),e=>e.status===429);
+ const url=new URL('https://console.example');
+ assert.ok(auth.sameOrigin(new Request(url,{headers:{origin:url.origin}}),url));
+ assert.equal(auth.sameOrigin(new Request(url,{headers:{origin:'https://other.example'}}),url),false);
+});
+test('parallel password checks cannot bypass the five-attempt limit',async()=>{
+ const attempts=await Promise.allSettled(Array.from({length:20},()=>auth.login('admin','wrong','parallel-ip')));
+ assert.equal(attempts.filter(r=>r.status==='fulfilled').length,5);
+ assert.equal(attempts.filter(r=>r.status==='rejected'&&r.reason.status===429).length,15);
+});
+test('masked credentials cannot follow edited connection destinations',async()=>{
+ assert.throws(()=>state.superpositionConnection({endpoint:'https://replacement.invalid'}),/credential|token/i);
+ const {databaseTestConnection}=await import('../server/connection-secrets.mjs');
+ const saved={host:'db.internal',port:5432,database:'payments',user:'reader',password:'saved',tlsMode:'verify'};
+ assert.throws(()=>databaseTestConnection(saved,{host:'replacement.invalid'}),/password/i);
+ assert.throws(()=>databaseTestConnection(saved,{tlsMode:'disable'}),/password/i);
+ assert.equal(databaseTestConnection(saved,{host:'replacement.invalid',password:'replacement'}).password,'replacement');
+ assert.equal(databaseTestConnection(saved,{host:'db.internal'}).password,'saved');
+});
+test('workers enroll, heartbeat, receive ordered commands and acknowledge once',()=>{
+ const identity=registry.enrollWorker({name:'worker-a',capacityTps:250,capacityVus:2000,version:'1'},'enroll-secret','enroll-secret');
+ assert.equal(registry.heartbeatWorker(identity.id,identity.token,{status:'ready'}).ok,true);
+ const command=registry.queueWorkerCommand(identity.id,{runId:'run-a',kind:'prepare',payload:{segment:{start:0,end:.5}}});
+ assert.equal(command.revision,1);
+ assert.deepEqual(registry.pendingWorkerCommands(identity.id,identity.token)[0].payload,{segment:{start:0,end:.5}});
+ assert.equal(registry.acknowledgeWorkerCommand(identity.id,identity.token,command.id,{ok:true}).ok,true);
+ assert.deepEqual(registry.pendingWorkerCommands(identity.id,identity.token),[]);
+ assert.throws(()=>registry.acknowledgeWorkerCommand(identity.id,identity.token,command.id,{ok:true}),/already acknowledged/);
+});
+test('settings and redaction never expose secrets; profiles validate paths and weights',async()=>{
+ const settings=state.publicSettings();assert.equal(settings.adminApiKey,'');assert.equal(settings.superposition.token,'');
+ settings.superposition.accessHeader='x-superposition-access';
+ assert.doesNotMatch(JSON.stringify(settings),/private-admin-test|private-sp-test/);
+ assert.equal(state.redact('private-admin-test private-sp-test'),'[redacted] [redacted]');
+ assert.equal(state.validateSettings({...settings,scenarios:[{name:'checkout',scenario:'sdk_checkout',merchant_path:'non_modular',weight:100}]}).config.scenarios[0].merchant_path,'modular');
+ await assert.rejects(state.saveSettings({...settings,scenarios:settings.scenarios.map(f=>({...f,weight:0}))}),/100/);
+ await assert.rejects(state.saveSettings({...settings,database:{...settings.database,tlsMode:'verify',caPath:'relative.pem'}}),/absolute/);
+ settings.superposition.pollSeconds=2.5;
+ settings.preAllocatedVusMultiplier=4;
+ settings.maxVusMultiplier=12;
+ settings.database={...settings.database,host:'database.internal',port:6432,database:'payments',user:'loadtest_reader',password:'database-secret',tlsMode:'verify',caPath:'/certs/database.pem'};
+ const saved=await state.saveSettings(settings);assert.equal(saved.totalRps,10);assert.equal(saved.superposition.pollSeconds,2.5);assert.equal(saved.superposition.accessHeader,'x-superposition-access');assert.equal(state.readJsonSync(state.configPath).fixtures.admin_api_key,'private-admin-test');
+ assert.deepEqual(saved.grafana.panels.map(panel=>panel.title),['RPS','API latency','TP latencies']);
+ assert.deepEqual(saved.smokeTest,{enabled:true,rps:1,durationSeconds:10});
+ assert.deepEqual(saved.database,{host:'database.internal',port:6432,database:'payments',user:'loadtest_reader',tlsMode:'verify',caPath:'/certs/database.pem',caCertificateId:'',password:'',hasPassword:true});
+ assert.equal(state.localSettings().database.password,'database-secret');
+ assert.equal(state.publicSettings().database.host,'database.internal');
+ assert.deepEqual(state.configuredVus(state.readJsonSync(state.configPath).load),{pre_allocated_vus_multiplier:4,max_vus_multiplier:12});
+ assert.deepEqual(state.withConfiguredVus({total_rps:200,pre_allocated_vus_multiplier:1,max_vus_multiplier:2},state.readJsonSync(state.configPath).load),
+ {total_rps:200,pre_allocated_vus_multiplier:4,max_vus_multiplier:12,request_timeout_ms:40000});
+ await assert.rejects(state.saveConnections({...saved,preAllocatedVusMultiplier:15,maxVusMultiplier:10}),/VU multipliers/);
+});
+test('Grafana panels cannot point to arbitrary origins or schemes',()=>{
+ assert.equal(state.panelPath('https://grafana.example/grafana/d-solo/k6/x?panelId=1','https://grafana.example'),'/grafana/d-solo/k6/x?panelId=1&theme=light');
+ assert.equal(state.panelPath('https://grafana.example/d/k6/x?viewPanel=panel-2&from=now-1h','https://grafana.example'),'/grafana/d-solo/k6/x?from=now-1h&panelId=2&theme=light');
+ assert.equal(state.panelPath('https://grafana.example/d-solo/k6/x?panelId=3&theme=dark','https://grafana.example'),'/grafana/d-solo/k6/x?panelId=3&theme=dark');
+ assert.throws(()=>state.panelPath('https://grafana.example/d/k6/x','https://grafana.example'),/Share → Embed/);
+ assert.throws(()=>state.panelPath('https://evil.example/grafana/d-solo/x','https://grafana.example'));
+ assert.throws(()=>state.httpUrl('file:///etc/passwd'));
+ assert.throws(()=>state.runDirectory('single:..'));
+});
+test('reconciliation distinguishes merchant/payment pairs and exact statuses',()=>{
+ const results=comparePayments([{merchant_id:'one',payment_id:'same',status:'succeeded'},
+ {merchant_id:'two',payment_id:'same',status:'processing'},{merchant_id:'three',payment_id:'none',status:'failed'}],
+ [{merchant_id:'one',payment_id:'same',status:'succeeded'},{merchant_id:'two',payment_id:'same',status:'succeeded'}]);
+ assert.deepEqual(results.map(r=>r.outcome),['match','mismatch','missing']);
+});
+test('saved run success TPS excludes failed iterations and response history paginates',async()=>{
+ const directory=path.join(config.output,'single/runs/run-test');await mkdir(directory,{recursive:true});
+ await writeFile(path.join(directory,'config.json'),JSON.stringify({load:{total_rps:10,duration_seconds:10},scenarios:config.scenarios}));
+ await writeFile(path.join(directory,'summary.json'),JSON.stringify({metrics:{iterations:{values:{count:100}},scenario_success_cit_off:{values:{count:30}},scenario_failure_cit_off:{values:{count:20}},achieved_tps_cit_off:{values:{value:3}}}}));
+ const db=new DatabaseSync(path.join(directory,'results.sqlite'));db.exec(await readFile('../k6/scenario-mix/recorder/schema.sql','utf8'));
+ db.prepare("INSERT INTO runs(run_id,started_at,ended_at,recording_state,enqueued,persisted) VALUES('test',1,10001,'complete',3,3)").run();
+ const insert=db.prepare("INSERT INTO request_events(run_id,attempt_id,flow_id,operation,role,observed_at,method,url,api_status_code,latency_ms) VALUES('test',?,'flow','payment_create','measured',1,'POST','http://test',500,2)");
+ for(let n=1;n<=3;n++)insert.run(n);db.close();
+ const run=await describeRun('single:run-test');assert.equal(run.successfulTps,3);assert.equal(run.iterations,100);assert.equal(run.flows[0].errors,20);
+ assert.equal(run.confirmErrorRate,0); // Failed payment-create calls are outside this display metric.
+ const page=requestHistory({id:run.id,limit:2});assert.equal(page.rows.length,2);assert.equal(page.next,2);
+ assert.equal(requestHistory({id:run.id,after:page.next,limit:2}).rows.length,1);
+});
+test('run navigation lists metadata without calculating every saved result',async()=>{
+ const directory=path.join(config.output,'single/runs/navigation-option');await mkdir(directory,{recursive:true});
+ const profile={id:'steady',name:'Steady load'};
+ await writeFile(path.join(directory,'config.json'),JSON.stringify({profile,environment:'gcp',fixtureSet:{id:'fixtures'},load:{total_rps:5,duration_seconds:10},scenarios:[]}));
+ const db=new DatabaseSync(path.join(directory,'results.sqlite'));db.exec(await readFile('../k6/scenario-mix/recorder/schema.sql','utf8'));
+ db.exec("INSERT INTO runs(run_id,started_at,ended_at,recording_state,enqueued,persisted) VALUES('navigation',1000,11000,'complete',50,50)");db.close();
+ const option=(await listRuns()).find(run=>run.id==='single:navigation-option');
+ assert.deepEqual(option,{id:'single:navigation-option',mode:'single',name:'navigation-option',profile,environment:'gcp',fixtureSetId:'fixtures',startedAt:1000,endedAt:11000,recordingState:'complete'});
+ // Detailed results remain available only when that run is selected.
+ assert.ok((await describeRun(option.id)).acceptance);
+});
+test('saved HTTP error card counts only measured payment confirmations',async()=>{
+ const directory=path.join(config.output,'single/runs/confirm-errors');await mkdir(directory,{recursive:true});
+ await writeFile(path.join(directory,'config.json'),JSON.stringify({load:{total_rps:10,duration_seconds:10},scenarios:config.scenarios}));
+ await writeFile(path.join(directory,'summary.json'),JSON.stringify({metrics:{http_req_failed:{values:{rate:.5}}}}));
+ const db=new DatabaseSync(path.join(directory,'results.sqlite'));db.exec(await readFile('../k6/scenario-mix/recorder/schema.sql','utf8'));
+ db.exec("INSERT INTO runs(run_id,started_at,ended_at,recording_state,enqueued,persisted) VALUES('test',1,10001,'complete',4,4)");
+ const insert=db.prepare("INSERT INTO request_events(run_id,attempt_id,flow_id,operation,role,observed_at,method,url,api_status_code,latency_ms) VALUES('test',?,'flow',?,'measured',1,'POST','http://test',?,2)");
+ insert.run(1,'pm_session_confirm',0);insert.run(2,'pm_session_confirm',400);insert.run(3,'payment_confirm',200);insert.run(4,'payment_confirm',500);db.close();
+ const run=await describeRun('single:confirm-errors');assert.equal(run.confirmErrorRate,50);assert.equal(run.errorRate,50);
+});
+test('restart recovery interrupts stale jobs and SSE reconnect sends current state',async()=>{
+ state.controlDb().prepare("INSERT INTO jobs(id,kind,mode,status,started_at) VALUES('stale','load','single','running',1)").run();
+ const jobs=await import('../server/jobs.mjs');jobs.initializeJobs();assert.equal(jobs.getJob('stale').status,'interrupted');
+ const response=jobs.jobEvents('stale',new Request('http://test/api/jobs/stale/events'));
+ assert.match(await response.text(),/interrupted/);
+});
+
+test('staged settings preserve shape and snapshot criteria',async()=>{
+ const input=state.publicSettings();
+ input.loadShape='staged';input.startRps=0;input.stagesJson=JSON.stringify([{target_rps:10,duration_seconds:4}]);
+ input.acceptance.maximumConfirmP99Ms=350;
+ const saved=await state.saveSettings(input);assert.equal(saved.totalRps,10);assert.equal(saved.durationSeconds,4);
+ const c=state.readJsonSync(state.configPath);assert.equal(c.load.total_rps,undefined);assert.equal(c.load.duration_seconds,undefined);assert.equal(c.load.start_rps,0);assert.equal(c.acceptance.maximumConfirmP99Ms,350);
+ await assert.rejects(state.saveSettings({...input,stagesJson:'[]'}),/positive/);
+ await state.saveSettings({...saved,loadShape:'flat'});assert.equal(state.readJsonSync(state.configPath).load.stages,undefined);
+});
+
+test('Results limits save through Settings, validate values and preserve profile isolation',async()=>{
+ const {getProfile,saveProfile,profileDraft}=await import('../server/profiles.mjs');
+ const settings=state.publicSettings();assert.equal(settings.resultsLimits.minimumThroughputPercent,97);
+ const profile=saveProfile({...profileDraft(),name:'Results snapshot scenario'});
+ const saved=await state.saveConnections({...settings,resultsLimits:{...settings.resultsLimits,maximumHoldP99Ms:250,recoveryWindowSeconds:15}});
+ assert.equal(saved.resultsLimits.maximumHoldP99Ms,250);assert.equal(saved.resultsLimits.recoveryWindowSeconds,15);
+ assert.equal(state.readJsonSync(state.configPath).resultsLimits.maximumHoldP99Ms,250);
+ assert.equal(getProfile(profile.id).version,profile.version);
+ await assert.rejects(state.saveConnections({...saved,resultsLimits:{...saved.resultsLimits,minimumThroughputPercent:101}}),/Invalid Results limit/);
+ assert.equal(state.publicSettings().resultsLimits.minimumThroughputPercent,97);
+ await state.saveConnections({...saved,resultsLimits:settings.resultsLimits});
+});
+
+test('versioned profiles are isolated from connection edits and reject stale saves',async()=>{
+ const {saveProfile,getProfile,profileDraft}=await import('../server/profiles.mjs');
+ const first=saveProfile({...profileDraft(),name:'Single 200 TPS',totalRps:200,durationSeconds:60});
+ const second=saveProfile({...first,totalRps:1000},first.id);
+ assert.equal(second.version,2);assert.equal(getProfile(first.id,1).totalRps,200);
+ assert.throws(()=>saveProfile({...first,totalRps:300},first.id),/changed/);
+ const settings=state.publicSettings();await state.saveConnections({...settings,scenarios:[],database:{...settings.database,user:'existing_user',password:'replacement-db-secret'}});
+ assert.equal(getProfile(first.id).totalRps,1000);assert.equal(state.publicSettings().database.user,'existing_user');
+ assert.throws(()=>saveProfile({...first,name:'bad',mode:'single',merchantCount:1500}),/Single/);
+});
+test('fixture compatibility includes merchant count and provisioning settings, not rate',async()=>{
+ const {fixtureSignature,validateFixtureSet}=await import('../server/profiles.mjs');
+ const c=state.readJsonSync(state.configPath),sig=fixtureSignature(c,'single',1);
+ assert.equal(sig,fixtureSignature({...c,load:{total_rps:1000}},'single',1));
+ assert.equal(sig,fixtureSignature({...c,services:{...c.services,modular_pm:'http://different'}},'single',1));
+ assert.equal(sig,fixtureSignature({...c,fixtures:{...c.fixtures,admin_api_key:'rotated',superposition:{...c.fixtures.superposition,endpoint:'http://different',token:'rotated',refresh_interval_seconds:1,poll_interval_seconds:.25}}},'single',1));
+ assert.notEqual(sig,fixtureSignature(c,'tenancy',1500));
+ assert.notEqual(sig,fixtureSignature({...c,fixtures:{...c.fixtures,router:'http://different'}},'single',1));
+ assert.notEqual(sig,fixtureSignature({...c,fixtures:{...c.fixtures,superposition:{...c.fixtures.superposition,defaults:{changed:true}}}},'single',1));
+ const dir=path.join(temporary,'fixture-set');await mkdir(dir);await writeFile(path.join(dir,'manifest.json'),JSON.stringify({state:'ready'}));
+ state.controlDb().prepare('INSERT INTO fixture_sets VALUES(?,?,?,?,?,?,NULL,?)').run('fixture-test','single',1,sig,dir,'ready',Date.now());
+ assert.equal(validateFixtureSet('fixture-test',{mode:'single',merchantCount:1},c).id,'fixture-test');
+ assert.throws(()=>validateFixtureSet('fixture-test',{mode:'tenancy',merchantCount:1500},c),/does not match/);
+});
+test('ramp editor round trips holds and calculates offered-flow preview',async()=>{
+ const {encodeStages,decodeStages,rampPoints}=await import('../src/ramp-editor.mjs');
+ const {loadShape}=await import('../src/load-shape.mjs');
+ const stages=encodeStages([{kind:'ramp',target:200,duration:60},{kind:'hold',target:99,duration:120},{kind:'ramp',target:1000,duration:60}],10);
+ assert.equal(stages[1].target_rps,200);assert.equal(decodeStages(JSON.stringify(stages),10)[1].kind,'hold');
+ assert.equal(loadShape({start_rps:10,stages}).duration,240);assert.equal(rampPoints(10,stages).at(-1).value,1000);
+ assert.throws(()=>encodeStages([{kind:'hold',duration:0}],10),/positive/);
+});
+test('new flows get unique metric names without changing existing flows',async()=>{
+ const {newFlow,profileSummary}=await import('../src/flow-catalog.mjs');
+ const flows=[{name:'guest',scenario:'guest',merchant_path:'modular',weight:50},{name:'guest_2',scenario:'guest',merchant_path:'non_modular',weight:50}];
+ const before=JSON.stringify(flows),flow=newFlow('guest',flows);assert.equal(flow.name,'guest_3');assert.equal(flow.weight,0);assert.equal(JSON.stringify(flows),before);
+ assert.match(profileSummary({mode:'tenancy',merchantCount:1500,totalRps:1000,durationSeconds:180,loadShape:'staged'}),/Tenancy · 1500 merchants · 1000 peak TPS · 3 min/);
+});
+
+test('new runs use the configured HTTP timeout even when a saved scenario has an older timeout',()=>{
+ assert.equal(state.withConfiguredVus({request_timeout_ms:30000},{request_timeout_ms:40000}).request_timeout_ms,40000);
+ assert.equal(state.withConfiguredVus({request_timeout_ms:40000},{}).request_timeout_ms,40000);
+});
diff --git a/loadtest/console/test/database-availability.test.mjs b/loadtest/console/test/database-availability.test.mjs
new file mode 100644
index 0000000000..1664237bc0
--- /dev/null
+++ b/loadtest/console/test/database-availability.test.mjs
@@ -0,0 +1,20 @@
+import test from 'node:test';
+import assert from 'node:assert/strict';
+import {watchDatabaseAvailability} from '../server/database-availability.mjs';
+test('probes mark only SQL availability transitions, independently of a long cloud operation',async()=>{
+ const samples=[true,false,false,true,true,false,true],events=[],observed=[];
+ let resolve;const finished=new Promise(r=>resolve=r);
+ const observer=watchDatabaseAvailability({intervalMs:1,check:async()=>{const ok=samples.shift();if(!ok)throw Error('connection unavailable');return {ok};},onSample:state=>{observed.push(state);if(!samples.length)resolve();},onChange:state=>events.push(state)});
+ await finished;await observer.stop();
+ assert.deepEqual(events,['unavailable','available','unavailable','available']);assert.equal(observed.length,7);
+});
+test('restarting from an unavailable observation records actual recovery',async()=>{
+ let resolve;const checked=new Promise(r=>resolve=r),events=[];
+ const observer=watchDatabaseAvailability({initial:'unavailable',intervalMs:1,check:async()=>({ok:true}),onChange:state=>{events.push(state);resolve();}});
+ await checked;await observer.stop();assert.deepEqual(events,['available']);
+});
+test('stopping an in-flight probe does not emit a late availability marker',async()=>{
+ let finish;const check=new Promise(r=>finish=r),events=[];
+ const observer=watchDatabaseAvailability({check:()=>check,onChange:s=>events.push(s)});
+ const stopped=observer.stop();finish({ok:false});await stopped;assert.deepEqual(events,[]);
+});
diff --git a/loadtest/console/test/database-recovery-gate.test.mjs b/loadtest/console/test/database-recovery-gate.test.mjs
new file mode 100644
index 0000000000..bfbb78b333
--- /dev/null
+++ b/loadtest/console/test/database-recovery-gate.test.mjs
@@ -0,0 +1,19 @@
+import test from 'node:test';
+import assert from 'node:assert/strict';
+import {databaseRecoveryGate} from '../server/database-recovery-gate.mjs';
+
+test('SQL recovery releases the load once while the cloud operation is still pending',async()=>{
+ const entry={status:'active',loadReleased:false};let releases=0;
+ const sample=databaseRecoveryGate(entry,async()=>{releases++;return true;});
+ await sample('available');assert.equal(releases,0);
+ await sample('unavailable');await sample('available');assert.equal(releases,0);
+ entry.status='restoring';await Promise.all([sample('available'),sample('available')]);
+ assert.equal(releases,1);assert.equal(entry.loadReleased,true);
+ await sample('available');assert.equal(releases,1);
+});
+test('failed load-clock release retries instead of falsely declaring it resumed',async()=>{
+ const entry={status:'restoring',databaseOutageObserved:true,loadReleased:false};let calls=0;
+ const sample=databaseRecoveryGate(entry,async()=>++calls>1);
+ await sample('available');assert.equal(entry.loadReleased,false);
+ await sample('available');assert.equal(entry.loadReleased,true);assert.equal(calls,2);
+});
diff --git a/loadtest/console/test/display-errors.test.mjs b/loadtest/console/test/display-errors.test.mjs
new file mode 100644
index 0000000000..9cf6a0ff6d
--- /dev/null
+++ b/loadtest/console/test/display-errors.test.mjs
@@ -0,0 +1,55 @@
+import test from 'node:test';
+import assert from 'node:assert/strict';
+import {mkdtemp,rm} from 'node:fs/promises';
+import os from 'node:os';
+import path from 'node:path';
+import {DatabaseSync} from 'node:sqlite';
+import {faultWindows,hiddenVaultError,decorateDisplayErrors} from '../server/display-errors.mjs';
+import {restoreDisplayErrors} from '../server/telemetry.mjs';
+
+const events=[
+ {at:1000,kind:'fault_started',message:'Card vault · outage'},
+ {at:10000,kind:'fault_restore',message:'Card vault · restoring'},
+ {at:20000,kind:'fault_restored',message:'Card vault · recovery verified'},
+ {at:40000,kind:'database_unavailable',message:'DB · unavailable'},
+ {at:50000,kind:'database_available',message:'DB · available'}
+];
+const timeout={observed_at:35000,latency_ms:30000,api_status_code:0,operation:'pm_session_confirm',message:'request timeout'};
+test('vault filtering follows request overlap, preserves DB errors and other transport failures',()=>{
+ const windows=faultWindows(events);
+ assert.equal(hiddenVaultError(timeout,windows),true); // Completed after recovery; started during the outage.
+ assert.equal(hiddenVaultError({...timeout,observed_at:45000},windows),false); // Also overlaps DB unavailability.
+ assert.equal(hiddenVaultError({...timeout,operation:'payment_confirm'},windows),false);
+ assert.equal(hiddenVaultError({...timeout,latency_ms:1000},windows),false);
+ assert.equal(hiddenVaultError({...timeout,message:'connection reset'},windows),false);
+ assert.equal(hiddenVaultError({...timeout,observed_at:15000,latency_ms:50,api_status_code:503},windows),true);
+ assert.equal(hiddenVaultError({...timeout,observed_at:15000,latency_ms:50,api_status_code:400},windows),false);
+ assert.equal(hiddenVaultError({...timeout,observed_at:45000,latency_ms:50,api_status_code:500},windows),false);
+ assert.equal(hiddenVaultError(timeout,faultWindows([])),false);
+});
+test('live and historical display agree while raw errors remain intact, including incremental recording',async()=>{
+ const directory=await mkdtemp(path.join(os.tmpdir(),'vault-display-'));
+ const db=new DatabaseSync(path.join(directory,'results.sqlite'));
+ try{
+ db.exec('CREATE TABLE runs(run_id TEXT,started_at INTEGER); INSERT INTO runs VALUES(\'run\',0); CREATE TABLE request_events(event_id INTEGER PRIMARY KEY,run_id TEXT,role TEXT,observed_at INTEGER,latency_ms REAL,operation TEXT,api_status_code INTEGER,message TEXT)');
+ const insert=db.prepare("INSERT INTO request_events(run_id,role,observed_at,latency_ms,operation,api_status_code,message) VALUES('run','measured',?,?,?,?,?)");
+ const rows=[{...timeout},{observed_at:36000,latency_ms:50,operation:'payment_confirm',api_status_code:200,message:''}];
+ for(const row of rows)insert.run(row.observed_at,row.latency_ms,row.operation,row.api_status_code,row.message);
+ const progress={elapsed_seconds:36,http_attempts:2,http_errors:1,trend:{t:36,intervalStart:0,intervalAttempts:2,intervalErrors:1}};
+ let live=decorateDisplayErrors(progress,directory,events,{},0);
+ assert.equal(live.display_error_rate,0);assert.equal(live.trend.errors,0);assert.equal(live.http_errors,1);
+ // The recorder has persisted another timeout before k6 publishes its new
+ // counters. Mixing these two clocks/counters used to create orange spikes.
+ const behind=decorateDisplayErrors({...progress,http_errors:0},directory,events,{},-128);
+ assert.equal(behind.display_error_rate,0);assert.equal(behind.trend.errors,0);
+ const ahead=decorateDisplayErrors({...progress,http_errors:2},directory,events,{},-128);
+ assert.equal(ahead.display_error_rate,0);assert.equal(ahead.trend.errors,0);
+ const dbError={observed_at:45000,latency_ms:100,operation:'payment_create',api_status_code:500,message:'database unavailable'};
+ insert.run(dbError.observed_at,dbError.latency_ms,dbError.operation,dbError.api_status_code,dbError.message);rows.push(dbError);
+ live=decorateDisplayErrors({...progress,elapsed_seconds:45,http_attempts:3,http_errors:2,trend:{t:45,intervalStart:36,intervalAttempts:1,intervalErrors:1}},directory,events,{},0);
+ const history=restoreDisplayErrors([{t:36},{t:45}],rows,0,events);
+ assert.deepEqual(history.map(p=>p.errors),[0,100]);assert.equal(live.trend.errors,100);
+ assert.equal(live.display_error_rate,33.33);assert.equal(live.hidden_vault_errors,1);assert.equal(live.http_errors,2);
+ assert.equal(db.prepare('SELECT COUNT(*) AS n FROM request_events WHERE api_status_code=0 OR api_status_code>=400').get().n,2);
+ }finally{db.close();await rm(directory,{recursive:true,force:true});}
+});
diff --git a/loadtest/console/test/distributed-runtime.test.mjs b/loadtest/console/test/distributed-runtime.test.mjs
new file mode 100644
index 0000000000..a1e20fadbb
--- /dev/null
+++ b/loadtest/console/test/distributed-runtime.test.mjs
@@ -0,0 +1,91 @@
+import test from 'node:test';
+import assert from 'node:assert/strict';
+import {mkdtemp,mkdir,readFile,writeFile} from 'node:fs/promises';
+import {DatabaseSync} from 'node:sqlite';
+import {createHash} from 'node:crypto';
+import os from 'node:os';
+import path from 'node:path';
+
+const root=await mkdtemp(path.join(os.tmpdir(),'distributed-runtime-'));process.env.LOADTEST_DATA_DIR=root;process.env.LOADTEST_CONSOLE_ROOT=path.resolve('.');process.env.LOADTEST_ROOT=path.resolve('..');
+const seed=JSON.parse(await readFile('../loadtest.config.example.json','utf8'));seed.output=path.join(root,'artifacts');process.env.LOADTEST_CONFIG_FILE=path.join(root,'seed.json');await writeFile(process.env.LOADTEST_CONFIG_FILE,JSON.stringify(seed));
+const state=await import('../server/state.mjs');state.initializeConfig();
+const registry=await import('../server/worker-registry.mjs'),{launchDistributedRun,aggregate}=await import('../server/distributed-runner.mjs'),{readWorkerBundle,storeWorkerArtifact}=await import('../server/worker-artifacts.mjs');
+test('distributed chart rates use wall time while pause and stage clocks retain active time',()=>{
+ const shards=[{status:'paused',progress:JSON.stringify({elapsed_seconds:30,control:{active_seconds:10},flows:{guest:{successes:20}}})}];
+ const progress=aggregate(shards,{wallElapsedSeconds:31});assert.equal(progress.elapsed_seconds,31);assert.equal(progress.control.active_seconds,10);
+ const {elapsed_seconds}=aggregate(shards);assert.equal(elapsed_seconds,30);
+});
+
+const delay=ms=>new Promise(resolve=>setTimeout(resolve,ms));
+async function caseRun(name,count=1){
+ state.controlDb().prepare('UPDATE load_workers SET last_seen=0').run();
+ const fixturePath=path.join(root,name+'-fixtures'),runPath=path.join(root,name);await mkdir(fixturePath);await mkdir(runPath);
+ const merchants=JSON.stringify([{merchant_id:'fake'}]);await writeFile(path.join(fixturePath,'merchants.json'),merchants);await writeFile(path.join(fixturePath,'manifest.json'),JSON.stringify({schema_version:1,state:'ready',merchants_sha256:createHash('sha256').update(merchants).digest('hex')}));
+ const identities=Array.from({length:count},(_,i)=>registry.enrollWorker({name:`${name}-${i}`,capacityTps:1,capacityVus:10},'fake','fake'));
+ let result=null;
+ const runner=await launchDistributedRun({runId:name,runPath,fixturePath,config:{mode:'single',load:{total_rps:count,duration_seconds:60,max_vus_multiplier:5},scenarios:[]},onDone:(error,value)=>{result={error,value};}});
+ return {identities,runner,get result(){return result;}};
+}
+test('cancel settles after workers finish and removes pending preparation/start commands',async()=>{
+ const probe=await caseRun('cancel-terminal');probe.runner.cancel();
+ const identity=probe.identities[0],commands=registry.pendingWorkerCommands(identity.id,identity.token);
+ assert.deepEqual(commands.map(c=>c.kind),['stop']);
+ registry.heartbeatWorker(identity.id,identity.token,{status:'idle',runId:'cancel-terminal',runStatus:'complete'});
+ await Promise.race([probe.runner.done,delay(3000).then(()=>{throw Error('Stop did not settle');})]);
+ assert.equal(probe.result.error,null);
+});
+test('one failed worker stops siblings and retains ownership until they drain',async()=>{
+ const probe=await caseRun('failure-drain',2),[failed,sibling]=probe.identities;
+ registry.heartbeatWorker(failed.id,failed.token,{status:'failed',runId:'failure-drain',runStatus:'failed',error:'injected failure'});
+ registry.heartbeatWorker(sibling.id,sibling.token,{status:'running',runId:'failure-drain',runStatus:'running'});
+ await delay(1200);
+ assert.equal(probe.result,null,'must not release a still-running sibling');
+ assert.deepEqual(registry.pendingWorkerCommands(sibling.id,sibling.token).map(c=>c.kind),['stop']);
+ registry.heartbeatWorker(sibling.id,sibling.token,{status:'idle',runId:'failure-drain',runStatus:'failed'});
+ await probe.runner.done;assert.match(probe.result.error.message,/injected failure/);
+});
+test('control plane prepares synchronized workers, receives artifacts and merges a run',async()=>{
+ const fixturePath=path.join(root,'fixtures'),runPath=path.join(root,'run');await mkdir(fixturePath);await mkdir(runPath);
+ const merchants=[{merchant_id:'m1'},{merchant_id:'m2'}],merchantText=JSON.stringify(merchants);await writeFile(path.join(fixturePath,'merchants.json'),merchantText);await writeFile(path.join(fixturePath,'manifest.json'),JSON.stringify({schema_version:1,state:'ready',router:'https://router.example',merchants_sha256:createHash('sha256').update(merchantText).digest('hex')}));
+ const identities=[0,1].map(index=>registry.enrollWorker({name:`worker-${index}`,capacityTps:5,capacityVus:50},'secret','secret'));
+ const config={mode:'single',services:{router:'https://router.example'},load:{total_rps:10,duration_seconds:1,max_vus_multiplier:5},scenarios:[{name:'flow',scenario:'guest',merchant_path:'non_modular',weight:100}]};
+ let finished;const runner=await launchDistributedRun({runId:'run-test',runPath,config,fixturePath,onDone:(error,result)=>finished={error,result}});
+ assert.equal(runner.plan.length,2);
+ for(const identity of identities){const command=registry.pendingWorkerCommands(identity.id,identity.token)[0],bundle=await readWorkerBundle(command.payload.bundleId,identity.id);assert.equal(JSON.parse(bundle.body).merchants.length,1);registry.acknowledgeWorkerCommand(identity.id,identity.token,command.id);registry.heartbeatWorker(identity.id,identity.token,{status:'ready',runId:'run-test',runStatus:'ready'});}
+ await delay(1200);
+ for(const identity of identities){const command=registry.pendingWorkerCommands(identity.id,identity.token)[0];assert.equal(command.kind,'start');registry.acknowledgeWorkerCommand(identity.id,identity.token,command.id);}
+ for(const action of ['gate','release','recover']){
+ const payload=action==='release'?{until_active_seconds:20}:undefined,controlled=runner.control(action,payload);
+ for(const identity of identities){const command=registry.pendingWorkerCommands(identity.id,identity.token)[0];assert.equal(command.kind,action);assert.ok(command.payload.effectiveAt<=Date.now());if(action==='release')assert.equal(command.payload.until_active_seconds,20);registry.acknowledgeWorkerCommand(identity.id,identity.token,command.id);}
+ await controlled;
+ }
+ const schema=await readFile('../k6/scenario-mix/recorder/schema.sql','utf8');
+ for(const [index,identity] of identities.entries()){
+ const file=path.join(root,`shard-${index}.sqlite`),db=new DatabaseSync(file);db.exec(schema);db.prepare("INSERT INTO runs(run_id,recording_state,started_at,ended_at,enqueued,persisted,metadata) VALUES(?,'complete',1,2,1,1,'{}')").run(`source-${index}`);db.prepare("INSERT INTO request_events(event_id,run_id,attempt_id,flow_id,operation,role,observed_at,method,url,api_status_code,latency_ms) VALUES(1,?,1,?,'payment_confirm','measured',1,'POST','/',200,?)").run(`source-${index}`,`source-${index}:flow:1`,10+index);db.close();
+ for(const [name,data] of [['results.sqlite',await readFile(file)],['summary.json',Buffer.from(JSON.stringify({metrics:{iterations:{type:'counter',values:{count:1}}}}))]])await storeWorkerArtifact({workerId:identity.id,runId:'run-test',name,body:new Blob([data]).stream(),contentLength:data.length});
+ registry.heartbeatWorker(identity.id,identity.token,{status:'idle',runId:'run-test',runStatus:'complete'});
+ }
+ await Promise.race([runner.done,delay(5000).then(()=>{throw new Error('Distributed run did not finish');})]);assert.equal(finished.error,null);assert.equal(finished.result.merged.workers,2);assert.ok((await readFile(path.join(runPath,'results.sqlite'))).length>0);
+});
+
+test('a failed worker command fails its shard and releases the coordinator',async()=>{
+ const fixturePath=path.join(root,'failure-fixtures'),runPath=path.join(root,'failure-run');await mkdir(fixturePath);await mkdir(runPath);
+ const merchants=[{merchant_id:'m1'}],merchantText=JSON.stringify(merchants);await writeFile(path.join(fixturePath,'merchants.json'),merchantText);await writeFile(path.join(fixturePath,'manifest.json'),JSON.stringify({schema_version:1,state:'ready',merchants_sha256:createHash('sha256').update(merchantText).digest('hex')}));
+ state.controlDb().prepare('UPDATE load_workers SET last_seen=0 WHERE id<>?').run('local');
+ const worker=registry.enrollWorker({name:'worker-command-failure',capacityTps:5,capacityVus:50},'secret','secret');
+ let finished;const runner=await launchDistributedRun({runId:'run-command-failure',runPath,config:{mode:'single',load:{total_rps:1,duration_seconds:1,max_vus_multiplier:5},scenarios:[]},fixturePath,onDone:(error,result)=>finished={error,result}});
+ assert.equal(runner.plan[0].workerId,worker.id);
+ const command=registry.pendingWorkerCommands(worker.id,worker.token)[0];registry.acknowledgeWorkerCommand(worker.id,worker.token,command.id,{ok:false,result:{error:'fixture preparation failed'}});
+ await Promise.race([runner.done,delay(3000).then(()=>{throw new Error('Failed distributed run did not settle');})]);assert.match(finished.error.message,/fixture preparation failed/);
+ assert.equal(state.controlDb().prepare('SELECT status FROM run_shards WHERE run_id=?').get('run-command-failure').status,'failed');
+});
+
+test('a lost worker heartbeat fails the run instead of waiting forever',async()=>{
+ const fixturePath=path.join(root,'offline-fixtures'),runPath=path.join(root,'offline-run');await mkdir(fixturePath);await mkdir(runPath);
+ const merchants=[{merchant_id:'m1'}],merchantText=JSON.stringify(merchants);await writeFile(path.join(fixturePath,'merchants.json'),merchantText);await writeFile(path.join(fixturePath,'manifest.json'),JSON.stringify({schema_version:1,state:'ready',merchants_sha256:createHash('sha256').update(merchantText).digest('hex')}));
+ state.controlDb().prepare('UPDATE load_workers SET last_seen=0 WHERE id<>?').run('local');
+ const worker=registry.enrollWorker({name:'worker-heartbeat-loss',capacityTps:5,capacityVus:50},'secret','secret');let finished;
+ const runner=await launchDistributedRun({runId:'run-heartbeat-loss',runPath,config:{mode:'single',load:{total_rps:1,duration_seconds:1,max_vus_multiplier:5},scenarios:[]},fixturePath,onDone:error=>finished=error});
+ state.controlDb().prepare('UPDATE load_workers SET last_seen=0 WHERE id=?').run(worker.id);
+ await Promise.race([runner.done,delay(3000).then(()=>{throw new Error('Offline distributed run did not settle');})]);assert.match(finished.message,/heartbeat timed out/);
+});
diff --git a/loadtest/console/test/distributed.test.mjs b/loadtest/console/test/distributed.test.mjs
new file mode 100644
index 0000000000..4a383805ea
--- /dev/null
+++ b/loadtest/console/test/distributed.test.mjs
@@ -0,0 +1,53 @@
+import test from 'node:test';
+import assert from 'node:assert/strict';
+import {planWorkerShards} from '../server/distributed.mjs';
+import {mergeWorkerShards} from '../server/merge-shards.mjs';
+import {workerLoadConfig} from '../server/worker-artifacts.mjs';
+import {shardLoadConfig} from '../../worker/executor.mjs';
+import {DatabaseSync} from 'node:sqlite';
+import {mkdtemp,readFile,writeFile} from 'node:fs/promises';
+import os from 'node:os';
+import path from 'node:path';
+
+const now=Date.now();
+test('distributed planner selects healthy capacity and creates exact contiguous shards',()=>{
+ const workers=Array.from({length:5},(_,index)=>({id:`w${index}`,name:`worker-${index}`,status:'idle',lastSeen:index===4?now-20000:now,capacityTps:250,capacityVus:1000}));
+ const plan=planWorkerShards(1000,3000,workers,{now});
+ assert.equal(plan.length,4);assert.equal(plan.reduce((sum,item)=>sum+item.offeredTps,0),1000);
+ assert.equal(plan[0].segmentStart,0);assert.equal(plan.at(-1).segmentEnd,1);
+ plan.slice(1).forEach((item,index)=>assert.equal(item.segmentStart,plan[index].segmentEnd));
+});
+
+test('distributed planner rejects insufficient live workers',()=>{
+ assert.throws(()=>planWorkerShards(1000,1000,[{id:'w1',status:'idle',lastSeen:now,capacityTps:250,capacityVus:1000}],{now}),/250\/1000 TPS/);
+});
+test('heterogeneous shards never exceed an individual worker capacity',()=>{
+ const workers=[90,10].map((capacityTps,i)=>({id:`w${i}`,status:'idle',lastSeen:now,capacityTps,capacityVus:capacityTps*10}));
+ const plan=planWorkerShards(100,1000,workers,{now});
+ assert.deepEqual(plan.map(s=>s.offeredTps),[90,10]);
+ for(const shard of plan){const worker=workers.find(w=>w.id===shard.workerId);assert.ok(shard.offeredTps<=worker.capacityTps);assert.ok(shard.requiredVus<=worker.capacityVus);}
+});
+
+test('worker bundles contain load inputs but no fault or fixture-control credentials',()=>{
+ const config={mode:'single',services:{router:'https://router'},load:{start_rps:1,stages:[{target_rps:4,duration_seconds:60,fault:{targetId:'postgres',action:'failover'}}]},scenarios:[{name:'guest'}],payment:{amount:100},thresholds:{failed:['rate<1']},fixtures:{admin_api_key:'secret',superposition:{token:'secret'}},faultPlan:[{target:{adapter:'gcp-alloydb',project:'secret-project'}}],database:{password:'secret'}};
+ const worker=workerLoadConfig(config);assert.equal(worker.load.stages[0].target_rps,4);assert.equal(worker.load.stages[0].fault,undefined);assert.equal(worker.fixtures,undefined);assert.equal(worker.faultPlan,undefined);assert.equal(worker.database,undefined);assert.doesNotMatch(JSON.stringify(worker),/secret-project|admin_api_key|superposition/);
+});
+
+test('each worker scales the entire ramp while preserving its timing',()=>{
+ const config=shardLoadConfig({load:{start_rps:100,stages:[{target_rps:200,duration_seconds:60},{target_rps:1000,duration_seconds:120}],pre_allocated_vus_multiplier:4,max_vus_multiplier:12}},{offeredTps:250,totalTps:1000});
+ assert.equal(config.load.start_rps,25);assert.deepEqual(config.load.stages.map(stage=>stage.target_rps),[50,250]);assert.deepEqual(config.load.stages.map(stage=>stage.duration_seconds),[60,120]);
+});
+
+test('worker SQLite shards merge with unique events and exact latency percentiles',async()=>{
+ const root=await mkdtemp(path.join(os.tmpdir(),'loadtest-shards-')),schema=await readFile('../k6/scenario-mix/recorder/schema.sql','utf8'),shards=[];
+ for(let n=0;n<2;n++){
+ const directory=path.join(root,`worker-${n}`),file=path.join(directory,'results.sqlite');await import('node:fs/promises').then(fs=>fs.mkdir(directory));const db=new DatabaseSync(file);db.exec(schema);
+ db.prepare("INSERT INTO runs(run_id,recording_state,started_at,ended_at,enqueued,persisted,metadata) VALUES(?,'complete',?,?,2,2,'{}')").run(`source-${n}`,1000+n,2000+n);
+ for(let e=0;e<2;e++){const id=e+1,payment=`pay-${n}-${e}`;db.prepare("INSERT INTO request_events(event_id,run_id,attempt_id,flow_id,operation,role,observed_at,method,url,payment_id,status,api_status_code,latency_ms) VALUES(?,?,?,?,?,'measured',?,'POST','/payments',?,'succeeded',200,?)").run(id,`source-${n}`,id,`source-${n}:flow:${id}`,'payment_confirm',1100+id,payment,10+n*20+e);db.prepare("INSERT INTO payments(run_id,payment_id,role,api_status_code,observed_at,response_event_id,status) VALUES(?,?,'measured',200,?,?, 'succeeded')").run(`source-${n}`,payment,1100+id,id);}
+ db.prepare('UPDATE request_events SET server_latency_ms=? WHERE event_id=1').run(n===0?0:20);
+ db.close();const summary=path.join(directory,'summary.json');await writeFile(summary,JSON.stringify({metrics:{iterations:{type:'counter',values:{count:2}},http_req_failed:{type:'rate',values:{passes:n+1,fails:9-n},thresholds:{'rate<0.01':{ok:n===0}}}}}));shards.push({workerId:`w${n}`,database:file,summary});
+ }
+ const runPath=path.join(root,'merged');await import('node:fs/promises').then(fs=>fs.mkdir(runPath));const result=await mergeWorkerShards({runPath,runId:'canonical',shards,config:{scenarios:[{name:'flow'}]}});assert.equal(result.enqueued,4);
+ const merged=new DatabaseSync(result.database,{readOnly:true});assert.equal(merged.prepare('SELECT count(*) n FROM request_events').get().n,4);assert.equal(merged.prepare('SELECT count(*) n FROM payments').get().n,4);assert.equal(merged.prepare('SELECT run_id FROM runs').get().run_id,'canonical');merged.close();
+ const summary=JSON.parse(await readFile(result.summary,'utf8'));assert.equal(summary.metrics.iterations.values.count,4);assert.equal(summary.metrics.payment_confirm_latency_ms.values['p(99)'],31);assert.equal(summary.metrics.payment_confirm_server_latency_ms.values['p(99)'],20);assert.equal(summary.metrics.payment_confirm_server_ms_flow.values['p(99)'],20);assert.equal(summary.metrics.http_req_failed.values.rate,.15);assert.equal(summary.metrics.http_req_failed.thresholds['rate<0.01'].ok,false);
+});
diff --git a/loadtest/console/test/duration.test.mjs b/loadtest/console/test/duration.test.mjs
new file mode 100644
index 0000000000..a51d01273e
--- /dev/null
+++ b/loadtest/console/test/duration.test.mjs
@@ -0,0 +1,7 @@
+import test from 'node:test';
+import assert from 'node:assert/strict';
+import {formatDuration} from '../src/duration.mjs';
+test('scenario durations use hours, minutes and seconds as needed',()=>{
+ for(const [seconds,label] of [[0,'0 sec'],[30,'30 sec'],[60,'1 min'],[90,'1 min 30 sec'],[300,'5 min'],[3661,'1 hr 1 min 1 sec']])assert.equal(formatDuration(seconds),label);
+ assert.equal(formatDuration(-1),'—');assert.equal(formatDuration(NaN),'—');
+});
diff --git a/loadtest/console/test/environments.test.mjs b/loadtest/console/test/environments.test.mjs
new file mode 100644
index 0000000000..5958c2812b
--- /dev/null
+++ b/loadtest/console/test/environments.test.mjs
@@ -0,0 +1,94 @@
+import test from 'node:test';import assert from 'node:assert/strict';
+import {mkdtemp,readFile,writeFile} from 'node:fs/promises';import os from 'node:os';import path from 'node:path';
+import {targetEnvironment,validateTargetProvider,requireSupportedEnvironment} from '../src/environments.mjs';
+import {normalizePaymentFlows,assertSupportedPaymentFlows} from '../src/payment-flows.mjs';
+const dir=await mkdtemp(path.join(os.tmpdir(),'testbench-environments-'));process.env.LOADTEST_DATA_DIR=dir;process.env.LOADTEST_CONSOLE_ROOT=path.resolve('.');process.env.LOADTEST_ROOT=path.resolve('..');
+const seed=JSON.parse(await readFile('../loadtest.config.example.json','utf8'));seed.fixtures.admin_api_key='local-admin-secret';seed.fixtures.superposition.token='local-sp-secret';seed.output=path.join(dir,'artifacts');
+process.env.LOADTEST_CONFIG_FILE=path.join(dir,'seed.json');await writeFile(process.env.LOADTEST_CONFIG_FILE,JSON.stringify(seed));
+const state=await import('../server/state.mjs');state.initializeConfig();
+const faults=await import('../server/faults.mjs');
+test('provider identity is explicit; unsupported and mismatched adapters never execute',()=>{
+ assert.equal(targetEnvironment({adapter:'kubernetes'}),null);assert.equal(targetEnvironment({adapter:'kubernetes',environment:'cloud'}),'gcp');
+ assert.throws(()=>requireSupportedEnvironment('aws'),/execution is not supported/);assert.throws(()=>requireSupportedEnvironment('azure'),/execution is not supported/);
+ assert.throws(()=>validateTargetProvider({environment:'local',adapter:'gcp-alloydb'},'postgres'),/does not support/);
+ assert.throws(()=>faults.makeFaultAdapter({adapter:'placeholder'}),/Unsupported/);
+});
+test('provider settings round-trip independently without returning or borrowing secrets',async()=>{
+ await state.saveConnections({...state.publicSettings(),database:{...state.publicSettings().database,password:'local-db-secret'}});
+ const draft=state.publicSettings('gcp');assert.equal(draft.hasAdminApiKey,false);assert.equal(draft.database.hasPassword,false);
+ await state.saveConnections({...draft,router:'https://router.example',modularPm:'https://pm.example/v2',adminApiKey:'gcp-admin-secret',superposition:{...draft.superposition,token:'gcp-sp-secret'},database:{...draft.database,password:'gcp-db-secret'}});
+ assert.equal(state.activeEnvironment(),'gcp');assert.equal(state.publicSettings().hasAdminApiKey,true);
+ const local=state.publicSettings('local');assert.equal(local.router,seed.services.router);assert.equal(local.database.hasPassword,true);assert.equal(local.database.password,'');
+ await state.saveConnections(local);assert.equal(state.activeEnvironment(),'local');assert.equal(state.localSettings().database.password,'local-db-secret');
+ assert.equal(state.publicSettings('gcp').router,'https://router.example');assert.doesNotMatch(JSON.stringify(state.publicSettings('gcp')),/gcp-admin-secret|gcp-db-secret|local-admin-secret/);
+ assert.equal(state.redact('gcp-admin-secret local-db-secret'),'[redacted] [redacted]');
+});
+test('fault targets stay scoped; a cloud target cannot shadow the local service',async()=>{
+ const local={id:'vault',label:'Card vault',serviceType:'card-vault',adapter:'local-vault',environment:'local',port:3001,repository:'/tmp/vault'};
+ faults.saveLocalFaultTargets([local]);
+ await state.saveConnections(state.publicSettings('gcp'));
+ const cloud={id:'vault',label:'Card vault',serviceType:'card-vault',adapter:'kubernetes',environment:'gcp',namespace:'test',deployment:'vault'};
+ faults.saveLocalFaultTargets([cloud]);assert.equal(faults.faultTargets().find(t=>t.id==='vault').adapter,'kubernetes');
+ await state.saveConnections(state.publicSettings('local'));assert.equal(faults.faultTargets().find(t=>t.id==='vault').adapter,'local-vault');
+ await assert.rejects(faults.checkLocalFaultTarget(cloud),/selected environment/);
+});
+test('provider switching is blocked while a job or recovery is active',async()=>{
+ const db=state.controlDb();db.prepare("INSERT INTO jobs(id,kind,status,started_at) VALUES('busy','load','running',?)").run(Date.now());
+ await assert.rejects(state.saveConnections(state.publicSettings('gcp')),/Finish active/);assert.equal(state.activeEnvironment(),'local');db.prepare("DELETE FROM jobs WHERE id='busy'").run();
+ await writeFile(path.join(dir,'fault-ledger.json'),'{}');await assert.rejects(state.saveConnections(state.publicSettings('gcp')),/recovery/);const {unlink}=await import('node:fs/promises');await unlink(path.join(dir,'fault-ledger.json'));
+});
+test('new flow execution always uses the payment-method service and unsupported flows fail explicitly',()=>{
+ const source=[{name:'nomod_guest',scenario:'guest',merchant_path:'non_modular',weight:100}];const next=normalizePaymentFlows(source);
+ assert.equal(next[0].merchant_path,'modular');assert.equal(next[0].name,'guest');assert.equal(source[0].merchant_path,'non_modular');
+ assert.throws(()=>assertSupportedPaymentFlows([{scenario:'mit',weight:10}]),/not yet supported/);assert.doesNotThrow(()=>assertSupportedPaymentFlows(next));
+});
+test('provider filtering happens before server-target deduplication',async()=>{
+ const file=path.join(dir,'server-targets.json');const local={id:'shared',serviceType:'card-vault',label:'Vault',environment:'local',adapter:'local-vault',port:3001,repository:'/tmp/vault'};
+ const cloud={id:'shared',serviceType:'card-vault',label:'Vault',environment:'gcp',adapter:'kubernetes',namespace:'test',deployment:'vault'};
+ await writeFile(file,JSON.stringify([cloud,local]));process.env.LOADTEST_FAULT_TARGETS=file;
+ try{assert.equal(faults.faultTargets().find(t=>t.id==='shared').adapter,'local-vault');}finally{delete process.env.LOADTEST_FAULT_TARGETS;}
+});
+test('legacy presets are flattened once and unclassified targets remain inert',async()=>{
+ const local={id:'vault',serviceType:'card-vault',label:'Vault',environment:'local',adapter:'local-vault',port:3001,repository:'/tmp/vault',presets:{cloud:{adapter:'kubernetes',namespace:'legacy',deployment:'vault',environment:'cloud'}}};
+ state.controlDb().prepare("INSERT OR REPLACE INTO console_preferences VALUES('fault-targets',?)").run(JSON.stringify([local]));
+ for(let i=0;i<3;i++)faults.saveLocalFaultTargets(faults.localFaultTargets());
+ const raw=JSON.parse(state.controlDb().prepare("SELECT value FROM console_preferences WHERE key='fault-targets'").get().value);
+ assert.equal(raw.length,2);assert.ok(raw.every(t=>!t.presets));
+ const ambiguous={id:'unknown',label:'Vault',serviceType:'card-vault',adapter:'kubernetes',namespace:'legacy',deployment:'vault',environment:'custom'};
+ state.controlDb().prepare("INSERT OR REPLACE INTO console_preferences VALUES('fault-targets',?)").run(JSON.stringify([ambiguous]));
+ assert.equal(faults.localFaultTargets()[0].environment,'unassigned');assert.ok(!faults.faultTargets().some(t=>t.id==='unknown'));
+});
+test('fault confirmation rejects provider and target changes before reserving or probing',async()=>{
+ const {startFaultTest}=await import('../server/jobs.mjs');
+ const before=state.controlDb().prepare('SELECT COUNT(*) n FROM jobs').get().n;
+ await assert.rejects(startFaultTest({environment:'gcp',targetId:'vault'}),/Environment changed/);
+ assert.equal(state.controlDb().prepare('SELECT COUNT(*) n FROM jobs').get().n,before);
+ faults.saveLocalFaultTargets([{id:'vault',label:'Vault',serviceType:'card-vault',environment:'local',adapter:'local-vault',port:3001,repository:'/tmp/vault'}]);
+ const target=faults.localFaultTargets()[0];
+ await assert.rejects(faults.testFault({id:'not-started',command:'fault-test',status:'running'},{environment:'local',targetId:'vault',action:'outage',confirm:'outage vault',durationSeconds:1,expectedTarget:{...target,port:3002}},()=>{}),/target changed/);
+ assert.equal(faults.faultStatus().active,null);
+});
+test('active jobs freeze connections, while historical reconciliation requires the run provider',async()=>{
+ const db=state.controlDb();db.prepare("INSERT INTO jobs(id,kind,status,started_at) VALUES('freeze','load','running',?)").run(Date.now());
+ try{await assert.rejects(state.saveConnections({...state.publicSettings(),router:'http://127.0.0.1:9999'}),/Finish active/);}finally{db.prepare("DELETE FROM jobs WHERE id='freeze'").run();}
+ const {mkdir}=await import('node:fs/promises');const directory=path.join(state.readJsonSync(state.configPath).output,'single/runs/provider-history');await mkdir(directory,{recursive:true});await writeFile(path.join(directory,'config.json'),JSON.stringify({environment:'gcp'}));
+ const {startReconciliation}=await import('../server/jobs.mjs');await assert.rejects(startReconciliation('single:provider-history'),/Select GCP/);
+});
+
+test('stalled DB recovery permits only a verified TLS repair with no active jobs',async()=>{
+ const previous=state.publicSettings();await state.saveConnections(state.publicSettings('gcp'));
+ const before=state.publicSettings(),ledger=path.join(dir,'fault-ledger.json');
+ await writeFile(ledger,JSON.stringify({target:{adapter:'gcp-alloydb'},status:'restoring',action:'failover'}));
+ const input={...before,database:{...before.database,tlsMode:'require',password:'gcp-db-secret'}};let probes=0;
+ const options={databaseTest:async database=>{probes++;assert.equal(database.tlsMode,'require');return {ok:true};}};
+ try{
+ await assert.rejects(state.saveConnections({...input,database:{...input.database,host:'other-db'}},options),/Finish active/);
+ const db=state.controlDb();db.prepare("INSERT INTO jobs(id,kind,status,started_at) VALUES('repair-busy','load','running',?)").run(Date.now());
+ try{await assert.rejects(state.saveConnections(input,options),/Finish active/);}finally{db.prepare("DELETE FROM jobs WHERE id='repair-busy'").run();}
+ assert.equal(probes,0);
+ await assert.rejects(state.saveConnections(input,{databaseTest:async()=>({ok:false})}),/Database TLS repair could not be verified/);
+ assert.equal(state.localSettings().database.tlsMode,before.database.tlsMode);
+ await state.saveConnections(input,options);assert.equal(probes,1);assert.equal(state.localSettings().database.tlsMode,'require');
+ assert.equal(JSON.parse(await readFile(ledger,'utf8')).status,'restoring');
+ }finally{const {unlink}=await import('node:fs/promises');await unlink(ledger);await state.saveConnections(previous);}
+});
diff --git a/loadtest/console/test/fault-notice.test.mjs b/loadtest/console/test/fault-notice.test.mjs
new file mode 100644
index 0000000000..3d9756d10e
--- /dev/null
+++ b/loadtest/console/test/fault-notice.test.mjs
@@ -0,0 +1,19 @@
+import test from 'node:test';
+import assert from 'node:assert/strict';
+import {faultNotice} from '../src/fault-notice.mjs';
+
+test('DB availability updates the notice independently of cloud operation completion',()=>{
+ const active={target:'PostgreSQL',status:'restoring',databaseAvailability:'unavailable'};
+ assert.match(faultNotice({active},{live:true}),/next stage waits for recovery/);
+ const recovered=faultNotice({active:{...active,databaseAvailability:'available'}},{live:true});
+ assert.equal(recovered,'PostgreSQL · recovered · cloud operation finishing in background');
+ assert.doesNotMatch(recovered,/restoring|waits for recovery/);
+ assert.equal(faultNotice({active:null,blocked:false},{live:true}),'');
+});
+test('failed verification preserves DB availability and non-DB recovery messages',()=>{
+ assert.equal(faultNotice({active:{target:'PostgreSQL',status:'recovery_failed',databaseAvailability:'available'},blocked:true}),
+ 'PostgreSQL · DB available · failover completion not verified');
+ assert.equal(faultNotice({active:{target:'Card vault',status:'restoring'}},{live:true}),
+ 'Card vault · restoring · next stage waits for recovery');
+ assert.doesNotMatch(faultNotice({active:{target:'Card vault',status:'restoring'}},{live:true,stopping:true}),/next stage/);
+});
diff --git a/loadtest/console/test/fault-plan.test.mjs b/loadtest/console/test/fault-plan.test.mjs
new file mode 100644
index 0000000000..33ea469b9f
--- /dev/null
+++ b/loadtest/console/test/fault-plan.test.mjs
@@ -0,0 +1,32 @@
+import test from 'node:test';import assert from 'node:assert/strict';
+import {decodeStages,encodeStages} from '../src/ramp-editor.mjs';
+import {snapshotFaultPlan,faultScheduler} from '../server/fault-plan.mjs';
+const targets=[{id:'redis',serviceType:'redis',environment:'local',actions:['outage'],port:6379,adapter:'process-compose'}];
+const stages=encodeStages([{kind:'ramp',target:20,duration:2},{kind:'fault',duration:3,fault:{targetId:'redis',action:'outage'}},{kind:'hold',duration:2}],10);
+test('fault steps preserve traffic, order and hidden target identity',()=>{
+ assert.equal(stages[1].target_rps,20);assert.deepEqual(encodeStages(decodeStages(JSON.stringify(stages),10),10),stages);
+ const plan=snapshotFaultPlan({stages},targets);targets[0].port=6380;assert.equal(plan[0].target.port,6379);assert.equal(plan[0].at,2);
+ assert.throws(()=>snapshotFaultPlan({stages},[]),/Timeline stage 2: fault target “redis” is no longer configured/);
+ const invalid=structuredClone(stages);invalid[1].fault.action='failover';
+ assert.throws(()=>snapshotFaultPlan({stages:invalid},[{id:'redis',label:'Redis',actions:['outage']}]),/Timeline stage 2: Redis does not support “failover”; choose outage/);
+ const legacy=structuredClone(stages);legacy[1].fault.action='restart';assert.equal(snapshotFaultPlan({stages:legacy},targets)[0].action,'outage');
+ assert.throws(()=>snapshotFaultPlan({stages},[{id:'redis',label:'Redis',serviceType:'redis',environment:'gcp',adapter:'gcp-redis',actions:['failover']}]),/does not support/);
+ assert.throws(()=>encodeStages([{kind:'fault',duration:301,fault:{targetId:'redis',action:'outage'}}],10),/300/);
+});
+test('scheduler follows active time, fires once and never injects a missed fault late',async()=>{
+ const plan=snapshotFaultPlan({stages},targets),claimed=new Set(),calls=[],events=[],controls=[];
+ const scheduler=faultScheduler(plan,{claim:i=>{if(claimed.has(i))return false;claimed.add(i);return true;},fire:async(...args)=>calls.push(args),event:(...args)=>events.push(args),gate:async()=>controls.push('gate'),release:async()=>controls.push('release'),recover:async()=>controls.push('recover')});
+ await scheduler({loadState:'running'},1);await scheduler({loadState:'paused'},3);assert.equal(calls.length,0);
+ await scheduler({loadState:'running'},2.1);await scheduler({loadState:'running'},3);assert.equal(calls.length,1);assert.equal(calls[0][1].durationSeconds,3);
+ assert.deepEqual(controls,['gate']);
+ const lifecycle=calls[0][3];await lifecycle.onStarted();await lifecycle.onRestore();await lifecycle.onRecovered();
+ assert.deepEqual(controls,['gate','release','gate','recover']);
+ claimed.clear();await scheduler({loadState:'running'},7);assert.equal(calls.length,1);assert.match(events[0][1],/missed/);
+});
+
+test('scheduler releases a setup gate when fault activation aborts',async()=>{
+ const controls=[];
+ const scheduler=faultScheduler(snapshotFaultPlan({stages},targets),{claim:()=>true,gate:async()=>controls.push('gate'),release:async()=>controls.push('release'),recover:async end=>controls.push(['recover',end]),fire:async(_job,_input,_target,lifecycle)=>lifecycle.onAborted(),event:()=>{}});
+ await scheduler({loadState:'running'},2);
+ assert.deepEqual(controls,['gate',['recover',stages[0].duration_seconds+stages[1].duration_seconds]]);
+});
diff --git a/loadtest/console/test/fault-test-job.test.mjs b/loadtest/console/test/fault-test-job.test.mjs
new file mode 100644
index 0000000000..9360249209
--- /dev/null
+++ b/loadtest/console/test/fault-test-job.test.mjs
@@ -0,0 +1,29 @@
+import test from 'node:test';
+import assert from 'node:assert/strict';
+import {mkdtemp,realpath} from 'node:fs/promises';
+import os from 'node:os';
+import path from 'node:path';
+process.env.LOADTEST_DATA_DIR=await realpath(await mkdtemp(path.join(os.tmpdir(),'console-outage-job-')));
+const jobs=await import('../server/jobs.mjs');
+const faults=await import('../server/faults.mjs');
+const waitFor=async(predicate,{attempts=100}={})=>{for(let i=0;i<attempts;i++){if(predicate())return;await new Promise(r=>setTimeout(r,20));}throw new Error('Timed out');};
+test('standalone test persists events, excludes competing jobs, and restores early',async()=>{
+ jobs.initializeJobs();await new Promise(r=>setTimeout(r,30));
+ const job=await jobs.startFaultTest({targetId:'demo',action:'outage',durationSeconds:30,confirm:'outage demo'});
+ assert.equal(job.command,'fault-test');
+ await waitFor(()=>jobs.getJob(job.id).events.some(e=>e.kind==='fault_started'));
+ await assert.rejects(jobs.startFaultTest({targetId:'demo',action:'outage',confirm:'outage demo'}),/recovery|already/);
+ await assert.rejects(jobs.startGenerator('load','single',{}),/recovery|already/);
+ jobs.cancelJob(job.id);
+ await waitFor(()=>jobs.getJob(job.id).status==='cancelled');
+ const result=jobs.getJob(job.id);
+ assert.ok(result.events.some(e=>e.kind==='fault_restored'));
+ assert.equal(result.result.recovered,true);
+ assert.equal(faults.faultStatus().active,null);
+ await faults.saveLocalFaultTargets([{id:'unavailable',adapter:'process-compose',serviceType:'redis',port:6379,controllerPort:1,process:'r1',binary:path.join(process.env.LOADTEST_DATA_DIR,'process-compose')}]);
+ const failed=await jobs.startFaultTest({targetId:'unavailable',action:'outage',durationSeconds:1,confirm:'outage unavailable'});
+ await waitFor(()=>jobs.getJob(failed.id).status==='failed',{attempts:350});
+ assert.match(jobs.getJob(failed.id).error,/Cannot reach process-compose/);
+ assert.equal(faults.faultStatus().active,null);
+ await jobs.shutdownJobs();
+});
diff --git a/loadtest/console/test/faults.test.mjs b/loadtest/console/test/faults.test.mjs
new file mode 100644
index 0000000000..4e71bad658
--- /dev/null
+++ b/loadtest/console/test/faults.test.mjs
@@ -0,0 +1,231 @@
+import test from 'node:test';
+import assert from 'node:assert/strict';
+import {mkdtemp,writeFile,readFile,realpath} from 'node:fs/promises';
+import os from 'node:os';
+import path from 'node:path';
+const temporary=await realpath(await mkdtemp(path.join(os.tmpdir(),'loadtest-fault-test-')));
+process.env.LOADTEST_DATA_DIR=temporary;
+const {validateTargets,makeFaultAdapter,fireFault,faultStatus,restoreFaults,initializeFaults,runCommandWithTimeout}=await import('../server/faults.mjs');
+const {evaluateAcceptance}=await import('../server/acceptance.mjs');
+test('targets reject command injection and duplicate IDs',()=>{
+ assert.throws(()=>validateTargets([{id:'unsafe',adapter:'docker',container:'x; rm -rf'}]),/Invalid/);
+ assert.throws(()=>validateTargets([{id:'x',adapter:'simulated'},{id:'x',adapter:'simulated'}]),/Duplicate/);
+});
+test('Docker restore checks identity and uses fixed argv',async()=>{
+ const calls=[];let id='same';
+ const adapter=makeFaultAdapter({adapter:'docker',container:'test'},async(binary,args)=>{calls.push([binary,args]);return JSON.stringify([{Id:id,State:{Running:true,Health:{Status:'healthy'}}}]);});
+ const before=await adapter.probe();await adapter.apply('outage');assert.deepEqual(calls.at(-1),['docker',['stop','--time','30','test']]);
+ id='replacement';await assert.rejects(adapter.restore(before),/identity/);assert.equal(calls.filter(c=>c[1][0]==='start').length,0);
+ id='same';await adapter.restore(before);assert.ok(await adapter.verify(before));
+});
+test('Kubernetes recovery waits for the configured number of Ready and available replicas',async()=>{
+ const info={metadata:{uid:'one',generation:2},spec:{replicas:2},status:{availableReplicas:2,readyReplicas:1,updatedReplicas:1,observedGeneration:2}};
+ const adapter=makeFaultAdapter({adapter:'kubernetes',context:'test',namespace:'local',deployment:'router'},async()=>JSON.stringify(info));
+ const before=await adapter.probe();assert.equal(await adapter.verify(before),false);info.status.readyReplicas=2;assert.equal(await adapter.verify(before),true);
+ info.status.availableReplicas=1;assert.equal(await adapter.verify(before),false);
+ info.status.availableReplicas=2;info.status.observedGeneration=1;assert.equal(await adapter.verify(before),false);
+ info.status.observedGeneration=2;info.metadata.uid='replacement';assert.equal(await adapter.verify(before),false);
+});
+test('an available deployment can recover while a surge pod is Pending',async()=>{
+ const info={metadata:{uid:'vault',generation:60},spec:{replicas:1},status:{replicas:2,updatedReplicas:1,readyReplicas:1,availableReplicas:1,observedGeneration:60}};
+ const adapter=makeFaultAdapter({adapter:'kubernetes',namespace:'test',deployment:'vault',recoveryReplicas:1},async()=>JSON.stringify(info));
+ const before=await adapter.probe();assert.equal(await adapter.verify(before),true);
+ info.status.availableReplicas=0;info.status.readyReplicas=0;assert.equal(await adapter.verify(before),false);
+});
+test('GCP failover requires an HA target',async()=>{
+ const adapter=makeFaultAdapter({adapter:'gcp-redis',project:'test',region:'us-central1',instance:'cache'},async()=>JSON.stringify({state:'READY',tier:'BASIC'}));
+ await assert.rejects(adapter.probe(),/HA/);
+});
+test('bounded fault commands terminate after their deadline',async()=>{
+ const started=Date.now();
+ await assert.rejects(runCommandWithTimeout(25)(process.execPath,['-e','setTimeout(()=>{},1000)']),error=>error.code==='COMMAND_TIMEOUT');
+ assert.ok(Date.now()-started<500);
+});
+test('simulation is exclusive, confirmed, durable and restores on cancellation',async()=>{
+ const events=[],emit=(id,kind,message)=>events.push({id,kind,message});
+ const lifecycle=[];
+ const job={id:'safe-test',command:'load',loadState:'running'};
+ await assert.rejects(fireFault({...job,loadState:'paused'},{},emit),/running/);
+ await assert.rejects(fireFault(job,{targetId:'demo',action:'outage'},emit),/Type outage demo/);
+ await fireFault(job,{targetId:'demo',action:'outage',confirm:'outage demo',durationSeconds:30},emit,()=>job,null,{onStarted:async()=>lifecycle.push('started'),onRestore:async()=>lifecycle.push('restore'),onRecovered:async()=>lifecycle.push('recovered'),onAborted:async()=>lifecycle.push('aborted')});
+ await assert.rejects(fireFault(job,{targetId:'demo',action:'outage',confirm:'outage demo'},emit),/active/);
+ for(let n=0;n<100;n++){if(events.some(e=>e.kind==='fault_started'))break;await new Promise(r=>setTimeout(r,10));}
+ assert.equal(JSON.parse(await readFile(path.join(temporary,'fault-ledger.json'),'utf8')).status,'active');
+ await restoreFaults(emit);assert.equal(faultStatus().active,null);assert.equal(JSON.parse(await readFile(path.join(temporary,'fault-ledger.json'),'utf8')),null);
+ assert.deepEqual(lifecycle,['started','restore','recovered']);
+ assert.ok(events.some(e=>e.kind==='fault_started'&&e.message.startsWith('SIMULATED')));assert.ok(events.some(e=>e.kind==='fault_restored'));
+});
+test('startup recovers a durable simulated fault',async()=>{
+ await writeFile(path.join(temporary,'fault-ledger.json'),JSON.stringify({jobId:'old',target:{id:'demo',label:'Demo',adapter:'simulated'},action:'outage',before:{ready:true}}));
+ const events=[];await initializeFaults((id,kind)=>events.push(kind));assert.equal(faultStatus().active,null);assert.ok(events.includes('fault_restored'));
+});
+test('startup clears a rejected failover without inventing recovery or reissuing it',async()=>{
+ await writeFile(path.join(temporary,'fault-ledger.json'),JSON.stringify({jobId:'rejected',target:{id:'pg',label:'PostgreSQL',adapter:'gcp-alloydb'},action:'failover',before:{failoverRequested:true,failoverRejected:'ABORTED: recent failover'}}));
+ const events=[];await initializeFaults((id,kind)=>events.push(kind));
+ assert.equal(faultStatus().active,null);assert.equal(faultStatus().blocked,false);
+ assert.equal(JSON.parse(await readFile(path.join(temporary,'fault-ledger.json'),'utf8')),null);
+ assert.deepEqual(events,['fault_skipped']);
+});
+test('rejected scheduled failover releases the load gate and retains its error',async()=>{
+ const bin=await mkdtemp(path.join(os.tmpdir(),'rejected-failover-'));
+ await writeFile(path.join(bin,'gcloud'),`#!/bin/sh
+case "$3" in
+ describe) echo '{"createTime":"original","state":"READY","availabilityType":"REGIONAL","instanceType":"PRIMARY"}' ;;
+ failover) echo 'ERROR: (gcloud.alloydb.instances.failover) ABORTED: another failover operation was recently executed' >&2; exit 1 ;;
+ *) exit 2 ;;
+esac
+`,{mode:0o700});
+ const previous=process.env.PATH,events=[],callbacks=[];
+ try{
+ process.env.PATH=bin;
+ const job={id:'rejected-live',command:'load',loadState:'running'};
+ const target={id:'pg',label:'PostgreSQL',adapter:'gcp-alloydb',actions:['failover'],project:'test',region:'asia-south1',cluster:'payments',instance:'primary'};
+ await fireFault(job,{targetId:'pg',action:'failover',confirm:'failover pg',durationSeconds:1},(id,kind)=>events.push(kind),()=>job,target,{onAborted:async()=>callbacks.push('released'),onRestore:async()=>callbacks.push('restore'),onRecovered:async()=>callbacks.push('recovered')});
+ for(let n=0;n<300&&faultStatus().active;n++)await new Promise(resolve=>setTimeout(resolve,10));
+ assert.equal(faultStatus().active,null);assert.equal(faultStatus().blocked,false);
+ assert.deepEqual(callbacks,['released']);assert.ok(events.includes('fault_error'));assert.ok(events.includes('fault_skipped'));
+ assert.equal(events.includes('fault_restored'),false);assert.equal(events.includes('fault_started'),false);
+ }finally{process.env.PATH=previous;}
+});
+test('acceptance cannot call missing metrics or incomplete recording a pass',()=>{
+ const run={complete:true,successfulTps:10,offeredTps:10,errorRate:0,confirmP99:100,dropped:0,gaps:0};
+ assert.equal(evaluateAcceptance(run).verdict,'pass');assert.equal(evaluateAcceptance({...run,complete:false}).verdict,'incomplete');
+ assert.equal(evaluateAcceptance({...run,confirmP99:null}).verdict,'unmeasured');assert.equal(evaluateAcceptance({...run,dropped:1}).verdict,'fail');
+ assert.equal(evaluateAcceptance({...run,activity:[{kind:'fault_started',message:'SIMULATED · test'},{kind:'fault_restored'}]}).resilience,'simulated');
+ assert.equal(evaluateAcceptance({...run,activity:[{kind:'fault_error'}]}).resilience,'incomplete');
+});
+
+test('local configuration rejects invalid ports, binaries and relative repositories',()=>{
+ assert.throws(()=>validateTargets([{id:'v',adapter:'local-vault',port:3001,repository:'relative'}]),/absolute/);
+ assert.throws(()=>validateTargets([{id:'db',adapter:'process-compose',port:5432,controllerPort:8090,process:'db',binary:'/bin/sh'}]),/binary/);
+ assert.throws(()=>validateTargets([{id:'db',adapter:'process-compose',port:0,controllerPort:8090,process:'db',binary:'process-compose'}]),/port/);
+});
+test('process-compose stops only the named process and restores it; array JSON supported',async()=>{
+ const {localAdapter}=await import('../server/local-faults.mjs');const calls=[];let status='Running',listening=true;
+ const adapter=localAdapter({adapter:'process-compose',binary:'process-compose',controllerPort:8090,port:5432,process:'p1'},async(binary,args)=>{calls.push([binary,args]);if(args.includes('list'))return JSON.stringify([{name:'p1',status},{name:'keeper',status:'Running'}]);if(args.includes('get'))return JSON.stringify([{name:'p1',namespace:'default',status}]);if(args.includes('stop')){status='Stopped';listening=false;}if(args.includes('start')){status='Running';listening=true;}return '';},{reachable:async()=>listening});
+ const before=await adapter.probe();await adapter.apply('outage',before);assert.ok(await adapter.isDown(before));assert.deepEqual(calls.find(c=>c[1].includes('stop')),['process-compose',['-p','8090','process','-a','127.0.0.1','stop','p1']]);await adapter.restore(before);assert.ok(await adapter.verify(before));
+ await assert.rejects(adapter.apply('outage',{identity:{name:'different'}}),/identity changed/);
+});
+test('process-compose controller API works without a CLI binary on PATH',async()=>{
+ const {localAdapter,processComposeController}=await import('../server/local-faults.mjs');
+ const target={adapter:'process-compose',binary:'process-compose',controllerPort:8090,port:6379,process:'r1'};
+ let status='Running',listening=true;const requests=[];
+ const request=async(url,options={})=>{const pathname=new URL(url).pathname,method=options.method||'GET';requests.push([method,pathname]);if(pathname==='/process/r1'&&method==='GET')return Response.json({name:'r1',namespace:'redis.r1',status});if(pathname==='/processes')return Response.json({data:[{name:'r1',status},{name:'keeper',status:'Running'}]});if(pathname==='/process/stop/r1'&&method==='PATCH'){status='Stopped';listening=false;return Response.json({r1:'stopped'});}if(pathname==='/process/start/r1'&&method==='POST'){status='Running';listening=true;return Response.json({r1:'started'});}return new Response('missing',{status:404});};
+ const adapter=localAdapter(target,async()=>{throw new Error('CLI must not run');},{controller:processComposeController(target,request),reachable:async()=>listening});
+ const before=await adapter.probe();await adapter.apply('outage',before);assert.ok(await adapter.isDown(before));await adapter.restore(before);assert.ok(await adapter.verify(before));
+ assert.deepEqual(requests.filter(([,pathname])=>pathname.includes('/stop/')||pathname.includes('/start/')),[['PATCH','/process/stop/r1'],['POST','/process/start/r1']]);
+});
+test('process-compose controller errors identify the endpoint and missing process',async()=>{
+ const {processComposeController}=await import('../server/local-faults.mjs');
+ const target={controllerPort:8090,process:'missing'};
+ await assert.rejects(processComposeController(target,async()=>{throw Object.assign(new Error('refused'),{cause:{code:'ECONNREFUSED'}});}).inspect(),/127\.0\.0\.1:8090: ECONNREFUSED/);
+ await assert.rejects(processComposeController(target,async()=>new Response('not found',{status:404})).inspect(),/Process missing is not configured/);
+});
+test('vault checks identity before signalling and recovers through its launcher',async()=>{
+ const {localAdapter}=await import('../server/local-faults.mjs');let pid=1234,listening=true,launches=0,kills=0;
+ const adapter=localAdapter({id:'vault',adapter:'local-vault',repository:temporary,port:3001},async(binary,args)=>binary==='lsof'?(args.includes('-t')?`${pid}\n`:`fcwd\nn${temporary}\nftxt\nn${temporary}/target/debug/locker\n`):'start-time',{reachable:async()=>listening,kill:()=>{kills++;listening=false;},launch:async()=>{launches++;listening=true;}});
+ const before=await adapter.probe();pid=2345;await assert.rejects(adapter.apply('outage',before),/identity changed/);assert.equal(kills,0);
+ pid=1234;await adapter.apply('outage',before);assert.equal(kills,1);assert.ok(await adapter.isDown());await adapter.restore(before);assert.equal(launches,1);await adapter.restore(before);assert.equal(launches,1);assert.ok(await adapter.verify());
+});
+test('local targets persist and remain separate from server-defined targets',async()=>{
+ const {saveLocalFaultTargets,localFaultTargets,faultTargets}=await import('../server/faults.mjs');
+ const targets=[{id:'vault-test',adapter:'local-vault',port:3001,repository:temporary}];await saveLocalFaultTargets(targets);assert.equal(localFaultTargets()[0].id,'vault-test');assert.ok(faultTargets().some(t=>t.id==='demo'));await saveLocalFaultTargets([]);
+});
+test('process-compose refuses to stop its last running process and restore is idempotent',async()=>{
+ const {localAdapter}=await import('../server/local-faults.mjs');const calls=[],info={name:'only',namespace:'default',status:'Running'};
+ const adapter=localAdapter({adapter:'process-compose',binary:'process-compose',controllerPort:8090,port:5432,process:'only'},async(b,args)=>{calls.push(args);return JSON.stringify([info]);},{reachable:async()=>true});
+ const before=await adapter.probe();await assert.rejects(adapter.apply('outage',before),/another running process/);await adapter.restore(before);assert.equal(calls.some(args=>args.includes('stop')||args.includes('start')),false);
+});
+test('one local target per service type, regardless of ID, label or port',()=>{
+ const vault={id:'vault',adapter:'local-vault',repository:temporary,port:3001};
+ const db={id:'db',adapter:'process-compose',serviceType:'postgres',binary:'process-compose',controllerPort:8090,process:'p1',port:5432};
+ assert.throws(()=>validateTargets([vault,{...vault,id:'other',port:3002}]),/Only one card-vault/);
+ assert.throws(()=>validateTargets([db,{...db,id:'other',label:'Renamed',port:5555}]),/Only one postgres/);
+ const redis={...db,id:'redis',serviceType:'redis',process:'r1',port:6379};
+ assert.throws(()=>validateTargets([redis,{...redis,id:'redis-two'}]),/Only one redis/);
+ assert.equal(validateTargets([vault,db,redis]).length,3);
+ assert.equal(validateTargets([{...redis,serviceType:undefined}])[0].serviceType,'redis');
+ assert.throws(()=>validateTargets([{...db,serviceType:'card-vault'}]),/Invalid fault service type/);
+});
+
+test('vault recovery resolves an executable Nix before stopping a service',async()=>{
+ const {nixExecutable}=await import('../server/local-faults.mjs');
+ const bin=await mkdtemp(path.join(os.tmpdir(),'loadtest-nix-test-'));await writeFile(path.join(bin,'nix'),'#!/bin/sh\nexit 0\n',{mode:0o700});
+ const previous=process.env.PATH;try{process.env.PATH=bin;assert.equal(await nixExecutable(),path.join(bin,'nix'));}finally{process.env.PATH=previous;}
+});
+test('vault without a flake uses its existing executable and rejects unrecoverable targets',async()=>{
+ const {vaultLaunchSpec}=await import('../server/local-faults.mjs');
+ const {mkdir}=await import('node:fs/promises');
+ const repository=await mkdtemp(path.join(os.tmpdir(),'vault-launch-'));
+ await writeFile(path.join(repository,'Cargo.toml'),'[package]');
+ await assert.rejects(vaultLaunchSpec({repository}),/Build the vault/);
+ await mkdir(path.join(repository,'target','debug'),{recursive:true});
+ const binary=path.join(repository,'target','debug','locker');await writeFile(binary,'#!/bin/sh\nexit 0\n',{mode:0o700});
+ assert.deepEqual(await vaultLaunchSpec({repository}),{binary,args:[]});
+});
+
+test('cloud presets persist, reject duplicates and invoke managed AlloyDB failover with fixed argv',async()=>{
+ const {configureFaultTarget,faultEnvironment}=await import('../src/fault-types.mjs');
+ const {saveLocalFaultTargets,localFaultTargets}=await import('../server/faults.mjs');
+ const target=configureFaultTarget({id:'postgres',serviceType:'postgres',label:'PostgreSQL',project:'hyperswitch-dev',region:'asia-south1',cluster:'dev-hyperswitch-alloydb',instance:'dev-hyperswitch-alloydb-primary'},'gcp');
+ const state=await import('../server/state.mjs');const previous=state.publicSettings();await state.saveConnections(state.publicSettings('gcp'));
+ assert.equal(faultEnvironment(target),'gcp');
+ await saveLocalFaultTargets([target]);
+ assert.equal(localFaultTargets()[0].actions[0],'failover');
+ assert.equal(localFaultTargets()[0].instance,'dev-hyperswitch-alloydb-primary');
+ const local=configureFaultTarget({...target,id:'other'},'local');
+ assert.throws(()=>validateTargets([target,local]),/Only one postgres/);
+ assert.throws(()=>validateTargets([{...target,project:'x;echo bad'}]),/Invalid/);
+ assert.throws(()=>validateTargets([{...target,serviceType:'redis'}]),/does not match/);
+ const calls=[];const info={createTime:'original',state:'READY',availabilityType:'REGIONAL',instanceType:'PRIMARY'};
+ const operation={name:'projects/hyperswitch-dev/locations/asia-south1/operations/operation-123',done:true,metadata:{verb:'failover',target:'projects/hyperswitch-dev/locations/asia-south1/clusters/dev-hyperswitch-alloydb/instances/dev-hyperswitch-alloydb-primary'}};
+ const adapter=makeFaultAdapter(target,async(binary,args)=>{calls.push([binary,args]);return JSON.stringify(args.includes('operations')||args.includes('failover')?operation:info);},{databaseCheck:async()=>({ok:true})});
+ const before=await adapter.probe();assert.ok(calls.every(c=>c[1].includes('describe')));
+ await adapter.apply('failover',before);
+ assert.deepEqual(calls.at(-1),['gcloud',['alloydb','instances','failover','dev-hyperswitch-alloydb-primary','--project','hyperswitch-dev','--region','asia-south1','--cluster','dev-hyperswitch-alloydb','--quiet','--async','--format=json']]);
+ info.state='MAINTENANCE';assert.equal(await adapter.verify(before),false);
+ info.state='READY';assert.equal(await adapter.verify(before),true);
+ info.createTime='replacement';assert.equal(await adapter.verify(before),false);
+ await saveLocalFaultTargets([]);await state.saveConnections(previous);
+});
+
+test('switching environments retains local values and custom target configuration',async()=>{
+ const {configureFaultTarget,faultEnvironment}=await import('../src/fault-types.mjs');
+ const original={id:'db',serviceType:'postgres',adapter:'process-compose',port:5555,process:'mydb',controllerPort:8091,binary:'process-compose'};
+ const cloud=configureFaultTarget(original,'cloud');
+ const custom=configureFaultTarget({...cloud,container:'db-test'},'aws');
+ assert.equal(custom.adapter,'placeholder');assert.equal(faultEnvironment(custom),'aws');
+ assert.deepEqual(validateTargets([custom])[0].actions,[]);
+ const local=configureFaultTarget(custom,'local');
+ assert.equal(local.port,5555);assert.equal(local.process,'mydb');assert.equal(local.controllerPort,8091);
+});
+
+test('explicit graceful cloud vault interruption preserves recovery replica configuration',async()=>{
+ const {configureFaultTarget}=await import('../src/fault-types.mjs');
+ const target=configureFaultTarget({id:'vault',serviceType:'card-vault',outageMode:'graceful',namespace:'hyperswitch',deployment:'hyperswitch-card-vault-hyperswitch-card-vault',recoveryReplicas:8},'gcp');
+ assert.equal(target.namespace,'hyperswitch');
+ assert.equal(target.deployment,'hyperswitch-card-vault-hyperswitch-card-vault');
+ assert.deepEqual(validateTargets([target])[0].actions,['outage']);
+ const calls=[],info={metadata:{uid:'vault',generation:1},spec:{replicas:3},status:{availableReplicas:3,updatedReplicas:3,observedGeneration:1}};
+ const adapter=makeFaultAdapter(target,async(binary,args)=>{calls.push([binary,args]);return JSON.stringify(info);});
+ const before=await adapter.probe();await adapter.apply('outage',before);
+ assert.deepEqual(calls.at(-1),['kubectl',['--namespace','hyperswitch','scale','deployment',target.deployment,'--replicas=0']]);
+ await adapter.restore(before);
+ assert.deepEqual(calls.at(-1),['kubectl',['--namespace','hyperswitch','scale','deployment',target.deployment,'--replicas=8']]);
+ const custom=configureFaultTarget({...target,namespace:'other',deployment:'custom-vault'},'cloud');
+ assert.equal(custom.namespace,'other');assert.equal(custom.deployment,'custom-vault');
+});
+
+test('new GCP targets require resource configuration instead of hardcoded defaults',async()=>{
+ const {configureFaultTarget}=await import('../src/fault-types.mjs');
+ const target=configureFaultTarget({id:'vault',serviceType:'card-vault',label:'Card vault'},'gcp');
+ assert.equal(target.namespace,'');assert.equal(target.deployment,'');assert.equal(target.recoveryReplicas,1);
+ assert.throws(()=>validateTargets([target]),/Invalid fault target/);
+});
+
+test('Kubernetes card-vault defaults to a snapshotted hard outage with an accurate command preview',async()=>{
+ const {faultCommandPreview}=await import('../src/fault-types.mjs');
+ const [target]=validateTargets([{id:'vault',serviceType:'card-vault',environment:'gcp',adapter:'kubernetes',namespace:'payments',deployment:'vault'}]);
+ assert.equal(target.outageMode,'hard');assert.match(faultCommandPreview(target),/--grace-period=0 --force/);assert.match(faultCommandPreview(target),/kubelet runtime/);
+ assert.throws(()=>validateTargets([{...target,outageMode:'arbitrary-command'}]),/outage mode/);
+});
diff --git a/loadtest/console/test/fixture-import.test.mjs b/loadtest/console/test/fixture-import.test.mjs
new file mode 100644
index 0000000000..d82d28293d
--- /dev/null
+++ b/loadtest/console/test/fixture-import.test.mjs
@@ -0,0 +1,26 @@
+import test from 'node:test';import assert from 'node:assert/strict';
+import {fixtureRequirements,normalizeImportedMerchants,verifyImportedMerchants,importFingerprint} from '../server/fixture-import.mjs';
+const config={environment:'local',services:{router:'http://router',modular_pm:'http://pm/v2'},fixtures:{admin_api_key:'admin'},scenarios:[{scenario:'guest_payment',merchant_path:'modular',weight:100}],connectors:{mode:'real',mix:[{connector:'stripe',weight:100}]}};
+const merchant={merchant_id:'merchant_1',profile_id:'pro_1',api_key:'secret-one',publishable_key:'pk_1',connector_accounts:{stripe:'mca_1'}};
+const account={merchant_connector_id:'mca_1',connector_name:'stripe',profile_id:'pro_1',disabled:false,payment_methods_enabled:[{payment_method:'card',payment_method_types:[{payment_method_type:'credit',recurring_enabled:true}]}]};
+function fetcher({connector=account,key='secret-one',pk='pk_1',profile='pro_1'}={}){return async(url,options)=>{
+ assert.equal(options.redirect,'manual');
+ if(url.endsWith('/connectors'))return options.headers['api-key']===key?Response.json([connector]):Response.json({error:'secret response MUST NOT escape'},{status:401});
+ if(url.includes('/business_profile/')){assert.equal(options.headers['api-key'],'secret-one');return Response.json({merchant_id:'merchant_1',profile_id:profile});}
+ return Response.json({merchant_id:'merchant_1',publishable_key:pk});
+};}
+test('valid imported merchant verifies read-only keys, profile and selected connector',async()=>{const result=await verifyImportedMerchants(config,[merchant],{fetcher:fetcher()});assert.equal(result.ok,true);assert.equal(result.checks.length,4);assert.ok(!JSON.stringify(result).includes('secret-one'));});
+test('rejected API key and connector setup have separate actionable results without raw bodies',async()=>{const result=await verifyImportedMerchants(config,[merchant],{fetcher:fetcher({key:'other'})});assert.equal(result.ok,false);assert.match(result.checks[0].message,/401/);assert.ok(result.checks.every(c=>c.stage==='credentials'));assert.equal(result.stages.setup.status,'blocked');assert.ok(!JSON.stringify(result).includes('MUST NOT escape'));});
+test('wrong publishable key, wrong profile and disabled connector fail independently',async()=>{const result=await verifyImportedMerchants(config,[merchant],{fetcher:fetcher({pk:'other',profile:'pro_other',connector:{...account,disabled:true}})});assert.equal(result.checks.filter(c=>!c.ok).length,2);});
+test('connector account must match selected connector, profile, and enabled card configuration',async()=>{for(const changed of [{connector_name:'adyen'},{profile_id:'other'},{payment_methods_enabled:[]}]){const result=await verifyImportedMerchants(config,[merchant],{fetcher:fetcher({connector:{...account,...changed}})});assert.equal(result.checks.at(-1).ok,false);}});
+test('import validates count, identities, duplicates and secrets; required publishable key is flow-dependent',()=>{assert.equal(normalizeImportedMerchants([merchant],1).length,1);assert.throws(()=>normalizeImportedMerchants([merchant],2),/exactly/);assert.throws(()=>normalizeImportedMerchants([merchant,merchant],2),/duplicate/);assert.throws(()=>normalizeImportedMerchants([{...merchant,api_key:'bad\nkey'}],1),/invalid/);assert.equal(fixtureRequirements(config).publishableKey,true);assert.equal(fixtureRequirements({...config,scenarios:[{scenario:'guest_payment',merchant_path:'legacy',weight:100}]}).publishableKey,false);});
+test('verification fingerprint changes with credentials, destination and scenario requirements',()=>{const first=importFingerprint(config,[merchant]);for(const changed of [{...config,services:{...config.services,router:'http://other'}},{...config,environment:'gcp'},{...config,connectors:{mode:'real',mix:[{connector:'adyen',weight:100}]}}])assert.notEqual(importFingerprint(changed,[merchant]),first);assert.notEqual(importFingerprint(config,[{...merchant,api_key:'rotated'}]),first);});
+test('aborted verification does not continue inspecting merchants',async()=>{const abort=new AbortController();abort.abort();await assert.rejects(verifyImportedMerchants(config,[merchant],{fetcher:fetcher(),signal:abort.signal}),/abort/i);});
+
+test('recurring capability is required only for flows that need it',async()=>{const connector={...account,payment_methods_enabled:[{payment_method:'card',payment_method_types:[{payment_method_type:'credit',recurring_enabled:false}]}]};assert.equal((await verifyImportedMerchants(config,[merchant],{fetcher:fetcher({connector})})).ok,true);assert.equal((await verifyImportedMerchants({...config,scenarios:[{scenario:'cit_off_session',merchant_path:'modular',weight:100}]},[merchant],{fetcher:fetcher({connector})})).checks.at(-1).ok,false);});
+
+test('bulk verification bounds concurrent inspections to four merchants',async()=>{let active=0,peak=0;const rows=Array.from({length:8},(_,i)=>({...merchant,merchant_id:`merchant_${i}`}));const result=await verifyImportedMerchants(config,rows,{fetcher:async(url,options)=>{active++;peak=Math.max(peak,active);await new Promise(r=>setTimeout(r,2));active--;const mid=url.match(/(?:account|accounts)\/(merchant_\d+)/)?.[1];if(url.endsWith('/connectors'))return Response.json([account]);if(url.includes('/business_profile/'))return Response.json({merchant_id:mid,profile_id:'pro_1'});return Response.json({merchant_id:mid,publishable_key:'pk_1'});}});assert.equal(result.ok,true);assert.equal(result.checks.length,32);assert.ok(peak>1&&peak<=4);});
+
+test('progress reports real ordered credential and setup stages with completed counts',async()=>{const updates=[];await verifyImportedMerchants(config,[merchant],{fetcher:fetcher(),onProgress:(checks,state)=>updates.push(structuredClone(state))});assert.equal(updates[0].phase,'credentials');const setup=updates.find(v=>v.phase==='setup');assert.equal(setup.stages.credentials.status,'passed');assert.equal(setup.stages.credentials.completed,3);assert.equal(setup.stages.setup.completed,0);assert.equal(updates.at(-1).phase,'saving');assert.equal(updates.at(-1).stages.setup.completed,1);});
+test('credential failure blocks connector validation for the entire import',async()=>{const result=await verifyImportedMerchants(config,[merchant],{fetcher:fetcher({pk:'wrong'})});assert.equal(result.phase,'failed');assert.equal(result.stages.setup.status,'blocked');assert.equal(result.stages.setup.completed,0);assert.ok(result.checks.every(c=>c.stage==='credentials'));});
+test('cancellation at stage transition never runs connector validation',async()=>{const abort=new AbortController();await assert.rejects(verifyImportedMerchants(config,[merchant],{fetcher:fetcher(),signal:abort.signal,onProgress:(_,state)=>{if(state.phase==='setup')abort.abort();}}),/abort/i);});
diff --git a/loadtest/console/test/grafana-isolation.test.mjs b/loadtest/console/test/grafana-isolation.test.mjs
new file mode 100644
index 0000000000..54a743e16f
--- /dev/null
+++ b/loadtest/console/test/grafana-isolation.test.mjs
@@ -0,0 +1,38 @@
+import test from 'node:test';
+import assert from 'node:assert/strict';
+import {mkdtemp} from 'node:fs/promises';
+import os from 'node:os';
+import path from 'node:path';
+import {createServer} from 'node:http';
+process.env.LOADTEST_DATA_DIR=await mkdtemp(path.join(os.tmpdir(),'grafana-isolation-'));
+process.env.ORIGIN='http://127.0.0.1:4174';process.env.GRAFANA_EMBED_ORIGIN='http://127.0.0.1:4176';
+const state=await import('../server/state.mjs');state.initializeConfig();
+const auth=await import('../server/auth.mjs');
+const {createGrafanaEmbed,grafanaEmbedRequest}=await import('../server/grafana-embed.mjs');
+test('active Grafana content is isolated with one-time tickets and revocable sessions',async()=>{
+ let headers,hits=0;
+ const upstream=createServer((req,res)=>{hits++;headers=req.headers;if(req.url==='/api/health'){res.setHeader('content-type','application/json');res.end('{"database":"ok"}');}else{res.setHeader('content-type','text/html');res.end('<script>/* untrusted upstream */</script>');}});
+ await new Promise(r=>upstream.listen(0,'127.0.0.1',r));
+ try{
+ process.env.GRAFANA_URL=`http://127.0.0.1:${upstream.address().port}`;process.env.GRAFANA_TOKEN='fake-viewer-token';
+ await state.atomicJson(state.localPath,{grafana:{baseUrl:process.env.GRAFANA_URL}});
+ process.env.ADMIN_PASSWORD_HASH=await auth.passwordHash('fake-test-password');
+ const session=await auth.login('admin','fake-test-password','grafana-test');
+ const {url}=createGrafanaEmbed(session,'/grafana/d-solo/test/panel?panelId=1');
+ assert.notEqual(new URL(url).origin,process.env.ORIGIN);
+ const handshake=await grafanaEmbedRequest(new Request(url));assert.equal(handshake.status,303);
+ assert.equal((await grafanaEmbedRequest(new Request(url))).status,401,'ticket cannot be replayed');
+ const cookie=handshake.headers.get('set-cookie').split(';')[0],panel=new URL(handshake.headers.get('location'),url);
+ assert.equal((await grafanaEmbedRequest(new Request(panel,{headers:{cookie:`loadtest_grafana=${new URL(url).searchParams.get('embed_ticket')}`}}))).status,401,'redeemed URL ticket is not a session credential');
+ assert.match(handshake.headers.get('set-cookie'),/HttpOnly/);assert.equal(handshake.headers.get('referrer-policy'),'no-referrer');
+ const response=await grafanaEmbedRequest(new Request(panel,{headers:{cookie}}));
+ assert.equal(response.status,200);assert.match(await response.text(),/untrusted upstream/);
+ assert.equal(headers.authorization,'Bearer fake-viewer-token');assert.equal(headers.cookie,undefined);
+ assert.equal((await grafanaEmbedRequest(new Request(new URL('/api/settings',panel),{headers:{cookie}}))).status,404);
+ assert.equal((await grafanaEmbedRequest(new Request(new URL('/grafana/api/ds/query',panel),{method:'POST',headers:{cookie,origin:process.env.ORIGIN},body:'{}'}))).status,403);
+ const main=await import('../src/routes/grafana/[...path]/+server.js');assert.equal((await main.GET()).status,403);
+ await state.atomicJson(state.localPath,{grafana:{baseUrl:'https://replacement.invalid'}});
+ const before=hits;assert.equal((await grafanaEmbedRequest(new Request(panel,{headers:{cookie}}))).status,403);assert.equal(hits,before,'saved token cannot follow another origin');
+ auth.logout(session);assert.equal((await grafanaEmbedRequest(new Request(panel,{headers:{cookie}}))).status,401);
+ }finally{upstream.closeAllConnections();await new Promise(r=>upstream.close(r));}
+});
diff --git a/loadtest/console/test/grafana-panels.test.mjs b/loadtest/console/test/grafana-panels.test.mjs
new file mode 100644
index 0000000000..479bc8e498
--- /dev/null
+++ b/loadtest/console/test/grafana-panels.test.mjs
@@ -0,0 +1,27 @@
+import test from 'node:test';
+import assert from 'node:assert/strict';
+import {unifiedPerformancePanels} from '../src/grafana-panels.mjs';
+import {pausedChartSamples} from '../src/chart-timeline.mjs';
+test('requested Grafana panels use the selected run range and Router-only filtering',()=>{
+ const panels=unifiedPerformancePanels({startedAt:1000,endedAt:301000});
+ assert.deepEqual(panels.map(p=>new URL(p.url,'http://console').searchParams.get('panelId')),['4','2','3']);
+ for(const p of panels){const u=new URL(p.url,'http://console');assert.ok(u.pathname.startsWith('/grafana/d-solo/'));assert.equal(u.searchParams.get('from'),'1000');assert.equal(u.searchParams.get('to'),'301000');assert.equal(u.searchParams.get('var-app'),'hyperswitch-router-hyperswitch-server');assert.equal(u.searchParams.has('refresh'),false);}
+});
+test('paused cards and native charts stop at zero throughput and resume with live data',()=>{
+ const telemetry=[{t:10,state:'running',successfulTps:5},{t:11,state:'paused',successfulTps:1,inFlight:0},{t:12,state:'paused',successfulTps:0,inFlight:0},{t:30,state:'paused',successfulTps:0,inFlight:0}];
+ assert.equal(pausedChartSamples(telemetry,'paused').at(-1).t,12);
+ assert.equal(pausedChartSamples(telemetry,'running').at(-1).t,30);
+ const run={startedAt:1000,loadState:'paused',telemetry};
+ const before=unifiedPerformancePanels(run),later=unifiedPerformancePanels({...run,telemetry:[...telemetry,{t:40,state:'paused',successfulTps:0,inFlight:0}]});
+ assert.deepEqual(before,later);
+ const url=new URL(before[0].url,'http://console');assert.equal(url.searchParams.get('to'),'13000');assert.equal(url.searchParams.has('refresh'),false);
+ const resumed=new URL(unifiedPerformancePanels({...run,loadState:'running'})[0].url,'http://console');assert.equal(resumed.searchParams.get('to'),'now');assert.equal(resumed.searchParams.get('refresh'),'1s');
+});
+test('live panels refresh without changing iframe URLs on every progress update',()=>{
+ const run={startedAt:1000};
+ const panels=unifiedPerformancePanels(run);
+ assert.equal(new URL(panels[0].url,'http://console').searchParams.get('to'),'now');
+ assert.equal(new URL(panels[0].url,'http://console').searchParams.get('refresh'),'1s');
+ assert.deepEqual(unifiedPerformancePanels({...run,iterations:100}),panels);
+ assert.deepEqual(unifiedPerformancePanels(null),[]);
+});
diff --git a/loadtest/console/test/http.test.mjs b/loadtest/console/test/http.test.mjs
new file mode 100644
index 0000000000..dd2a7237e2
--- /dev/null
+++ b/loadtest/console/test/http.test.mjs
@@ -0,0 +1,240 @@
+import test from 'node:test';
+import {scenarioChecksVersion} from '../server/scenario-checks.mjs';
+import assert from 'node:assert/strict';
+import { mkdtemp,readFile,writeFile } from 'node:fs/promises';
+import os from 'node:os';
+import path from 'node:path';
+import { spawn } from 'node:child_process';
+import { createServer } from 'node:http';
+import { once } from 'node:events';
+import { passwordHash } from '../server/auth.mjs';
+import { mockServer } from '../../k6/scenario-mix/test/mock-server.mjs';
+
+const wait=ms=>new Promise(resolve=>setTimeout(resolve,ms));
+test('SSR, authentication, Grafana proxy, jobs, SSE, cancellation and restart',async()=>{
+ const temporary=await mkdtemp(path.join(os.tmpdir(),'loadtest-console-http-'));
+ const target=await mockServer({listPolls:0,baselinePolls:0});
+ let lastHeaders;
+ let lastGrafanaPath;
+ const grafana=createServer((req,res)=>{
+ lastHeaders=req.headers;lastGrafanaPath=req.url;
+ if(req.url==='/api/health'){res.setHeader('content-type','application/json');res.end('{"database":"ok","version":"12"}');return;}
+ res.setHeader('content-type','text/html');res.end('<base href="/"><script>window.grafanaBootData={"appSubUrl":"","appUrl":"http://upstream/"}</script><script src="public/build/runtime.js"></script>');
+ });
+ grafana.listen(0,'127.0.0.1');await once(grafana,'listening');
+ const port=39000+Math.floor(Math.random()*1000),origin=`http://127.0.0.1:${port}`;
+ const config=JSON.parse(await readFile('../loadtest.config.example.json','utf8'));
+ config.output=path.join(temporary,'artifacts');config.services={router:target.url,modular_pm:`${target.url}/v2`};
+ config.fixtures.router=target.url;config.fixtures.admin_api_key='mock-private-admin';
+ config.fixtures.superposition={endpoint:target.url,token:'mock-sp-token',organization_id:'org',workspace_id:'dev',refresh_interval_seconds:0,defaults:{flag:true}};
+ config.load={...config.load,total_rps:10,duration_seconds:6};
+ const seed=path.join(temporary,'seed.json');await writeFile(seed,JSON.stringify(config));
+ const env={...process.env,HOST:'127.0.0.1',PORT:String(port),ORIGIN:origin,LOADTEST_DATA_DIR:temporary,
+ LOADTEST_CONFIG_FILE:seed,ADMIN_PASSWORD_HASH:await passwordHash('console test password'),ADMIN_USERNAME:'admin',
+ GRAFANA_URL:`http://127.0.0.1:${grafana.address().port}`,GRAFANA_TOKEN:'secret-grafana-test',NODE_ENV:'production'};
+ let server,output='',cookie;
+ function launch(){server=spawn(process.execPath,['start.mjs'],{cwd:path.resolve('.'),env,stdio:['ignore','pipe','pipe']});server.stdout.on('data',d=>output+=d);server.stderr.on('data',d=>output+=d);}
+ async function ready(){for(let i=0;i<100;i++){try{if((await fetch(origin+'/health')).ok)return;}catch{}await wait(100);}throw Error(output);}
+ async function request(url,method='GET',body=null,useCookie=true,customHeaders={}){
+ return fetch(origin+url,{method,redirect:'manual',headers:{...(useCookie&&cookie?{cookie}:{}),origin,...(body?{'content-type':'application/json'}:{}),...customHeaders},...(body?{body:JSON.stringify(body)}:{})});
+ }
+ async function completed(id){for(let i=0;i<400;i++){const job=await (await request(`/api/jobs/${id}`)).json();if(!['starting','running','pausing','paused','cancelling'].includes(job.status))return job;await wait(100);}throw Error('Job timed out');}
+ try {
+ launch();await ready();
+ assert.equal((await request('/api/settings','GET',null,false)).status,401);
+ assert.equal((await request('/api/faults/targets','GET',null,false)).status,401);
+ assert.equal((await request('/grafana/d-solo/k6/test','GET',null,false)).status,401);
+ assert.equal((await request('/')).status,303);
+ const response=await fetch(origin+'/login',{method:'POST',redirect:'manual',headers:{origin,accept:'text/html'},body:new URLSearchParams({username:'admin',password:'console test password'})});
+ assert.equal(response.status,303);cookie=response.headers.get('set-cookie').split(';')[0];assert.match(response.headers.get('set-cookie'),/HttpOnly/);
+ assert.equal((await request('/')).status,303);
+ const page=await request('/scenarios');assert.equal(page.status,200);const libraryHtml=await page.text();assert.match(libraryHtml,/Build traffic patterns and resilience tests/);assert.doesNotMatch(libraryHtml,/>Unavailable<|<p[^>]*>Requires GCP database failover/);assert.match(libraryHtml,/environment-label[^>]*>Local</);
+ const builtIns=(await (await request('/api/profiles')).json()).filter(p=>p.isDefault);
+ assert.deepEqual(builtIns.map(p=>p.id).sort(),['default:card-vault-outage','default:db-failover','default:ramped-load','default:steady-load','default:tenancy-steady-load']);
+ for(const builtIn of builtIns){
+ const endpoint=`/api/profiles/${encodeURIComponent(builtIn.id)}`;
+ assert.equal((await request(endpoint,'PUT',{...builtIn,name:'Changed'})).status,403);
+ assert.equal((await request(endpoint,'DELETE')).status,403);
+ assert.equal((await request(endpoint+'/archive','PUT',{archived:true})).status,403);
+ }
+ const locked=await request('/scenarios?view=edit&profile=default%3Asteady-load');assert.match(await locked.text(),/Save as new scenario/);
+ const copyResponse=await request('/api/scenarios/save','POST',{profile:{...builtIns.find(p=>p.id==='default:steady-load'),totalRps:7}});assert.equal(copyResponse.status,200,await copyResponse.clone().text());
+ const copied=(await copyResponse.json()).profile;assert.notEqual(copied.id,'default:steady-load');assert.equal(copied.totalRps,7);assert.equal(copied.isDefault,undefined);
+ assert.equal((await (await request('/api/profiles/default%3Asteady-load')).json()).totalRps,5);
+ assert.equal((await request(`/api/profiles/${copied.id}`,'DELETE')).status,200);
+ const unavailable=await request('/api/runs','POST',{mode:'single',profileId:'default:db-failover'});assert.equal(unavailable.status,409);
+ let initialProfile=(await (await request('/api/profiles')).json()).find(p=>!p.isDefault);
+ if(!initialProfile){
+ const draft=await (await request('/api/settings')).json();
+ initialProfile=await (await request('/api/profiles','POST',{...draft,name:'Initial HTTP scenario',merchantCount:1})).json();
+ }
+ const editor=await request(`/scenarios?view=edit&profile=${initialProfile.id}`);assert.equal(editor.status,200);assert.match(await editor.text(),/100% allocated/);
+ assert.match(await (await request(`/scenarios?view=edit&profile=${initialProfile.id}`)).text(),/Fault targets/);
+ const sharedTargets=await (await request('/api/faults/targets')).json();
+ const savedScenarioResponse=await request('/api/scenarios/save','POST',{profile:{...initialProfile,name:'Atomic HTTP scenario'},targets:sharedTargets,expectedTargets:JSON.stringify(sharedTargets)});
+ assert.equal(savedScenarioResponse.status,200,await savedScenarioResponse.clone().text());
+ const savedScenario=await savedScenarioResponse.json();assert.equal(savedScenario.profile.version,initialProfile.version+1);
+ const allocationResponse=await request(`/api/workers/plan?profile=${initialProfile.id}`);
+ // With no remote workers registered, planning explains the capacity blocker.
+ assert.equal(allocationResponse.status,400);assert.match((await allocationResponse.json()).error,/worker|capacity/i);
+ const settings=await (await request('/api/settings')).json();assert.equal(settings.adminApiKey,'');assert.doesNotMatch(JSON.stringify(settings),/mock-private-admin|mock-sp-token|secret-grafana-test/);
+ assert.equal((await request('/api/settings','PUT',settings,true,{origin:'https://other.example'})).status,403);
+ const gcpDraft=await (await request('/api/settings?environment=gcp')).json();assert.equal(gcpDraft.environment,'gcp');assert.equal(gcpDraft.hasAdminApiKey,false);
+ const placeholder=await (await request('/api/settings?environment=aws')).json();assert.equal(placeholder.environment,'aws');assert.equal(placeholder.database.hasPassword,false);
+ assert.equal((await request('/api/settings','PUT',placeholder)).status,200);
+ assert.match(await (await request('/scenarios')).text(),/environment-label[^>]*>AWS</);
+ for(const endpoint of ['/api/fixtures','/api/smoke']){const blocked=await request(endpoint,'POST',{mode:'single'});assert.equal(blocked.status,400);assert.match((await blocked.json()).error,/execution is not supported/);}
+ const blockedCheck=await request('/api/settings/services/test','POST',{kind:'router',endpoint:target.url,environment:'aws'});assert.equal(blockedCheck.status,400);
+ assert.equal((await request('/api/settings','PUT',await (await request('/api/settings?environment=local')).json())).status,200);
+ assert.equal((await (await request('/api/settings')).json()).router,settings.router);
+ const localTargets=[{id:'vault',label:'Vault test',adapter:'local-vault',port:3001,repository:temporary}];
+ assert.equal((await request('/api/faults/targets','PUT',localTargets)).status,200);
+ assert.equal((await (await request('/api/faults/targets')).json())[0].id,'vault');
+ assert.ok((await (await request('/api/faults')).json()).targets.some(t=>t.id==='vault'));
+ assert.equal((await request('/api/faults/targets','PUT',[],true,{origin:'https://other.example'})).status,403);
+ assert.equal((await request('/api/faults/targets','PUT',[])).status,200);
+ assert.equal((await request('/api/faults/test','POST',{targetId:'demo',action:'outage',confirm:'outage demo'},false)).status,401);
+ const testResponse=await request('/api/faults/test','POST',{targetId:'demo',action:'outage',durationSeconds:30,confirm:'outage demo'});
+ assert.equal(testResponse.status,202);const outageTest=await testResponse.json();assert.equal(outageTest.command,'fault-test');
+ assert.equal((await request('/api/fixtures','POST',{mode:'single'})).status,409);
+ // Reloading the browser does not own the standalone outage or recovery.
+ assert.equal((await request('/scenarios')).status,200);
+ for(let n=0;n<50;n++){if((await (await request(`/api/jobs/${outageTest.id}`)).json()).events.some(e=>e.kind==='fault_started'))break;await wait(20);}
+ const restoreResponse=await request('/api/faults/restore','POST',{});assert.equal(restoreResponse.status,200);
+ for(let n=0;n<100;n++){if(!(await (await request('/api/faults')).json()).active)break;await wait(20);}
+ const tested=await completed(outageTest.id);assert.equal(tested.status,'complete');assert.ok(tested.events.some(e=>e.kind==='fault_restored'));
+ let profile=await (await request('/api/profiles')).json();profile=profile.find(p=>!p.isDefault);
+ async function saveLoad(){profile=await (await request(`/api/profiles/${profile.id}`,'PUT',{...profile,...settings,name:'HTTP test profile',merchantCount:1})).json();assert.ok(profile.id,JSON.stringify(profile));}
+ async function startLoad(){return (await request('/api/runs','POST',{mode:'single',profileId:profile.id,version:profile.version})).json();}
+ settings.preAllocatedVusMultiplier=4;settings.maxVusMultiplier=12;
+ assert.equal((await request('/api/settings','PUT',settings)).status,200);
+ assert.equal((await request('/api/settings/database/test','POST',{host:'127.0.0.1',port:1,database:'test',user:'missing',password:''})).status,400);
+ const serviceCheck=await (await request('/api/settings/services/test','POST',{kind:'router',endpoint:origin})).json();assert.equal(serviceCheck.ok,true,JSON.stringify(serviceCheck));
+ const superpositionCheckResponse=await request('/api/settings/services/test','POST',{kind:'superposition',endpoint:settings.superposition.endpoint,superposition:settings.superposition});
+ assert.equal(superpositionCheckResponse.status,200,await superpositionCheckResponse.clone().text());
+ const superpositionCheck=await superpositionCheckResponse.json();assert.equal(superpositionCheck.ok,true);assert.match(superpositionCheck.message,/Authenticated/);
+ for(const route of ['/fixtures','/performance','/results'])assert.equal((await request(route)).status,200);
+ const resultsPage=await (await request('/results')).text();assert.doesNotMatch(resultsPage,/Run \/ scenario|run-library/);assert.match(resultsPage,/No runs yet|run-select/);
+ assert.equal((await request('/results?run=single%3Amissing')).status,200);
+ const panels=[{title:'One',url:'/grafana/d-solo/k6/test?panelId=1'},{title:'Two',url:'/grafana/d-solo/k6/test?panelId=2'}];
+ assert.equal((await request('/api/grafana/panels','PUT',panels)).status,200);
+ assert.equal((await (await request('/api/grafana/panels')).json()).length,2);
+ assert.equal((await request(panels[0].url)).status,403);
+ const {url:embedUrl}=await (await request(`/api/grafana/embed?panel=${encodeURIComponent(panels[0].url)}`)).json();
+ assert.notEqual(new URL(embedUrl).origin,origin);
+ const handshake=await fetch(embedUrl,{redirect:'manual'});assert.equal(handshake.status,303);
+ const embedCookie=handshake.headers.get('set-cookie').split(';')[0],embedOrigin=new URL(embedUrl).origin;
+ const embeddedResponse=await fetch(new URL(handshake.headers.get('location'),embedUrl),{headers:{cookie:embedCookie}});
+ assert.equal(embeddedResponse.status,200);assert.equal(lastHeaders.authorization,'Bearer secret-grafana-test');assert.equal(lastHeaders.cookie,undefined);
+ assert.match(lastGrafanaPath,/^\/d-solo\/k6\/test\?panelId=1/);
+ const embedded=await embeddedResponse.text();
+ assert.match(embedded,/<base href="\/grafana\/">/);assert.match(embedded,/"appSubUrl":"\/grafana"/);
+ assert.equal((await fetch(embedOrigin+'/grafana/public/build/runtime.js',{headers:{cookie:embedCookie}})).status,200);assert.equal(lastGrafanaPath,'/public/build/runtime.js');
+ for(const route of ['/grafana/api/admin/users','/grafana/api/ds/queryevil'])assert.equal((await fetch(embedOrigin+route,{method:'POST',headers:{cookie:embedCookie,origin:embedOrigin},body:'{}'})).status,403);
+ assert.equal((await fetch(embedOrigin+'/api/settings',{headers:{cookie:embedCookie}})).status,404);
+ const fixtures=await (await request('/api/fixtures','POST',{mode:'single',profileId:'default:db-failover'})).json();
+ assert.equal((await request('/api/runs','POST',{mode:'single'})).status,409);
+ const completedFixtures=await completed(fixtures.id);assert.equal(completedFixtures.status,'complete');assert.equal(completedFixtures.progress.setup.stage,'ready');assert.equal(completedFixtures.progress.setup.superposition.status,'complete');
+ const runsBeforeSmoke=(await (await request('/api/runs')).json()).length;
+ const smokeResponse=await request('/api/smoke','POST',{mode:'single',profileId:profile.id,version:profile.version,fixtureSetId:completedFixtures.fixtureSetId,rps:1,durationSeconds:1});
+ assert.equal(smokeResponse.status,202);const smoke=await smokeResponse.json();assert.equal(smoke.command,'smoke');assert.equal(smoke.runId,undefined);
+ assert.equal((await request('/api/runs','POST',{mode:'single'})).status,409);
+ const completedSmoke=await completed(smoke.id);assert.equal(completedSmoke.status,'complete',completedSmoke.error);assert.match(completedSmoke.output,/recording disabled/);
+ assert.equal(completedSmoke.profile.totalRps,1);assert.equal(completedSmoke.profile.durationSeconds,1);
+ assert.ok(completedSmoke.progress.elapsed_seconds>0,JSON.stringify(completedSmoke.progress));
+ assert.ok(completedSmoke.progress.trend?.t>0,JSON.stringify(completedSmoke.progress));
+ await assert.rejects(readFile(path.join(temporary,'jobs',smoke.id,'smoke','results.sqlite'),'utf8'),error=>error.code==='ENOENT');
+ assert.equal((await (await request('/api/runs')).json()).length,runsBeforeSmoke);
+ const job=await startLoad();
+ const firstEvents=await request(`/api/jobs/${job.id}/events`),reader=firstEvents.body.getReader();
+ assert.match(new TextDecoder().decode((await reader.read()).value),/event: progress/);await reader.cancel();
+ let progress;
+ for(let n=0;n<20;n++){await wait(250);progress=await (await request(`/api/jobs/${job.id}`)).json();if(progress.progress.elapsed_seconds>0)break;}
+ assert.ok(progress.progress.elapsed_seconds>0,JSON.stringify(progress));
+ assert.equal((await request('/performance')).status,200);
+ assert.equal((await (await request(`/api/jobs/${job.id}`)).json()).status,'running');
+ assert.equal((await request('/api/faults','POST',{jobId:job.id,targetId:'demo',action:'outage'})).status,400);
+ assert.equal((await request('/api/faults','POST',{jobId:job.id,targetId:'demo',action:'outage',durationSeconds:1,confirm:'outage demo'})).status,202);
+ for(let n=0;n<50;n++){if(!(await (await request('/api/faults')).json()).active)break;await wait(100);}
+ const pause=await request(`/api/jobs/${job.id}/pause`,'POST');assert.equal(pause.status,200,await pause.clone().text());
+ let paused;
+ for(let n=0;n<50;n++){paused=await (await request(`/api/jobs/${job.id}`)).json();if(paused.loadState==='paused')break;await wait(100);}
+ assert.equal(paused.loadState,'paused');assert.equal(paused.progress.control.in_flight,0);
+ assert.equal((await request('/api/runs','POST',{mode:'single'})).status,409);
+ await wait(1300);
+ const stillPaused=await (await request(`/api/jobs/${job.id}`)).json();assert.equal(stillPaused.progress.control.active_seconds,paused.progress.control.active_seconds);
+ assert.equal((await request(`/api/jobs/${job.id}/resume`,'POST')).status,200);
+ settings.totalRps=11;settings.durationSeconds=12;settings.resultsLimits.maximumHoldP99Ms=250;assert.equal((await request('/api/settings','PUT',settings)).status,200);await saveLoad();
+ const immutable=await (await request(`/api/jobs/${job.id}`)).json();assert.equal(immutable.profile.totalRps,10);assert.equal(immutable.profile.durationSeconds,6);
+ assert.match(immutable.runId,/-single-10tps-/);
+ const snapshot=JSON.parse(await readFile(path.join(temporary,'jobs',job.id,'config.json'),'utf8'));
+ assert.equal(snapshot.mode,'single');assert.equal(snapshot.load.total_rps,10);
+ assert.equal(snapshot.load.pre_allocated_vus_multiplier,4);assert.equal(snapshot.load.max_vus_multiplier,12);
+ assert.equal(snapshot.resultsLimits.maximumHoldP99Ms,160);
+ assert.equal((await (await request('/api/settings')).json()).resultsLimits.maximumHoldP99Ms,250);
+ settings.totalRps=10;settings.durationSeconds=6;assert.equal((await request('/api/settings','PUT',settings)).status,200);await saveLoad();
+ const end=await completed(job.id);assert.equal(end.status,'complete',end.output);
+ const run=await (await request(`/api/runs/${encodeURIComponent(end.runId)}`)).json();
+ assert.equal(run.successfulTps,10);assert.equal(run.iterations,60);assert.equal(run.gaps,0);assert.ok(run.complete);assert.ok(run.confirmP99!=null);assert.equal(run.acceptance.resilience,'simulated');assert.ok(run.activity.some(e=>e.kind==='pause'));assert.ok(run.activity.some(e=>e.kind==='fault_restored'));
+ assert.ok(run.telemetry.length>=2);assert.ok(run.telemetry.at(-1).recorded>0);
+ assert.equal(run.scenarioChecks.limits.maximumHoldP99Ms,160);assert.ok(run.scenarioChecks.groups.some(group=>group.kind==='hold'));
+ const recordedChecks=JSON.parse(await readFile(path.join(snapshot.output,'single','runs',end.runId.split(':')[1],'scenario-checks.json'),'utf8'));
+ assert.equal(recordedChecks.summary.version,scenarioChecksVersion);assert.equal(recordedChecks.summary.limits.maximumHoldP99Ms,160);
+ assert.ok(run.telemetry.every((point,index)=>!index || point.t>run.telemetry[index-1].t));
+ const history=await (await request(`/api/runs/${encodeURIComponent(end.runId)}/requests?limit=2`)).json();assert.equal(history.rows.length,2);assert.ok(history.next);
+ settings.loadShape='staged';settings.startRps=0;settings.stagesJson=JSON.stringify([{target_rps:10,duration_seconds:4}]);
+ assert.equal((await request('/api/settings','PUT',settings)).status,200);await saveLoad();
+ const staged=await startLoad();
+ assert.equal((await completed(staged.id)).status,'complete');
+ const stagedRun=await (await request(`/api/runs/${encodeURIComponent(staged.runId)}`)).json();
+ assert.equal(stagedRun.durationSeconds,4);assert.equal(stagedRun.offeredTps,10);assert.equal(stagedRun.expectedAverageTps,5);
+ assert.ok(stagedRun.iterations>=18&&stagedRun.iterations<=21,JSON.stringify(stagedRun));assert.equal(stagedRun.gaps,0);
+ settings.startRps=10;settings.stagesJson=JSON.stringify([{target_rps:10,duration_seconds:3,fault:{targetId:'demo',action:'outage'}},{target_rps:10,duration_seconds:3}]);
+ await saveLoad();const scheduled=await startLoad();
+ const scheduledEnd=await completed(scheduled.id);assert.equal(scheduledEnd.status,'complete',JSON.stringify(scheduledEnd));
+ assert.equal(scheduledEnd.events.filter(e=>e.kind==='scheduled_fault').length,1);
+ assert.equal(scheduledEnd.events.filter(e=>e.kind==='fault_started').length,1);
+ assert.equal(scheduledEnd.events.filter(e=>e.kind==='fault_restored').length,1);
+ assert.equal(scheduledEnd.profile.timeline.at(-1).end,6);
+ const plannedRun=await (await request(`/api/runs/${encodeURIComponent(scheduled.runId)}`)).json();assert.equal(plannedRun.timeline[0].fault.action,'outage');assert.equal(plannedRun.timeline.at(-1).end,6);assert.doesNotMatch(JSON.stringify(plannedRun.timeline),/secret|repository|controllerPort/);
+ const plannedPage=await (await request(`/performance?run=${encodeURIComponent(scheduled.runId)}`)).text();assert.match(plannedPage,/recovery planned/);assert.match(plannedPage,/over the full 6 second test/);
+ const faultSnapshot=JSON.parse(await readFile(path.join(temporary,'jobs',scheduled.id,'config.json'),'utf8'));
+ assert.equal(faultSnapshot.faultPlan[0].target.id,'demo');assert.equal(faultSnapshot.faultPlan[0].at,0);
+ settings.stagesJson=JSON.stringify([{target_rps:10,duration_seconds:20,fault:{targetId:'demo',action:'outage'}},{target_rps:10,duration_seconds:3}]);await saveLoad();
+ const cancelFault=await startLoad();
+ for(let i=0;i<100;i++){if((await (await request('/api/faults')).json()).active?.occurred)break;await wait(100);}
+ assert.equal((await (await request('/api/faults')).json()).active?.occurred,true);
+ assert.equal((await request(`/api/jobs/${cancelFault.id}/cancel`,'POST')).status,200);
+ const cancelledFault=await completed(cancelFault.id);assert.equal(cancelledFault.status,'cancelled');
+ const restored=await (await request('/api/faults')).json();assert.equal(restored.active,null);assert.equal(restored.blocked,false);assert.ok(cancelledFault.events.some(e=>e.kind==='fault_restored'));
+ settings.loadShape='flat';assert.equal((await request('/api/settings','PUT',settings)).status,200);await saveLoad();
+ target.state.errorCustomers=true;settings.durationSeconds=3;assert.equal((await request('/api/settings','PUT',settings)).status,200);await saveLoad();
+ const failing=await startLoad();
+ const failed=await completed(failing.id);assert.equal(failed.status,'failed');assert.equal(failed.exitCode,99);
+ const failedRun=await (await request(`/api/runs/${encodeURIComponent(failing.runId)}`)).json();assert.equal(failedRun.complete,true);assert.equal(failedRun.recordingState,'complete');assert.equal(failedRun.loadState,'failed');assert.equal(failedRun.acceptance.verdict,'fail');
+ target.state.errorCustomers=false;settings.durationSeconds=6;assert.equal((await request('/api/settings','PUT',settings)).status,200);await saveLoad();
+ // Restart preserves sessions and completed jobs.
+ server.kill('SIGTERM');await once(server,'exit');launch();await ready();
+ assert.equal((await request('/api/settings')).status,200);assert.equal((await (await request(`/api/jobs/${job.id}`)).json()).status,'complete');
+ settings.durationSeconds=20;assert.equal((await request('/api/settings','PUT',settings)).status,200);await saveLoad();
+ const cancelled=await startLoad();await wait(1300);
+ assert.equal((await request(`/api/jobs/${cancelled.id}/cancel`,'POST')).status,200);
+ assert.equal((await completed(cancelled.id)).status,'cancelled');
+ const replay=await request(`/api/jobs/${cancelled.id}/events`);assert.match(await replay.text(),/cancelled/);
+ const shutdown=await startLoad();await wait(1300);
+ server.kill('SIGTERM');await once(server,'exit');launch();await ready();
+ assert.ok(['running','complete'].includes((await (await request(`/api/jobs/${shutdown.id}`)).json()).status));
+ assert.equal((await completed(shutdown.id)).status,'complete');
+ const interrupted=await startLoad();await wait(1300);
+ server.kill('SIGKILL');await once(server,'exit');launch();await ready();
+ assert.ok(['running','complete'].includes((await (await request(`/api/jobs/${interrupted.id}`)).json()).status));
+ await request(`/api/jobs/${interrupted.id}/cancel`,'POST');await completed(interrupted.id);
+ // A worker crash is different from an SSR restart: recover and mark incomplete.
+ const orphan=await startLoad();await wait(1300);
+ const daemon=JSON.parse(await readFile(path.join(temporary,'worker-service.json'),'utf8'));
+ process.kill(daemon.pid,'SIGKILL');
+ const recovered=await (await request(`/api/jobs/${orphan.id}`)).json();assert.equal(recovered.status,'interrupted');
+ assert.equal((await (await request(`/api/runs/${encodeURIComponent(orphan.runId)}`)).json()).complete,false);
+ assert.equal((await request('/logout','POST')).status,303);assert.equal((await request('/api/settings')).status,401);
+ } finally {server?.kill('SIGTERM');const daemon=JSON.parse(await readFile(path.join(temporary,'worker-service.json'),'utf8').catch(()=>'null'));if(daemon)try{process.kill(daemon.pid,'SIGTERM');}catch{}target.server.close();grafana.close();}
+});
diff --git a/loadtest/console/test/import-state.test.mjs b/loadtest/console/test/import-state.test.mjs
new file mode 100644
index 0000000000..63e3875134
--- /dev/null
+++ b/loadtest/console/test/import-state.test.mjs
@@ -0,0 +1,8 @@
+import test from 'node:test';import assert from 'node:assert/strict';
+import {acceptImportUpdate,importView} from '../src/import-state.mjs';
+const job=(status='running',checked=1,phase='credentials')=>({id:'attempt',status,progress:{verification:{profileId:'scenario',checked,phase,checks:[]}}});
+test('import observer rejects other attempts, scenarios and older progress',()=>{const current=job();assert.equal(acceptImportUpdate(current,{...job(),id:'old'},'scenario'),false);assert.equal(acceptImportUpdate(current,job(),'other'),false);assert.equal(acceptImportUpdate(current,job('running',0),'scenario'),false);assert.equal(acceptImportUpdate(current,job('running',2),'scenario'),true);});
+test('late active event cannot replace terminal success or cancellation',()=>{for(const status of ['complete','cancelled','failed'])assert.equal(acceptImportUpdate(job(status,4),job('running',5),'scenario'),false);assert.equal(acceptImportUpdate(job(),job('complete',4),'scenario'),true);});
+test('inline view distinguishes credential failure, setup failure, ready and cancelled',()=>{for(const stage of ['credentials','setup']){const value=job('failed');value.progress.verification.checks=[{stage,merchant:'merchant',label:'Check',message:'Reason',ok:false}];const view=importView(value);assert.match(view.title,stage==='setup'?/Setup/:/Credential/);assert.match(view.detail,/Reason/);}assert.equal(importView(job('complete')).phase,'ready');assert.equal(importView(job('cancelled')).phase,'cancelled');assert.equal(importView(null),null);});
+
+test('equal-count stage snapshots never move backwards',()=>{assert.equal(acceptImportUpdate(job('running',3,'setup'),job('running',3,'credentials'),'scenario'),false);assert.equal(acceptImportUpdate(job('running',3,'credentials'),job('running',3,'setup'),'scenario'),true);});
diff --git a/loadtest/console/test/infrastructure-settings.test.mjs b/loadtest/console/test/infrastructure-settings.test.mjs
new file mode 100644
index 0000000000..33abfed775
--- /dev/null
+++ b/loadtest/console/test/infrastructure-settings.test.mjs
@@ -0,0 +1,72 @@
+import test from 'node:test';
+import assert from 'node:assert/strict';
+import {mkdtemp,writeFile,chmod,mkdir} from 'node:fs/promises';
+import os from 'node:os';
+import path from 'node:path';
+import {rootCertificates} from 'node:tls';
+import {resolveK6Binary} from '../server/k6-binary.mjs';
+import {testServiceEndpoint,testSuperpositionEndpoint} from '../server/service-checks.mjs';
+import {databaseConnectionOptions,databaseConnectionError} from '../server/database-options.mjs';
+import {importCertificate,listCertificates,readImportedCertificate,removeCertificate} from '../server/certificates.mjs';
+
+test('k6-sqlite resolution honors configuration, source build, PATH and gives an actionable error',async()=>{
+ const root=await mkdtemp(path.join(os.tmpdir(),'k6-resolution-')),source=path.join(root,'k6/scenario-mix/bin/k6-sqlite');
+ await mkdir(path.dirname(source),{recursive:true});
+ await writeFile(source,'#!/bin/sh\n');await chmod(source,0o700);
+ assert.equal(await resolveK6Binary({loadtestRoot:root,consoleRoot:path.join(root,'console'),pathValue:''}),source);
+ const configured=path.join(root,'configured');await writeFile(configured,'#!/bin/sh\n');await chmod(configured,0o700);
+ assert.equal(await resolveK6Binary({configured,loadtestRoot:'/missing',consoleRoot:'/missing',pathValue:''}),configured);
+ await assert.rejects(resolveK6Binary({configured:'/missing',loadtestRoot:'/missing',consoleRoot:'/missing',pathValue:''}),/npm run build:recorder/);
+});
+
+test('service endpoint checks are read-only, timed and reject unhealthy responses',async()=>{
+ let request;
+ const healthy=await testServiceEndpoint('router','https://router.example/base',{fetcher:async(url,options)=>{request={url:String(url),options};return new Response('{}',{status:200});}});
+ assert.equal(request.url,'https://router.example/base/health');assert.equal(request.options.method,'GET');assert.equal(healthy.ok,true);
+ let prefixed;
+ await testServiceEndpoint('modularPm','http://127.0.0.1:8081/v2',{fetcher:async(url)=>{prefixed=String(url);return new Response('{}',{status:200});}});
+ assert.equal(prefixed,'http://127.0.0.1:8081/v2/health');
+ await assert.rejects(testServiceEndpoint('superposition','https://sp.example',{fetcher:async()=>new Response('',{status:503})}),/503/);
+ await assert.rejects(testServiceEndpoint('unknown','https://sp.example',{fetcher:async()=>new Response()}),/Unknown/);
+});
+
+test('Superposition checks authenticate by reading a configured default',async()=>{
+ let request;
+ const config={endpoint:'https://sp.example/base',token:'secret',access_header:'x-superposition-access',organization_id:'org',workspace_id:'dev',defaults:{flag:true}};
+ const healthy=await testSuperpositionEndpoint(config,{fetcher:async(url,options)=>{request={url:String(url),options};return new Response('{}',{status:200});}});
+ assert.equal(request.url,'https://sp.example/default-config/flag');
+ assert.equal(request.options.headers['x-superposition-access'],'secret');assert.equal(request.options.headers['x-org-id'],'org');
+ assert.equal(healthy.ok,true);
+});
+
+test('database TLS verifies system or supplied certificate authorities',()=>{
+ const database={host:'db.example',port:5432,database:'hyperswitch',user:'reader',password:'secret'};
+ assert.equal(databaseConnectionOptions({...database,tlsMode:'disable'}).ssl,false);
+ assert.deepEqual(databaseConnectionOptions({...database,tlsMode:'require'}).ssl,{rejectUnauthorized:false});
+ assert.deepEqual(databaseConnectionOptions({...database,tlsMode:'verify'}).ssl,{rejectUnauthorized:true});
+ const configured=databaseConnectionOptions({...database,tlsMode:'verify',caPath:'/certs/db.pem'},{readCa:()=> '-----BEGIN CERTIFICATE-----\ntest\n-----END CERTIFICATE-----'});
+ assert.equal(configured.ssl.rejectUnauthorized,true);assert.match(configured.ssl.ca,/BEGIN CERTIFICATE/);
+ assert.throws(()=>databaseConnectionOptions({...database,tlsMode:'verify',caPath:'relative.pem'}),/absolute/);
+ assert.throws(()=>databaseConnectionOptions({...database,tlsMode:'verify',caPath:'/certs/bad'},{readCa:()=> 'not a certificate'}),/PEM/);
+});
+
+test('certificate bundles are validated, stored by opaque ID and usable by database TLS',async()=>{
+ const root=await mkdtemp(path.join(os.tmpdir(),'loadtest-certificates-'));
+ const certificate=await importCertificate(root,{name:'Test trust',pem:rootCertificates[0]});
+ assert.equal(listCertificates(root)[0].id,certificate.id);
+ assert.match(certificate.fingerprint,/^[0-9A-F:]+$/);
+ const configured=databaseConnectionOptions({host:'db',port:5432,database:'db',user:'reader',password:'secret',tlsMode:'verify',caCertificateId:certificate.id},{readCertificate:id=>readImportedCertificate(root,id)});
+ assert.match(configured.ssl.ca,/BEGIN CERTIFICATE/);
+ await removeCertificate(root,certificate.id);assert.deepEqual(listCertificates(root),[]);
+ await assert.rejects(importCertificate(root,{name:'Bad',pem:'not a certificate'}),/PEM encoded/);
+});
+
+test('database errors give actionable field-level guidance',()=>{
+ for(const code of ['DEPTH_ZERO_SELF_SIGNED_CERT','SELF_SIGNED_CERT_IN_CHAIN','UNABLE_TO_VERIFY_LEAF_SIGNATURE','UNABLE_TO_GET_ISSUER_CERT_LOCALLY'])assert.match(databaseConnectionError({code,message:'Node.js advice'}),/Custom CA certificate/);
+ assert.match(databaseConnectionError({code:'DEPTH_ZERO_SELF_SIGNED_CERT'},{caCertificateId:'selected-ca'}),/selected CA does not trust the current database certificate/);
+ assert.match(databaseConnectionError({code:'ERR_TLS_CERT_ALTNAME_INVALID'}),/Host field/);
+ assert.match(databaseConnectionError({code:'28P01'}),/username and password/);
+ assert.match(databaseConnectionError({code:'42501'}),/read access to payment_intent/);
+ assert.match(databaseConnectionError({code:'CERT_HAS_EXPIRED'}),/expired/);
+ assert.equal(databaseConnectionError({message:'Connection timed out'}),'Database connection failed: Connection timed out');
+});
diff --git a/loadtest/console/test/interaction-models.test.mjs b/loadtest/console/test/interaction-models.test.mjs
new file mode 100644
index 0000000000..d49fc46200
--- /dev/null
+++ b/loadtest/console/test/interaction-models.test.mjs
@@ -0,0 +1,142 @@
+import test from 'node:test';
+import assert from 'node:assert/strict';
+import {mkdtemp,mkdir,readFile,writeFile} from 'node:fs/promises';
+import path from 'node:path';
+import os from 'node:os';
+import {balanceWeights} from '../src/flow-catalog.mjs';
+import {switchFaultEnvironment} from '../src/fault-types.mjs';
+const temporary=await mkdtemp(path.join(os.tmpdir(),'console-interactions-'));
+process.env.LOADTEST_DATA_DIR=temporary;process.env.LOADTEST_CONSOLE_ROOT=path.resolve('.');process.env.LOADTEST_ROOT=path.resolve('..');
+const config=JSON.parse(await readFile('../loadtest.config.example.json','utf8'));config.output=path.join(temporary,'artifacts');
+process.env.LOADTEST_CONFIG_FILE=path.join(temporary,'seed.json');await writeFile(process.env.LOADTEST_CONFIG_FILE,JSON.stringify(config));
+const state=await import('../server/state.mjs');state.initializeConfig();
+const profiles=await import('../server/profiles.mjs'),faults=await import('../server/faults.mjs');
+test('deleted fixture sets stay removed after CLI import and preserve saved artifacts',async()=>{
+ const directory=path.join(config.output,'single','fixtures');await mkdir(directory,{recursive:true});
+ await writeFile(path.join(directory,'manifest.json'),JSON.stringify({state:'ready',merchant_count:1}));
+ const artifact=path.join(directory,'merchants.json');await writeFile(artifact,'[{"merchant_id":"existing"}]');
+ const set=profiles.listFixtureSets().find(s=>s.mode==='single');assert.ok(set);
+ assert.deepEqual(profiles.deleteFixtureSet(set.id),{id:set.id,deleted:true});
+ assert.equal(profiles.listFixtureSets().some(s=>s.id===set.id),false);
+ assert.equal(profiles.listFixtureSets().some(s=>s.mode==='single'),false);
+ assert.throws(()=>profiles.getFixtureSet(set.id),e=>e.status===404);
+ assert.equal(await readFile(artifact,'utf8'),'[{"merchant_id":"existing"}]');
+ assert.throws(()=>profiles.deleteFixtureSet('missing'),e=>e.status===404);
+});
+test('fixture deletion is blocked during active and paused generators',()=>{
+ const db=state.controlDb();
+ db.prepare('INSERT INTO fixture_sets VALUES(?,?,?,?,?,?,?,?)').run('delete-guard','tenancy',100,'signature','/unused','ready',null,1);
+ for(const kind of ['fixtures','load','smoke'])for(const status of ['starting','running','pausing','paused','cancelling']){
+ db.prepare('INSERT INTO jobs(id,kind,mode,status,started_at) VALUES(?,?,?,?,?)').run('deletion-job',kind,'tenancy',status,1);
+ assert.throws(()=>profiles.deleteFixtureSet('delete-guard'),e=>e.status===409);
+ assert.equal(profiles.getFixtureSet('delete-guard').status,'ready');
+ db.prepare('DELETE FROM jobs WHERE id=?').run('deletion-job');
+ }
+ profiles.deleteFixtureSet('delete-guard');
+});
+test('scenario and shared targets save atomically, conflicts preserve both, archive preserves versions',()=>{
+ const original=profiles.saveProfile({...profiles.profileDraft(),name:'Original scenario'}),targets=[{id:'redis',label:'Redis',serviceType:'redis',environment:'local',adapter:'process-compose',binary:'process-compose',controllerPort:8090,process:'r1',port:6379}];
+ const before=JSON.stringify(faults.localFaultTargets());
+ assert.throws(()=>profiles.saveScenario({profile:{...original,name:''},targets,expectedTargets:before}),/name/i);
+ assert.equal(JSON.stringify(faults.localFaultTargets()),before);assert.equal(profiles.getProfile(original.id).version,original.version);
+ const saved=profiles.saveScenario({profile:{...original,name:'Saved together'},targets,expectedTargets:before});
+ assert.equal(saved.profile.version,original.version+1);assert.equal(faults.localFaultTargets().length,1);
+ assert.throws(()=>profiles.saveScenario({profile:saved.profile,targets:[],expectedTargets:before}),/changed/i);
+ assert.equal(profiles.getProfile(original.id).version,saved.profile.version);assert.equal(faults.localFaultTargets().length,1);
+ profiles.archiveProfile(original.id,true);assert.equal(profiles.listProfiles().some(p=>p.id===original.id),false);
+ assert.equal(profiles.listProfiles({includeArchived:true}).find(p=>p.id===original.id).archived,true);
+ profiles.archiveProfile(original.id,false);assert.equal(profiles.getProfile(original.id).version,saved.profile.version);
+});
+test('scenario deletion removes the profile and its saved versions',()=>{
+ const profile=profiles.saveProfile({...profiles.profileDraft(),name:'Delete me'}),deleted=profiles.deleteProfile(profile.id);
+ assert.deepEqual(deleted,{id:profile.id,deleted:true});assert.throws(()=>profiles.getProfile(profile.id),/not found/i);
+ assert.equal(state.controlDb().prepare('SELECT COUNT(*) count FROM profile_versions WHERE profile_id=?').get(profile.id).count,0);
+});
+test('deleting custom scenarios preserves the five immutable defaults',()=>{
+ for(const profile of profiles.listProfiles({includeArchived:true}).filter(p=>!p.isDefault))profiles.deleteProfile(profile.id);
+ assert.equal(profiles.listProfiles().length,5);
+ assert.ok(profiles.listProfiles().every(p=>p.isDefault));
+});
+test('environment presets round trip without discarding edited values',()=>{
+ const local={id:'vault',label:'Card vault',adapter:'local-vault',serviceType:'card-vault',environment:'local',repository:'/tmp/vault',port:3009};
+ const cloud=switchFaultEnvironment(local,'cloud');cloud.namespace='custom-namespace';
+ const restored=switchFaultEnvironment(cloud,'local');assert.equal(restored.port,3009);assert.equal(restored.repository,'/tmp/vault');
+ assert.equal(switchFaultEnvironment(restored,'cloud').namespace,'custom-namespace');
+});
+test('explicit weight balancing totals exactly 100 and preserves hidden fields',()=>{
+ const flows=[{name:'a',weight:25,extra:'keep'},{name:'b',weight:25},{name:'c',weight:0}];
+ assert.deepEqual(balanceWeights(flows).map(f=>f.weight),[25,25,50]);
+ for(const weights of [[1,1,1],[0,0,0],[150,20,3],[.25,.5,.25]]){
+ const result=balanceWeights(weights.map(weight=>({weight})),true);assert.equal(result.reduce((n,f)=>n+f.weight,0),100);assert.ok(result.every(f=>f.weight>=0));}
+ assert.equal(balanceWeights(flows,true)[0].extra,'keep');assert.equal(flows[2].weight,0);
+});
+
+test('default scenarios reject edit, deletion and archival through the server',()=>{
+ for(const profile of profiles.listProfiles().filter(p=>p.isDefault)){
+ assert.throws(()=>profiles.saveProfile({...profile,name:'Changed'},profile.id),e=>e.status===403);
+
+ assert.throws(()=>profiles.deleteProfile(profile.id),e=>e.status===403);
+ assert.throws(()=>profiles.archiveProfile(profile.id,true),e=>e.status===403);
+ assert.equal(profiles.getProfile(profile.id).name,profile.name);
+ }
+ assert.throws(()=>profiles.getProfile('default:steady-load',99),/version not found/i);
+});
+test('default load definitions and provider-specific faults remain distinct',async()=>{
+ const {defaultScenarios}=await import('../server/default-scenarios.mjs');
+ const local=defaultScenarios('local',[{id:'actual-vault',serviceType:'card-vault',environment:'local',adapter:'local-vault',actions:['outage']}]);
+ assert.deepEqual(local.map(p=>p.name),['Card vault outage','DB failover','Steady load','Ramped load','Tenancy steady load']);
+ assert.ok(local.every(p=>p.durationSeconds===300));
+ assert.equal(local[0].load.stages[1].duration_seconds,30);
+ assert.equal(local[2].totalRps,5);assert.equal(local[2].durationSeconds,300);
+ const tenancy=profiles.getProfile('default:tenancy-steady-load');
+ assert.equal(tenancy.mode,'tenancy');assert.equal(tenancy.merchantCount,100);
+ assert.equal(tenancy.totalRps,5);assert.equal(tenancy.durationSeconds,300);assert.equal(tenancy.loadShape,'flat');
+ assert.deepEqual(tenancy.load,local[2].load);assert.deepEqual(tenancy.scenarios,local[2].scenarios);assert.deepEqual(tenancy.acceptance,local[2].acceptance);
+ assert.equal(local[3].totalRps,10);assert.equal(local[3].version,3);assert.equal(profiles.getProfile('default:ramped-load',3).totalRps,10);assert.equal(local[3].durationSeconds,300);
+ assert.equal(local[0].load.stages[1].fault.targetId,'actual-vault');assert.equal(local[0].unavailableReason,null);
+ assert.match(local[1].unavailableReason,/GCP/);assert.equal(local[1].load.stages[1].fault.action,'failover');
+ const cloud=defaultScenarios('gcp',[{id:'ha-primary',serviceType:'postgres',environment:'gcp',adapter:'gcp-alloydb',actions:['failover']}]);
+ assert.equal(cloud[1].unavailableReason,null);assert.equal(cloud[1].load.stages[1].fault.targetId,'ha-primary');
+ assert.ok(cloud[0].unavailableReason);assert.ok(defaultScenarios('aws').every(p=>p.unavailableReason));
+ assert.ok(defaultScenarios('local',[{id:'fake',serviceType:'card-vault',environment:'local',adapter:'simulated',actions:['outage']}])[0].unavailableReason);
+ local[2].scenarios[0].weight=0;assert.equal(defaultScenarios('local')[2].scenarios[0].weight,50);
+});
+
+
+test('custom scenarios sort by creation time ahead of defaults, and edits retain their position',()=>{
+ const first=profiles.saveProfile({...profiles.profileDraft(),name:'Earlier'});
+ const second=profiles.saveProfile({...profiles.profileDraft(),name:'Later'});
+ const db=state.controlDb();db.prepare('UPDATE profiles SET created_at=? WHERE id=?').run(100,first.id);db.prepare('UPDATE profiles SET created_at=? WHERE id=?').run(200,second.id);
+ const updated=profiles.saveProfile({...first,name:'Earlier edited'},first.id);
+ assert.equal(updated.createdAt,100);
+ const list=profiles.listProfiles(),custom=list.filter(p=>!p.isDefault);
+ assert.ok(custom.findIndex(p=>p.id===second.id)<custom.findIndex(p=>p.id===first.id));
+ assert.ok(list.slice(-5).every(p=>p.isDefault));assert.ok(list.slice(0,-5).every(p=>!p.isDefault));
+});
+test('saving an edited default creates an independent scenario and keeps the built-in intact',()=>{
+ const original=profiles.getProfile('default:steady-load');
+ const saved=profiles.saveScenario({profile:{...original,totalRps:7}}).profile;
+ assert.notEqual(saved.id,original.id);assert.equal(saved.version,1);assert.equal(saved.isDefault,undefined);assert.equal(saved.totalRps,7);assert.equal(saved.name,'Steady load (copy)');
+ assert.equal(profiles.getProfile(original.id).totalRps,5);
+ const renamed=profiles.saveScenario({profile:{...original,name:'My steady load'}}).profile;
+ assert.equal(renamed.name,'My steady load');assert.notEqual(renamed.id,saved.id);
+ assert.equal(profiles.getProfile(original.id).name,'Steady load');
+});
+
+test('fixture list exposes created/imported sources and excludes unverified imports',async()=>{
+ const db=state.controlDb();
+ for(const status of ['creating','failed','interrupted','ready']){
+ const directory=path.join(temporary,'import-list-'+status);await mkdir(directory);
+ await writeFile(path.join(directory,'manifest.json'),JSON.stringify({source:'imported',state:status,verification:{ok:status==='ready',checks:[]}}));
+ await writeFile(path.join(directory,'merchants.json'),'[]');
+ db.prepare('INSERT INTO fixture_sets VALUES(?,?,?,?,?,?,?,?)').run('import-list-'+status,'single',1,'imported',directory,status,null,1);
+ }
+ const directory=path.join(temporary,'created-list');await mkdir(directory);
+ db.prepare('INSERT INTO fixture_sets VALUES(?,?,?,?,?,?,?,?)').run('created-list','single',1,'signature',directory,'failed',null,1);
+ const list=profiles.listFixtureSets();
+ assert.deepEqual(list.filter(row=>row.id.startsWith('import-list-')).map(row=>row.id),['import-list-ready']);
+ assert.equal(list.find(row=>row.id==='import-list-ready').source,'imported');
+ assert.equal(list.find(row=>row.id==='created-list').source,'created');
+ // Failed import evidence remains available to its inline attempt, not the fixture catalogue.
+ assert.equal(profiles.getFixtureSet('import-list-failed').status,'failed');
+});
diff --git a/loadtest/console/test/job-status.test.mjs b/loadtest/console/test/job-status.test.mjs
new file mode 100644
index 0000000000..a30b05730e
--- /dev/null
+++ b/loadtest/console/test/job-status.test.mjs
@@ -0,0 +1,10 @@
+import test from 'node:test';
+import assert from 'node:assert/strict';
+import {finalJobStatus} from '../server/jobs.mjs';
+
+test('a load cannot complete when fault recovery was not verified',()=>{
+ assert.equal(finalJobStatus({failure:null,recoveryError:'Recovery could not be verified'}),'failed');
+ assert.equal(finalJobStatus({failure:'k6 threshold failed'}),'failed');
+ assert.equal(finalJobStatus({cancelled:true,recoveryError:'Recovery could not be verified'}),'cancelled');
+ assert.equal(finalJobStatus({}),'complete');
+});
diff --git a/loadtest/console/test/k6-output.test.mjs b/loadtest/console/test/k6-output.test.mjs
new file mode 100644
index 0000000000..bfd146f696
--- /dev/null
+++ b/loadtest/console/test/k6-output.test.mjs
@@ -0,0 +1,35 @@
+import test from 'node:test';
+import assert from 'node:assert/strict';
+import { k6Output } from '../src/k6-output.mjs';
+
+test('k6 progress replaces previous frames and preserves warnings and summary', () => {
+ const output = `k6 started\n\nrunning (0m01.0s), 001/120 VUs\nmod_cit_off [ 1% ] 01/60 VUs 1.5 iters/s\n\nWARN request failed\nrunning (0m02.0s), 002/120 VUs\nmod_cit_off [ 2% ] 02/60 VUs 1.5 iters/s\nnomod_sdk [ 2% ] 01/36 VUs 0.9 iters/s\n\nhttp_req_duration: 100ms\n`;
+ const result = k6Output(output);
+ assert.match(result.progress,/0m02/);
+ assert.doesNotMatch(result.progress,/0m01|1%/);
+ assert.match(result.progress,/nomod_sdk/);
+ assert.match(result.history,/WARN request failed/);
+ assert.match(result.history,/http_req_duration/);
+ assert.doesNotMatch(result.history,/VUs/);
+ assert.match(result.before,/k6 started/);
+ assert.match(result.before,/WARN request failed/);
+ assert.match(result.after,/http_req_duration/);
+});
+
+test('ANSI output and truncated progress rows remain readable', () => {
+ const result = k6Output('\x1b[2Kmod_guest [ 50% ] 1/10 VUs 1 iters/s\rmod_guest [ 51% ] 1/10 VUs 1 iters/s');
+ assert.equal(result.progress.split('\n').length,1);
+ assert.match(result.progress,/51%/);
+ assert.equal(result.history,'');
+ assert.equal(k6Output('Creating fixtures\nReady').history,'Creating fixtures\nReady');
+});
+
+test('fixture progress replaces each labelled row and retains intervening logs',()=>{
+ const result=k6Output('Organization ready\nMerchants [--------------------] 0% 0/1\nMerchants [====================] 100% 1/1\nResolve flags [--------------------] 0% 0/1\nResolve flags [====================] 100% 1/1\nWaiting for service refresh\nService refresh [--------------------] 0% 0/30\nWARN preserved\nService refresh [==------------------] 10% 3/30 | 27s remaining\nService refresh [====----------------] 20% 6/30 | 24s remaining\n');
+ assert.equal((result.history.match(/Merchants \[/g)||[]).length,1);assert.equal((result.history.match(/Service refresh \[/g)||[]).length,1);assert.match(result.history,/24s remaining/);assert.doesNotMatch(result.history,/27s remaining|0% 0\//);assert.match(result.history,/Organization ready/);assert.match(result.history,/WARN preserved/);
+});
+test('fixture readiness remains pending while Superposition refresh is running',async()=>{
+ const {fixtureSteps}=await import('../src/fixture-steps.mjs');const steps=fixtureSteps({status:'running',progress:{fixtures:{completed:1,total:1},setup:{stage:'superposition',superposition:{status:'waiting',remainingSeconds:27,totalSeconds:30}}}});
+ assert.equal(steps[0].status,'complete');assert.equal(steps[1].status,'complete');assert.equal(steps[2].status,'running');assert.equal(steps[2].detail,'27s remaining');assert.equal(steps[3].status,'pending');
+ const done=fixtureSteps({status:'complete',progress:{setup:{superposition:{status:'complete'}}}});assert.ok(done.every(step=>step.status==='complete'));
+});
diff --git a/loadtest/console/test/kubernetes-faults.test.mjs b/loadtest/console/test/kubernetes-faults.test.mjs
new file mode 100644
index 0000000000..653d4f4ebe
--- /dev/null
+++ b/loadtest/console/test/kubernetes-faults.test.mjs
@@ -0,0 +1,48 @@
+import test from 'node:test';
+import assert from 'node:assert/strict';
+import {kubernetesAdapter} from '../server/kubernetes-faults.mjs';
+function fixture(){
+ const info={metadata:{uid:'deployment-uid',generation:1},spec:{replicas:2,selector:{matchLabels:{app:'vault'}}},status:{replicas:2,availableReplicas:2,readyReplicas:2,observedGeneration:1}};
+ const pod=(name,uid,owner='ours')=>({metadata:{name,uid,ownerReferences:[{uid:owner,controller:true}]},spec:{nodeName:'node-1'}});
+ const state={pods:[pod('vault-a','pod-a'),pod('vault-b','pod-b'),pod('unrelated','foreign','theirs')],running:['pod-a','pod-b'],denied:false,missing:false},calls=[];
+ const command=async(binary,args)=>{
+ assert.equal(binary,'kubectl');calls.push(args);
+ if(args.includes('--raw')){if(state.denied)throw Error('Forbidden');return JSON.stringify({kind:'PodList',items:state.running.map(uid=>({metadata:{uid}}))});}
+ const i=args.indexOf('get');if(i>=0){
+ if(args[i+1]==='deployment')return JSON.stringify(info);
+ if(args[i+1]==='replicasets')return JSON.stringify({items:[{metadata:{uid:'ours',ownerReferences:[{uid:'deployment-uid',controller:true}]}},{metadata:{uid:'theirs',ownerReferences:[{uid:'different',controller:true}]}}]});
+ if(args[i+1]==='pods')return JSON.stringify({items:state.pods});
+ if(args[i+1]==='pod')return state.missing?'':JSON.stringify(state.pods.find(p=>p.metadata.name===args[i+2]));
+ }
+ if(args.includes('scale')){info.spec.replicas=Number(args.find(a=>a.startsWith('--replicas=')).split('=')[1]);return '';}
+ if(args.includes('delete')){state.pods=state.pods.filter(p=>p.metadata.name!==args[args.indexOf('pod')+1]);return '';}
+ throw Error('Unexpected command');
+ };
+ const target={context:'explicit-context',namespace:'payments',deployment:'vault',outageMode:'hard'};
+ return {adapter:kubernetesAdapter(target,command),state,info,calls,target,command};
+}
+test('hard outage terminates only captured deployment-owned pods after scale-zero',async()=>{
+ const {adapter,calls,state}=fixture(),before=await adapter.probe();assert.deepEqual(before.pods.map(p=>p.uid),['pod-a','pod-b']);await adapter.apply('outage',before);
+ const mutations=calls.filter(a=>a.includes('scale')||a.includes('delete'));assert.ok(mutations[0].includes('--replicas=0'));assert.equal(mutations.length,3);
+ for(const args of mutations.slice(1)){for(const flag of ['--grace-period=0','--force','--wait=false'])assert.ok(args.includes(flag));assert.equal(args[1],'explicit-context');}
+ assert.deepEqual(state.pods.map(p=>p.metadata.name),['unrelated']);
+});
+test('API deletion alone cannot start downtime while captured containers remain in runtime',async()=>{
+ const {adapter,state,info}=fixture(),before=await adapter.probe();await adapter.apply('outage',before);Object.assign(info.status,{replicas:0,availableReplicas:0,readyReplicas:0});
+ assert.equal(await adapter.isDown(before),false);state.running=[];assert.equal(await adapter.isDown(before),true);
+ state.pods.push({metadata:{name:'replacement',uid:'new',ownerReferences:[{uid:'ours',controller:true}]},spec:{nodeName:'node-1'}});assert.equal(await adapter.isDown(before),false);
+});
+test('runtime permissions are preflighted, verification fails closed, recovery remains possible',async()=>{
+ const {adapter,state,calls,info}=fixture();state.denied=true;await assert.rejects(adapter.probe(),/nodes\/proxy/);assert.equal(calls.some(a=>a.includes('scale')||a.includes('delete')),false);
+ state.denied=false;const before=await adapter.probe();await adapter.apply('outage',before);Object.assign(info.status,{replicas:0,availableReplicas:0});state.denied=true;await assert.rejects(adapter.isDown(before),/Forbidden/);
+ await adapter.restore(before);assert.equal(info.spec.replicas,2);
+});
+test('identity changes prevent mutation of replacement deployments',async()=>{
+ const {adapter,info,calls}=fixture(),before=await adapter.probe();info.metadata.uid='replacement';await assert.rejects(adapter.apply('outage',before),/identity changed/);await assert.rejects(adapter.restore(before),/identity changed/);assert.equal(calls.some(a=>a.includes('scale')||a.includes('delete')),false);
+});
+test('scale-down may remove captured pods before the explicit deletion',async()=>{
+ const {adapter,state,calls}=fixture(),before=await adapter.probe();state.missing=true;await adapter.apply('outage',before);assert.equal(calls.some(a=>a.includes('delete')),false);
+});
+test('graceful targets retain scale-only behavior',async()=>{
+ const {target,command,calls,info}=fixture(),adapter=kubernetesAdapter({...target,outageMode:'graceful'},command),before=await adapter.probe();assert.equal(before.pods,undefined);await adapter.apply('outage',before);assert.equal(calls.some(a=>a.includes('--raw')||a.includes('delete')),false);await adapter.restore(before);assert.equal(info.spec.replicas,2);assert.equal(await adapter.verify(before),true);
+});
diff --git a/loadtest/console/test/latency-drift.test.mjs b/loadtest/console/test/latency-drift.test.mjs
new file mode 100644
index 0000000000..0f9bc3a418
--- /dev/null
+++ b/loadtest/console/test/latency-drift.test.mjs
@@ -0,0 +1,28 @@
+import test from 'node:test';
+import assert from 'node:assert/strict';
+import {matchedLatencyDrift} from '../server/latency-drift.mjs';
+const windows=[{from:0,to:90000}];
+const sample=(second,flow,ms)=>({observed_at:second*1000,flow_name:flow,server_latency_ms:ms});
+const rows=[sample(5,'cit',100),sample(10,'guest',20),sample(15,'guest',20),sample(31,'cit',100),sample(59,'guest',20),sample(70,'cit',100),sample(80,'cit',100),sample(85,'guest',20)];
+test('bounded expansion matches per-flow counts instead of allowing the mixture to change the median',()=>{
+ const r=matchedLatencyDrift(rows,windows);
+ assert.deepEqual(r.counts,[{flow:'cit',count:2},{flow:'guest',count:2}]);
+ assert.equal(r.samplesPerWindow,4);assert.equal(r.firstMedianMs,60);assert.equal(r.lastMedianMs,60);assert.equal(r.percent,0);
+ assert.equal(r.firstWindow.to,31000);assert.equal(r.lastWindow.from,59000);assert.ok(r.firstWindow.to<r.lastWindow.from);
+});
+test('real latency increases still fail while sample selection is independent of latency',()=>{
+ const r=matchedLatencyDrift(rows.map(r=>({...r,server_latency_ms:r.observed_at>45000?r.server_latency_ms*2:r.server_latency_ms})),windows);
+ assert.equal(r.percent,100);assert.deepEqual(r.counts,[{flow:'cit',count:2},{flow:'guest',count:2}]);
+});
+test('latency decreases show the absolute percentage difference rather than zero',()=>{
+ const r=matchedLatencyDrift([sample(5,'cit',83.5),sample(85,'cit',80.5)],windows);
+ assert.ok(Math.abs(r.percent-100*3/83.5)<1e-10);
+});
+test('unmatched flow types report insufficient evidence and never borrow across the tolerance bound',()=>{
+ const r=matchedLatencyDrift([...rows,sample(1,'sdk',1),sample(45,'sdk',1)],windows);
+ assert.equal(r.percent,null);assert.match(r.reason,/sdk/);
+});
+test('tiny windows keep their early and late samples disjoint and expose the effective tolerance',()=>{
+ const r=matchedLatencyDrift([sample(.1,'a',10),sample(2.9,'a',11)],[{from:0,to:3000}]);
+ assert.equal(r.toleranceSeconds,.25);assert.equal(r.percent,10);assert.equal(r.samplesPerWindow,1);
+});
diff --git a/loadtest/console/test/live-chart.test.mjs b/loadtest/console/test/live-chart.test.mjs
new file mode 100644
index 0000000000..ad7a329130
--- /dev/null
+++ b/loadtest/console/test/live-chart.test.mjs
@@ -0,0 +1,68 @@
+import test from 'node:test';import assert from 'node:assert/strict';import {readFile} from 'node:fs/promises';import {compile} from 'svelte/compiler';import {render} from 'svelte/server';
+const source=await readFile(new URL('../src/LiveChart.svelte',import.meta.url),'utf8');
+const compiled=compile(source,{generate:'server',filename:'LiveChart.svelte'});
+let js=compiled.js.code.replace(/from ['"](svelte[^'"]*)['"]/g,(_,name)=>`from '${import.meta.resolve(name)}'`).replace("'./chart-timeline.mjs'",JSON.stringify(new URL('../src/chart-timeline.mjs',import.meta.url).href));
+const {default:Chart}=await import('data:text/javascript;base64,'+Buffer.from(js).toString('base64'));
+test('full horizon and planned stages render before and during execution',()=>{
+ const timeline=[{start:0,end:10,from:10,target:10,kind:'hold'},{start:10,end:15,from:10,target:10,kind:'fault',fault:{target:'PostgreSQL',action:'outage'}}];
+ const empty=render(Chart,{props:{durationSeconds:15,timeline}}).body;assert.match(empty,/full 15 second test/);assert.match(empty,/Not run yet/);assert.match(empty,/PostgreSQL · fault planned/);assert.match(empty,/recovery planned/);const unrun=empty.match(/<rect x="([\d.]+)" y="35" width="([\d.]+)" height="185" fill="#f0f2f5"/);assert.ok(unrun);
+ const activity=[{at:8000,kind:'fault_requested',message:'Fault requested'},{at:9000,kind:'fault_started',message:'Fault confirmed'},{at:11000,kind:'fault_restore',message:'Recovery requested'},{at:13000,kind:'fault_restored',message:'Recovery verified'}];
+ const live=render(Chart,{props:{durationSeconds:15,timeline,points:[{t:8,activeSeconds:5,successfulTps:10}],activity}}).body;assert.match(live,/full 18 second test/);const future=live.match(/<rect x="([\d.]+)" y="35" width="([\d.]+)" height="185" fill="#f0f2f5"/);assert.ok(future);assert.ok(Math.abs(Number(future[2])/Number(unrun[2])-10/18)<1e-6);assert.ok(Math.abs(Number(future[1])+Number(future[2])-Number(unrun[1])-Number(unrun[2]))<1e-6);assert.match(live,/Fault requested/);assert.match(live,/Fault confirmed/);assert.match(live,/Recovery requested/);assert.match(live,/Recovery verified/);assert.match(live,/stroke="#398453"/);
+ const errors=render(Chart,{props:{durationSeconds:15,timeline,points:[{t:8,activeSeconds:5,errors:100}],metric:'errors',activity}}).body;assert.match(errors,/full 18 second test/);
+});
+test('active run status renders inside the timeline card',()=>{
+ const status={state:'running',smoke:false,label:'Single · 5 TPS',clock:'20 / 85s active',pending:false,faultActive:false,faultBlocked:false,cancel:()=>{},pause:()=>{},resume:()=>{},createFault:()=>{}};
+ const page=render(Chart,{props:{durationSeconds:85,runStatus:status}}).body;
+ assert.match(page,/Single · 5 TPS/);assert.match(page,/20 \/ 85s active/);assert.match(page,/Ⅱ Pause/);assert.match(page,/>Stop</);assert.doesNotMatch(page,/Create fault|>More</);
+});
+test('Grafana mode retains run controls while hiding native graph and filters',()=>{
+ const html=render(Chart,{props:{showMetrics:false,runStatus:{state:'running',live:true,label:'5 TPS',clock:'20s active',pause:()=>{},cancel:()=>{}}}}).body;
+ assert.match(html,/Load controls/);assert.match(html,/Ⅱ Pause/);assert.match(html,/>Stop</);
+ assert.match(html,/class="chart-filters[^>]*hidden/);assert.match(html,/class="plot[^>]*hidden/);
+});
+
+test('stopping is visible and disables duplicate cancellation while cleanup continues',()=>{
+ const page=render(Chart,{props:{runStatus:{state:'stopping',live:true,stopping:true,label:'9 TPS',clock:'40 / 121s active',cancel:()=>{}}}}).body;
+ assert.match(page,/Stopping…/);assert.match(page,/<button[^>]*disabled[^>]*>Stopping…<\/button>/);
+ assert.match(page,/Stop requested/);assert.doesNotMatch(page,/Ⅱ Pause|Run again|View results/);
+});
+test('load actions appear beside the card title before the status row',()=>{
+ for(const status of [{state:'running',live:true,pause:()=>{},cancel:()=>{}},{state:'cancelled',live:false,runAgain:()=>{},resultsUrl:'/results?run=test'}]){
+ const page=render(Chart,{props:{runStatus:{label:'9 TPS',clock:'40 / 121s active',...status}}}).body;
+ assert.ok(page.indexOf('Load timeline')<page.indexOf('class="actions'));
+ assert.ok(page.indexOf('class="actions')<page.indexOf('timeline-run-toolbar'));
+ }
+});
+
+test('ready actions share the timeline card header',()=>{
+ const page=render(Chart,{props:{runStatus:{state:'idle',live:true,label:'',clock:'141s · up to 9 TPS',startLoad:()=>{},smokeTest:()=>{}}}}).body;
+ assert.match(page,/Run smoke test/);assert.match(page,/Start load/);assert.match(page,/>Ready</);
+ assert.ok(page.indexOf('Start load')<page.indexOf('timeline-run-toolbar'));
+});
+test('flow-rate charts connect measured successful samples with pointed peaks',()=>{
+ const page=render(Chart,{props:{durationSeconds:10,points:[{t:1,successfulTps:0},{t:2,successfulTps:1}]}}).body;
+ assert.match(page,/d="M131\.6,220\.0 L215\.2,[\d.]+" fill="none" stroke="#0561e2"/);
+});
+test('failover request renders a dashed marker alongside observed DB availability',()=>{
+ const activity=[{at:2000,kind:'fault_requested',message:'PostgreSQL · failover requested'},
+ {at:4000,kind:'database_unavailable',message:'DB · unavailable'},
+ {at:6000,kind:'database_available',message:'DB · available'}];
+ const page=render(Chart,{props:{durationSeconds:10,startedAt:0,activity}}).body;
+ assert.match(page,/stroke="#5277b8" stroke-dasharray="4 3"[^>]*><title>2\.0s · PostgreSQL · failover requested/);
+ assert.match(page,/4\.0s · DB · unavailable/);assert.match(page,/6\.0s · DB · available/);
+});
+
+test('throughput plots successful completions rather than admitted flows, including narrow recovery spikes',()=>{
+ const points=Array.from({length:1200},(_,i)=>({t:i+1,intervalStart:i,tps:5,successfulTps:i===601?50:i===600?0:5,flows:{guest:{tps:5,successfulTps:i===601?20:0}}}));
+ const page=render(Chart,{props:{durationSeconds:1200,points}}).body;
+ assert.match(page,/Successful flows \/ second/);
+ assert.match(page,/Successfully completed flows per second/);
+ assert.match(page,/>57.5<\/text>/);
+ const guest=render(Chart,{props:{durationSeconds:1200,points,flow:'guest'}}).body;
+ assert.match(guest,/>23.0<\/text>/);
+});
+
+test('latency charts connect sample peaks through explicit zero outage samples',()=>{
+ const page=render(Chart,{props:{durationSeconds:10,metric:'serverP99',points:[{t:1,intervalStart:0,successfulTps:5,serverP99:100},{t:2,intervalStart:1,successfulTps:0,serverP99:null},{t:3,intervalStart:2,successfulTps:5,serverP99:1000}]}}).body;
+ assert.match(page,/d="M131\.6,[\d.]+ L215\.2,220\.0 L298\.8,[\d.]+" fill="none" stroke="#0561e2"/);
+});
diff --git a/loadtest/console/test/metrics-view.test.mjs b/loadtest/console/test/metrics-view.test.mjs
new file mode 100644
index 0000000000..18a9053f7f
--- /dev/null
+++ b/loadtest/console/test/metrics-view.test.mjs
@@ -0,0 +1,25 @@
+import test from 'node:test';
+import assert from 'node:assert/strict';
+import {readFile} from 'node:fs/promises';
+import {compile} from 'svelte/compiler';
+import {render} from 'svelte/server';
+async function component(name,dependencies={}){
+ const file=new URL(`../src/${name}`,import.meta.url);
+ const js=compile(await readFile(file,'utf8'),{generate:'server',filename:name}).js.code
+ .replace(/from ['"](svelte[^'"]*)['"]/g,(_,name)=>`from '${import.meta.resolve(name)}'`)
+ .replace(/from ['"](\.[^'"]+)['"]/g,(_,relative)=>`from '${dependencies[relative]||new URL(relative,file).href}'`);
+ return 'data:text/javascript;base64,'+Buffer.from(js).toString('base64');
+}
+const panel=await component('GrafanaPanel.svelte');
+const graphs=await component('GrafanaMetrics.svelte',{'./GrafanaPanel.svelte':panel});
+const {default:View}=await import(await component('MetricsView.svelte',{'./GrafanaMetrics.svelte':graphs}));
+const props={run:{startedAt:1000,endedAt:301000},grafana:{hasIdentity:true,baseUrl:'http://localhost:3002'}};
+test('native mode does not load Grafana iframes',()=>{
+ const html=render(View,{props}).body;
+ assert.match(html,/Metrics source/);assert.doesNotMatch(html,/<iframe|<details/);
+});
+test('Grafana mode reserves three panels while isolated embed URLs load on the client',()=>{
+ const html=render(View,{props:{...props,value:'grafana'}}).body;
+ assert.equal((html.match(/class="grafana-panel"/g)||[]).length,3);assert.doesNotMatch(html,/<iframe /);
+ assert.doesNotMatch(html,/<h3|<details/);assert.match(html,/Open ↗/);
+});
diff --git a/loadtest/console/test/navigation.test.mjs b/loadtest/console/test/navigation.test.mjs
new file mode 100644
index 0000000000..ef03ac6e56
--- /dev/null
+++ b/loadtest/console/test/navigation.test.mjs
@@ -0,0 +1,27 @@
+import test from 'node:test';
+import assert from 'node:assert/strict';
+import {readFile} from 'node:fs/promises';
+
+// Keep the URL logic real while replacing SvelteKit's browser-only history API.
+const source=(await readFile(new URL('../src/navigation.mjs',import.meta.url),'utf8'))
+ .replace("import {writable} from 'svelte/store';",'const writable=value=>({set(next){value=next;},get(){return value;}});')
+ .replace("import {replaceState} from '$app/navigation';",'const replaceState=url=>{window.location.href=url.href;};');
+const {setQuery,sectionHref,navigationContext}=await import(`data:text/javascript;base64,${Buffer.from(source).toString('base64')}`);
+
+test('metrics preference survives URL updates and section navigation',()=>{
+ globalThis.window={location:{href:'http://localhost/performance?run=one&flow=guest'}};
+ try{
+ setQuery({metrics:'grafana'});
+ assert.equal(new URL(window.location.href).searchParams.get('metrics'),'grafana');
+ setQuery({run:'two'});
+ const results=new URL(sectionHref('results',new URL(window.location.href),navigationContext.get()),'http://localhost');
+ assert.equal(results.searchParams.get('metrics'),'grafana');
+ assert.equal(results.searchParams.get('run'),'two');
+ const fixtures=new URL(sectionHref('fixtures',results,navigationContext.get()),results);
+ const performance=new URL(sectionHref('performance',fixtures,navigationContext.get()),results);
+ assert.equal(performance.searchParams.get('metrics'),'grafana');
+ setQuery({metrics:'native'});
+ const native=new URL(sectionHref('results',new URL(window.location.href),navigationContext.get()),results);
+ assert.equal(native.searchParams.get('metrics'),'native');
+ }finally{delete globalThis.window;}
+});
diff --git a/loadtest/console/test/payment-index.test.mjs b/loadtest/console/test/payment-index.test.mjs
new file mode 100644
index 0000000000..5eb6d79e66
--- /dev/null
+++ b/loadtest/console/test/payment-index.test.mjs
@@ -0,0 +1,45 @@
+import test from 'node:test';
+import assert from 'node:assert/strict';
+import {mkdtemp,readFile,writeFile,mkdir,rm} from 'node:fs/promises';
+import path from 'node:path';import os from 'node:os';import {DatabaseSync} from 'node:sqlite';
+const temporary=await mkdtemp(path.join(os.tmpdir(),'payment-index-'));
+process.env.LOADTEST_DATA_DIR=temporary;process.env.LOADTEST_CONSOLE_ROOT=path.resolve('.');process.env.LOADTEST_ROOT=path.resolve('..');
+const config=JSON.parse(await readFile('../loadtest.config.example.json','utf8'));config.output=path.join(temporary,'artifacts');
+process.env.LOADTEST_CONFIG_FILE=path.join(temporary,'seed.json');await writeFile(process.env.LOADTEST_CONFIG_FILE,JSON.stringify(config));
+const state=await import('../server/state.mjs');state.initializeConfig();
+const {createPaymentIndex,seedPaymentIndex,rebuildBuckets,outcomeWriter,paymentBars,paymentPage,paymentDetail,nextDiscrepancy}=await import('../server/reconciliation-index.mjs');
+const directory=path.join(config.output,'single/runs/test');await mkdir(directory,{recursive:true});
+const db=new DatabaseSync(path.join(directory,'reconciliation.sqlite'));
+const n=Number(process.env.CONSOLE_SCALE_PAYMENTS||10000);
+test(`exact bounded reconciliation queries over ${n.toLocaleString()} payments`,()=>{
+ const started=performance.now();createPaymentIndex(db);
+ db.exec('BEGIN');const chunk=100000;
+ for(let offset=0;offset<n;offset+=chunk)db.prepare(`WITH RECURSIVE sequence(x) AS (SELECT ? UNION ALL SELECT x+1 FROM sequence WHERE x<?) INSERT INTO reconciliation_payments(id,elapsed_ms,merchant_id,payment_id,recorded_status,database_status,outcome) SELECT x,CAST((x-1)/2 AS INTEGER),'merchant','p'||CAST(x AS INTEGER),'succeeded',CASE WHEN x%100003=0 THEN NULL WHEN x%17009=0 THEN 'failed' ELSE 'succeeded' END,CASE WHEN x%100003=0 THEN 'missing' WHEN x%17009=0 THEN 'mismatch' ELSE 'match' END FROM sequence`).run(offset+1,Math.min(n,offset+chunk));
+ rebuildBuckets(db);db.prepare('INSERT INTO reconciliation_meta VALUES(?,?)').run('duration',Math.ceil(n/2));db.exec('COMMIT');
+ const built=performance.now(),overview=paymentBars({id:'single:test',bars:300}),queried=performance.now();
+ assert.equal(overview.mode,'buckets');assert.ok(overview.rows.length<=302);
+ assert.equal(Object.values(overview.totals).reduce((a,b)=>a+b,0),n);
+ const exact=db.prepare("SELECT SUM(outcome='match') matched,SUM(outcome='missing') missing,SUM(outcome='mismatch') mismatch FROM reconciliation_payments").get();
+ assert.equal(overview.totals.match,exact.matched);assert.equal(overview.totals.missing,exact.missing);assert.equal(overview.totals.mismatch,exact.mismatch);
+ assert.equal(overview.rows.reduce((s,r)=>s+r.missing+r.mismatch,0),exact.missing+exact.mismatch);
+ assert.ok(Buffer.byteLength(JSON.stringify(overview))<180000);
+ const detail=paymentBars({id:'single:test',from:100,to:110,bars:100});assert.equal(detail.mode,'payments');assert.equal(detail.rows.length,20);
+ const stableDetail=paymentBars({id:'single:test',from:0,to:159,bars:300});assert.equal(stableDetail.rows.length,318);assert.equal(stableDetail.mode,'payments');
+ const edges=paymentBars({id:'single:test',from:123,to:4567,bars:30});assert.equal(edges.rows.reduce((s,r)=>s+r.match+r.missing+r.mismatch,0),(4567-123)*2);
+ const first=paymentPage({id:'single:test',filter:'all',limit:7}),second=paymentPage({id:'single:test',filter:'all',...first.next,limit:7});assert.equal(new Set([...first.rows,...second.rows].map(r=>r.id)).size,14);
+ assert.equal(paymentDetail({id:'single:test',merchant:'merchant',payment:'p1'}).id,1);
+ assert.ok(!nextDiscrepancy({id:'single:test',after:n}));
+ if(n>17009)assert.equal(nextDiscrepancy({id:'single:test'}).id,17009);
+ console.log(JSON.stringify({payments:n,buildMs:Math.round(built-started),overviewMs:Math.round(queried-built),bars:overview.rows.length,payloadBytes:Buffer.byteLength(JSON.stringify(overview)),discrepancies:exact.missing+exact.mismatch}));
+});
+test('pending bars update transactionally, first observation defines load time',()=>{
+ const source=path.join(directory,'results.sqlite'),input=new DatabaseSync(source);input.exec(`CREATE TABLE request_events(merchant_id TEXT,payment_id TEXT,observed_at INTEGER,run_id TEXT,role TEXT,operation TEXT,api_status_code INTEGER,event_id INTEGER,message TEXT,error_body TEXT);CREATE TABLE payments(run_id TEXT,merchant_id TEXT,payment_id TEXT,status TEXT,observed_at INTEGER,role TEXT);
+ INSERT INTO payments VALUES('run','m','a','succeeded',2000,'measured'),('run','m','b','requires_payment_method',3000,'measured');
+ INSERT INTO request_events(merchant_id,payment_id,observed_at) VALUES('m','a',1100),('m','a',2000),('m','b',1200);`);input.close();
+ seedPaymentIndex(db,source,{runId:'run',startedAt:1000,durationSeconds:3});
+ assert.equal(paymentBars({id:'single:test'}).totals.pending,2);
+ db.exec('BEGIN');outcomeWriter(db)([{merchantId:'m',paymentId:'a',databaseStatus:'succeeded',outcome:'match'},{merchantId:'m',paymentId:'b',databaseStatus:null,outcome:'missing'}]);db.exec('COMMIT');
+ const result=paymentBars({id:'single:test'});assert.deepEqual(result.totals,{match:1,missing:1,mismatch:0,pending:0,creation_unknown:0});assert.equal(result.rows[0].elapsed_ms,100);
+ assert.equal(paymentPage({id:'single:test',filter:'discrepancies'}).rows[0].payment_id,'b');
+});
+test.after(async()=>{db.close();await rm(temporary,{recursive:true,force:true});});
diff --git a/loadtest/console/test/postgres.test.mjs b/loadtest/console/test/postgres.test.mjs
new file mode 100644
index 0000000000..807bd2902c
--- /dev/null
+++ b/loadtest/console/test/postgres.test.mjs
@@ -0,0 +1,57 @@
+import test from 'node:test';
+import assert from 'node:assert/strict';
+import { mkdtemp,readFile,writeFile,mkdir } from 'node:fs/promises';
+import os from 'node:os';
+import path from 'node:path';
+import { DatabaseSync } from 'node:sqlite';
+import pg from 'pg';
+
+// Opt in against an existing HS database; this test only reads PostgreSQL.
+test('PostgreSQL reconciliation batches, persists outcomes and rejects incomplete recording',
+ {skip:process.env.CONSOLE_TEST_PG!=='1'},async()=>{
+ const temporary=await mkdtemp(path.join(os.tmpdir(),'loadtest-console-pg-'));
+ process.env.LOADTEST_DATA_DIR=temporary;
+ process.env.LOADTEST_CONSOLE_ROOT=path.resolve('.');process.env.LOADTEST_ROOT=path.resolve('..');
+ const config=JSON.parse(await readFile('../loadtest.config.example.json','utf8'));config.output=path.join(temporary,'artifacts');
+ process.env.LOADTEST_CONFIG_FILE=path.join(temporary,'seed.json');await writeFile(process.env.LOADTEST_CONFIG_FILE,JSON.stringify(config));
+ const state=await import('../server/state.mjs');state.initializeConfig();
+ const {databaseConnectionOptions}=await import('../server/database-options.mjs');
+ const {queryWorker}=await import('../server/workers.mjs');
+ const database={host:process.env.PGHOST,port:Number(process.env.PGPORT || 5432),database:process.env.PGDATABASE,
+ user:process.env.PGUSER,password:process.env.PGPASSWORD,ssl:['require','verify-ca','verify-full'].includes(process.env.PGSSLMODE),caPath:process.env.PGSSLROOTCERT || ''};
+ const pool=new pg.Pool({...databaseConnectionOptions(database),max:1});
+ let rows;
+ try {
+ const client=await pool.connect();
+ try {await client.query('BEGIN READ ONLY');rows=(await client.query('SELECT merchant_id,payment_id,status::text AS status FROM payment_intent WHERE status IS NOT NULL LIMIT 2')).rows;await client.query('COMMIT');}
+ finally{client.release();}
+ }finally{await pool.end();}
+ assert.equal(rows.length,2,'Provide a database with at least two payments for this integration test');
+ const directory=path.join(config.output,'single/runs/recon-test');await mkdir(directory,{recursive:true});
+ await writeFile(path.join(directory,'config.json'),JSON.stringify(config));
+ const db=new DatabaseSync(path.join(directory,'results.sqlite'));
+ db.exec(await readFile('../k6/scenario-mix/recorder/schema.sql','utf8'));
+ db.exec("INSERT INTO runs(run_id,started_at,ended_at,recording_state,enqueued,persisted) VALUES('recon',1,2,'complete',1004,1004)");
+ const insert=db.prepare("INSERT INTO payments(run_id,merchant_id,payment_id,status,role,api_status_code,observed_at,response_event_id) VALUES('recon',?,?,?,'measured',200,1,1)");
+ insert.run(rows[0].merchant_id,rows[0].payment_id,rows[0].status);
+ insert.run(rows[1].merchant_id,rows[1].payment_id,'test-client-mismatch');
+ for(let n=0;n<1002;n++)insert.run('console-test-absent',`zz-console-test-${n}`,'succeeded');
+ const failure=db.prepare("INSERT INTO request_events(run_id,attempt_id,flow_id,merchant_id,payment_id,operation,role,observed_at,method,url,api_status_code,latency_ms,message) VALUES('recon',?,'flow',?,?,?,'measured',1,'POST','http://test',0,30000,'request timeout')");
+ failure.run(1,rows[0].merchant_id,rows[0].payment_id,'payment_confirm');failure.run(2,rows[1].merchant_id,rows[1].payment_id,'payment_confirm');
+ failure.run(3,'absent-merchant','absent-payment','payment_confirm');failure.run(4,'absent-merchant',null,'payment_create');failure.run(5,'absent-merchant',null,'customer_create');
+ const progress=[];
+ const result=await queryWorker('reconcile',{id:'single:recon-test',database},p=>progress.push(p.compared));
+ const batches=[0,...Array.from({length:10},(_,i)=>(i+1)*100),1004];assert.deepEqual(progress,batches);assert.equal(result.expected,1004);assert.deepEqual(result.timeline.map(p=>p.compared),batches);assert.equal(result.timeline.at(-1).match,1);assert.equal(result.timeline.at(-1).missing,1002);assert.ok(result.timeline.every((p,i,all)=>!i||p.t>=all[i-1].t));assert.equal(result.match,1);assert.equal(result.mismatch,1);assert.equal(result.missing,1002);assert.equal(result.creationUnknown,1);assert.equal(result.confirmationFailed,2);assert.equal(result.accounted,1005);
+ assert.deepEqual({attempts:result.transport.attempts,checked:result.transport.checkedPayments,found:result.transport.found,missing:result.transport.missing,unresolved:result.transport.unresolved},{attempts:5,checked:3,found:2,missing:1,unresolved:2});
+ assert.match(result.discrepancies.find(r=>r.paymentId===rows[1].payment_id).reason,/Transport failure/);
+ assert.ok(result.comparedAt);assert.ok(result.truncated);assert.equal(result.discrepancies.length,200);
+ const saved=JSON.parse(await readFile(path.join(directory,'reconciliation.json'),'utf8'));assert.equal(saved.total,1004);
+ const output=new DatabaseSync(path.join(directory,'reconciliation.sqlite'),{readOnly:true});
+ assert.equal(output.prepare('SELECT COUNT(*) n FROM comparisons').get().n,1004);assert.equal(output.prepare('SELECT COUNT(*) n FROM transport_comparisons').get().n,3);output.close();
+ db.exec("UPDATE runs SET recording_state='incomplete',enqueued=1005");
+ await assert.rejects(queryWorker('reconcile',{id:'single:recon-test',database}),/incomplete/);
+ assert.equal((await queryWorker('reconcile',{id:'single:recon-test',database,allowIncomplete:true})).total,1004);
+ db.exec("DELETE FROM payments; UPDATE runs SET recording_state='complete',enqueued=persisted");
+ const onlyTransport=await queryWorker('reconcile',{id:'single:recon-test',database});assert.equal(onlyTransport.total,0);assert.equal(onlyTransport.transport.checkedPayments,3);assert.equal(onlyTransport.transport.unresolved,2);
+ db.close();
+ });
diff --git a/loadtest/console/test/ramp-editor.test.mjs b/loadtest/console/test/ramp-editor.test.mjs
new file mode 100644
index 0000000000..241e9a7fce
--- /dev/null
+++ b/loadtest/console/test/ramp-editor.test.mjs
@@ -0,0 +1,20 @@
+import test from 'node:test';
+import assert from 'node:assert/strict';
+import {stageRates,encodeStages} from '../src/ramp-editor.mjs';
+
+test('hold display follows starting TPS and ignores stale targets',()=>{
+ const rows=[{kind:'hold',target:4,duration:60},{kind:'ramp',target:4,duration:60}];
+ assert.deepEqual(stageRates(rows,1),[1,4]);
+ assert.deepEqual(stageRates(rows,2),[2,4]);
+ assert.deepEqual(stageRates(rows,1),encodeStages(rows,1).map(s=>s.target_rps));
+});
+
+test('holds inherit preceding ramps across faults, reordering and removal',()=>{
+ const ramp={kind:'ramp',target:3,duration:60};
+ const hold={kind:'hold',target:9,duration:60};
+ const fault={kind:'fault',target:9,duration:10,fault:{targetId:'demo',action:'outage'}};
+ assert.deepEqual(stageRates([ramp,fault,hold],1),[3,3,3]);
+ assert.deepEqual(stageRates([hold,fault,ramp],1),[1,1,3]);
+ assert.deepEqual(stageRates([fault,hold],1),[1,1]);
+ assert.deepEqual(stageRates([{...ramp,kind:'hold'},hold],1),[1,1]);
+});
diff --git a/loadtest/console/test/reconciliation-integration.test.mjs b/loadtest/console/test/reconciliation-integration.test.mjs
new file mode 100644
index 0000000000..d0389747ce
--- /dev/null
+++ b/loadtest/console/test/reconciliation-integration.test.mjs
@@ -0,0 +1,32 @@
+import test from 'node:test';import assert from 'node:assert/strict';
+import {mkdtemp,readFile,writeFile,mkdir,rm} from 'node:fs/promises';import path from 'node:path';import os from 'node:os';import {DatabaseSync} from 'node:sqlite';import pg from 'pg';
+const temporary=await mkdtemp(path.join(os.tmpdir(),'recon-integration-'));
+process.env.LOADTEST_DATA_DIR=temporary;process.env.LOADTEST_CONSOLE_ROOT=path.resolve('.');process.env.LOADTEST_ROOT=path.resolve('..');
+const config=JSON.parse(await readFile('../loadtest.config.example.json','utf8'));config.output=path.join(temporary,'artifacts');
+process.env.LOADTEST_CONFIG_FILE=path.join(temporary,'seed.json');await writeFile(process.env.LOADTEST_CONFIG_FILE,JSON.stringify(config));
+const state=await import('../server/state.mjs');state.initializeConfig();
+const {reconcileRun,requestHistory}=await import('../server/queries.mjs');const {paymentBars,paymentPage}=await import('../server/reconciliation-index.mjs');const {csvStream,csvCell}=await import('../server/csv-stream.mjs');
+const directory=path.join(config.output,'single/runs/integration');await mkdir(directory,{recursive:true});await writeFile(path.join(directory,'config.json'),JSON.stringify(config));
+const db=new DatabaseSync(path.join(directory,'results.sqlite'));db.exec(await readFile('../k6/scenario-mix/recorder/schema.sql','utf8'));
+db.exec("INSERT INTO runs(run_id,started_at,ended_at,recording_state,enqueued,persisted) VALUES('run',1000,5000,'complete',2402,2402)");
+const event=db.prepare("INSERT INTO request_events(run_id,attempt_id,flow_id,merchant_id,operation,role,observed_at,method,url,payment_id,status,api_status_code,latency_ms,message) VALUES('run',?,'guest','merchant','payment_confirm','measured',?,'POST','http://mock',?,'succeeded',?,30,?)"),payment=db.prepare("INSERT INTO payments(run_id,payment_id,merchant_id,status,role,api_status_code,observed_at,response_event_id) VALUES('run',?,'merchant','succeeded','measured',200,?,?)");
+for(let i=1;i<=1201;i++){event.run(i,1000+i,'p'+i,i===2?0:200,i===2?'request timeout':null);payment.run('p'+i,2000+i,i);}event.run(1202,1300,null,0,'request timeout');
+db.exec("UPDATE request_events SET operation='payment_create' WHERE attempt_id=1202");
+event.run(1203,1301,null,503,'application unavailable');
+db.exec("UPDATE request_events SET operation='payment_create' WHERE attempt_id=1203");
+event.run(1204,2400,'p4',504,'confirmation timed out');
+test('comparison persists exact bar outcomes, transport evidence, filters and streaming exports',async()=>{
+ const Original=pg.Pool,queries=[];pg.Pool=class{async connect(){return{async query(sql,args){queries.push(sql);if(!args)return {rows:[]};return {rows:args[1].filter(id=>id!=='p3').map((id)=>({merchant_id:'merchant',payment_id:id,status:id==='p2'?'failed':'succeeded'}))};},release(){}};}async end(){}};
+ let result;try{result=await reconcileRun({id:'single:integration',database:{host:'mock',port:5432,user:'reader'} });}finally{pg.Pool=Original;}
+ assert.equal(result.total,1201);assert.equal(result.match,1199);assert.equal(result.missing,1);assert.equal(result.mismatch,1);assert.equal(result.transport.unresolved,1);assert.equal(result.transport.found,1);
+ assert.ok(queries.includes('BEGIN ISOLATION LEVEL REPEATABLE READ READ ONLY'));assert.match(result.discrepancies.find(p=>p.paymentId==='p2').reason,/Transport failure/);
+ assert.equal(result.creationUnknown,2);assert.equal(result.confirmationFailed,2);assert.equal(result.accounted,1203);
+ const chart=paymentBars({id:'single:integration'});assert.deepEqual(chart.totals,{match:1199,missing:1,mismatch:1,pending:0,creation_unknown:2});
+ const unknown=paymentPage({id:'single:integration',filter:'creation_unknown'});assert.equal(unknown.rows.length,2);assert.equal(unknown.rows[1].api_status_code,503);assert.ok(unknown.rows.every(r=>r.event_id&&r.payment_id===''));
+ const failedConfirm=paymentPage({id:'single:integration',filter:'confirmation_failed'});assert.equal(failedConfirm.rows.length,2);assert.equal(failedConfirm.rows.find(r=>r.payment_id==='p4').outcome,'match');
+ const page=paymentPage({id:'single:integration',filter:'discrepancies'});assert.equal(page.rows.length,4);assert.equal(page.rows[0].elapsed_ms,2);
+ assert.equal(requestHistory({id:'single:integration',status:'transport'}).rows.length,2);assert.equal(requestHistory({id:'single:integration',payment:'p2',merchant:'merchant'}).rows[0].message,'request timeout');assert.equal(requestHistory({id:'single:integration',search:'p%'}).rows.length,0);
+ const csv=await new Response(csvStream('payment-page',{id:'single:integration',filter:'all'},['payment_id','outcome'])).text();assert.equal(csv.trim().split('\r\n').length,1204);assert.match(csv,/"p2","mismatch"/);assert.match(csv,/"p3","missing"/);assert.match(csv,/"","creation_unknown"/);
+ assert.equal(csvCell('=formula'),`"'=formula"`);assert.equal(csvCell('a,"b"'),`"a,""b"""`);
+});
+test.after(async()=>{db.close();await rm(temporary,{recursive:true,force:true});});
diff --git a/loadtest/console/test/reconciliation-refresh.test.mjs b/loadtest/console/test/reconciliation-refresh.test.mjs
new file mode 100644
index 0000000000..ce7a8added
--- /dev/null
+++ b/loadtest/console/test/reconciliation-refresh.test.mjs
@@ -0,0 +1,31 @@
+import test from 'node:test';
+import assert from 'node:assert/strict';
+import {readFile} from 'node:fs/promises';
+import vm from 'node:vm';
+
+// Execute the actual stream handler with a controlled API and event stream.
+const source=await readFile(new URL('../src/RunScreen.svelte',import.meta.url),'utf8');
+const handler=source.slice(source.indexOf(' function watchReconciliation(runId){'),source.indexOf(' const modeLabel'));
+function screen(fetchRun){
+ const state={selectedRun:{id:'run-a',scenarioChecks:{verdict:'incomplete'}},reconciliationJob:{id:'job'},reconciliationEvents:null,reconciling:true,reconciliation:null,runTimeline:[],error:'',api:{run:fetchRun},watchJobStream(id,callback){state.complete=callback;return {close(){}};}};
+ vm.createContext(state);vm.runInContext(handler,state);state.watchReconciliation('run-a');return state;
+}
+test('completed reconciliation refreshes run summary from the server',async()=>{
+ const refreshed={id:'run-a',scenarioChecks:{groups:[{kind:'integrity',checks:[{actual:0,outcome:'pass'}]}]}};
+ const state=screen(async id=>{assert.equal(id,'run-a');return refreshed;});
+ await state.complete({status:'completed',result:{missing:0,total:1459}});
+ assert.equal(state.selectedRun,refreshed);
+ assert.equal(state.reconciliation.missing,0);assert.equal(state.reconciling,false);
+});
+test('a late refresh cannot overwrite another selected run',async()=>{
+ let resolve;const state=screen(()=>new Promise(r=>resolve=r));
+ const pending=state.complete({status:'completed',result:{missing:0}});
+ state.selectedRun={id:'run-b'};resolve({id:'run-a'});await pending;
+ assert.equal(state.selectedRun.id,'run-b');
+});
+test('failed reconciliation retains its error and does not fetch a new verdict',async()=>{
+ const state=screen(()=>assert.fail('failed job must not refresh'));
+ await state.complete({status:'failed',error:'Database unavailable'});
+ assert.equal(state.error,'Database unavailable');
+ assert.equal(state.selectedRun.scenarioChecks.verdict,'incomplete');
+});
diff --git a/loadtest/console/test/reconciliation-ui.test.mjs b/loadtest/console/test/reconciliation-ui.test.mjs
new file mode 100644
index 0000000000..1927dbecee
--- /dev/null
+++ b/loadtest/console/test/reconciliation-ui.test.mjs
@@ -0,0 +1,17 @@
+import test from 'node:test';
+import assert from 'node:assert/strict';
+import {readFile} from 'node:fs/promises';
+import {compile} from 'svelte/compiler';
+import {render} from 'svelte/server';
+const source=await readFile(new URL('../src/ReconciliationSummary.svelte',import.meta.url),'utf8');
+const compiled=compile(source,{generate:'server',filename:'ReconciliationSummary.svelte'});
+const js=compiled.js.code.replace(/from ['"](svelte[^'"]*)['"]/g,(_,name)=>`from '${import.meta.resolve(name)}'`);
+const {default:Component}=await import('data:text/javascript;base64,'+Buffer.from(js).toString('base64'));
+test('summary renders real outcome history, counts, and legacy/failed states',()=>{
+ const result={total:10,expected:10,match:7,missing:2,mismatch:1,timeline:[{t:0,match:0,missing:0,mismatch:0},{t:2,match:7,missing:2,mismatch:1}],elapsedSeconds:2};
+ const html=render(Component,{props:{result}}).body;
+ assert.match(html,/Reconciled/);assert.match(html,/10 outcomes/);assert.doesNotMatch(html,/<svg|failure-summary|verdict/);assert.match(html,/recorded outcomes/);
+ const legacy=render(Component,{props:{result:{...result,timeline:undefined}}}).body;assert.match(legacy,/recorded outcomes/);assert.doesNotMatch(legacy,/<svg/);
+ const failed=render(Component,{props:{result,job:{status:'failed',error:'Database unavailable',progress:{compared:0}}}}).body;assert.match(failed,/Comparison failed/);assert.match(failed,/Database unavailable/);assert.doesNotMatch(failed,/Reconciled/);
+ const live=render(Component,{props:{running:true,job:{progress:{compared:4,expected:10,match:4}}}}).body;assert.match(live,/Comparing…/);assert.match(live,/<progress/);assert.match(live,/4 \/ 10 payment IDs compared/);
+});
diff --git a/loadtest/console/test/result-test-cases.test.mjs b/loadtest/console/test/result-test-cases.test.mjs
new file mode 100644
index 0000000000..f5922fa810
--- /dev/null
+++ b/loadtest/console/test/result-test-cases.test.mjs
@@ -0,0 +1,76 @@
+import test from 'node:test';import assert from 'node:assert/strict';
+import {testCaseCatalog,testCasePlan,resultTestCases} from '../src/result-test-cases.mjs';
+const check=(id,actual=10,outcome='pass')=>({id,label:id,actual,limit:60,comparison:'≤',unit:'s',outcome});
+const hold=(index,intent)=>({id:`stage-${index}`,stageIndex:index,kind:'hold',state:'complete',title:'Hold',checks:[check('throughput',95),check('p99',80)]});
+const fault=index=>({id:`fault-${index}`,stageIndex:index,kind:'fault',state:'complete',title:'Database failover',checks:[check('recovery',20),{...check('failed',4,'recorded'),limit:null}]});
+const config={load:{stages:[{}, {fault:{targetId:'postgres',action:'failover'}},{fault:{targetId:'card-vault'}}]},faultPlan:[{index:1,action:'failover',target:{id:'postgres'}},{index:2,target:{id:'card-vault'}}]};
+test('all ten original test cases belong to the two finalized sections',()=>{
+ assert.equal(testCaseCatalog.length,10);assert.equal(new Set(testCaseCatalog.map(t=>t.id)).size,10);
+ assert.deepEqual(testCaseCatalog.filter(t=>t.section==='load').map(t=>t.id),['TC-01','TC-02','TC-03','TC-09']);
+ assert.equal(testCaseCatalog.filter(t=>t.section==='faults').length,6);
+});
+test('current hold + DB + vault run maps to original TCs; ramps do not imply a burst',()=>{
+ const groups=[hold(0),fault(1),fault(2),{id:'stage-3',stageIndex:3,kind:'ramp',state:'complete',checks:[check('throughput',99)]}];
+ const plan=testCasePlan(config,groups);assert.deepEqual(plan.map(p=>p.id),['TC-02','TC-04','TC-05','TC-10']);
+ const sections=resultTestCases({groups,testCasePlan:plan});assert.deepEqual(sections.map(s=>s.title),['Load & performance','Faults & recovery']);
+ assert.ok(sections[0].cases.some(c=>c.title==='Ramp observations'));assert.ok(!sections[0].cases.some(c=>c.id==='TC-03'));
+});
+test('repeated failovers stay in one TC and retain every original observation',()=>{
+ const groups=[fault(1),fault(2)];groups[1].checks[0].actual=70;groups[1].checks[0].outcome='fail';
+ const cfg={load:{},faultPlan:[{index:1,action:'failover',target:{id:'postgres'}},{index:2,action:'failover',target:{id:'postgres'}}]};
+ const before=JSON.stringify(groups),sections=resultTestCases({groups,testCasePlan:testCasePlan(cfg,groups)});
+ const tc=sections[0].cases.find(c=>c.id==='TC-04');assert.equal(tc.occurrences,2);assert.equal(tc.outcome,'fail');assert.match(tc.observed,/70 s recovery/);assert.equal(tc.checks.filter(c=>c.id==='recovery').length,2);assert.equal(JSON.stringify(groups),before);
+});
+test('fault failures have a separate total line and recovery summaries show only time',()=>{
+ const groups=[fault(1),fault(2)];
+ const rows=resultTestCases({groups,testCasePlan:[{id:'TC-04',groupIds:groups.map(g=>g.id)}]}).flatMap(s=>s.cases);
+ const row=rows.find(c=>c.id==='TC-04');
+ assert.equal(row.observed,'20 s recovery');
+ assert.equal(row.checks.find(c=>c.id==='total-failed').actual,8);
+ assert.equal(row.checks.find(c=>c.id==='total-failed').label,'Total failed requests');
+ assert.equal(row.checks.some(c=>c.id==='failed'),false);
+});
+test('reconnection and merchant coverage require evidence; vault checks use measured criteria',()=>{
+ const groups=[hold(0),fault(1),fault(2)],cfg={...config,mode:'tenancy',fixtureSet:{merchantCount:1500}};
+ const rows=resultTestCases({groups,testCasePlan:testCasePlan(cfg,groups)}).flatMap(s=>s.cases);
+ for(const id of ['TC-05','TC-09'])assert.equal(rows.find(r=>r.id===id).outcome,'not_measured');
+ const reconnect=rows.find(r=>r.id==='TC-05');
+ assert.ok(reconnect.checks.every(c=>c.id!=='pod-restarts'));
+ assert.doesNotMatch(JSON.stringify(reconnect),/pod restarts|restart evidence/i);
+ assert.equal(rows.find(r=>r.id==='TC-10').outcome,'pass');
+ assert.ok(rows.find(r=>r.id==='TC-10').checks.every(c=>!['unattended','unaffected-flows'].includes(c.id)));
+ assert.match(rows.find(r=>r.id==='TC-09').observed,/1,500 merchants configured/);
+});
+test('application reconnection is measured from resumed successful confirmations, with no pod checks',()=>{
+ const recovery={id:'recovery-1',kind:'recovery',state:'complete',checks:[{id:'completed',actual:104,limit:null,outcome:'recorded'}]};
+ const summary={groups:[fault(1),recovery],testCasePlan:[{id:'TC-05',groupIds:['fault-1','recovery-1']}]};
+ const row=resultTestCases(summary).flatMap(s=>s.cases)[0];
+ assert.equal(row.outcome,'pass');assert.equal(row.checks[0].actual,104);
+ assert.match(row.observed,/104 successful confirmations/);assert.doesNotMatch(JSON.stringify(row),/not measured|pod-restarts/i);
+ recovery.checks[0].actual=0;assert.equal(resultTestCases(summary).flatMap(s=>s.cases)[0].outcome,'fail');
+});
+test('calibration and burst require explicit intent; unsupported selected cases are Not run',()=>{
+ const groups=[hold(0),hold(1)],cfg={load:{stages:[{intent:'calibration'},{intent:'burst'}],testCases:['TC-07','TC-08']}};
+ const plan=testCasePlan(cfg,groups);assert.deepEqual(plan.map(p=>p.id),['TC-01','TC-03','TC-07','TC-08']);
+ const rows=resultTestCases({groups,testCasePlan:plan}).flatMap(s=>s.cases);
+ assert.equal(rows.find(r=>r.id==='TC-01').outcome,'not_measured');
+ for(const id of ['TC-07','TC-08'])assert.equal(rows.find(r=>r.id===id).outcome,'not_run');
+});
+test('unexecuted fault cases stay Not run even if run-wide integrity evidence exists',()=>{
+ const groups=[{...fault(1),state:'not_run'}, {id:'integrity',kind:'integrity',checks:[check('lost',0)]}];
+ const rows=resultTestCases({groups,testCasePlan:testCasePlan(config,groups)}).flatMap(s=>s.cases);
+ assert.ok(rows.every(r=>r.outcome==='not_run'));
+});
+test('a DB stop is not a failover and a burst-labelled ramp is not a burst hold',()=>{
+ const groups=[fault(1),{...hold(0),kind:'ramp'}];
+ const cfg={load:{stages:[{intent:'burst'},{fault:{targetId:'postgres',action:'outage'}}]},faultPlan:[{index:1,action:'outage',target:{id:'postgres'}}]};
+ assert.deepEqual(testCasePlan(cfg,groups),[]);
+});
+test('a hidden latency failure has an explicit reason even when throughput passes',()=>{
+ const group=hold(0);group.checks=[{...check('throughput',99.5),unit:'%',limit:97,comparison:'≥'},{...check('p99',556.7,'fail'),unit:'ms',limit:160}];
+ const tc=resultTestCases({groups:[group]}).flatMap(s=>s.cases)[0];
+ assert.equal(tc.outcome,'fail');assert.equal(tc.failureReason,'Steady p99 exceeds 160 ms');
+ const pooled={checks:group.checks.map(c=>c.id==='p99'?{...c,actual:102,outcome:'pass'}:c)};
+ const corrected=resultTestCases({groups:[group],steady:pooled}).flatMap(s=>s.cases)[0];
+ assert.equal(corrected.outcome,'pass');assert.equal(corrected.failureReason,null);
+});
diff --git a/loadtest/console/test/run-lifecycle.test.mjs b/loadtest/console/test/run-lifecycle.test.mjs
new file mode 100644
index 0000000000..2e275edfc2
--- /dev/null
+++ b/loadtest/console/test/run-lifecycle.test.mjs
@@ -0,0 +1,15 @@
+import test from 'node:test';
+import assert from 'node:assert/strict';
+import {recordingFinished,runJobPresentation} from '../src/run-lifecycle.mjs';
+test('completed load and recording remain complete while cloud cleanup keeps the job active',()=>{
+ const job={command:'load',status:'running',progress:{control:{state:'completed'}}};
+ assert.equal(recordingFinished(job),true);
+ assert.deepEqual(runJobPresentation(job.status,{recording_state:'complete',ended_at:100}),{jobStatus:'complete',cleanupPending:true});
+ assert.deepEqual(runJobPresentation('failed',{recording_state:'complete',ended_at:100}),{jobStatus:'failed',cleanupPending:false});
+});
+test('running, draining, incomplete recordings and smoke tests are not prematurely completed',()=>{
+ for(const state of ['running','draining','paused'])assert.equal(recordingFinished({command:'load',progress:{control:{state}}}),false);
+ assert.equal(recordingFinished({command:'smoke',progress:{control:{state:'completed'}}}),false);
+ assert.equal(runJobPresentation('running',{recording_state:'running'}).jobStatus,'running');
+ assert.equal(runJobPresentation('cancelling',{recording_state:'incomplete',ended_at:100}).jobStatus,'cancelling');
+});
diff --git a/loadtest/console/test/run-summary.test.mjs b/loadtest/console/test/run-summary.test.mjs
new file mode 100644
index 0000000000..8552603fa3
--- /dev/null
+++ b/loadtest/console/test/run-summary.test.mjs
@@ -0,0 +1,76 @@
+import test from 'node:test';
+import assert from 'node:assert/strict';
+import {readFile} from 'node:fs/promises';
+import {compile} from 'svelte/compiler';
+import {render} from 'svelte/server';
+const source=await readFile(new URL('../src/RunSummary.svelte',import.meta.url),'utf8');
+const compiled=compile(source,{generate:'server',filename:'RunSummary.svelte'});
+const overviewUrl=new URL('../src/result-test-cases.mjs',import.meta.url).href;
+const child=compile(await readFile(new URL('../src/ScenarioChecks.svelte',import.meta.url),'utf8'),{generate:'server',filename:'ScenarioChecks.svelte'}).js.code.replace(/from ['"](svelte[^'"]*)['"]/g,(_,name)=>`from '${import.meta.resolve(name)}'`).replace("'./result-test-cases.mjs'",JSON.stringify(overviewUrl)).replace("'./flow-catalog.mjs'",JSON.stringify(new URL('../src/flow-catalog.mjs',import.meta.url).href));
+const childUrl='data:text/javascript;base64,'+Buffer.from(child).toString('base64');
+const js=compiled.js.code.replace(/from ['"](svelte[^'"]*)['"]/g,(_,name)=>`from '${import.meta.resolve(name)}'`).replace("'./environments.mjs'",JSON.stringify(new URL('../src/environments.mjs',import.meta.url).href)).replace("'./ScenarioChecks.svelte'",JSON.stringify(childUrl)).replace("'./result-test-cases.mjs'",JSON.stringify(overviewUrl));
+const {default:Summary}=await import('data:text/javascript;base64,'+Buffer.from(js).toString('base64'));
+const run={startedAt:1000,endedAt:2000,activeSeconds:141,wallSeconds:234,mode:'single',offeredTps:9,persisted:6000,iterations:1475,serverP99:1065.27,serverLatencyPhases:[{state:'normal',count:100,p50:40,p95:60,p99:80},{state:'outage',count:10,p50:30,p95:50,p99:70},{state:'recovery',count:20,p50:90,p95:1000,p99:1500}],profile:{version:12},fixtureSetId:'8eb569d4-fixtures',savedSettings:{limitsSaved:true},hiddenVaultErrors:101,displayErrorRate:1.32,acceptance:{verdict:'fail',resilience:'recovery verified',checks:[{label:'Successful TPS',actual:9.16,limit:6.30638,outcome:'pass'},{label:'HTTP errors (%)',actual:2.99,limit:1,outcome:'fail'}]}};
+test('saved checks show their limits, raw observations, and final verdict',()=>{
+ const html=render(Summary,{props:{run}}).body;
+ assert.match(html,/Failed/);assert.match(html,/2\.99%/);assert.doesNotMatch(html,/1\.32%/);
+ assert.match(html,/≥ 6\.31 TPS/);assert.match(html,/≤ 1%/);assert.doesNotMatch(html,/vault-related failures|Fault recovery/);assert.equal((html.match(/<tr>/g)||[]).length,8);
+ assert.match(html,/Server-side latency/);assert.match(html,/p50 · ms/);assert.match(html,/p95 · ms/);assert.match(html,/p99 · ms/);assert.match(html,/After recovery · first 10s/);assert.match(html,/Completed flows/);assert.doesNotMatch(html,/Client-side latency|Dropped flows|Recording gaps/);assert.doesNotMatch(html,/Scenario v12|Fixture 8eb569d4/);
+});
+test('live and legacy runs do not claim a final saved verdict',()=>{
+ assert.match(render(Summary,{props:{run:{...run,live:true}}}).body,/In progress/);
+ const html=render(Summary,{props:{run:{...run,savedSettings:{limitsSaved:false}}}}).body;
+ assert.doesNotMatch(html,/Failed|Passed|≤ 1%/);assert.match(html,/Recorded/);
+});
+test('scenario stages render checks with explicit missing and failed verdicts',()=>{
+ const scenarioChecks={verdict:'fail',passed:1,evaluated:2,groups:[{id:'stage-0',kind:'hold',title:'1. Hold · 10 TPS',verdict:'fail',latencySamples:12,checks:[
+ {id:'throughput',label:'Achieved vs offered throughput',actual:95,limit:97,unit:'%',comparison:'≥',outcome:'fail'},
+ {id:'p99',label:'Server-side latency · p99',actual:80,limit:160,unit:'ms',comparison:'≤',outcome:'pass'},
+ {id:'errors',label:'HTTP errors',actual:null,limit:1,unit:'%',comparison:'≤',outcome:'not_measured'}]}]};
+ const html=render(Summary,{props:{run:{...run,scenarioChecks}}}).body;
+ assert.match(html,/0\/1 test cases passed/);assert.match(html,/Load &amp; performance|Load & performance/);assert.match(html,/≥ 97%/);assert.match(html,/95%/);assert.match(html,/>Fail</);assert.doesNotMatch(html,/≥ 6\.31 TPS|Hold · 10 TPS/);
+});
+test('scenario-derived latency phases take precedence over legacy presentation phases',()=>{
+ const scenarioChecks={verdict:'recorded',groups:[],states:[{state:'normal',count:10,p50:9999,p95:9999,p99:9999}]};
+ const html=render(Summary,{props:{run:{...run,scenarioChecks}}}).body;
+ assert.match(html,/9,999/);assert.doesNotMatch(html,/>40<|>60<|>80</);
+});
+test('steady-load details show one latency set without case IDs or repeated stages',()=>{
+ const checks=[{id:'throughput',label:'Achieved vs offered throughput',actual:98,limit:97,unit:'%',comparison:'≥',outcome:'pass'},{id:'p99',label:'Server-side latency · p99',actual:9999,unit:'ms',outcome:'recorded'}];
+ const scenarioChecks={verdict:'pass',steady:{checks:[checks[0]]},groups:[0,2].map(i=>({id:`stage-${i}`,kind:'hold',title:`${i+1}. Hold · 6 TPS`,state:'complete',checks}))};
+ const html=render(Summary,{props:{run:{...run,scenarioChecks}}}).body;
+ assert.match(html,/Steady-load performance/);assert.equal((html.match(/p99 · ms/g)||[]).length,1);assert.match(html,/Steady load/);
+ assert.doesNotMatch(html,/TC-\d+|Hold ·|Server-side latency · p99|9,999|9999/);
+ assert.match(html,/>40</);assert.match(html,/>60</);assert.match(html,/>80</);
+});
+
+test('measurement-only rows retain values without claiming a recorded verdict or limit',()=>{
+ const checks=[
+ {id:'throughput',label:'Achieved vs offered throughput',actual:99.88,limit:97,unit:'%',comparison:'≥',outcome:'pass'},
+ {id:'tps',label:'Successful TPS',actual:6.65,limit:null,unit:'TPS',outcome:'recorded'},
+ {id:'completed',label:'Completed flows',actual:2397,limit:null,unit:'flows',outcome:'recorded'}
+ ];
+ const scenarioChecks={verdict:'pass',steady:{checks},groups:[{id:'stage-0',kind:'hold',state:'complete',title:'Hold',checks}]};
+ const html=render(Summary,{props:{run:{...run,scenarioChecks}}}).body;
+ assert.match(html,/6\.65 TPS/);assert.match(html,/2,397 flows/);assert.match(html,/>Pass</);
+ assert.doesNotMatch(html,/>Recorded</);assert.match(html,/>—</);
+});
+
+test('run-wide target completion is a separate strict check from window throughput',()=>{
+ const completion={expected:4200,successful:4200,check:{id:'completion',label:'Target flows completed successfully',actual:100,limit:100,unit:'%',comparison:'≥',outcome:'pass'}};
+ const scenarioChecks={verdict:'pass',completion,groups:[]};
+ const html=render(Summary,{props:{run:{...run,scenarioChecks}}}).body;
+ assert.match(html,/Flow completion/);assert.match(html,/4,200 \/ 4,200 flows · 100%/);assert.match(html,/1\/1 test cases passed/);assert.match(html,/100% of target flows/);
+ const failed={...completion,successful:4199,check:{...completion.check,actual:100*4199/4200,outcome:'fail'}};
+ const failure=render(Summary,{props:{run:{...run,scenarioChecks:{...scenarioChecks,verdict:'fail',completion:failed}}}}).body;
+ assert.match(failure,/Failed/);assert.match(failure,/0\/1 test cases passed/);
+});
+
+test('missing payment integrity explicitly requires reconciliation and updates with evidence',()=>{
+ const fault={id:'fault-1',kind:'fault',target:'Card vault',state:'complete',checks:[{id:'recovery',label:'Recovery after restoration starts',actual:54.414,limit:60,unit:'s',comparison:'≤',outcome:'pass'}]};
+ const make=verified=>({...run,scenarioChecks:{verdict:verified?'pass':'incomplete',testCasePlan:[{id:'TC-10',groupIds:['fault-1','integrity']}],groups:[fault,{id:'integrity',kind:'integrity',checks:[{id:'lost',label:'Acknowledged payments lost',actual:verified?0:null,limit:0,unit:'payments',comparison:'≤',outcome:verified?'pass':'not_measured'}]}]}});
+ const pending=render(Summary,{props:{run:make(false)}}).body;
+ assert.match(pending,/Reconciliation required/);assert.doesNotMatch(pending,/Pending verification/);
+ const verified=render(Summary,{props:{run:make(true)}}).body;
+ assert.match(verified,/0 payments/);assert.doesNotMatch(verified,/Reconciliation required|Pending verification/);
+});
diff --git a/loadtest/console/test/scenario-checks.test.mjs b/loadtest/console/test/scenario-checks.test.mjs
new file mode 100644
index 0000000000..62c119204f
--- /dev/null
+++ b/loadtest/console/test/scenario-checks.test.mjs
@@ -0,0 +1,228 @@
+import test from 'node:test';
+import assert from 'node:assert/strict';
+import {mkdtemp,readFile,writeFile,rm} from 'node:fs/promises';
+import {DatabaseSync} from 'node:sqlite';
+import path from 'node:path';import os from 'node:os';
+import {evaluateScenarioChecks,scenarioChecks,faultOccurrences} from '../server/scenario-checks.mjs';
+import {defaultResultsLimits,validateResultsLimits} from '../src/results-limits.mjs';
+import {executionSample,executionClock,stageIntervals} from '../server/execution-clock.mjs';
+
+const recording={run_id:'run',started_at:1000,ended_at:31000,recording_state:'complete',persisted:100};
+const config={load:{total_rps:10,duration_seconds:30},resultsLimits:{...defaultResultsLimits}};
+const samples=Array.from({length:31},(_,i)=>({at:1000+i*1000,active:i}));
+const rows=Array.from({length:300},(_,i)=>({observed_at:1050+i*100,operation:'payment_confirm',api_status_code:200,status:'succeeded',server_latency_ms:50,latency_ms:10}));
+const flows=rows.map(r=>({at:r.observed_at,success:1}));
+const evaluate=changes=>evaluateScenarioChecks({config,recording,samples,requests:rows,flows,jobStatus:'complete',...changes});
+const row=(group,id)=>group.checks.find(r=>r.id===id);
+test('generic steady verdict and drift use the combined settled period, not individual hold verdicts',()=>{
+ const cfg={...config,resultsLimits:{...defaultResultsLimits,recoveryWindowSeconds:1},load:{start_rps:5,stages:[{target_rps:5,duration_seconds:20},{target_rps:5,duration_seconds:80}]}};
+ const requests=Array.from({length:500},(_,i)=>({observed_at:1050+i*200,operation:'payment_confirm',api_status_code:200,status:'succeeded',server_latency_ms:i<25?50:60,latency_ms:10}));
+ const result=evaluateScenarioChecks({config:cfg,recording:{...recording,ended_at:101000},samples:Array.from({length:101},(_,i)=>({at:1000+i*1000,active:i})),requests,flows:requests.map(r=>({at:r.observed_at,success:1})),jobStatus:'complete'});
+ assert.equal(row(result.groups[0],'drift').outcome,'fail');
+ assert.equal(row(result.steady,'drift').actual,0);
+ assert.equal(result.verdict,'pass');
+ assert.equal(row(result.steady,'tps').actual,5);
+});
+test('outage and recovery percentiles use settled samples while keeping genuine slow tails',()=>{
+ const cfg={...config,resultsLimits:{...defaultResultsLimits,recoveryWindowSeconds:2},load:{start_rps:5,stages:[{target_rps:5,duration_seconds:10},{target_rps:5,duration_seconds:20,fault:{targetId:'vault',action:'outage'}},{target_rps:5,duration_seconds:30}]},faultPlan:[{index:1,target:{id:'vault',serviceType:'card-vault'}}]};
+ const ev=[{at:10000,kind:'scheduled_fault',message:'scheduled step 2'},{at:10000,kind:'fault_requested'},{at:12000,kind:'fault_started'},{at:22000,kind:'fault_restore'},{at:30000,kind:'fault_restored'}];
+ const req=(at,ms,extra={})=>({observed_at:at,latency_ms:20,operation:'payment_confirm',api_status_code:200,status:'succeeded',server_latency_ms:ms,...extra});
+ const normal=req(5000,50),outage=req(16000,60),recovered=req(40000,70);
+ const requests=[normal,outage,recovered,req(1000,9000),req(12500,9000),req(25000,9000),req(31000,9000),req(45000,9000,{flow_started_at:15000})];
+ const input={config:cfg,recording:{...recording,started_at:0,ended_at:60000},events:ev,samples:Array.from({length:61},(_,i)=>({at:i*1000,active:i})),flows:[],jobStatus:'complete'};
+ const result=evaluateScenarioChecks({...input,requests});
+ assert.deepEqual(result.states.map(s=>[s.state,s.count,s.p99]),[['normal',1,50],['outage',1,60],['recovery',1,70]]);
+ assert.equal(row(result.groups.find(g=>g.kind==='recovery'),'p99').actual,70);
+ const slow=evaluateScenarioChecks({...input,requests:[...requests,req(50000,1500)]});
+ assert.ok(slow.states.find(s=>s.state==='recovery').p99>1400);
+ assert.equal(row(slow.groups.find(g=>g.kind==='recovery'),'p99').outcome,'fail');
+ assert.equal(result.groups.find(g=>g.kind==='fault').checks.find(c=>c.id==='failed').actual,0);
+});
+
+test('steady measurements exclude recovery and late outage completions without trimming healthy tail latency',()=>{
+ const start=1000,end=61000;
+ const cfg={...config,faultPlan:[{index:1,target:{id:'vault',label:'Card vault',serviceType:'card-vault'}}],load:{start_rps:5,stages:[{target_rps:5,duration_seconds:20},{target_rps:5,duration_seconds:10,fault:{targetId:'vault',action:'outage'}},{target_rps:5,duration_seconds:30}]}};
+ const ev=[{at:21000,kind:'scheduled_fault',message:'scheduled step 2'},{at:21000,kind:'fault_requested'},{at:22000,kind:'fault_started'},{at:30000,kind:'fault_restore'},{at:31000,kind:'fault_restored'}];
+ const healthy=Array.from({length:200},(_,i)=>({observed_at:i<100?1050+i*200:41050+(i-100)*200,operation:'payment_confirm',api_status_code:200,status:'succeeded',latency_ms:10,server_latency_ms:i>=190?1000:50}));
+ const delayed=Array.from({length:100},()=>({...healthy[0],observed_at:45000,latency_ms:20000,server_latency_ms:20000}));
+ const recovery={...healthy[0],observed_at:46000,latency_ms:11000,server_latency_ms:11000};
+ const requests=[...healthy,...delayed,recovery];
+ const result=evaluateScenarioChecks({config:cfg,recording:{...recording,started_at:start,ended_at:end},events:ev,samples:Array.from({length:61},(_,i)=>({at:start+i*1000,active:i})),requests,flows:requests.map(r=>({at:r.observed_at,startedAt:r.observed_at-r.latency_ms,success:1})),jobStatus:'complete'});
+ assert.equal(result.steady.durationSeconds,40);
+ assert.equal(row(result.steady,'tps').actual,5);
+ assert.equal(row(result.steady,'throughput').actual,100);
+ assert.equal(row(result.steady,'completed').actual,200);
+ assert.equal(row(result.steady,'p99').actual,50);
+ assert.equal(row(result.steady,'p99').outcome,'pass');
+ const recovered=result.groups.find(g=>g.kind==='recovery');
+ assert.equal(row(recovered,'p99').actual,1000);assert.equal(row(recovered,'p99').limit,300);assert.equal(row(recovered,'p99').outcome,'fail');
+ assert.equal(result.states.find(s=>s.state==='normal').count,50);
+ assert.equal(result.states.find(s=>s.state==='outage').count,0);
+ assert.equal(result.states.find(s=>s.state==='recovery').count,100);
+});
+
+test('holds count successful completions, payment HTTP errors and successful-only percentiles',()=>{
+ const errors=[{...rows[0],api_status_code:500,server_latency_ms:50000},{...rows[1],api_status_code:200,status:'failed',server_latency_ms:60000},{...rows[2],operation:'pm_session_confirm',api_status_code:0}];
+ const group=evaluate({requests:[...rows,...errors]}).groups[0];
+ assert.equal(row(group,'throughput').actual,100);assert.equal(row(group,'throughput').outcome,'pass');
+ assert.equal(row(group,'completed').actual,300);assert.equal(row(group,'p99').actual,50);
+ assert.equal(row(group,'errors').actual,100/302);assert.equal(row(group,'errors').outcome,'fail');assert.equal(row(group,'drift').actual,0);
+});
+
+test('ramp target uses integrated offered rate, not its final target',()=>{
+ const ramp={...config,load:{start_rps:0,stages:[{target_rps:20,duration_seconds:30}]}};
+ const group=evaluate({config:ramp}).groups[0];
+ assert.equal(group.kind,'ramp');assert.equal(row(group,'throughput').actual,100);assert.equal(row(group,'p99').limit,500);
+});
+
+test('pause plateaus do not inflate active-stage duration or offered work',()=>{
+ const clock=executionClock([{at:1000,active:0},{at:11000,active:10},{at:21000,active:10},{at:31000,active:20}],recording);
+ const windows=stageIntervals(clock,{start:0,end:20});assert.deepEqual(windows.map(w=>[w.from,w.to]),[[1000,11000],[21000,31000]]);
+ const result=evaluate({config:{...config,load:{total_rps:10,duration_seconds:20}},samples:clock.points,flows:flows.filter(f=>f.at<11000||f.at>=21000)});
+ assert.equal(row(result.groups[0],'throughput').actual,100);assert.equal(result.groups[0].durationSeconds,20);
+ assert.equal(executionSample({control:{active_seconds:10,state:'running'}},{total_rps:10,duration_seconds:20},1000).stageIndex,0);
+});
+
+const faultConfig={...config,load:{start_rps:10,stages:[{target_rps:10,duration_seconds:10},{target_rps:10,duration_seconds:10,fault:{targetId:'vault',action:'outage'}},{target_rps:10,duration_seconds:10}]},faultPlan:[{index:1,target:{id:'vault',label:'Card vault'}}]};
+const events=[{at:11000,kind:'scheduled_fault',message:'scheduled step 2'},{at:11000,kind:'fault_requested',message:'Card vault · outage requested'},{at:12000,kind:'fault_started',message:'Card vault · outage'},{at:21000,kind:'fault_restore',message:'Card vault · restoring'},{at:23000,kind:'fault_restored',message:'Card vault · recovery verified'}];
+test('fault groups include delayed failures, exclude them from normal stages, and time recovery from restore',()=>{
+ const error={observed_at:25000,operation:'pm_session_confirm',api_status_code:500,latency_ms:10000,server_latency_ms:4000};
+ const summary=evaluate({config:faultConfig,events,requests:[...rows,error]});
+ assert.deepEqual(summary.groups.map(g=>g.kind),['hold','fault','recovery','hold','integrity']);
+ const fault=summary.groups.find(g=>g.kind==='fault'),after=summary.groups.find(g=>g.id==='stage-2');
+ assert.equal(row(fault,'failed').actual,1);assert.equal(row(fault,'recovery').actual,2);assert.equal(row(fault,'errors').limit,null);
+ assert.equal(row(after,'errors').actual,null);assert.equal(row(after,'throughput').limit,97);
+ assert.equal(summary.groups.find(g=>g.kind==='recovery').state,'partial');
+ assert.equal(row(summary.groups.at(-1),'lost').outcome,'not_measured');
+});
+
+test('DB availability ends outage before provider operation finishes, repeated faults stay separate',()=>{
+ const stages=[{index:0,fault:{}},{index:1,fault:{}}];
+ const event=(at,kind,message='')=>({at,kind,message});
+ const faults=faultOccurrences([event(1,'scheduled_fault','scheduled step 1'),event(2,'fault_requested'),event(3,'database_unavailable'),event(4,'fault_restore'),event(5,'database_available'),event(10,'fault_restored'),event(11,'scheduled_fault','scheduled step 2'),event(12,'fault_requested'),event(13,'fault_restore'),event(15,'fault_restored')],stages,20);
+ assert.equal(faults.length,2);assert.equal(faults[0].to,5);assert.equal(faults[1].recoveredAt,15);assert.equal(faults[1].stageIndex,1);
+});
+
+test('a recovery boundary overlapping the next stage does not disable its healthy checks',()=>{
+ const group=evaluate({config:faultConfig,events}).groups.find(g=>g.id==='stage-2');
+ assert.equal(row(group,'errors').limit,.1);assert.equal(row(group,'throughput').limit,97);
+ assert.equal(group.state,'complete');assert.equal(group.durationSeconds,0);
+});
+
+test('unverified recovery over its deadline fails and simulations cannot pass a real recovery check',()=>{
+ const incomplete=events.filter(e=>e.kind!=='fault_restored');
+ const result=evaluate({config:faultConfig,events:incomplete,recording:{...recording,ended_at:100000},samples:[...samples,{at:100000,active:30}]});
+ const recovery=row(result.groups.find(g=>g.kind==='fault'),'recovery');
+ assert.equal(recovery.actual,79);assert.equal(recovery.outcome,'fail');assert.equal(recovery.lowerBound,true);
+ const simulation=evaluate({config:faultConfig,events:events.map(e=>e.kind==='fault_started'?{...e,message:'SIMULATED · Card vault · outage'}:e)});
+ assert.equal(row(simulation.groups.find(g=>g.kind==='fault'),'recovery').outcome,'recorded');
+});
+
+test('custom limits change only the supplied run snapshot',()=>{
+ const slow=rows.map(r=>({...r,server_latency_ms:200}));
+ assert.equal(row(evaluate({requests:slow}).groups[0],'p99').outcome,'fail');
+ const relaxed={...config,resultsLimits:{...defaultResultsLimits,maximumHoldP99Ms:250}};
+ assert.equal(row(evaluate({config:relaxed,requests:slow}).groups[0],'p99').outcome,'pass');
+ assert.equal(evaluate().limits.maximumHoldP99Ms,160);
+ assert.equal(row(evaluate({flows:flows.slice(0,200)}).groups[0],'throughput').outcome,'fail');
+});
+
+test('cancelled and missing-clock runs never pass unexecuted stages',()=>{
+ const summary=evaluate({config:faultConfig,samples:samples.slice(0,6),jobStatus:'cancelled'});
+ assert.equal(summary.verdict,'incomplete');assert.equal(summary.groups[0].state,'partial');assert.equal(row(summary.groups[0],'throughput').outcome,'not_measured');
+ assert.equal(summary.groups[1].state,'not_run');assert.equal(summary.groups.find(g=>g.kind==='fault').verdict,'not_run');
+ const missing=evaluate({samples:[]});assert.equal(row(missing.groups[0],'throughput').outcome,'not_measured');assert.notEqual(missing.verdict,'pass');
+});
+
+test('legacy runs preserve saved limits but do not invent server-latency thresholds',()=>{
+ const old=evaluate({config:{load:config.load,acceptance:{minimumSuccessRatio:.95,maximumErrorPercent:1}}});
+ assert.equal(row(old.groups[0],'throughput').limit,95);assert.equal(row(old.groups[0],'p99').limit,null);assert.equal(row(old.groups[0],'p99').outcome,'recorded');
+ assert.equal(old.verdict,'recorded');
+});
+
+test('reconciliation is required before claiming zero acknowledged payments lost',()=>{
+ const base={config:faultConfig,events};
+ assert.equal(row(evaluate({...base,reconciliation:{recordingState:'complete',missing:0,total:300,expected:300}}).groups.at(-1),'lost').outcome,'pass');
+ assert.equal(row(evaluate({...base,reconciliation:{recordingState:'complete',missing:1,total:300,expected:300}}).groups.at(-1),'lost').outcome,'fail');
+ assert.equal(row(evaluate({...base,reconciliation:{recordingState:'incomplete',missing:0,total:300,expected:300}}).groups.at(-1),'lost').outcome,'not_measured');
+});
+
+test('Results limits reject invalid numbers, bounds and fractional lost-payment limits',()=>{
+ for(const limits of [{minimumThroughputPercent:101},{maximumHttpErrorPercent:-1},{maximumHoldP99Ms:Infinity},{recoveryWindowSeconds:0},{maximumLostPayments:.5},{maximumRecoverySeconds:''}])assert.throws(()=>validateResultsLimits(limits),/Invalid Results limit/);
+ assert.deepEqual(validateResultsLimits(),defaultResultsLimits);assert.equal(validateResultsLimits({maximumHoldP99Ms:'200'}).maximumHoldP99Ms,200);
+});
+
+test('SQLite-backed summaries persist, honor snapshots and refresh after reconciliation',async()=>{
+ const directory=await mkdtemp(path.join(os.tmpdir(),'scenario-checks-'));
+ try{
+ const db=new DatabaseSync(path.join(directory,'results.sqlite'));db.exec(await readFile('../k6/scenario-mix/recorder/schema.sql','utf8'));
+ const insert=db.prepare("INSERT INTO request_events(event_id,run_id,attempt_id,flow_id,operation,role,observed_at,method,url,status,api_status_code,latency_ms,server_latency_ms) VALUES(?,'run',?,?,?,'measured',?,'POST','/','succeeded',200,10,50)");
+ rows.forEach((r,i)=>{insert.run(i+1,i+1,`run:guest:1:${i}`,'payment_create',r.observed_at-20);insert.run(i+1001,i+1001,`run:guest:1:${i}`,'payment_confirm',r.observed_at);});db.close();
+ await writeFile(path.join(directory,'execution.jsonl'),samples.map(s=>JSON.stringify(s)).join('\n'));
+ const input={config:faultConfig,recording,events,jobStatus:'complete'};
+ const first=await scenarioChecks(directory,input),artifact=JSON.parse(await readFile(path.join(directory,'scenario-checks.json')));
+ assert.equal(row(first.groups[0],'completed').actual,100);assert.equal(artifact.summary.version,16);
+ const second=await scenarioChecks(directory,{...input,reconciliation:{recordingState:'complete',total:300,expected:300,missing:0}});
+ assert.equal(row(second.groups.at(-1),'lost').outcome,'pass');
+ assert.notEqual(JSON.parse(await readFile(path.join(directory,'scenario-checks.json'))).fingerprint,artifact.fingerprint);
+ const saved=structuredClone(config);validateResultsLimits({minimumThroughputPercent:80});
+ assert.equal((await scenarioChecks(directory,{...input,config:saved})).limits.minimumThroughputPercent,97);
+ }finally{await rm(directory,{recursive:true,force:true});}
+});
+
+test('confirmation completion counts only confirmations including drain, with strict success outside outages',()=>{
+ const requests=[2050,3050,4150].map(at=>({operation:'payment_confirm',observed_at:at,api_status_code:200,status:'succeeded',latency_ms:150}));
+ const input={config:{...config,load:{total_rps:1,duration_seconds:3}},recording:{...recording,ended_at:4200},samples:[{at:1000,active:0},{at:2000,active:1},{at:3000,active:2},{at:4000,active:3},{at:4200,active:3}],requests:[...requests,{operation:'customer_create',observed_at:1500,api_status_code:500}],jobStatus:'complete',control:{started_flows:4,dropped:0,active_seconds:3}};
+ const result=evaluateScenarioChecks(input);
+ assert.equal(result.completion.expected,3);assert.equal(result.completion.successful,3);assert.equal(result.completion.check.actual,100);assert.equal(result.completion.check.outcome,'pass');
+ assert.equal(result.completion.started,4);assert.equal(result.completion.scope,'payment_confirm_outside_outage');
+ const failed=evaluateScenarioChecks({...input,requests:[...requests.slice(0,2),{...requests[2],api_status_code:500,status:'failed'}]});
+ assert.equal(failed.completion.check.outcome,'fail');
+ const empty=evaluateScenarioChecks({...input,requests:[]});assert.equal(empty.completion.check.outcome,'not_measured');
+ const cancelled=evaluateScenarioChecks({...input,jobStatus:'cancelled',recording:{...input.recording,recording_state:'incomplete'}});
+ assert.notEqual(cancelled.completion.check.outcome,'pass');assert.equal(cancelled.verdict,'incomplete');
+});
+test('outage confirmation failures remain visible without failing outside-outage completion',()=>{
+ const input={config:faultConfig,recording,samples,events,jobStatus:'complete',requests:[...rows,{operation:'payment_confirm',api_status_code:500,status:'failed',observed_at:22000,latency_ms:1000},{operation:'customer_create',api_status_code:500,observed_at:20000,latency_ms:100}],flows};
+ const result=evaluateScenarioChecks(input);
+ assert.equal(result.completion.check.outcome,'pass');assert.equal(result.completion.outageFailures,1);assert.ok(result.completion.outageAttempts>1);
+ const bad=evaluateScenarioChecks({...input,requests:[...input.requests,{operation:'payment_confirm',api_status_code:500,status:'failed',observed_at:5000,latency_ms:10}]});
+ assert.equal(bad.completion.check.outcome,'fail');
+});
+
+test('non-confirmation request durations cannot affect any server latency percentile',()=>{
+ const result=evaluate({requests:[...rows,{...rows[0],operation:'customer_create',server_latency_ms:999999},{...rows[0],operation:'pm_session_confirm',server_latency_ms:999999}]});
+ assert.equal(row(result.steady,'p99').actual,50);assert.equal(result.states.find(s=>s.state==='normal').p99,50);
+});
+
+test('unavailable informational outage latency cannot block measured recovery and integrity',()=>{
+ const result=evaluate({config:faultConfig,events,requests:rows.filter(r=>r.observed_at<19000||r.observed_at>23000),reconciliation:{recordingState:'complete',total:300,expected:300,missing:0}});
+ const fault=result.groups.find(g=>g.kind==='fault');
+ assert.equal(row(fault,'p99').actual,null);assert.equal(row(fault,'p99').limit,null);assert.equal(row(fault,'p99').outcome,'recorded');
+ assert.equal(row(result.groups.find(g=>g.kind==='integrity'),'lost').outcome,'pass');
+});
+
+test('outage payment-creation failures exclude successes, other operations and failures outside outage',()=>{
+ const request=(operation,observed_at,api_status_code,latency_ms=10)=>({operation,observed_at,api_status_code,latency_ms});
+ const result=evaluate({config:faultConfig,events,requests:[...rows,request('payment_create',20000,500),request('payment_create',26000,0,6000),request('payment_create',20000,200),request('customer_create',20000,500),request('pm_session_create',20000,500),request('payment_confirm',20000,500),request('payment_create',5000,500)]});
+ assert.equal(row(result.groups.find(g=>g.kind==='fault'),'failed-creation').actual,2);
+});
+
+test('HTTP errors include payment create and confirm failures without dilution by setup requests',()=>{
+ const request=(operation,api_status_code)=>({operation,api_status_code,observed_at:5000,latency_ms:10});
+ const requests=[request('payment_create',200),request('payment_create',500),request('payment_confirm',200),request('payment_confirm',0),...Array.from({length:100},()=>request('customer_create',200)),request('pm_session_create',500)];
+ const result=evaluate({requests});
+ assert.equal(row(result.steady,'errors').actual,50);assert.equal(row(result.groups[0],'errors').actual,50);
+ assert.equal(result.httpErrorScope,'payment_create_and_confirm');
+});
+
+test('DB recovery counts observed unavailability even when availability precedes scheduled restoration',()=>{
+ const ev=[{at:10000,kind:'scheduled_fault',message:'scheduled step 2'},{at:10000,kind:'fault_requested'},{at:11000,kind:'database_unavailable'},{at:18000,kind:'database_available'},{at:21000,kind:'fault_restore'},{at:23000,kind:'fault_restored'}];
+ const result=evaluate({config:faultConfig,events:ev});
+ const recovery=row(result.groups.find(g=>g.kind==='fault'),'recovery');
+ assert.equal(recovery.actual,7);assert.equal(recovery.outcome,'pass');
+ assert.equal(recovery.label,'Database availability restored after outage');
+ const pending=evaluate({config:faultConfig,events:ev.slice(0,3),recording:{...recording,ended_at:100000},samples:[...samples,{at:100000,active:30}]});
+ const overdue=row(pending.groups.find(g=>g.kind==='fault'),'recovery');
+ assert.equal(overdue.actual,89);assert.equal(overdue.outcome,'fail');
+});
diff --git a/loadtest/console/test/service-health.test.mjs b/loadtest/console/test/service-health.test.mjs
new file mode 100644
index 0000000000..895f45db6a
--- /dev/null
+++ b/loadtest/console/test/service-health.test.mjs
@@ -0,0 +1,32 @@
+import test from 'node:test';
+import assert from 'node:assert/strict';
+import {faultHealthOverride,pendingHealth} from '../src/service-health.mjs';
+const database={id:'database',label:'DB'};
+const targets=[{id:'postgres',adapter:'gcp-alloydb',serviceType:'postgres',label:'PostgreSQL'}];
+const fault=active=>({active:{targetId:'postgres',target:'PostgreSQL',action:'failover',status:'active',...active}});
+test('DB represents failover before and after the command completes without claiming an outage',()=>{
+ for(const occurred of [false,true])assert.equal(faultHealthOverride(database,fault({occurred}),targets).state,'recovering');
+ assert.equal(faultHealthOverride(database,fault({status:'restoring'}),targets).state,'recovering');
+ assert.equal(faultHealthOverride(database,fault({status:'recovery_failed'}),targets).state,'offline');
+ assert.equal(faultHealthOverride(database,{active:null},targets),null);
+});
+test('database outage, legacy targets, and unrelated services stay distinct',()=>{
+ assert.equal(faultHealthOverride(database,fault({action:'outage',occurred:true}),targets).state,'offline');
+ assert.equal(faultHealthOverride(database,fault({}),[{id:'postgres',label:'PostgreSQL'}]).state,'recovering');
+ assert.equal(faultHealthOverride({id:'router'},fault({}),targets),null);
+ assert.equal(faultHealthOverride(database,fault({simulated:true}),targets),null);
+});
+test('DB health uses SQL availability while the provider operation is still restoring',()=>{
+ assert.equal(faultHealthOverride(database,fault({status:'restoring',databaseAvailability:'available'}),targets).state,'online');
+ assert.equal(faultHealthOverride(database,fault({status:'restoring',databaseAvailability:'unavailable'}),targets).state,'offline');
+});
+test('failed card-vault recovery falls back to a current readiness probe',()=>{
+ const service={id:'fault-vault',targetId:'vault'};
+ const vaultFault={active:{targetId:'vault',target:'Card vault',status:'recovery_failed',action:'outage',occurred:true}};
+ assert.equal(faultHealthOverride(service,vaultFault,[{id:'vault',serviceType:'card-vault'}]),null);
+});
+test('background refresh preserves the measured result; fault overrides apply immediately',()=>{
+ for(const state of ['online','offline'])assert.equal(pendingHealth(database,{state,message:'Measured'},null).state,state);
+ assert.equal(pendingHealth(database,null,null).state,'checking');
+ assert.equal(pendingHealth(database,{state:'online'},faultHealthOverride(database,fault({}),targets)).state,'recovering');
+});
diff --git a/loadtest/console/test/successful-latency.test.mjs b/loadtest/console/test/successful-latency.test.mjs
new file mode 100644
index 0000000000..640901be39
--- /dev/null
+++ b/loadtest/console/test/successful-latency.test.mjs
@@ -0,0 +1,56 @@
+import test from 'node:test';
+import assert from 'node:assert/strict';
+import {DatabaseSync} from 'node:sqlite';
+import {mkdtemp,writeFile,rm} from 'node:fs/promises';
+import os from 'node:os';import path from 'node:path';
+import {successfulServerLatency,latencyPhase,latencyPercentile,settledLatencyWindows,containedLatencySample} from '../server/successful-latency.mjs';
+import {readTelemetry} from '../server/telemetry.mjs';
+import {faultWindows} from '../server/display-errors.mjs';
+test('settled windows exclude transitions, restoration and flows crossing state boundaries',()=>{
+ const windows=settledLatencyWindows({normalWindows:[{from:0,to:3000},{from:3000,to:5000},{from:12000,to:15000},{from:15000,to:20000}],faults:[{stageIndex:1,from:5000,startedAt:6000,restoreAt:9000,recoveredAt:12000}],startedAt:0,end:20000,settlingSeconds:1});
+ assert.deepEqual(windows.normal,[{from:1000,to:5000}]);
+ assert.deepEqual(windows.outage,[{from:7000,to:9000,stageIndex:1}]);
+ assert.deepEqual(windows.recovery,[{from:13000,to:20000,stageIndex:1}]);
+ assert.equal(containedLatencySample({observed_at:8000,latency_ms:100},windows.outage),true);
+ assert.equal(containedLatencySample({observed_at:10000,latency_ms:100},windows.outage),false);
+ assert.equal(containedLatencySample({observed_at:14000,latency_ms:100,flow_started_at:8000},windows.recovery),false);
+ assert.equal(containedLatencySample({observed_at:17000,latency_ms:100,flow_started_at:13500},windows.recovery),true);
+ assert.equal(containedLatencySample({observed_at:18000,flow_started_at:14000},[{from:13000,to:15000},{from:16000,to:20000}]),false);
+ const short=settledLatencyWindows({normalWindows:[],faults:[{stageIndex:0,from:0,startedAt:0,restoreAt:500}],startedAt:0,end:500,settlingSeconds:1});
+ assert.deepEqual(short.outage,[]);
+});
+test('provider-prefixed vault events retain outage and recovery latency windows',()=>{
+ const windows=faultWindows([{at:1000,kind:'fault_started',message:'GCP · Card vault · outage'},{at:2000,kind:'fault_restored',message:'GCP · Card vault · recovery verified'}]);
+ assert.deepEqual(windows.vault,[[1000,2000]]);
+ assert.equal(latencyPhase({observed_at:2100,latency_ms:200},windows),'outage');
+ assert.equal(latencyPhase({observed_at:2200,latency_ms:100},windows),'recovery');
+});
+test('summary and existing chart values exclude HTTP and payment-status failures',async()=>{
+ const directory=await mkdtemp(path.join(os.tmpdir(),'successful-latency-'));
+ try{
+ const db=new DatabaseSync(path.join(directory,'results.sqlite'));
+ db.exec('CREATE TABLE request_events(event_id INTEGER,run_id TEXT,operation TEXT,role TEXT,api_status_code INTEGER,status TEXT,server_latency_ms REAL,flow_id TEXT,observed_at INTEGER,latency_ms REAL DEFAULT 0)');
+ const insert=db.prepare('INSERT INTO request_events(event_id,run_id,operation,role,api_status_code,status,server_latency_ms,flow_id,observed_at) VALUES(?,?,?,?,?,?,?,?,?)');
+ const rows=[[200,'succeeded',100],[200,'requires_capture',110],[500,'succeeded',20000],[200,'failed',30000],[0,'succeeded',40000]];
+ rows.forEach(([code,status,latency],i)=>insert.run(i,'run','payment_confirm','measured',code,status,latency,'merchant:guest:1:1',1200+i));
+ insert.run(6,'failed-run','payment_confirm','measured',500,'failed',50000,'merchant:guest:1:1',1400);
+ db.close();
+ const recording={run_id:'run',started_at:1000,ended_at:2000,persisted:5};
+ const result=successfulServerLatency(directory,recording);
+ assert.equal(result.p99,109.9);assert.equal(result.phases[0].p50,105);assert.equal(result.phases[0].p95,109.5);assert.equal(result.phases[1].count,0);
+ const phased=successfulServerLatency(directory,recording,[{at:1100,kind:'database_unavailable'},{at:1500,kind:'database_available'}]);assert.equal(phased.phases[1].count,2);assert.equal(phased.phases[0].count,0);assert.equal(result.flows.guest,109.9);
+ assert.equal(successfulServerLatency(directory,{...recording,run_id:'failed-run'}).p99,null);
+ await writeFile(path.join(directory,'telemetry.jsonl'),JSON.stringify({t:1,started:5,serverP99:40000,flows:{guest:{started:5,serverP99:40000}}})+'\n');
+ const chart=await readTelemetry(directory,recording);
+ assert.equal(chart[0].serverP99,109.9);assert.equal(chart[0].flows.guest.serverP99,109.9);
+ }finally{await rm(directory,{recursive:true,force:true});}
+});
+
+test('phase classification uses request overlap, prioritizes outages, and bounds recovery',()=>{
+ const windows={vault:[[1000,2000]],database:[[2500,3000]]};
+ assert.equal(latencyPhase({observed_at:2200,latency_ms:300},windows),'outage');
+ assert.equal(latencyPhase({observed_at:2400,latency_ms:100},windows),'recovery');
+ assert.equal(latencyPhase({observed_at:2600,latency_ms:100},windows),'outage');
+ assert.equal(latencyPhase({observed_at:14000,latency_ms:100},windows),'normal');
+ assert.equal(latencyPercentile([],.5),null);assert.equal(latencyPercentile([0],.99),0);
+});
diff --git a/loadtest/console/test/telemetry.test.mjs b/loadtest/console/test/telemetry.test.mjs
new file mode 100644
index 0000000000..f16a81ec3c
--- /dev/null
+++ b/loadtest/console/test/telemetry.test.mjs
@@ -0,0 +1,52 @@
+import test from 'node:test';import assert from 'node:assert/strict';import {mkdtemp,writeFile} from 'node:fs/promises';import {DatabaseSync} from 'node:sqlite';import os from 'node:os';import path from 'node:path';
+import {readTelemetry,startedTelemetry} from '../server/telemetry.mjs';
+import {aggregate} from '../server/distributed-runner.mjs';
+test('live and distributed counters include HTTP errors from every operation',async()=>{
+ const {telemetryPoint}=await import('../server/telemetry.mjs');
+ const p={elapsed_seconds:1,http_attempts:30,http_errors:20,confirm_http_attempts:10,confirm_http_errors:1,recorder:{persisted:30,enqueued:30},flows:{}};
+ assert.equal(telemetryPoint(p).errors,100*20/30);
+ assert.equal(telemetryPoint({...p,elapsed_seconds:2,http_attempts:40,http_errors:25,confirm_http_attempts:20},telemetryPoint(p)).errors,50);
+ const merged=aggregate([{progress:JSON.stringify(p)},{progress:JSON.stringify({...p,confirm_http_attempts:5,confirm_http_errors:0})}]);
+ assert.equal(merged.confirm_http_attempts,15);assert.equal(merged.confirm_http_errors,1);assert.equal(merged.http_errors,40);
+});
+test('historical error graph includes measured requests across all operations',async()=>{
+ const directory=await mkdtemp(path.join(os.tmpdir(),'confirm-errors-')),db=new DatabaseSync(path.join(directory,'results.sqlite'));
+ db.exec('CREATE TABLE request_events(event_id INTEGER PRIMARY KEY,run_id TEXT,operation TEXT,role TEXT,observed_at INTEGER,api_status_code INTEGER)');
+ const insert=db.prepare('INSERT INTO request_events(run_id,operation,role,observed_at,api_status_code) VALUES(?,?,?,?,?)');
+ insert.run('run','pm_session_confirm','measured',1500,0);insert.run('run','payment_confirm','fixture',1500,500);
+ insert.run('run','payment_confirm','measured',1500,200);insert.run('run','payment_confirm','measured',2500,500);insert.run('run','payment_confirm','measured',2500,200);insert.run('run','pm_session_confirm','measured',3500,400);insert.run('run','payment_confirm','measured',3500,200);db.close();
+ await writeFile(path.join(directory,'telemetry.jsonl'),[1,2,3].map(t=>JSON.stringify({t,errors:100,started:0,flows:{}})).join('\n'));
+ const points=await readTelemetry(directory,{run_id:'run',started_at:1000,ended_at:4000,persisted:7});
+ assert.deepEqual(points.map(p=>p.errors),[50,50,50]);assert.equal(points.at(-1).displayHttpAttempts,6);assert.equal(points.at(-1).displayHttpErrors,3);
+});
+test('old recording traffic is reconstructed from first attempts, including failed creates',async()=>{
+ const directory=await mkdtemp(path.join(os.tmpdir(),'flow-starts-')),db=new DatabaseSync(path.join(directory,'results.sqlite'));
+ db.exec('CREATE TABLE request_events(run_id TEXT,flow_id TEXT,observed_at INTEGER,latency_ms REAL)');const insert=db.prepare('INSERT INTO request_events VALUES(?,?,?,?)');
+ insert.run('run','run:guest:1:1',6100,5000);insert.run('run','run:guest:2:1',6200,5000);insert.run('run','run:guest:1:1',6300,20);db.close();
+ await writeFile(path.join(directory,'telemetry.jsonl'),[{t:2,successes:0,tps:0,flows:{guest:{successes:0,failures:0,tps:0}}},{t:7,successes:1,tps:.2,flows:{guest:{successes:1,failures:1,tps:.2}}}].map(JSON.stringify).join('\n'));
+ const points=await readTelemetry(directory,{run_id:'run',started_at:1000,ended_at:8000,persisted:3});
+ assert.equal(points[0].started,2);assert.equal(points[0].tps,1);assert.equal(points[0].flows.guest.tps,1);assert.equal(points[1].tps,0);assert.equal(points[1].successfulTps,.2);
+});
+test('compacted counter history retains rate over the full sampled interval',()=>{
+ const points=startedTelemetry([{t:1,started:5,successfulTps:0,flows:{guest:{started:5,successfulTps:0}}},{t:3,started:15,successfulTps:0,flows:{guest:{started:15,successfulTps:0}}}]);assert.equal(points[1].tps,5);assert.equal(points[1].flows.guest.tps,5);
+});
+test('distributed traffic sums admissions before responses return',()=>{
+ const progress=started_flows=>JSON.stringify({elapsed_seconds:10,control:{active_seconds:10,started_flows,flow_starts:{guest:started_flows},in_flight:started_flows},flows:{guest:{successes:0,failures:0}}});
+ const p=aggregate([{status:'running',progress:progress(50)},{status:'running',progress:progress(30)}]);assert.equal(p.control.started_flows,80);assert.equal(p.control.flow_starts.guest,80);assert.equal(p.control.in_flight,80);
+ const legacy=aggregate([{status:'running',progress:'{}'}]);assert.equal(legacy.control.started_flows,undefined);
+});
+
+test('server latency propagates and aggregates samples instead of worker percentiles',async()=>{
+ const {telemetryPoint}=await import('../server/telemetry.mjs');
+ const point=telemetryPoint({elapsed_seconds:1,server_p99_ms:0,recorder:{persisted:0,enqueued:0},flows:{guest:{server_p99_ms:12}}});
+ assert.equal(point.serverP99,0);assert.equal(point.flows.guest.serverP99,12);
+ const shards=[{status:'running',progress:JSON.stringify({server_samples_ms:[0,10],flows:{guest:{server_samples_ms:[0,10]}}})},{status:'running',progress:JSON.stringify({server_samples_ms:[30],flows:{guest:{server_samples_ms:[30]}}})}];
+ assert.equal(aggregate(shards).server_p99_ms,10);assert.equal(aggregate(shards).flows.guest.server_p99_ms,10);assert.equal(aggregate([{progress:'{}'}]).server_p99_ms,null);
+});
+
+test('older chart points recover server latency from recorded responses by interval',async()=>{
+ const {restoreServerLatency}=await import('../server/telemetry.mjs');
+ const points=[{t:1,flows:{guest:{}}},{t:2,flows:{guest:{}}},{t:3,flows:{guest:{}}},{t:4,serverP99:99,flows:{guest:{serverP99:99}}}];
+ const rows=[{observed_at:1500,flow_id:'run:guest:1:1',server_latency_ms:0},{observed_at:1800,flow_id:'run:guest:2:1',server_latency_ms:12},{observed_at:2500,flow_id:'run:guest:3:1',server_latency_ms:20}];
+ const result=restoreServerLatency(points,rows,1000);assert.deepEqual(result.map(p=>p.serverP99),[0,20,null,99]);assert.equal(result[1].flows.guest.serverP99,20);assert.equal(result[3].flows.guest.serverP99,99);
+});
diff --git a/loadtest/console/test/worker-result.test.mjs b/loadtest/console/test/worker-result.test.mjs
new file mode 100644
index 0000000000..fb65ce2633
--- /dev/null
+++ b/loadtest/console/test/worker-result.test.mjs
@@ -0,0 +1,14 @@
+import test from 'node:test';
+import assert from 'node:assert/strict';
+import { workerFailure } from '../server/worker-result.mjs';
+
+test('threshold exits describe failed checks without calling complete recording a worker crash', () => {
+ const summary = {metrics:{http_req_failed:{thresholds:{'rate<0.01':{ok:false}}},dropped_iterations:{thresholds:{'count==0':{ok:true}}}}};
+ const message = workerFailure(99, null, summary);
+ assert.match(message, /thresholds failed/);
+ assert.match(message, /http_req_failed \(rate<0.01\)/);
+ assert.doesNotMatch(message, /dropped_iterations/);
+ assert.match(message, /Results/);
+ assert.equal(workerFailure(0), null);
+ assert.equal(workerFailure(1,{error:'Recording incomplete'}), 'Recording incomplete');
+});
diff --git a/loadtest/console/test/worker-upload-http.test.mjs b/loadtest/console/test/worker-upload-http.test.mjs
new file mode 100644
index 0000000000..b7c17e7b27
--- /dev/null
+++ b/loadtest/console/test/worker-upload-http.test.mjs
@@ -0,0 +1,33 @@
+import test from 'node:test';
+import assert from 'node:assert/strict';
+import {mkdtemp,mkdir,writeFile,readFile} from 'node:fs/promises';
+import os from 'node:os';import path from 'node:path';
+import {spawn} from 'node:child_process';
+import {once} from 'node:events';
+import {Readable} from 'node:stream';
+import {WorkerExecutor} from '../../worker/executor.mjs';
+const temporary=await mkdtemp(path.join(os.tmpdir(),'worker-upload-http-'));
+process.env.LOADTEST_DATA_DIR=temporary;
+process.env.LOADTEST_CONSOLE_ROOT=path.resolve('.');process.env.LOADTEST_ROOT=path.resolve('..');
+const state=await import('../server/state.mjs');state.initializeConfig();
+const {passwordHash}=await import('../server/auth.mjs');
+test('real worker streams recordings above 512KB through the production HTTP adapter',async()=>{
+ const port=42000+Math.floor(Math.random()*1000),origin=`http://127.0.0.1:${port}`;
+ const env={...process.env,HOST:'127.0.0.1',PORT:String(port),ORIGIN:origin,GRAFANA_PROXY_PORT:String(port+1000),GRAFANA_EMBED_ORIGIN:`http://127.0.0.1:${port+1000}`,ADMIN_PASSWORD_HASH:await passwordHash('fake-test-password'),LOADTEST_WORKER_ENROLLMENT_TOKEN:'fake-enrollment'};
+ delete env.BODY_SIZE_LIMIT;
+ const child=spawn(process.execPath,['start.mjs'],{env,stdio:['ignore','pipe','pipe']});let output='';child.stdout.on('data',d=>output+=d);child.stderr.on('data',d=>output+=d);
+ try{
+ let ready=false;for(let n=0;n<150;n++){try{ready=(await fetch(origin+'/health')).ok;}catch{}if(ready)break;await new Promise(r=>setTimeout(r,100));}assert.ok(ready,output);
+ const enrollment=await fetch(origin+'/api/worker/v1/enroll',{method:'POST',headers:{authorization:'Bearer fake-enrollment','content-type':'application/json'},body:JSON.stringify({name:'http-worker',capacityTps:1,capacityVus:10})});assert.equal(enrollment.status,201);
+ const identity=await enrollment.json();state.controlDb().prepare("INSERT INTO run_shards(id,run_id,worker_id,status,offered_tps,segment_start,segment_end,updated_at) VALUES('probe','probe',?,'uploading',1,0,1,?)").run(identity.id,Date.now());
+ const outputDir=path.join(temporary,'output');await mkdir(outputDir);const artifact=Buffer.alloc(600000,65);await writeFile(path.join(outputDir,'results.sqlite'),artifact);await writeFile(path.join(outputDir,'summary.json'),'{}');
+ const executor=new WorkerExecutor({server:origin,identity,request:()=>{},dataDir:temporary});executor.runs.set('probe',{output:outputDir});
+ await executor.upload('probe',{authorization:`Bearer ${identity.token}`});
+ assert.deepEqual(await readFile(path.join(temporary,'worker-artifacts','probe',identity.id,'results.sqlite')),artifact);
+ const denied=await fetch(`${origin}/api/worker/v1/workers/${identity.id}/runs/probe/artifacts/summary.json`,{method:'PUT',headers:{authorization:'Bearer wrong','content-type':'application/json'},body:'{}'});assert.equal(denied.status,401);
+ const oversized=await fetch(origin+'/login',{method:'POST',headers:{origin,'content-type':'application/x-www-form-urlencoded'},body:Readable.from([Buffer.alloc(700000),Buffer.alloc(700000)]),duplex:'half'});assert.equal(oversized.status,413);
+ }finally{
+ if(child.exitCode===null&&child.signalCode===null){child.kill('SIGTERM');await once(child,'exit');}
+ const daemon=JSON.parse(await readFile(path.join(temporary,'worker-service.json'),'utf8').catch(()=>'null'));if(daemon)try{process.kill(daemon.pid,'SIGTERM');}catch{}
+ }
+});
diff --git a/loadtest/console/vite.config.js b/loadtest/console/vite.config.js
new file mode 100644
index 0000000000..6dadebcf9c
--- /dev/null
+++ b/loadtest/console/vite.config.js
@@ -0,0 +1,8 @@
+import { defineConfig, loadEnv } from 'vite';
+import { sveltekit } from '@sveltejs/kit/vite';
+import {startGrafanaProxy} from './server/grafana-embed.mjs';
+
+export default defineConfig(({mode}) => {
+ for(const [key,value] of Object.entries(loadEnv(mode,process.cwd(),''))) process.env[key] ??= value;
+ return {plugins:[sveltekit(),{name:'isolated-grafana',async configureServer(server){const proxy=await startGrafanaProxy();server.httpServer?.once('close',()=>proxy.close());}}],server:{host:'127.0.0.1',watch:{ignored:['**/.data/**']}},build:{target:'es2022'}};
+});
diff --git a/loadtest/docker-compose.yaml b/loadtest/docker-compose.yaml
deleted file mode 100644
index 1e2c32b1b1..0000000000
--- a/loadtest/docker-compose.yaml
+++ /dev/null
@@ -1,127 +0,0 @@
-version: "2"
-
-networks:
- loadtest_net:
-
-services:
- db:
- image: postgres
- restart: always
- environment:
- POSTGRES_USER: postgres
- POSTGRES_PASSWORD: postgres
- POSTGRES_DB: loadtest_router
- networks:
- - loadtest_net
- healthcheck:
- test: [ "CMD-SHELL", "pg_isready -U postgres" ]
- interval: 5s
- timeout: 5s
- retries: 5
-
- stripe-mock:
- image: heyrutvik/stripe-mock:latest
- networks:
- - loadtest_net
-
- redis-queue:
- image: redis:7
- networks:
- - loadtest_net
-
- router-server:
- build:
- context: ..
- dockerfile: ./loadtest/Dockerfile
- cpuset: "0"
- volumes:
- - ./config:/config
- - ./logs.tmp:/app/logs
- command:
- - /bin/bash
- - -c
- - |
- ./diesel migration run
- ./router -f /config/development.toml
- ports:
- - "8080"
- environment:
- DATABASE_URL: postgres://postgres:postgres@db/loadtest_router
- RUST_LOG: INFO
- RUN_ENV: development
- OTEL_EXPORTER_OTLP_ENDPOINT: http://otel-collector:4317
- networks:
- - loadtest_net
- healthcheck:
- test: curl --fail http://router-server:8080/health || exit 1
- interval: 5s
- timeout: 5s
- retries: 5
- depends_on:
- db:
- condition: service_healthy
- stripe-mock:
- condition: service_started
- redis-queue:
- condition: service_started
- influxdb:
- condition: service_started
- otel-collector:
- condition: service_started
- tempo:
- condition: service_started
- grafana:
- condition: service_started
-
- k6:
- image: loadimpact/k6:latest
- volumes:
- - ./k6:/scripts
- command: run /scripts/${LOADTEST_K6_SCRIPT}
- networks:
- - loadtest_net
- environment:
- - LOADTEST_RUN_NAME=${LOADTEST_RUN_NAME}
- - K6_OUT=influxdb=http://influxdb:8086/scripts
- depends_on:
- router-server:
- condition: service_healthy
-
- influxdb:
- image: influxdb:1.8
- networks:
- - loadtest_net
- environment:
- - INFLUXDB_DB=scripts
-
- otel-collector:
- image: otel/opentelemetry-collector:latest
- command: --config=/etc/otel-collector.yaml
- networks:
- - loadtest_net
- volumes:
- - ./config/otel-collector.yaml:/etc/otel-collector.yaml
-
- tempo:
- image: grafana/tempo:latest
- command: -config.file=/etc/tempo.yaml
- volumes:
- - ./config/tempo.yaml:/etc/tempo.yaml
- - ./tempo.tmp:/tmp/tempo
- networks:
- - loadtest_net
-
- grafana:
- image: grafana/grafana:latest
- ports:
- - "3002:3000"
- networks:
- - loadtest_net
- environment:
- - GF_AUTH_ANONYMOUS_ORG_ROLE=Admin
- - GF_AUTH_ANONYMOUS_ENABLED=true
- - GF_AUTH_BASIC_ENABLED=false
- volumes:
- - ./grafana/dashboards:/var/lib/grafana/dashboards
- - ./grafana/grafana-dashboard.yaml:/etc/grafana/provisioning/dashboards/dashboard.yaml
- - ./grafana/grafana-datasource.yaml:/etc/grafana/provisioning/datasources/datasource.yaml
diff --git a/loadtest/grafana/dashboards/k6-load-testing-results_rev3.json b/loadtest/grafana/dashboards/k6-load-testing-results_rev3.json
deleted file mode 100644
index 3b8bb35e30..0000000000
--- a/loadtest/grafana/dashboards/k6-load-testing-results_rev3.json
+++ /dev/null
@@ -1,1617 +0,0 @@
-{
- "__inputs": [
- {
- "name": "DS_K6",
- "label": "k6",
- "description": "",
- "type": "datasource",
- "pluginId": "influxdb",
- "pluginName": "InfluxDB"
- }
- ],
- "__requires": [
- {
- "type": "grafana",
- "id": "grafana",
- "name": "Grafana",
- "version": "4.4.1"
- },
- {
- "type": "panel",
- "id": "graph",
- "name": "Graph",
- "version": ""
- },
- {
- "type": "panel",
- "id": "heatmap",
- "name": "Heatmap",
- "version": ""
- },
- {
- "type": "datasource",
- "id": "influxdb",
- "name": "InfluxDB",
- "version": "1.0.0"
- },
- {
- "type": "panel",
- "id": "singlestat",
- "name": "Singlestat",
- "version": ""
- }
- ],
- "annotations": {
- "list": []
- },
- "description": "A dashboard for visualizing results from the k6.io load testing tool, using the InfluxDB exporter",
- "editable": true,
- "gnetId": 2587,
- "graphTooltip": 2,
- "hideControls": false,
- "id": null,
- "uid": "k6",
- "links": [],
- "refresh": "5s",
- "rows": [
- {
- "collapse": false,
- "height": "250px",
- "panels": [
- {
- "aliasColors": {},
- "bars": true,
- "dashLength": 10,
- "dashes": false,
- "datasource": "K6InfluxDB",
- "fill": 1,
- "id": 1,
- "interval": ">1s",
- "legend": {
- "alignAsTable": true,
- "avg": false,
- "current": false,
- "max": true,
- "min": true,
- "show": true,
- "total": false,
- "values": true
- },
- "lines": false,
- "linewidth": 1,
- "links": [],
- "nullPointMode": "null",
- "percentage": false,
- "pointradius": 5,
- "points": false,
- "renderer": "flot",
- "seriesOverrides": [],
- "spaceLength": 10,
- "span": 3,
- "stack": false,
- "steppedLine": false,
- "targets": [
- {
- "alias": "Active VUs",
- "dsType": "influxdb",
- "groupBy": [
- {
- "params": [
- "$__interval"
- ],
- "type": "time"
- },
- {
- "params": [
- "none"
- ],
- "type": "fill"
- }
- ],
- "measurement": "vus",
- "orderByTime": "ASC",
- "policy": "default",
- "refId": "A",
- "resultFormat": "time_series",
- "select": [
- [
- {
- "params": [
- "value"
- ],
- "type": "field"
- },
- {
- "params": [],
- "type": "mean"
- }
- ]
- ],
- "tags": []
- }
- ],
- "thresholds": [],
- "timeFrom": null,
- "timeShift": null,
- "title": "Virtual Users",
- "tooltip": {
- "shared": true,
- "sort": 0,
- "value_type": "individual"
- },
- "type": "graph",
- "xaxis": {
- "buckets": null,
- "mode": "time",
- "name": null,
- "show": true,
- "values": []
- },
- "yaxes": [
- {
- "format": "short",
- "label": null,
- "logBase": 1,
- "max": null,
- "min": null,
- "show": true
- },
- {
- "format": "short",
- "label": null,
- "logBase": 1,
- "max": null,
- "min": null,
- "show": true
- }
- ]
- },
- {
- "aliasColors": {},
- "bars": true,
- "dashLength": 10,
- "dashes": false,
- "datasource": "K6InfluxDB",
- "fill": 1,
- "id": 17,
- "interval": "1s",
- "legend": {
- "alignAsTable": true,
- "avg": true,
- "current": false,
- "max": true,
- "min": false,
- "rightSide": false,
- "show": true,
- "total": false,
- "values": true
- },
- "lines": false,
- "linewidth": 1,
- "links": [],
- "nullPointMode": "null",
- "percentage": false,
- "pointradius": 5,
- "points": false,
- "renderer": "flot",
- "seriesOverrides": [],
- "spaceLength": 10,
- "span": 3,
- "stack": false,
- "steppedLine": false,
- "targets": [
- {
- "alias": "Requests per Second",
- "dsType": "influxdb",
- "groupBy": [
- {
- "params": [
- "$__interval"
- ],
- "type": "time"
- },
- {
- "params": [
- "null"
- ],
- "type": "fill"
- }
- ],
- "measurement": "http_reqs",
- "orderByTime": "ASC",
- "policy": "default",
- "refId": "A",
- "resultFormat": "time_series",
- "select": [
- [
- {
- "params": [
- "value"
- ],
- "type": "field"
- },
- {
- "params": [],
- "type": "sum"
- }
- ]
- ],
- "tags": []
- }
- ],
- "thresholds": [],
- "timeFrom": null,
- "timeShift": null,
- "title": "Requests per Second",
- "tooltip": {
- "shared": true,
- "sort": 0,
- "value_type": "individual"
- },
- "type": "graph",
- "xaxis": {
- "buckets": null,
- "mode": "time",
- "name": null,
- "show": true,
- "values": []
- },
- "yaxes": [
- {
- "format": "short",
- "label": null,
- "logBase": 1,
- "max": null,
- "min": null,
- "show": true
- },
- {
- "format": "short",
- "label": null,
- "logBase": 1,
- "max": null,
- "min": null,
- "show": true
- }
- ]
- },
- {
- "aliasColors": {},
- "bars": true,
- "dashLength": 10,
- "dashes": false,
- "datasource": "K6InfluxDB",
- "fill": 1,
- "id": 7,
- "interval": "1s",
- "legend": {
- "alignAsTable": true,
- "avg": true,
- "current": false,
- "max": false,
- "min": false,
- "show": true,
- "total": true,
- "values": true
- },
- "lines": false,
- "linewidth": 1,
- "links": [],
- "nullPointMode": "null",
- "percentage": false,
- "pointradius": 5,
- "points": false,
- "renderer": "flot",
- "seriesOverrides": [
- {
- "alias": "Num Errors",
- "color": "#BF1B00"
- }
- ],
- "spaceLength": 10,
- "span": 3,
- "stack": true,
- "steppedLine": false,
- "targets": [
- {
- "alias": "Num Errors",
- "dsType": "influxdb",
- "groupBy": [
- {
- "params": [
- "$__interval"
- ],
- "type": "time"
- },
- {
- "params": [
- "none"
- ],
- "type": "fill"
- }
- ],
- "measurement": "errors",
- "orderByTime": "ASC",
- "policy": "default",
- "refId": "C",
- "resultFormat": "time_series",
- "select": [
- [
- {
- "params": [
- "value"
- ],
- "type": "field"
- },
- {
- "params": [],
- "type": "count"
- }
- ]
- ],
- "tags": []
- }
- ],
- "thresholds": [],
- "timeFrom": null,
- "timeShift": null,
- "title": "Errors Per Second",
- "tooltip": {
- "shared": true,
- "sort": 0,
- "value_type": "individual"
- },
- "type": "graph",
- "xaxis": {
- "buckets": null,
- "mode": "time",
- "name": null,
- "show": true,
- "values": []
- },
- "yaxes": [
- {
- "format": "short",
- "label": null,
- "logBase": 1,
- "max": null,
- "min": null,
- "show": true
- },
- {
- "format": "short",
- "label": null,
- "logBase": 1,
- "max": null,
- "min": null,
- "show": true
- }
- ]
- },
- {
- "aliasColors": {},
- "bars": true,
- "dashLength": 10,
- "dashes": false,
- "datasource": "K6InfluxDB",
- "fill": 1,
- "id": 10,
- "interval": ">1s",
- "legend": {
- "alignAsTable": true,
- "avg": true,
- "current": false,
- "max": false,
- "min": false,
- "show": true,
- "total": true,
- "values": true
- },
- "lines": false,
- "linewidth": 1,
- "links": [],
- "nullPointMode": "null",
- "percentage": false,
- "pointradius": 5,
- "points": false,
- "renderer": "flot",
- "seriesOverrides": [
- {
- "alias": "Num Errors",
- "color": "#BF1B00"
- }
- ],
- "spaceLength": 10,
- "span": 3,
- "stack": true,
- "steppedLine": false,
- "targets": [
- {
- "alias": "$tag_check",
- "dsType": "influxdb",
- "groupBy": [
- {
- "params": [
- "$__interval"
- ],
- "type": "time"
- },
- {
- "params": [
- "check"
- ],
- "type": "tag"
- },
- {
- "params": [
- "none"
- ],
- "type": "fill"
- }
- ],
- "measurement": "checks",
- "orderByTime": "ASC",
- "policy": "default",
- "refId": "C",
- "resultFormat": "time_series",
- "select": [
- [
- {
- "params": [
- "value"
- ],
- "type": "field"
- },
- {
- "params": [],
- "type": "sum"
- }
- ]
- ],
- "tags": []
- }
- ],
- "thresholds": [],
- "timeFrom": null,
- "timeShift": null,
- "title": "Checks Per Second",
- "tooltip": {
- "shared": true,
- "sort": 0,
- "value_type": "individual"
- },
- "type": "graph",
- "xaxis": {
- "buckets": null,
- "mode": "time",
- "name": null,
- "show": true,
- "values": []
- },
- "yaxes": [
- {
- "format": "none",
- "label": null,
- "logBase": 1,
- "max": null,
- "min": null,
- "show": true
- },
- {
- "format": "short",
- "label": null,
- "logBase": 1,
- "max": null,
- "min": null,
- "show": true
- }
- ]
- }
- ],
- "repeat": null,
- "repeatIteration": null,
- "repeatRowId": null,
- "showTitle": false,
- "title": "Dashboard Row",
- "titleSize": "h6"
- },
- {
- "collapse": false,
- "height": "",
- "panels": [
- {
- "cacheTimeout": null,
- "colorBackground": false,
- "colorValue": false,
- "colors": [
- "rgba(245, 54, 54, 0.9)",
- "rgba(237, 129, 40, 0.89)",
- "rgba(50, 172, 45, 0.97)"
- ],
- "datasource": "K6InfluxDB",
- "decimals": 2,
- "format": "ms",
- "gauge": {
- "maxValue": 100,
- "minValue": 0,
- "show": false,
- "thresholdLabels": false,
- "thresholdMarkers": true
- },
- "height": "50px",
- "id": 11,
- "interval": null,
- "links": [],
- "mappingType": 1,
- "mappingTypes": [
- {
- "name": "value to text",
- "value": 1
- },
- {
- "name": "range to text",
- "value": 2
- }
- ],
- "maxDataPoints": 100,
- "nullPointMode": "connected",
- "nullText": null,
- "postfix": "",
- "postfixFontSize": "50%",
- "prefix": "",
- "prefixFontSize": "50%",
- "rangeMaps": [
- {
- "from": "null",
- "text": "N/A",
- "to": "null"
- }
- ],
- "span": 2,
- "sparkline": {
- "fillColor": "rgba(31, 118, 189, 0.18)",
- "full": false,
- "lineColor": "rgb(31, 120, 193)",
- "show": false
- },
- "tableColumn": "",
- "targets": [
- {
- "dsType": "influxdb",
- "groupBy": [
- {
- "params": [
- "$__interval"
- ],
- "type": "time"
- },
- {
- "params": [
- "null"
- ],
- "type": "fill"
- }
- ],
- "orderByTime": "ASC",
- "policy": "default",
- "query": "SELECT mean(\"value\") FROM $Measurement WHERE $timeFilter ",
- "rawQuery": true,
- "refId": "A",
- "resultFormat": "time_series",
- "select": [
- [
- {
- "params": [
- "value"
- ],
- "type": "field"
- },
- {
- "params": [],
- "type": "mean"
- }
- ]
- ],
- "tags": []
- }
- ],
- "thresholds": "",
- "title": "$Measurement (mean)",
- "type": "singlestat",
- "valueFontSize": "80%",
- "valueMaps": [
- {
- "op": "=",
- "text": "N/A",
- "value": "null"
- }
- ],
- "valueName": "avg"
- },
- {
- "cacheTimeout": null,
- "colorBackground": false,
- "colorValue": false,
- "colors": [
- "rgba(245, 54, 54, 0.9)",
- "rgba(237, 129, 40, 0.89)",
- "rgba(50, 172, 45, 0.97)"
- ],
- "datasource": "K6InfluxDB",
- "decimals": 2,
- "format": "ms",
- "gauge": {
- "maxValue": 100,
- "minValue": 0,
- "show": false,
- "thresholdLabels": false,
- "thresholdMarkers": true
- },
- "height": "50px",
- "id": 14,
- "interval": null,
- "links": [],
- "mappingType": 1,
- "mappingTypes": [
- {
- "name": "value to text",
- "value": 1
- },
- {
- "name": "range to text",
- "value": 2
- }
- ],
- "maxDataPoints": 100,
- "nullPointMode": "connected",
- "nullText": null,
- "postfix": "",
- "postfixFontSize": "50%",
- "prefix": "",
- "prefixFontSize": "50%",
- "rangeMaps": [
- {
- "from": "null",
- "text": "N/A",
- "to": "null"
- }
- ],
- "span": 2,
- "sparkline": {
- "fillColor": "rgba(31, 118, 189, 0.18)",
- "full": false,
- "lineColor": "rgb(31, 120, 193)",
- "show": false
- },
- "tableColumn": "",
- "targets": [
- {
- "dsType": "influxdb",
- "groupBy": [
- {
- "params": [
- "$__interval"
- ],
- "type": "time"
- },
- {
- "params": [
- "null"
- ],
- "type": "fill"
- }
- ],
- "orderByTime": "ASC",
- "policy": "default",
- "query": "SELECT max(\"value\") FROM $Measurement WHERE $timeFilter",
- "rawQuery": true,
- "refId": "A",
- "resultFormat": "time_series",
- "select": [
- [
- {
- "params": [
- "value"
- ],
- "type": "field"
- },
- {
- "params": [],
- "type": "mean"
- }
- ]
- ],
- "tags": []
- }
- ],
- "thresholds": "",
- "title": "$Measurement (max)",
- "type": "singlestat",
- "valueFontSize": "80%",
- "valueMaps": [
- {
- "op": "=",
- "text": "N/A",
- "value": "null"
- }
- ],
- "valueName": "avg"
- },
- {
- "cacheTimeout": null,
- "colorBackground": false,
- "colorValue": false,
- "colors": [
- "rgba(245, 54, 54, 0.9)",
- "rgba(237, 129, 40, 0.89)",
- "rgba(50, 172, 45, 0.97)"
- ],
- "datasource": "K6InfluxDB",
- "decimals": 2,
- "format": "ms",
- "gauge": {
- "maxValue": 100,
- "minValue": 0,
- "show": false,
- "thresholdLabels": false,
- "thresholdMarkers": true
- },
- "height": "50px",
- "id": 15,
- "interval": null,
- "links": [],
- "mappingType": 1,
- "mappingTypes": [
- {
- "name": "value to text",
- "value": 1
- },
- {
- "name": "range to text",
- "value": 2
- }
- ],
- "maxDataPoints": 100,
- "nullPointMode": "connected",
- "nullText": null,
- "postfix": "",
- "postfixFontSize": "50%",
- "prefix": "",
- "prefixFontSize": "50%",
- "rangeMaps": [
- {
- "from": "null",
- "text": "N/A",
- "to": "null"
- }
- ],
- "span": 2,
- "sparkline": {
- "fillColor": "rgba(31, 118, 189, 0.18)",
- "full": false,
- "lineColor": "rgb(31, 120, 193)",
- "show": false
- },
- "tableColumn": "",
- "targets": [
- {
- "dsType": "influxdb",
- "groupBy": [
- {
- "params": [
- "$__interval"
- ],
- "type": "time"
- },
- {
- "params": [
- "null"
- ],
- "type": "fill"
- }
- ],
- "orderByTime": "ASC",
- "policy": "default",
- "query": "SELECT median(\"value\") FROM $Measurement WHERE $timeFilter",
- "rawQuery": true,
- "refId": "A",
- "resultFormat": "time_series",
- "select": [
- [
- {
- "params": [
- "value"
- ],
- "type": "field"
- },
- {
- "params": [],
- "type": "mean"
- }
- ]
- ],
- "tags": []
- }
- ],
- "thresholds": "",
- "title": "$Measurement (med)",
- "type": "singlestat",
- "valueFontSize": "80%",
- "valueMaps": [
- {
- "op": "=",
- "text": "N/A",
- "value": "null"
- }
- ],
- "valueName": "avg"
- },
- {
- "cacheTimeout": null,
- "colorBackground": false,
- "colorValue": false,
- "colors": [
- "rgba(245, 54, 54, 0.9)",
- "rgba(237, 129, 40, 0.89)",
- "rgba(50, 172, 45, 0.97)"
- ],
- "datasource": "K6InfluxDB",
- "decimals": 2,
- "format": "ms",
- "gauge": {
- "maxValue": 100,
- "minValue": 0,
- "show": false,
- "thresholdLabels": false,
- "thresholdMarkers": true
- },
- "height": "50px",
- "id": 16,
- "interval": null,
- "links": [],
- "mappingType": 1,
- "mappingTypes": [
- {
- "name": "value to text",
- "value": 1
- },
- {
- "name": "range to text",
- "value": 2
- }
- ],
- "maxDataPoints": 100,
- "nullPointMode": "connected",
- "nullText": null,
- "postfix": "",
- "postfixFontSize": "50%",
- "prefix": "",
- "prefixFontSize": "50%",
- "rangeMaps": [
- {
- "from": "null",
- "text": "N/A",
- "to": "null"
- }
- ],
- "span": 2,
- "sparkline": {
- "fillColor": "rgba(31, 118, 189, 0.18)",
- "full": false,
- "lineColor": "rgb(31, 120, 193)",
- "show": false
- },
- "tableColumn": "",
- "targets": [
- {
- "dsType": "influxdb",
- "groupBy": [
- {
- "params": [
- "$__interval"
- ],
- "type": "time"
- },
- {
- "params": [
- "null"
- ],
- "type": "fill"
- }
- ],
- "orderByTime": "ASC",
- "policy": "default",
- "query": "SELECT min(\"value\") FROM $Measurement WHERE $timeFilter and value > 0",
- "rawQuery": true,
- "refId": "A",
- "resultFormat": "time_series",
- "select": [
- [
- {
- "params": [
- "value"
- ],
- "type": "field"
- },
- {
- "params": [],
- "type": "mean"
- }
- ]
- ],
- "tags": []
- }
- ],
- "thresholds": "",
- "title": "$Measurement (min)",
- "type": "singlestat",
- "valueFontSize": "80%",
- "valueMaps": [
- {
- "op": "=",
- "text": "N/A",
- "value": "null"
- }
- ],
- "valueName": "current"
- },
- {
- "cacheTimeout": null,
- "colorBackground": false,
- "colorValue": false,
- "colors": [
- "rgba(245, 54, 54, 0.9)",
- "rgba(237, 129, 40, 0.89)",
- "rgba(50, 172, 45, 0.97)"
- ],
- "datasource": "K6InfluxDB",
- "decimals": 2,
- "format": "ms",
- "gauge": {
- "maxValue": 100,
- "minValue": 0,
- "show": false,
- "thresholdLabels": false,
- "thresholdMarkers": true
- },
- "height": "50px",
- "id": 12,
- "interval": null,
- "links": [],
- "mappingType": 1,
- "mappingTypes": [
- {
- "name": "value to text",
- "value": 1
- },
- {
- "name": "range to text",
- "value": 2
- }
- ],
- "maxDataPoints": 100,
- "nullPointMode": "connected",
- "nullText": null,
- "postfix": "",
- "postfixFontSize": "50%",
- "prefix": "",
- "prefixFontSize": "50%",
- "rangeMaps": [
- {
- "from": "null",
- "text": "N/A",
- "to": "null"
- }
- ],
- "span": 2,
- "sparkline": {
- "fillColor": "rgba(31, 118, 189, 0.18)",
- "full": false,
- "lineColor": "rgb(31, 120, 193)",
- "show": false
- },
- "tableColumn": "",
- "targets": [
- {
- "dsType": "influxdb",
- "groupBy": [
- {
- "params": [
- "$__interval"
- ],
- "type": "time"
- },
- {
- "params": [
- "null"
- ],
- "type": "fill"
- }
- ],
- "orderByTime": "ASC",
- "policy": "default",
- "query": "SELECT percentile(\"value\", 90) FROM $Measurement WHERE $timeFilter",
- "rawQuery": true,
- "refId": "A",
- "resultFormat": "time_series",
- "select": [
- [
- {
- "params": [
- "value"
- ],
- "type": "field"
- },
- {
- "params": [],
- "type": "mean"
- }
- ]
- ],
- "tags": []
- }
- ],
- "thresholds": "",
- "title": "$Measurement (p90)",
- "type": "singlestat",
- "valueFontSize": "80%",
- "valueMaps": [
- {
- "op": "=",
- "text": "N/A",
- "value": "null"
- }
- ],
- "valueName": "avg"
- },
- {
- "cacheTimeout": null,
- "colorBackground": false,
- "colorValue": false,
- "colors": [
- "rgba(245, 54, 54, 0.9)",
- "rgba(237, 129, 40, 0.89)",
- "rgba(50, 172, 45, 0.97)"
- ],
- "datasource": "K6InfluxDB",
- "decimals": 2,
- "format": "ms",
- "gauge": {
- "maxValue": 100,
- "minValue": 0,
- "show": false,
- "thresholdLabels": false,
- "thresholdMarkers": true
- },
- "height": "50px",
- "id": 13,
- "interval": null,
- "links": [],
- "mappingType": 1,
- "mappingTypes": [
- {
- "name": "value to text",
- "value": 1
- },
- {
- "name": "range to text",
- "value": 2
- }
- ],
- "maxDataPoints": 100,
- "nullPointMode": "connected",
- "nullText": null,
- "postfix": "",
- "postfixFontSize": "50%",
- "prefix": "",
- "prefixFontSize": "50%",
- "rangeMaps": [
- {
- "from": "null",
- "text": "N/A",
- "to": "null"
- }
- ],
- "span": 2,
- "sparkline": {
- "fillColor": "rgba(31, 118, 189, 0.18)",
- "full": false,
- "lineColor": "rgb(31, 120, 193)",
- "show": false
- },
- "tableColumn": "",
- "targets": [
- {
- "dsType": "influxdb",
- "groupBy": [
- {
- "params": [
- "$__interval"
- ],
- "type": "time"
- },
- {
- "params": [
- "null"
- ],
- "type": "fill"
- }
- ],
- "orderByTime": "ASC",
- "policy": "default",
- "query": "SELECT percentile(\"value\", 95) FROM $Measurement WHERE $timeFilter ",
- "rawQuery": true,
- "refId": "A",
- "resultFormat": "time_series",
- "select": [
- [
- {
- "params": [
- "value"
- ],
- "type": "field"
- },
- {
- "params": [],
- "type": "mean"
- }
- ]
- ],
- "tags": []
- }
- ],
- "thresholds": "",
- "title": "$Measurement (p95)",
- "type": "singlestat",
- "valueFontSize": "80%",
- "valueMaps": [
- {
- "op": "=",
- "text": "N/A",
- "value": "null"
- }
- ],
- "valueName": "avg"
- },
- {
- "aliasColors": {},
- "bars": false,
- "dashLength": 10,
- "dashes": false,
- "datasource": "K6InfluxDB",
- "description": "Grouped by 1 sec intervals",
- "fill": 1,
- "height": "250px",
- "id": 5,
- "interval": ">1s",
- "legend": {
- "alignAsTable": false,
- "avg": false,
- "current": false,
- "max": false,
- "min": false,
- "show": true,
- "total": false,
- "values": false
- },
- "lines": true,
- "linewidth": 1,
- "links": [],
- "nullPointMode": "null",
- "percentage": false,
- "pointradius": 5,
- "points": false,
- "renderer": "flot",
- "seriesOverrides": [],
- "spaceLength": 10,
- "span": 6,
- "stack": false,
- "steppedLine": false,
- "targets": [
- {
- "alias": "max",
- "dsType": "influxdb",
- "groupBy": [
- {
- "params": [
- "$__interval"
- ],
- "type": "time"
- },
- {
- "params": [
- "none"
- ],
- "type": "fill"
- }
- ],
- "measurement": "/^$Measurement$/",
- "orderByTime": "ASC",
- "policy": "default",
- "query": "SELECT max(\"value\") FROM /^$Measurement$/ WHERE $timeFilter and value > 0 GROUP BY time($__interval) fill(none)",
- "rawQuery": true,
- "refId": "C",
- "resultFormat": "time_series",
- "select": [
- [
- {
- "params": [
- "value"
- ],
- "type": "field"
- },
- {
- "params": [],
- "type": "max"
- }
- ]
- ],
- "tags": []
- },
- {
- "alias": "p95",
- "dsType": "influxdb",
- "groupBy": [
- {
- "params": [
- "$__interval"
- ],
- "type": "time"
- },
- {
- "params": [
- "none"
- ],
- "type": "fill"
- }
- ],
- "measurement": "/^$Measurement$/",
- "orderByTime": "ASC",
- "policy": "default",
- "query": "SELECT percentile(\"value\", 95) FROM /^$Measurement$/ WHERE $timeFilter and value > 0 GROUP BY time($__interval) fill(none)",
- "rawQuery": true,
- "refId": "D",
- "resultFormat": "time_series",
- "select": [
- [
- {
- "params": [
- "value"
- ],
- "type": "field"
- },
- {
- "params": [
- 95
- ],
- "type": "percentile"
- }
- ]
- ],
- "tags": []
- },
- {
- "alias": "p90",
- "dsType": "influxdb",
- "groupBy": [
- {
- "params": [
- "$__interval"
- ],
- "type": "time"
- },
- {
- "params": [
- "none"
- ],
- "type": "fill"
- }
- ],
- "measurement": "/^$Measurement$/",
- "orderByTime": "ASC",
- "policy": "default",
- "query": "SELECT percentile(\"value\", 90) FROM /^$Measurement$/ WHERE $timeFilter and value > 0 GROUP BY time($__interval) fill(none)",
- "rawQuery": true,
- "refId": "A",
- "resultFormat": "time_series",
- "select": [
- [
- {
- "params": [
- "value"
- ],
- "type": "field"
- },
- {
- "params": [
- "90"
- ],
- "type": "percentile"
- }
- ]
- ],
- "tags": []
- },
- {
- "alias": "min",
- "dsType": "influxdb",
- "groupBy": [
- {
- "params": [
- "$__interval"
- ],
- "type": "time"
- },
- {
- "params": [
- "none"
- ],
- "type": "fill"
- }
- ],
- "measurement": "/^$Measurement$/",
- "orderByTime": "ASC",
- "policy": "default",
- "query": "SELECT min(\"value\") FROM /^$Measurement$/ WHERE $timeFilter and value > 0 GROUP BY time($__interval) fill(none)",
- "rawQuery": true,
- "refId": "E",
- "resultFormat": "time_series",
- "select": [
- [
- {
- "params": [
- "value"
- ],
- "type": "field"
- },
- {
- "params": [],
- "type": "min"
- }
- ]
- ],
- "tags": []
- }
- ],
- "thresholds": [],
- "timeFrom": null,
- "timeShift": null,
- "title": "$Measurement (over time)",
- "tooltip": {
- "shared": true,
- "sort": 0,
- "value_type": "individual"
- },
- "type": "graph",
- "xaxis": {
- "buckets": null,
- "mode": "time",
- "name": null,
- "show": true,
- "values": []
- },
- "yaxes": [
- {
- "format": "ms",
- "label": null,
- "logBase": 2,
- "max": null,
- "min": null,
- "show": true
- },
- {
- "format": "short",
- "label": null,
- "logBase": 1,
- "max": null,
- "min": null,
- "show": true
- }
- ]
- },
- {
- "cards": {
- "cardPadding": null,
- "cardRound": null
- },
- "color": {
- "cardColor": "rgb(0, 234, 255)",
- "colorScale": "sqrt",
- "colorScheme": "interpolateRdYlGn",
- "exponent": 0.5,
- "mode": "spectrum"
- },
- "dataFormat": "timeseries",
- "datasource": "K6InfluxDB",
- "heatmap": {},
- "height": "250px",
- "highlightCards": true,
- "id": 8,
- "interval": ">1s",
- "links": [],
- "span": 6,
- "targets": [
- {
- "dsType": "influxdb",
- "groupBy": [
- {
- "params": [
- "$__interval"
- ],
- "type": "time"
- },
- {
- "params": [
- "null"
- ],
- "type": "fill"
- }
- ],
- "measurement": "http_req_duration",
- "orderByTime": "ASC",
- "policy": "default",
- "query": "SELECT \"value\" FROM $Measurement WHERE $timeFilter and value > 0",
- "rawQuery": true,
- "refId": "A",
- "resultFormat": "time_series",
- "select": [
- [
- {
- "params": [
- "value"
- ],
- "type": "field"
- },
- {
- "params": [],
- "type": "mean"
- }
- ]
- ],
- "tags": []
- }
- ],
- "title": "$Measurement (over time)",
- "tooltip": {
- "show": true,
- "showHistogram": true
- },
- "tooltipDecimals": null,
- "type": "heatmap",
- "xAxis": {
- "show": true
- },
- "xBucketNumber": null,
- "xBucketSize": null,
- "yAxis": {
- "decimals": null,
- "format": "ms",
- "logBase": 2,
- "max": null,
- "min": null,
- "show": true,
- "splitFactor": null
- },
- "yBucketNumber": null,
- "yBucketSize": null
- }
- ],
- "repeat": "Measurement",
- "repeatIteration": null,
- "repeatRowId": null,
- "showTitle": true,
- "title": "$Measurement",
- "titleSize": "h6"
- },
- {
- "collapse": false,
- "height": 250,
- "panels": [],
- "repeat": null,
- "repeatIteration": null,
- "repeatRowId": null,
- "showTitle": false,
- "title": "Dashboard Row",
- "titleSize": "h6"
- }
- ],
- "schemaVersion": 14,
- "style": "dark",
- "tags": [],
- "templating": {
- "list": [
- {
- "allValue": null,
- "current": {
- "selected": true,
- "tags": [],
- "text": "http_req_duration",
- "value": [
- "http_req_duration"
- ]
- },
- "hide": 0,
- "includeAll": true,
- "label": null,
- "multi": true,
- "name": "Measurement",
- "options": [
- {
- "selected": false,
- "text": "All",
- "value": "$__all"
- },
- {
- "selected": true,
- "text": "http_req_duration",
- "value": "http_req_duration"
- },
- {
- "selected": false,
- "text": "http_req_blocked",
- "value": "http_req_blocked"
- },
- {
- "selected": false,
- "text": "http_req_connecting",
- "value": "http_req_connecting"
- },
- {
- "selected": false,
- "text": "http_req_looking_up",
- "value": "http_req_looking_up"
- },
- {
- "selected": false,
- "text": "http_req_receiving",
- "value": "http_req_receiving"
- },
- {
- "selected": false,
- "text": "http_req_sending",
- "value": "http_req_sending"
- },
- {
- "selected": false,
- "text": "http_req_waiting",
- "value": "http_req_waiting"
- }
- ],
- "query": "http_req_duration,http_req_blocked,http_req_connecting,http_req_looking_up,http_req_receiving,http_req_sending,http_req_waiting",
- "type": "custom"
- }
- ]
- },
- "time": {
- "from": "now-3m",
- "to": "now"
- },
- "timepicker": {
- "refresh_intervals": [
- "5s",
- "10s",
- "30s",
- "1m",
- "5m",
- "15m",
- "30m",
- "1h",
- "2h",
- "1d"
- ],
- "time_options": [
- "5m",
- "15m",
- "1h",
- "6h",
- "12h",
- "24h",
- "2d",
- "7d",
- "30d"
- ]
- },
- "timezone": "browser",
- "title": "k6 Load Testing Results",
- "version": 22
-}
diff --git a/loadtest/grafana/grafana-dashboard.yaml b/loadtest/grafana/grafana-dashboard.yaml
deleted file mode 100644
index d51fd65a6e..0000000000
--- a/loadtest/grafana/grafana-dashboard.yaml
+++ /dev/null
@@ -1,8 +0,0 @@
-apiVersion: 1
-providers:
- - name: 'default'
- org_id: 1
- folder: ''
- type: 'file'
- options:
- path: /var/lib/grafana/dashboards
\ No newline at end of file
diff --git a/loadtest/grafana/grafana-datasource.yaml b/loadtest/grafana/grafana-datasource.yaml
deleted file mode 100644
index 16034cb2ca..0000000000
--- a/loadtest/grafana/grafana-datasource.yaml
+++ /dev/null
@@ -1,16 +0,0 @@
-apiVersion: 1
-
-datasources:
- - name: K6InfluxDB
- type: influxdb
- access: proxy
- database: scripts
- url: http://influxdb:8086
- isDefault: false
-
- - name: Tempo
- type: tempo
- access: proxy
- url: http://tempo:3200
- isDefault: true
- editable: true
diff --git a/loadtest/k6/benchmark/.empty b/loadtest/k6/benchmark/.empty
deleted file mode 100644
index e69de29bb2..0000000000
diff --git a/loadtest/k6/health.js b/loadtest/k6/health.js
deleted file mode 100644
index 04d7cbee1c..0000000000
--- a/loadtest/k6/health.js
+++ /dev/null
@@ -1,30 +0,0 @@
-import http from "k6/http";
-import { sleep, check } from "k6";
-import { Counter } from "k6/metrics";
-import { readBaseline, storeResult } from "./helper/compare-result.js";
-
-export const requests = new Counter('http_reqs');
-
-const baseline = readBaseline("health");
-
-export const options = {
- stages: [
- { duration: "10s", target: 25 }, // ramp up users to 25 in 10 seconds
- { duration: "10s", target: 25 }, // maintain 25 users for 10 seconds
- { duration: "10s", target: 0 } // ramp down to 0 users in 10 seconds
- ],
- thresholds: {
- "http_req_duration": ["p(90) < 15"], // 90% of requests must finish within 15ms.
- },
-};
-
-export default function () {
- const res = http.get("http://router-server:8080/health");
- check(res, {
- "health status 200": (r) => r.status === 200,
- });
-}
-
-export function handleSummary(data) {
- return storeResult("health", baseline, data)
-}
diff --git a/loadtest/k6/helper/compare-result.js b/loadtest/k6/helper/compare-result.js
deleted file mode 100644
index 6877ac197f..0000000000
--- a/loadtest/k6/helper/compare-result.js
+++ /dev/null
@@ -1,61 +0,0 @@
-import { textSummary } from "./k6-summary.js";
-
-function compute(baseline, result) {
- return ((1 - (result/baseline)) * -100).toFixed(2)
-}
-
-function buildResult(baseline, data) {
- return function(metrics, fields) {
- const result = {}
- metrics.forEach(metric => {
- result[metric] = {}
- fields.forEach(field => {
- let a = baseline.metrics[metric]["values"][field]
- let b = data.metrics[metric]["values"][field]
- result[metric][field] = compute(a, b) + "%"
- })
- })
- return result
- }
-}
-
-function compareResult(baseline, data) {
- // note: we can add more metrics. we grouped them based on the field they contain.
- // todo: add validation whether threshold/check are being matched or vus are the same as baseline run.
- const computeResult = buildResult(baseline, data)
-
- const group1 = ["http_req_duration"]
- const group1_fields = data.options.summaryTrendStats
- const group1_result = computeResult(group1, group1_fields)
-
- const group2 = ["http_reqs"]
- const group2_fields = ["rate"]
- const group2_result = computeResult(group2, group2_fields)
-
- return Object.assign(group1_result, group2_result)
-}
-
-export function readBaseline(scenario) {
- let baseline = null;
- if (__ENV.LOADTEST_RUN_NAME != "baseline") {
- baseline = JSON.parse(open(`./benchmark/baseline_${scenario}.json`, "r"))
- }
- return baseline
-}
-
-export function storeResult(scenario, baseline, data) {
- const file = `/scripts/benchmark/${__ENV.LOADTEST_RUN_NAME}_${scenario}`
- const summary = textSummary(data, { indent: ' ', enableColors: false })
- const result = {
- [`${file}.json`]: JSON.stringify(data, null, 2),
- [`${file}.summary`]: summary
- }
- if (baseline != null) {
- const diff = JSON.stringify(compareResult(baseline, data), null, 2)
- result[`${file}.diff`] = diff
- result["stdout"] = diff
- } else {
- result["stdout"] = summary
- }
- return result
-}
\ No newline at end of file
diff --git a/loadtest/k6/helper/k6-summary.js b/loadtest/k6/helper/k6-summary.js
deleted file mode 100644
index f8135cb5a1..0000000000
--- a/loadtest/k6/helper/k6-summary.js
+++ /dev/null
@@ -1,477 +0,0 @@
-var forEach = function (obj, callback) {
- for (var key in obj) {
- if (obj.hasOwnProperty(key)) {
- if (callback(key, obj[key])) {
- break
- }
- }
- }
-}
-
-var palette = {
- bold: 1,
- faint: 2,
- red: 31,
- green: 32,
- cyan: 36,
- //TODO: add others?
-}
-
-var groupPrefix = '█'
-var detailsPrefix = '↳'
-var succMark = '✓'
-var failMark = '✗'
-var defaultOptions = {
- indent: ' ',
- enableColors: true,
- summaryTimeUnit: null,
- summaryTrendStats: null,
-}
-
-// strWidth tries to return the actual width the string will take up on the
-// screen, without any terminal formatting, unicode ligatures, etc.
-function strWidth(s) {
- // TODO: determine if NFC or NFKD are not more appropriate? or just give up? https://hsivonen.fi/string-length/
- var data = s.normalize('NFKC') // This used to be NFKD in Go, but this should be better
- var inEscSeq = false
- var inLongEscSeq = false
- var width = 0
- for (var char of data) {
- if (char.done) {
- break
- }
-
- // Skip over ANSI escape codes.
- if (char == '\x1b') {
- inEscSeq = true
- continue
- }
- if (inEscSeq && char == '[') {
- inLongEscSeq = true
- continue
- }
- if (inEscSeq && inLongEscSeq && char.charCodeAt(0) >= 0x40 && char.charCodeAt(0) <= 0x7e) {
- inEscSeq = false
- inLongEscSeq = false
- continue
- }
- if (inEscSeq && !inLongEscSeq && char.charCodeAt(0) >= 0x40 && char.charCodeAt(0) <= 0x5f) {
- inEscSeq = false
- continue
- }
-
- if (!inEscSeq && !inLongEscSeq) {
- width++
- }
- }
- return width
-}
-
-function summarizeCheck(indent, check, decorate) {
- if (check.fails == 0) {
- return decorate(indent + succMark + ' ' + check.name, palette.green)
- }
-
- var succPercent = Math.floor((100 * check.passes) / (check.passes + check.fails))
- return decorate(
- indent +
- failMark +
- ' ' +
- check.name +
- '\n' +
- indent +
- ' ' +
- detailsPrefix +
- ' ' +
- succPercent +
- '% — ' +
- succMark +
- ' ' +
- check.passes +
- ' / ' +
- failMark +
- ' ' +
- check.fails,
- palette.red
- )
-}
-
-function summarizeGroup(indent, group, decorate) {
- var result = []
- if (group.name != '') {
- result.push(indent + groupPrefix + ' ' + group.name + '\n')
- indent = indent + ' '
- }
-
- for (var i = 0; i < group.checks.length; i++) {
- result.push(summarizeCheck(indent, group.checks[i], decorate))
- }
- if (group.checks.length > 0) {
- result.push('')
- }
- for (var i = 0; i < group.groups.length; i++) {
- Array.prototype.push.apply(result, summarizeGroup(indent, group.groups[i], decorate))
- }
-
- return result
-}
-
-function displayNameForMetric(name) {
- var subMetricPos = name.indexOf('{')
- if (subMetricPos >= 0) {
- return '{ ' + name.substring(subMetricPos + 1, name.length - 1) + ' }'
- }
- return name
-}
-
-function indentForMetric(name) {
- if (name.indexOf('{') >= 0) {
- return ' '
- }
- return ''
-}
-
-function humanizeBytes(bytes) {
- var units = ['B', 'kB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB']
- var base = 1000
- if (bytes < 10) {
- return bytes + ' B'
- }
-
- var e = Math.floor(Math.log(bytes) / Math.log(base))
- var suffix = units[e | 0]
- var val = Math.floor((bytes / Math.pow(base, e)) * 10 + 0.5) / 10
- return val.toFixed(val < 10 ? 1 : 0) + ' ' + suffix
-}
-
-var unitMap = {
- s: { unit: 's', coef: 0.001 },
- ms: { unit: 'ms', coef: 1 },
- us: { unit: 'µs', coef: 1000 },
-}
-
-function toFixedNoTrailingZeros(val, prec) {
- // TODO: figure out something better?
- return parseFloat(val.toFixed(prec)).toString()
-}
-
-function toFixedNoTrailingZerosTrunc(val, prec) {
- var mult = Math.pow(10, prec)
- return toFixedNoTrailingZeros(Math.trunc(mult * val) / mult, prec)
-}
-
-function humanizeGenericDuration(duration) {
- if (duration === 0) {
- return '0s'
- }
-
- if (duration < 0.001) {
- // smaller than a microsecond, print nanoseconds
- return Math.trunc(duration * 1000000) + 'ns'
- }
- if (duration < 1) {
- // smaller than a millisecond, print microseconds
- return toFixedNoTrailingZerosTrunc(duration * 1000, 2) + 'µs'
- }
- if (duration < 1000) {
- // duration is smaller than a second
- return toFixedNoTrailingZerosTrunc(duration, 2) + 'ms'
- }
-
- var result = toFixedNoTrailingZerosTrunc((duration % 60000) / 1000, duration > 60000 ? 0 : 2) + 's'
- var rem = Math.trunc(duration / 60000)
- if (rem < 1) {
- // less than a minute
- return result
- }
- result = (rem % 60) + 'm' + result
- rem = Math.trunc(rem / 60)
- if (rem < 1) {
- // less than an hour
- return result
- }
- return rem + 'h' + result
-}
-
-function humanizeDuration(duration, timeUnit) {
- if (timeUnit !== '' && unitMap.hasOwnProperty(timeUnit)) {
- return (duration * unitMap[timeUnit].coef).toFixed(2) + unitMap[timeUnit].unit
- }
-
- return humanizeGenericDuration(duration)
-}
-
-function humanizeValue(val, metric, timeUnit) {
- if (metric.type == 'rate') {
- // Truncate instead of round when decreasing precision to 2 decimal places
- return (Math.trunc(val * 100 * 100) / 100).toFixed(2) + '%'
- }
-
- switch (metric.contains) {
- case 'data':
- return humanizeBytes(val)
- case 'time':
- return humanizeDuration(val, timeUnit)
- default:
- return toFixedNoTrailingZeros(val, 6)
- }
-}
-
-function nonTrendMetricValueForSum(metric, timeUnit) {
- switch (metric.type) {
- case 'counter':
- return [
- humanizeValue(metric.values.count, metric, timeUnit),
- humanizeValue(metric.values.rate, metric, timeUnit) + '/s',
- ]
- case 'gauge':
- return [
- humanizeValue(metric.values.value, metric, timeUnit),
- 'min=' + humanizeValue(metric.values.min, metric, timeUnit),
- 'max=' + humanizeValue(metric.values.max, metric, timeUnit),
- ]
- case 'rate':
- return [
- humanizeValue(metric.values.rate, metric, timeUnit),
- succMark + ' ' + metric.values.passes,
- failMark + ' ' + metric.values.fails,
- ]
- default:
- return ['[no data]']
- }
-}
-
-function summarizeMetrics(options, data, decorate) {
- var indent = options.indent + ' '
- var result = []
-
- var names = []
- var nameLenMax = 0
-
- var nonTrendValues = {}
- var nonTrendValueMaxLen = 0
- var nonTrendExtras = {}
- var nonTrendExtraMaxLens = [0, 0]
-
- var trendCols = {}
- var numTrendColumns = options.summaryTrendStats.length
- var trendColMaxLens = new Array(numTrendColumns).fill(0)
- forEach(data.metrics, function (name, metric) {
- names.push(name)
- // When calculating widths for metrics, account for the indentation on submetrics.
- var displayName = indentForMetric(name) + displayNameForMetric(name)
- var displayNameWidth = strWidth(displayName)
- if (displayNameWidth > nameLenMax) {
- nameLenMax = displayNameWidth
- }
-
- if (metric.type == 'trend') {
- var cols = []
- for (var i = 0; i < numTrendColumns; i++) {
- var tc = options.summaryTrendStats[i]
- var value = metric.values[tc]
- if (tc === 'count') {
- value = value.toString()
- } else {
- value = humanizeValue(value, metric, options.summaryTimeUnit)
- }
- var valLen = strWidth(value)
- if (valLen > trendColMaxLens[i]) {
- trendColMaxLens[i] = valLen
- }
- cols[i] = value
- }
- trendCols[name] = cols
- return
- }
- var values = nonTrendMetricValueForSum(metric, options.summaryTimeUnit)
- nonTrendValues[name] = values[0]
- var valueLen = strWidth(values[0])
- if (valueLen > nonTrendValueMaxLen) {
- nonTrendValueMaxLen = valueLen
- }
- nonTrendExtras[name] = values.slice(1)
- for (var i = 1; i < values.length; i++) {
- var extraLen = strWidth(values[i])
- if (extraLen > nonTrendExtraMaxLens[i - 1]) {
- nonTrendExtraMaxLens[i - 1] = extraLen
- }
- }
- })
-
- // sort all metrics but keep sub metrics grouped with their parent metrics
- names.sort(function (metric1, metric2) {
- var parent1 = metric1.split('{', 1)[0]
- var parent2 = metric2.split('{', 1)[0]
- var result = parent1.localeCompare(parent2)
- if (result !== 0) {
- return result
- }
- var sub1 = metric1.substring(parent1.length)
- var sub2 = metric2.substring(parent2.length)
- return sub1.localeCompare(sub2)
- })
-
- var getData = function (name) {
- if (trendCols.hasOwnProperty(name)) {
- var cols = trendCols[name]
- var tmpCols = new Array(numTrendColumns)
- for (var i = 0; i < cols.length; i++) {
- tmpCols[i] =
- options.summaryTrendStats[i] +
- '=' +
- decorate(cols[i], palette.cyan) +
- ' '.repeat(trendColMaxLens[i] - strWidth(cols[i]))
- }
- return tmpCols.join(' ')
- }
-
- var value = nonTrendValues[name]
- var fmtData = decorate(value, palette.cyan) + ' '.repeat(nonTrendValueMaxLen - strWidth(value))
-
- var extras = nonTrendExtras[name]
- if (extras.length == 1) {
- fmtData = fmtData + ' ' + decorate(extras[0], palette.cyan, palette.faint)
- } else if (extras.length > 1) {
- var parts = new Array(extras.length)
- for (var i = 0; i < extras.length; i++) {
- parts[i] =
- decorate(extras[i], palette.cyan, palette.faint) +
- ' '.repeat(nonTrendExtraMaxLens[i] - strWidth(extras[i]))
- }
- fmtData = fmtData + ' ' + parts.join(' ')
- }
-
- return fmtData
- }
-
- for (var name of names) {
- var metric = data.metrics[name]
- var mark = ' '
- var markColor = function (text) {
- return text
- } // noop
-
- if (metric.thresholds) {
- mark = succMark
- markColor = function (text) {
- return decorate(text, palette.green)
- }
- forEach(metric.thresholds, function (name, threshold) {
- if (!threshold.ok) {
- mark = failMark
- markColor = function (text) {
- return decorate(text, palette.red)
- }
- return true // break
- }
- })
- }
- var fmtIndent = indentForMetric(name)
- var fmtName = displayNameForMetric(name)
- fmtName =
- fmtName +
- decorate(
- '.'.repeat(nameLenMax - strWidth(fmtName) - strWidth(fmtIndent) + 3) + ':',
- palette.faint
- )
-
- result.push(indent + fmtIndent + markColor(mark) + ' ' + fmtName + ' ' + getData(name))
- }
-
- return result
-}
-
-function generateTextSummary(data, options) {
- var mergedOpts = Object.assign({}, defaultOptions, data.options, options)
- var lines = []
-
- // TODO: move all of these functions into an object with methods?
- var decorate = function (text) {
- return text
- }
- if (mergedOpts.enableColors) {
- decorate = function (text, color /*, ...rest*/) {
- var result = '\x1b[' + color
- for (var i = 2; i < arguments.length; i++) {
- result += ';' + arguments[i]
- }
- return result + 'm' + text + '\x1b[0m'
- }
- }
-
- Array.prototype.push.apply(
- lines,
- summarizeGroup(mergedOpts.indent + ' ', data.root_group, decorate)
- )
-
- Array.prototype.push.apply(lines, summarizeMetrics(mergedOpts, data, decorate))
-
- return lines.join('\n')
-}
-
-exports.humanizeValue = humanizeValue
-exports.textSummary = generateTextSummary
-
-var replacements = {
- '&': '&amp;',
- '<': '&lt;',
- '>': '&gt;',
- "'": '&#39;',
- '"': '&quot;',
-}
-
-function escapeHTML(str) {
- // TODO: something more robust?
- return str.replace(/[&<>'"]/g, function (char) {
- return replacements[char]
- })
-}
-
-function generateJUnitXML(data, options) {
- var failures = 0
- var cases = []
-
- forEach(data.metrics, function (metricName, metric) {
- if (!metric.thresholds) {
- return
- }
- forEach(metric.thresholds, function (thresholdName, threshold) {
- if (threshold.ok) {
- cases.push(
- '<testcase name="' + escapeHTML(metricName) + ' - ' + escapeHTML(thresholdName) + '" />'
- )
- } else {
- failures++
- cases.push(
- '<testcase name="' +
- escapeHTML(metricName) +
- ' - ' +
- escapeHTML(thresholdName) +
- '"><failure message="failed" /></testcase>'
- )
- }
- })
- })
-
- var name = options && options.name ? escapeHTML(options.name) : 'k6 thresholds'
-
- return (
- '<?xml version="1.0"?>\n<testsuites tests="' +
- cases.length +
- '" failures="' +
- failures +
- '">\n' +
- '<testsuite name="' +
- name +
- '" tests="' +
- cases.length +
- '" failures="' +
- failures +
- '">' +
- cases.join('\n') +
- '\n</testsuite >\n</testsuites >'
- )
-}
-
-exports.jUnit = generateJUnitXML
diff --git a/loadtest/k6/helper/misc.js b/loadtest/k6/helper/misc.js
deleted file mode 100644
index 7edda1eaa7..0000000000
--- a/loadtest/k6/helper/misc.js
+++ /dev/null
@@ -1,3 +0,0 @@
-export function random_string() {
- return Math.random().toString(36).slice(-5)
-}
\ No newline at end of file
diff --git a/loadtest/k6/helper/setup.js b/loadtest/k6/helper/setup.js
deleted file mode 100644
index 18f10242a6..0000000000
--- a/loadtest/k6/helper/setup.js
+++ /dev/null
@@ -1,140 +0,0 @@
-import http from "k6/http";
-import { check } from "k6";
-
-export function setup_merchant_apikey() {
- let params = {
- "headers": {
- "Content-Type": "application/json",
- "api-key" : "test_admin"
- }
- };
- let merchant_account_payload = {
- "merchant_id":`merchant_${Date.now()}`,
- "merchant_name":"NewAge Retailer",
- "merchant_details":{
- "primary_contact_person":"John Test",
- "primary_email":"[email protected]",
- "primary_phone":"sunt laborum",
- "secondary_contact_person":"John Test2",
- "secondary_email":"[email protected]",
- "secondary_phone":"cillum do dolor id",
- "website":"www.example.com",
- "about_business":"Online Retail with a wide selection of organic products for North America",
- "address":{
- "line1":"Vivamus vitae",
- "line2":"Libero eget",
- "line3":"Cras ultrices",
- "city":"Nascetur",
- "state":"Purus",
- "zip":"010101",
- "country":"ZX"
- }
- },
- "return_url":"www.example.com/success",
- "webhook_details":{
- "webhook_version":"1.0.1",
- "webhook_username":"wh_store",
- "webhook_password":"pwd_wh@101"
- },
- "routing_algorithm": {
- "type": "single",
- "data": "checkout"
- },
- "sub_merchants_enabled":false,
- "metadata":{
- "city":"NY",
- "unit":"245"
- }
- }
- let ma_res = http.post("http://router-server:8080/accounts", JSON.stringify(merchant_account_payload), params);
-
- let json = ma_res.json();
- let merchant_id = json.merchant_id;
- let api_key = json.api_key;
-
- let connector_account_payload = {
- "connector_type":"fiz_operations",
- "connector_name":"stripe",
- "connector_account_details":{
- "auth_type":"HeaderKey",
- "api_key":"Bearer sk_test_123"
- },
- "test_mode":false,
- "disabled":false,
- "payment_methods_enabled":[
- {
- "payment_method":"wallet",
- "payment_method_types":[
- "upi_collect",
- "upi_intent"
- ],
- "payment_method_issuers":[
- "labore magna ipsum",
- "aute"
- ],
- "payment_schemes":[
- "Discover",
- "Discover"
- ],
- "accepted_currencies":[
- "AED",
- "AED"
- ],
- "accepted_countries":[
- "in",
- "us"
- ],
- "minimum_amount":1,
- "maximum_amount":68607706,
- "recurring_enabled":true,
- "installment_payment_enabled":true
- }
- ],
- "metadata":{
- "city":"NY",
- "unit":"245"
- }
- }
- let ca_res = http.post(`http://router-server:8080/account/${merchant_id}/connectors`, JSON.stringify(connector_account_payload), params);
-
- let update_merchant_account_payload = {
- "merchant_id":merchant_id,
- "merchant_name":"NewAge Retailer",
- "merchant_details":{
- "primary_contact_person":"John Test",
- "primary_email":"[email protected]",
- "primary_phone":"veniam aute officia ullamco esse",
- "secondary_contact_person":"John Test2",
- "secondary_email":"[email protected]",
- "secondary_phone":"proident adipisicing officia nulla",
- "website":"www.example.com",
- "about_business":"Online Retail with a wide selection of organic products for North America",
- "address":{
- "line1":"Vivamus vitae",
- "line2":"Libero eget",
- "line3":"Cras ultrices",
- "city":"Nascetur",
- "state":"Purus",
- "zip":"010101",
- "country":"ZX"
- }
- },
- "return_url":"www.example.com/success",
- "webhook_details":{
- "webhook_version":"1.0.1",
- "webhook_username":"wh_store",
- "webhook_password":"pwd_wh@101"
- },
- "routing_algorithm": {
- "type": "single",
- "data": "stripe"
- },
- "metadata":{
- "city":"NY",
- "unit":"245"
- }
- }
- let uma_res = http.post(`http://router-server:8080/accounts/${merchant_id}`, JSON.stringify(update_merchant_account_payload), params);
-
- return { "api_key": api_key }
-}
diff --git a/loadtest/k6/payment-confirm.js b/loadtest/k6/payment-confirm.js
deleted file mode 100644
index 60f896faee..0000000000
--- a/loadtest/k6/payment-confirm.js
+++ /dev/null
@@ -1,75 +0,0 @@
-import http from "k6/http";
-import { sleep, check } from "k6";
-import { Counter } from "k6/metrics";
-import { setup_merchant_apikey } from "./helper/setup.js";
-import { random_string } from "./helper/misc.js";
-import { readBaseline, storeResult } from "./helper/compare-result.js";
-
-export const requests = new Counter("http_reqs");
-
-const baseline = readBaseline("payment-confirm");
-
-export const options = {
- stages: [
- { duration: "10s", target: 25 }, // ramp up users to 25 in 10 seconds
- { duration: "10s", target: 25 }, // maintain 25 users for 10 seconds
- { duration: "10s", target: 0 } // ramp down to 0 users in 10 seconds
- ],
- thresholds: {
- 'http_req_duration': ['p(90) < 500'], // 90% of requests must finish within 500ms.
- },
-};
-
-export function setup() {
- return setup_merchant_apikey();
-}
-
-export default function (data) {
- let payload = {
- "amount": 6540,
- "currency": "USD",
- "confirm": true,
- "capture_method": "automatic",
- "capture_on": "2022-09-10T10:11:12Z",
- "amount_to_capture": 6540,
- "customer_id": random_string(),
- "email": "[email protected]",
- "name": "John Doe",
- "phone": "999999999",
- "phone_country_code": "+65",
- "description": "Its my first payment request",
- "authentication_type": "no_three_ds",
- "return_url": "https://google.com",
- "payment_method": "card",
- "setup_future_usage": "on_session",
- "payment_method_data": {
- "card": {
- "card_number": "4242424242424242",
- "card_exp_month": "10",
- "card_exp_year": "35",
- "card_holder_name": "John Doe",
- "card_cvc": "123"
- }
- },
- "statement_descriptor_name": "Juspay",
- "statement_descriptor_suffix": "Router",
- "metadata": {
- "udf1": "value1",
- "new_customer": "true",
- "login_date": "2019-09-10T10:11:12Z"
- }
- };
- let res = http.post("http://router-server:8080/payments", JSON.stringify(payload), {
- "headers": {
- "Content-Type": "application/json",
- "api-key" : data.api_key
- },
- });
- check(res, {
- "confirm payment status 200": (r) => r.status === 200,
- });
-}
-
-export function handleSummary(data) {
- return storeResult("payment-confirm", baseline, data)
-}
diff --git a/loadtest/k6/payment-create-and-confirm.js b/loadtest/k6/payment-create-and-confirm.js
deleted file mode 100644
index aafa52052b..0000000000
--- a/loadtest/k6/payment-create-and-confirm.js
+++ /dev/null
@@ -1,81 +0,0 @@
-import http from "k6/http";
-import { sleep, check } from "k6";
-import { Counter } from "k6/metrics";
-import { setup_merchant_apikey } from "./helper/setup.js";
-import { random_string } from "./helper/misc.js";
-import { readBaseline, storeResult } from "./helper/compare-result.js";
-
-export const requests = new Counter("http_reqs");
-
-const baseline = readBaseline("payment-create-and-confirm");
-
-export const options = {
- stages: [
- { duration: "10s", target: 25 }, // ramp up users to 25 in 10 seconds
- { duration: "10s", target: 25 }, // maintain 25 users for 10 seconds
- { duration: "10s", target: 0 } // ramp down to 0 users in 10 seconds
- ],
- thresholds: {
- 'http_req_duration': ['p(90) < 500'], // 90% of requests must finish within 500ms.
- },
-};
-
-export function setup() {
- return setup_merchant_apikey();
-}
-
-export default function(data) {
- const create_payment_payload = {
- "amount": 6540,
- "currency": "USD",
- "confirm": false,
- "capture_method": "automatic",
- "capture_on": "2022-09-10T10:11:12Z",
- "amount_to_capture": 6540,
- "customer_id": random_string(),
- "description": "Its my first payment request",
- "return_url": "http://example.com/payments",
- "authentication_type": "three_ds",
- "payment_method": "card",
- "statement_descriptor_name": "Juspay",
- "statement_descriptor_suffix": "Router"
- };
- let create_payment_res = http.post("http://router-server:8080/payments", JSON.stringify(create_payment_payload), {
- "headers": {
- "Content-Type": "application/json",
- "api-key" : data.api_key
- },
- });
- check(create_payment_res, {
- "create payment status 200": (r) => r.status === 200,
- });
- const payment_id = create_payment_res.json().payment_id;
- const confirm_payment_payload = {
- "return_url": "http://example.com/payments",
- "setup_future_usage": "off_session",
- "authentication_type": "no_three_ds",
- "payment_method": "card",
- "payment_method_data": {
- "card": {
- "card_number": "4242424242424242",
- "card_exp_month": "10",
- "card_exp_year": "35",
- "card_holder_name": "John Doe",
- "card_cvc": "123"
- }
- }
- };
- let confirm_payment_res = http.post(`http://router-server:8080/payments/${payment_id}/confirm`, JSON.stringify(confirm_payment_payload), {
- "headers": {
- "Content-Type": "application/json",
- "api-key" : data.api_key
- },
- });
- check(confirm_payment_res, {
- "confirm payment status 200": (r) => r.status === 200,
- });
-};
-
-export function handleSummary(data) {
- return storeResult("payment-create-and-confirm", baseline, data)
-}
diff --git a/loadtest/k6/rps.js b/loadtest/k6/rps.js
deleted file mode 100644
index 7ac6c566fb..0000000000
--- a/loadtest/k6/rps.js
+++ /dev/null
@@ -1,34 +0,0 @@
-import { group } from 'k6';
-import { Counter } from "k6/metrics";
-import { readBaseline, storeResult } from "./helper/compare-result.js";
-import { setup_merchant_apikey } from "./helper/setup.js";
-import paymentCreateAndConfirmFunc from './payment-create-and-confirm.js';
-import paymentConfirmFunc from './payment-confirm.js';
-
-export const requests = new Counter("http_reqs");
-
-const baseline = readBaseline("rps");
-
-export const options = {
- scenarios: {
- contacts: {
- executor: 'per-vu-iterations',
- vus: 10,
- iterations: 100,
- maxDuration: '5m',
- },
- },
-};
-
-export function setup() {
- return setup_merchant_apikey()
-}
-
-export default function (data) {
- group("create payment and confirm", function() { paymentCreateAndConfirmFunc(data) });
- group("create confirmed payment", function() { paymentConfirmFunc(data) });
-}
-
-export function handleSummary(data) {
- return storeResult("rps", baseline, data)
-}
diff --git a/loadtest/k6/scenario-mix/.gitignore b/loadtest/k6/scenario-mix/.gitignore
new file mode 100644
index 0000000000..3b5cc1089b
--- /dev/null
+++ b/loadtest/k6/scenario-mix/.gitignore
@@ -0,0 +1,11 @@
+/bin/
+/fixtures/
+/runs/
+/config.json
+/provision-config.json
+merchants.json*
+provision-failures.json
+*.sqlite
+*.sqlite-wal
+*.sqlite-shm
+*.generated.js
diff --git a/loadtest/k6/scenario-mix/README.md b/loadtest/k6/scenario-mix/README.md
new file mode 100644
index 0000000000..4bc3546446
--- /dev/null
+++ b/loadtest/k6/scenario-mix/README.md
@@ -0,0 +1,26 @@
+# Console load engine
+
+This directory contains the k6 engine used by the [load-test console](../../console/README.md).
+The console owns configuration, fixture compatibility, scheduling, fault recovery,
+recording and reconciliation. No legacy runner or deployment scripts are required.
+
+Build the native recorder with Go 1.24.4 and a C compiler:
+
+```sh
+bash recorder/build.sh
+```
+
+The engine exports `fixtures` and `load` from `run.mjs`. It calls the configured
+Router and payment-method service directly, records responses through the native
+SQLite extension, and emits progress for the console and optional remote worker.
+`superposition.mjs` applies and verifies fixture defaults; `reconcile.mjs` supports
+CSV reconciliation, while the console compares against PostgreSQL directly.
+
+Run engine tests (from this directory):
+
+```sh
+K6_SQLITE_BINARY="$PWD/bin/k6-sqlite" node --test test/*.test.mjs
+```
+
+Keep generated binaries, merchant credentials, recordings and runtime configuration
+out of version control. See `.gitignore` and the console documentation.
diff --git a/loadtest/k6/scenario-mix/config.example.json b/loadtest/k6/scenario-mix/config.example.json
new file mode 100644
index 0000000000..75e869408b
--- /dev/null
+++ b/loadtest/k6/scenario-mix/config.example.json
@@ -0,0 +1,93 @@
+{
+ "services": {
+ "router": "http://127.0.0.1:8080",
+ "modular_pm": "http://127.0.0.1:8081/v2"
+ },
+ "target_headers": {
+ "router": {},
+ "modular_pm": {}
+ },
+ "merchant": {
+ "api_key": "merchant_api_key_here",
+ "publishable_key": "pk_test_here",
+ "profile_id": "pro_here"
+ },
+ "load": {
+ "total_rps": 10,
+ "duration_seconds": 60,
+ "request_timeout_ms": 40000,
+ "think_time_ms": 0,
+ "pre_allocated_vus_multiplier": 0.5,
+ "max_vus_multiplier": 2
+ },
+ "payment": {
+ "amount": 1000,
+ "currency": "USD",
+ "session_expiry": 900,
+ "card": {
+ "card_number": "4242424242424242",
+ "card_exp_month": "10",
+ "card_exp_year": "35",
+ "card_holder_name": "Load Test",
+ "card_cvc": "123"
+ },
+ "card_pool": [],
+ "metadata_update": {
+ "card_exp_month": "11",
+ "card_exp_year": "36",
+ "card_holder_name": "Updated Load Test"
+ }
+ },
+ "sdk": {
+ "wallets": []
+ },
+ "scenarios": [
+ {
+ "name": "guest",
+ "merchant_path": "modular",
+ "scenario": "guest",
+ "weight": 43
+ },
+ {
+ "name": "cit_off",
+ "merchant_path": "modular",
+ "scenario": "cit_off_session",
+ "weight": 43
+ },
+ {
+ "name": "meta_chg",
+ "merchant_path": "modular",
+ "scenario": "cit_metadata_changed",
+ "weight": 0
+ },
+ {
+ "name": "sdk",
+ "merchant_path": "modular",
+ "scenario": "sdk_checkout",
+ "weight": 14
+ },
+ {
+ "name": "mit",
+ "merchant_path": "modular",
+ "scenario": "mit",
+ "weight": 0
+ },
+ {
+ "name": "saved_card",
+ "merchant_path": "modular",
+ "scenario": "saved_card_checkout",
+ "weight": 0
+ }
+ ],
+ "thresholds": {
+ "payment_confirm_ms_nomod_guest": [
+ "p(90)<500"
+ ],
+ "payment_confirm_ms_mod_cit_off": [
+ "p(90)<800"
+ ],
+ "payment_confirm_ms_nomod_mit": [
+ "p(90)<800"
+ ]
+ }
+}
diff --git a/loadtest/k6/scenario-mix/connectors.mjs b/loadtest/k6/scenario-mix/connectors.mjs
new file mode 100644
index 0000000000..bc37e59871
--- /dev/null
+++ b/loadtest/k6/scenario-mix/connectors.mjs
@@ -0,0 +1,27 @@
+export function connectorSchedule(plan){
+ if(!plan)return null;
+ if(!Array.isArray(plan.mix)||!plan.mix.length)throw new Error('Connector mix is empty');
+ const rows=plan.mix;let total=0;const slots=[];
+ for(const row of rows){if(!Number.isInteger(row.weight)||row.weight<1||row.weight>100)throw new Error('Invalid connector weight');total+=row.weight;}
+ if(total!==100)throw new Error('Connector weights must total 100%');
+ const current=rows.map(()=>0);for(let i=0;i<100;i++){for(let j=0;j<rows.length;j++)current[j]+=rows[j].weight;let winner=0;for(let j=1;j<rows.length;j++)if(current[j]>current[winner])winner=j;slots.push(rows[winner].connector);current[winner]-=100;}return slots;
+}
+export function selectedConnector(slots,iteration,merchant){
+ if(!slots)return null;
+ const cycle=Math.floor(iteration/100),name=slots[(iteration+cycle)%100];
+ const account=merchant.connector_accounts?.[name]||(name==='stripe_test'&&slots.every(c=>c===name)?merchant.merchant_connector_id:null);
+ if(!account)throw new Error(`Fixture has no ${name} connector account`);
+ return {connector:name,merchant_connector_id:account};
+}
+export const connectorRouting=choice=>choice?{routing:{type:'single',data:choice}}:{};
+
+// Synthetic browser context for card sandbox authorizations (including non-3DS
+// connectors such as Adyen). Explicit payment configuration can override it.
+export const connectorBrowserInfo=(overrides={})=>({accept_header:'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',language:'en-US',screen_height:1080,screen_width:1920,color_depth:24,user_agent:'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 Chrome/131.0.0.0 Safari/537.36',time_zone:0,java_enabled:false,java_script_enabled:true,ip_address:'127.0.0.1',...overrides});
+
+// Provider sandbox cards are test fixtures, separate from connector identity
+// and credentials. Adyen's successful non-3DS card is also used by
+// cypress-tests/cypress/e2e/configs/Payment/Adyen.js; Stripe's 4242 card is
+// deliberately a refusal card there. Explicit overrides allow negative tests.
+const sandboxCards={adyen:{card_number:'4111111111111111',card_exp_month:'03',card_exp_year:'30',card_holder_name:'Load Test',card_cvc:'737'}};
+export const connectorTestCard=(connector,fallback,overrides={})=>overrides[connector]||sandboxCards[connector]||fallback;
diff --git a/loadtest/k6/scenario-mix/diagnostics.mjs b/loadtest/k6/scenario-mix/diagnostics.mjs
new file mode 100644
index 0000000000..23a726cf74
--- /dev/null
+++ b/loadtest/k6/scenario-mix/diagnostics.mjs
@@ -0,0 +1,18 @@
+const sensitive=/(api[_ -]?key|client[_ -]?secret|authorization|password|access[_ -]?token|card[_ -]?(?:number|cvc)|cvc|cvv)(["']?\s*[=:]\s*)("[^"]*"|'[^']*'|[^\s;,]+)/gi;
+export function diagnosticText(value){
+ return String(value).replace(/\bBearer\s+[A-Za-z0-9._~+/=-]+/gi,'Bearer [redacted]')
+ .replace(sensitive,'$1$2[redacted]').replace(/\b(?:\d[ -]?){13,19}\b/g,'[redacted]').slice(0,512);
+}
+export function diagnosticBody(text){
+ if(text.length>65536)return '[oversized error response omitted]';
+ let value;try{value=JSON.parse(text);}catch{return '[non-JSON error response omitted]';}
+ const project=(value,depth=0)=>{
+ if(typeof value==='string')return diagnosticText(value);
+ if(!value||typeof value!=='object'||Array.isArray(value)||depth>3)return null;
+ return Object.fromEntries(['error','code','type','message'].filter(key=>Object.hasOwn(value,key)).map(key=>[key,project(value[key],depth+1)]));
+ };
+ const result=JSON.stringify(project(value));return result.length<=4096?result:'{"message":"Error diagnostic exceeded limit"}';
+}
+export function diagnosticUrl(value){
+ try{const url=new URL(value);url.username='';url.password='';for(const key of [...url.searchParams.keys()])if(/key|secret|token|password|cvc|cvv|card/i.test(key))url.searchParams.set(key,'[redacted]');return url.href;}catch{return diagnosticText(value);}
+}
diff --git a/loadtest/k6/scenario-mix/progress.mjs b/loadtest/k6/scenario-mix/progress.mjs
new file mode 100644
index 0000000000..c3087e0c36
--- /dev/null
+++ b/loadtest/k6/scenario-mix/progress.mjs
@@ -0,0 +1,20 @@
+import { clearLine, cursorTo } from 'node:readline';
+
+// Redraw one terminal line; keep redirected output readable and bounded.
+export function progress(label, total) {
+ let lastTime = 0, lastBucket = -1;
+ const terminal = Boolean(process.stdout.isTTY);
+ function update(done, detail = '') {
+ const fraction = total > 0 ? Math.min(1, done / total) : 1;
+ const bucket = Math.floor(fraction * 10);
+ const now = Date.now();
+ if (done !== total && (terminal ? now - lastTime < 200 : bucket === lastBucket)) return;
+ lastTime = now; lastBucket = bucket;
+ const filled = Math.floor(fraction * 20);
+ const line = `${label} [${'='.repeat(filled)}${'-'.repeat(20 - filled)}] ${Math.floor(fraction * 100)}% ${done}/${total}${detail ? ` | ${detail}` : ''}`;
+ if (terminal) { clearLine(process.stdout, 0); cursorTo(process.stdout, 0); process.stdout.write(line); }
+ else console.log(line);
+ }
+ update(0);
+ return { update, finish() { if (terminal) process.stdout.write('\n'); } };
+}
diff --git a/loadtest/k6/scenario-mix/provision-config.example.json b/loadtest/k6/scenario-mix/provision-config.example.json
new file mode 100644
index 0000000000..e30a2358b9
--- /dev/null
+++ b/loadtest/k6/scenario-mix/provision-config.example.json
@@ -0,0 +1,32 @@
+{
+ "router": "http://127.0.0.1:8080",
+ "admin_api_key": "${ROUTER_ADMIN_API_KEY}",
+ "merchant_count": 1500,
+ "merchant_id_prefix": "loadtest_mix",
+ "concurrency": 20,
+ "output": "merchants.json",
+ "connector": {
+ "connector_name": "stripe",
+ "connector_account_details": {
+ "auth_type": "HeaderKey",
+ "api_key": "${STRIPE_TEST_API_KEY}"
+ },
+ "test_mode": true,
+ "business_country": "US",
+ "business_label": "default"
+ },
+ "superposition": {
+ "endpoint": "http://127.0.0.1:8082",
+ "token": "${SUPERPOSITION_TOKEN}",
+ "organization_id": "localorg",
+ "workspace_id": "dev",
+ "refresh_interval_seconds": 300,
+ "defaults": {
+ "system.should_trigger_backwards_compatibility_inline": true
+ }
+ },
+ "retry": {
+ "attempts": 3,
+ "backoff_ms": 500
+ }
+}
diff --git a/loadtest/k6/scenario-mix/provision-merchants.mjs b/loadtest/k6/scenario-mix/provision-merchants.mjs
new file mode 100644
index 0000000000..eceeb7fb10
--- /dev/null
+++ b/loadtest/k6/scenario-mix/provision-merchants.mjs
@@ -0,0 +1,582 @@
+#!/usr/bin/env node
+/**
+ * provision-merchants.mjs — one-time/occasional admin job that creates N
+ * merchants (account + API key + Stripe connector) via the Hyperswitch admin
+ * API and writes their credentials to a manifest (merchants.json) that
+ * scenario-mix.js's `merchant_pool` config consumes.
+ *
+ * This is orchestration/setup work, not traffic — it is deliberately a
+ * separate, plain Node.js script rather than a k6 script, so merchant
+ * creation is never part of the measured load, and so progress can be
+ * persisted to disk incrementally (crash-safe, resumable) instead of only at
+ * the very end the way k6's handleSummary would force.
+ *
+ * Usage:
+ * cp provision-config.example.json provision-config.json # fill in admin_api_key
+ * node provision-merchants.mjs # create/top-up up to merchant_count
+ * node provision-merchants.mjs --mode=cleanup # delete every merchant in the manifest
+ * or:
+ * PROVISION_CONFIG=/path/to/provision-config.json node provision-merchants.mjs
+ *
+ * Rerunning in provision mode is safe: merchant IDs are deterministic
+ * (`${prefix}_0001` ...), entries already present in the manifest are
+ * skipped, and a merchant_id that already exists on the server (partial
+ * prior run) is recovered via GET instead of failing.
+ */
+import { existsSync, readFileSync } from "node:fs";
+import { writeFile, rename } from "node:fs/promises";
+import path from "node:path";
+import { pathToFileURL } from "node:url";
+import { FixtureRecorder, recordedFetch } from "./sqlite.mjs";
+import { progress } from "./progress.mjs";
+
+// Defaults for connector shape; authentication must come from configuration.
+const DEFAULT_CONNECTOR = {
+ connector_type: "payment_processor",
+ connector_name: "stripe",
+ connector_account_details: {
+ auth_type: "HeaderKey",
+ api_key: "",
+ },
+ test_mode: false,
+ disabled: false,
+ payment_methods_enabled: [
+ {
+ payment_method: "card",
+ payment_method_types: [
+ {
+ payment_method_type: "credit",
+ card_networks: ["Visa", "Mastercard"],
+ minimum_amount: 1,
+ maximum_amount: 68607706,
+ recurring_enabled: true,
+ installment_payment_enabled: true,
+ },
+ {
+ payment_method_type: "debit",
+ card_networks: ["Visa", "Mastercard"],
+ minimum_amount: 1,
+ maximum_amount: 68607706,
+ recurring_enabled: true,
+ installment_payment_enabled: true,
+ },
+ ],
+ },
+ {
+ payment_method: "pay_later",
+ payment_method_types: [
+ {
+ payment_method_type: "klarna",
+ payment_experience: "redirect_to_url",
+ minimum_amount: 1,
+ maximum_amount: 68607706,
+ recurring_enabled: true,
+ installment_payment_enabled: true,
+ },
+ {
+ payment_method_type: "affirm",
+ payment_experience: "redirect_to_url",
+ minimum_amount: 1,
+ maximum_amount: 68607706,
+ recurring_enabled: true,
+ installment_payment_enabled: true,
+ },
+ {
+ payment_method_type: "afterpay_clearpay",
+ payment_experience: "redirect_to_url",
+ minimum_amount: 1,
+ maximum_amount: 68607706,
+ recurring_enabled: true,
+ installment_payment_enabled: true,
+ },
+ ],
+ },
+ ],
+ metadata: {
+ city: "NY",
+ unit: "245",
+ },
+ business_country: "US",
+ business_label: "default",
+};
+
+let activeRecorder = null;
+export function setFixtureRecorder(recorder) { activeRecorder = recorder; }
+async function fixtureFetch(url, options = {}) {
+ const match = /\/(?:accounts|account|api_keys)\/([^/?]+)/.exec(url);
+ let body = {};
+ try { body = JSON.parse(options.body || "{}"); } catch (_) { /* optional body */ }
+ const merchantId = match?.[1] || body.merchant_id || null;
+ const operation = `${options.method || "GET"}_${new URL(url).pathname.replaceAll("/", "_")}`;
+ return recordedFetch(activeRecorder,url,options,{ flow_id: `${activeRecorder?.runId || "fixture"}:${merchantId || new URL(url).pathname}`, merchant_id: merchantId, operation, role: "fixture" });
+}
+function fail(message) { throw new Error(`provision-merchants: ${message}`); }
+
+function resolvePath(p) {
+ return path.resolve(process.cwd(), p);
+}
+
+function sleep(ms) {
+ return new Promise((resolve) => setTimeout(resolve, ms));
+}
+
+// ---------------------------------------------------------------------------
+// Config
+// ---------------------------------------------------------------------------
+
+export function loadConfig(configPath = process.env.PROVISION_CONFIG || "./provision-config.json") {
+ let raw;
+ try {
+ raw = readFileSync(resolvePath(configPath), "utf8");
+ } catch (error) {
+ fail(`cannot read config at "${configPath}" (set PROVISION_CONFIG): ${error.message}`);
+ }
+ let cfg;
+ try {
+ cfg = JSON.parse(raw,(_key,value) => {
+ if (typeof value !== "string") return value;
+ const reference = /^\$\{([A-Za-z_][A-Za-z0-9_]*)\}$/.exec(value);
+ if (!reference) return value;
+ if (!process.env[reference[1]]) throw new Error(`Environment variable ${reference[1]} is required`);
+ return process.env[reference[1]];
+ });
+ } catch (error) {
+ fail(`config at "${configPath}" is not valid JSON: ${error.message}`);
+ }
+ if (!cfg.router) fail("router is required");
+ if (!cfg.admin_api_key) fail("admin_api_key is required");
+ const merchantCount = Number(cfg.merchant_count);
+ if (!Number.isSafeInteger(merchantCount) || merchantCount <= 0) fail("merchant_count must be a number > 0");
+ const prefix = cfg.merchant_id_prefix || "loadtest_mix";
+ if (!/^[A-Za-z0-9_]+$/.test(prefix)) fail("merchant_id_prefix must use only letters, digits and underscores");
+ const concurrency = cfg.concurrency === undefined ? 20 : Number(cfg.concurrency);
+ if (!Number.isSafeInteger(concurrency) || concurrency < 1) fail("concurrency must be a positive integer");
+ if (!cfg.connector?.connector_account_details) fail("connector.connector_account_details is required");
+ const attempts = cfg.retry?.attempts ?? 3;
+ const backoff = cfg.retry?.backoff_ms ?? 500;
+ if (!Number.isSafeInteger(attempts) || attempts < 1 || !Number.isFinite(backoff) || backoff < 0) fail("retry attempts/backoff_ms are invalid");
+ const output = cfg.output || "merchants.json";
+ if (cfg.organization_id !== undefined && typeof cfg.organization_id !== "string") {
+ fail("organization_id must be a string when set");
+ }
+ return {
+ router: cfg.router.replace(/\/$/, ""),
+ admin_api_key: cfg.admin_api_key,
+ merchant_count: merchantCount,
+ merchant_id_prefix: prefix,
+ concurrency,
+ output,
+ // Every merchant this script creates is placed under one organization
+ // (accountBody's organization_id) so the pool reads as a single tenant
+ // rather than 1500 stray orgs. Leave unset to have the script create one
+ // organization on first run and cache its id next to the manifest (see
+ // resolveOrganizationId) — set it explicitly to reuse an org you already
+ // have, or to pin the same org across manifest files/output paths.
+ organization_id: cfg.organization_id || null,
+ organization_name: cfg.organization_name || `${prefix} loadtest org`,
+ connector: { ...DEFAULT_CONNECTOR, ...cfg.connector },
+ connectors:cfg.connectors,connectorAccounts:cfg.connectorAccounts,
+ superposition: cfg.superposition || null,
+ retry: {
+ attempts,
+ backoff_ms: backoff,
+ },
+ };
+}
+
+function merchantIdFor(cfg, index) {
+ const width = Math.max(4, String(cfg.merchant_count).length);
+ return `${cfg.merchant_id_prefix}_${String(index + 1).padStart(width, "0")}`;
+}
+
+// ---------------------------------------------------------------------------
+// Manifest (merchants.json): loaded once, rewritten atomically after every
+// successful merchant so a crash never loses more than the merchant in
+// flight. Writes are serialized through a promise chain — concurrent
+// provisioning workers all schedule onto the same chain rather than racing
+// to write the file at once.
+// ---------------------------------------------------------------------------
+
+function loadManifest(manifestPath) {
+ if (!existsSync(manifestPath)) return [];
+ let parsed;
+ try {
+ parsed = JSON.parse(readFileSync(manifestPath, "utf8"));
+ } catch (error) {
+ fail(`cannot read existing manifest at "${manifestPath}": ${error.message}`);
+ }
+ if (!Array.isArray(parsed)) fail(`existing manifest at "${manifestPath}" must be a JSON array`);
+ return parsed;
+}
+
+let writeChain = Promise.resolve();
+function scheduleWrite(manifestPath, manifest) {
+ const snapshot = structuredClone(manifest);
+ writeChain = writeChain
+ .then(() => writeManifestAtomic(manifestPath, snapshot));
+ return writeChain;
+}
+async function writeManifestAtomic(manifestPath, manifest) {
+ const tmpPath = `${manifestPath}.tmp`;
+ await writeFile(tmpPath, JSON.stringify(manifest, null, 2), { mode: 0o600 });
+ await rename(tmpPath, manifestPath);
+}
+
+// ---------------------------------------------------------------------------
+// HTTP helpers
+// ---------------------------------------------------------------------------
+
+function adminHeaders(cfg) {
+ return { Authorization: `admin-api-key=${cfg.admin_api_key}`, "api-key": cfg.admin_api_key, "content-type": "application/json" };
+}
+
+function merchantHeaders(apiKey) {
+ return { "api-key": apiKey, "content-type": "application/json" };
+}
+
+async function safeText(res) {
+ try {
+ return await res.text();
+ } catch (_) {
+ return "";
+ }
+}
+
+async function withRetry(fn, retry, label) {
+ let lastError;
+ for (let attempt = 1; attempt <= retry.attempts; attempt += 1) {
+ try {
+ return await fn();
+ } catch (error) {
+ if (error.recordingFatal) throw error;
+ lastError = error;
+ if (attempt < retry.attempts) await sleep(retry.backoff_ms * attempt);
+ }
+ }
+ throw new Error(`${label}: ${lastError.message}`);
+}
+
+function accountBody(merchantId, orgId) {
+ return {
+ merchant_id: merchantId,
+ locker_id: "m0010",
+ merchant_name: `Loadtest Merchant ${merchantId}`,
+ merchant_details: {
+ primary_contact_person: "John Test",
+ primary_email: "[email protected]",
+ primary_phone: "sunt laborum",
+ secondary_contact_person: "John Test2",
+ secondary_email: "[email protected]",
+ secondary_phone: "cillum do dolor id",
+ website: "www.example.com",
+ about_business: "Online Retail with a wide selection of organic products for North America",
+ address: {
+ line1: "1467",
+ line2: "Harrison Street",
+ line3: "Harrison Street",
+ city: "San Fransico",
+ state: "California",
+ zip: "94122",
+ country: "US",
+ },
+ },
+ return_url: "https://google.com/success",
+ webhook_details: {
+ webhook_version: "1.0.1",
+ webhook_username: "ekart_retail",
+ webhook_password: "password_ekart@123",
+ payment_created_enabled: true,
+ payment_succeeded_enabled: true,
+ payment_failed_enabled: true,
+ },
+ sub_merchants_enabled: false,
+ metadata: {
+ city: "NY",
+ unit: "245",
+ },
+ primary_business_details: [{ country: "US", business: "default" }],
+ // Omitting this makes Router create a brand-new organization per
+ // merchant (MerchantAccountCreate.organization_id doc comment,
+ // crates/api_models/src/admin.rs) — passing the same orgId for every
+ // merchant in the batch is what keeps the whole pool under one org.
+ organization_id: orgId,
+ };
+}
+
+async function createOrganization(cfg) {
+ const res = await fixtureFetch(`${cfg.router}/organization`, {
+ method: "POST",
+ headers: adminHeaders(cfg),
+ body: JSON.stringify({ organization_name: cfg.organization_name }),
+ });
+ if (!res.ok) throw new Error(`organization create failed (${res.status}): ${await safeText(res)}`);
+ return res.json();
+}
+
+// The org id must stay identical across reruns of this script (a rerun
+// that minted a second org would split the pool across two orgs instead of
+// growing one), so an auto-created org is cached in a sidecar file next to
+// the manifest rather than only printed for the user to copy by hand.
+function orgCachePath(manifestPath) {
+ return `${manifestPath}.org`;
+}
+
+async function resolveOrganizationId(cfg, manifestPath) {
+ if (cfg.organization_id) return cfg.organization_id;
+ const cachePath = orgCachePath(manifestPath);
+ if (existsSync(cachePath)) {
+ const cached = JSON.parse(readFileSync(cachePath, "utf8"));
+ if (cached.organization_id) return cached.organization_id;
+ }
+ console.log(`no organization_id configured — creating one organization ("${cfg.organization_name}") for this batch...`);
+ const org = await createOrganization(cfg);
+ if (typeof org.organization_id !== "string" || !org.organization_id) throw new Error("organization response missing organization_id");
+ await writeFile(cachePath, JSON.stringify({ organization_id: org.organization_id }, null, 2),{ mode: 0o600 });
+ console.log(`created organization ${org.organization_id} (cached at ${cachePath}) — every merchant will be created under it. Set "organization_id" in provision-config.json to pin or reuse this value explicitly.`);
+ return org.organization_id;
+}
+
+// A merchant_id that already exists on the server (left over from a prior
+// run that crashed between account creation and the manifest write) is
+// recovered via GET rather than treated as a failure, so reruns stay safe.
+async function createOrRecoverAccount(merchantId, orgId, cfg) {
+ const createRes = await fixtureFetch(`${cfg.router}/accounts`, {
+ method: "POST",
+ headers: adminHeaders(cfg),
+ body: JSON.stringify(accountBody(merchantId, orgId)),
+ });
+ if (createRes.ok) return createRes.json();
+ const recoverRes = await fixtureFetch(`${cfg.router}/accounts/${merchantId}`, { headers: adminHeaders(cfg) });
+ if (recoverRes.ok) {
+ const account = await recoverRes.json();
+ if (account.organization_id !== orgId) throw new Error(`recovered ${merchantId} belongs to another organization`);
+ return account;
+ }
+ throw new Error(`account create failed (${createRes.status}) and recovery GET also failed (${recoverRes.status}): ${await safeText(createRes)}`);
+}
+
+async function createApiKey(merchantId, cfg) {
+ const res = await fixtureFetch(`${cfg.router}/api_keys/${merchantId}`, {
+ method: "POST",
+ headers: adminHeaders(cfg),
+ body: JSON.stringify({ name: "scenario-mix loadtest", expiration: "2069-09-23T01:02:03.000Z" }),
+ });
+ if (!res.ok) throw new Error(`api_key create failed (${res.status}): ${await safeText(res)}`);
+ return res.json();
+}
+
+// Unlike account create/delete (admin auth), connector create AND list are
+// merchant-scoped auth (ApiKeyAuthWithMerchantIdFromRouteAllowPlatform —
+// crates/router/src/routes/admin.rs, connector_create/connector_list) and
+// check the api-key header against that merchant's own api_keys table
+// entry, not the admin key. Must use the key this merchant's createApiKey()
+// just minted.
+async function findExistingConnector(merchantId, apiKey, cfg) {
+ const label = `${cfg.connector.connector_name}_${cfg.connector.business_country}_${cfg.connector.business_label}`;
+ const res = await fixtureFetch(`${cfg.router}/account/${merchantId}/connectors`, { headers: merchantHeaders(apiKey) });
+ if (!res.ok) throw new Error(`connector list failed (${res.status}): ${await safeText(res)}`);
+ const list = await res.json();
+ const match = Array.isArray(list) ? list.find((c) => c.connector_label === label) : null;
+ if (!match) throw new Error(`connector list has no "${label}" entry to recover`);
+ return match;
+}
+
+// A merchant recovered via GET in createOrRecoverAccount (left over from an
+// earlier partial run) may already have this connector attached — Router
+// rejects a second create for the same (profile_id, connector_label) with a
+// 400 rather than upserting. Recover the existing merchant_connector_id
+// instead of failing, same spirit as createOrRecoverAccount above.
+async function createConnector(merchantId, apiKey, cfg) {
+ const res = await fixtureFetch(`${cfg.router}/account/${merchantId}/connectors`, {
+ method: "POST",
+ headers: merchantHeaders(apiKey),
+ body: JSON.stringify({ ...cfg.connector, profile_id: cfg.checkpoints[merchantId].profile_id }),
+ });
+ if (res.ok) return res.json();
+ const body = await safeText(res);
+ if (res.status === 400 && body.includes("already exists")) {
+ return findExistingConnector(merchantId, apiKey, cfg);
+ }
+ throw new Error(`connector create failed (${res.status}) for ${cfg.connector.connector_name}; check sandbox credentials and metadata`);
+}
+
+async function deleteAccount(merchantId, cfg) {
+ const res = await fixtureFetch(`${cfg.router}/accounts/${merchantId}`, { method: "DELETE", headers: adminHeaders(cfg) });
+ if (!res.ok) throw new Error(`delete failed (${res.status}): ${await safeText(res)}`);
+}
+
+// ---------------------------------------------------------------------------
+// Concurrency: a fixed-size worker pool pulling from a shared cursor. Each
+// merchant's own 3 calls (account -> api_key -> connector) stay sequential
+// since each depends on the last; merchants themselves run in parallel.
+// ---------------------------------------------------------------------------
+
+async function mapLimit(items, limit, worker) {
+ let cursor = 0;
+ async function run() {
+ while (cursor < items.length) {
+ const index = cursor;
+ cursor += 1;
+ await worker(items[index], index);
+ }
+ }
+ const results = await Promise.allSettled(Array.from({ length: Math.min(limit, items.length) }, run));
+ const failure = results.find((result) => result.status === "rejected");
+ if (failure) throw failure.reason;
+}
+
+// ---------------------------------------------------------------------------
+// Provision mode
+// ---------------------------------------------------------------------------
+
+async function provisionOne(index, cfg, existing, orgId) {
+ const merchantId = merchantIdFor(cfg, index);
+ if (existing.has(merchantId)) return { status: "skipped", merchantId };
+ try {
+ const account = await withRetry(() => createOrRecoverAccount(merchantId, orgId, cfg), cfg.retry, `account ${merchantId}`);
+ const profileId = account.default_profile;
+ const publishableKey = account.publishable_key;
+ if (!profileId || !publishableKey) {
+ throw new Error(`account response missing default_profile/publishable_key: ${JSON.stringify(account)}`);
+ }
+
+ const cached = cfg.checkpoints[merchantId];
+ const apiKeyResp = cached?.api_key ? cached : await withRetry(() => createApiKey(merchantId, cfg), cfg.retry, `api_key ${merchantId}`);
+ if (!apiKeyResp.api_key) throw new Error(`api_key response missing api_key: ${JSON.stringify(apiKeyResp)}`);
+
+ cfg.checkpoints[merchantId] = { api_key: apiKeyResp.api_key, profile_id: profileId, publishable_key: publishableKey };
+ await scheduleWrite(cfg.checkpointPath, cfg.checkpoints);
+ const accounts={};
+ for(const connector of cfg.connectors||[cfg.connector]){
+ const result=await withRetry(()=>createConnector(merchantId,apiKeyResp.api_key,{...cfg,connector}),cfg.retry,`connector ${connector.connector_name}`);
+ if(!result.merchant_connector_id)throw new Error('Connector response missing account ID');
+ accounts[connector.connector_name]=result.merchant_connector_id;
+ }
+ const connectorResp={merchant_connector_id:Object.values(accounts)[0]};
+ if (!connectorResp.merchant_connector_id) {
+ throw new Error(`connector response missing merchant_connector_id: ${JSON.stringify(connectorResp)}`);
+ }
+
+ return {
+ status: "created",
+ merchantId,
+ entry: {
+ merchant_id: merchantId,
+ api_key: apiKeyResp.api_key,
+ publishable_key: publishableKey,
+ profile_id: profileId,
+ merchant_connector_id: connectorResp.merchant_connector_id,
+ connector_accounts:accounts,
+ },
+ };
+ } catch (error) {
+ if (error.recordingFatal) throw error;
+ return { status: "failed", merchantId, error: error.message };
+ }
+}
+
+export async function provision(cfg) {
+ cfg.checkpointPath = `${resolvePath(cfg.output)}.checkpoints`;
+ cfg.checkpoints = existsSync(cfg.checkpointPath) ? JSON.parse(readFileSync(cfg.checkpointPath,"utf8")) : {};
+ const manifestPath = resolvePath(cfg.output);
+ const manifest = loadManifest(manifestPath);
+ const existing = new Map(manifest.map((entry) => [entry.merchant_id, entry]));
+ const expectedIds = new Set(Array.from({ length: cfg.merchant_count },(_,index) => merchantIdFor(cfg,index)));
+ if (existing.size !== manifest.length || manifest.some((entry) => !expectedIds.has(entry.merchant_id) || !entry.api_key || !entry.profile_id || !entry.publishable_key || !entry.merchant_connector_id)) {
+ throw new Error("Existing fixture manifest has invalid, duplicate, or unexpected merchants; use a new output directory");
+ }
+ const failures = [];
+ let createdCount = 0;
+ let skippedCount = 0;
+
+ const orgId = await resolveOrganizationId(cfg, manifestPath);
+ console.log(`provisioning up to ${cfg.merchant_count} merchants under organization ${orgId} (${existing.size} already in manifest) at concurrency ${cfg.concurrency}...`);
+
+ const indices = Array.from({ length: cfg.merchant_count }, (_, i) => i);
+ const bar = progress("Merchants", cfg.merchant_count);
+ let completed = 0;
+ try {
+ await mapLimit(indices, cfg.concurrency, async (index) => {
+ try {
+ const result = await provisionOne(index, cfg, existing, orgId);
+ if (result.status === "skipped") {
+ skippedCount += 1;
+ return;
+ }
+ if (result.status === "created") {
+ manifest.push(result.entry);
+ existing.set(result.merchantId, result.entry);
+ createdCount += 1;
+ await scheduleWrite(manifestPath, manifest);
+ return;
+ }
+ failures.push({ merchant_id: result.merchantId, error: result.error });
+ console.error(`FAILED ${result.merchantId}: ${result.error}`);
+ } finally {
+ bar.update(++completed, `created=${createdCount} reused=${skippedCount} failed=${failures.length}`);
+ }
+ });
+ } finally { bar.finish(); }
+
+ await writeChain;
+ if (failures.length) {
+ await writeFile(path.join(path.dirname(manifestPath), "provision-failures.json"), JSON.stringify(failures, null, 2));
+ }
+
+ console.log(`\ndone: created=${createdCount} skipped=${skippedCount} failed=${failures.length} total_in_manifest=${manifest.length}`);
+ if (failures.length) {
+ throw new Error(`${failures.length} fixtures failed; rerun to resume`);
+ }
+ return { merchants: manifest, organization_id: orgId };
+}
+
+// ---------------------------------------------------------------------------
+// Cleanup mode
+// ---------------------------------------------------------------------------
+
+async function cleanup(cfg) {
+ const manifestPath = resolvePath(cfg.output);
+ let manifest = loadManifest(manifestPath);
+ if (!manifest.length) {
+ console.log("nothing to clean up — manifest is empty or missing");
+ return;
+ }
+ console.log(`deleting ${manifest.length} merchants at concurrency ${cfg.concurrency}...`);
+ const failures = [];
+ let deletedCount = 0;
+
+ await mapLimit(manifest.slice(), cfg.concurrency, async (entry) => {
+ try {
+ await withRetry(() => deleteAccount(entry.merchant_id, cfg), cfg.retry, `delete ${entry.merchant_id}`);
+ deletedCount += 1;
+ manifest = manifest.filter((m) => m.merchant_id !== entry.merchant_id);
+ await scheduleWrite(manifestPath, manifest);
+ if (deletedCount % 50 === 0) console.log(`deleted ${deletedCount}...`);
+ } catch (error) {
+ failures.push({ merchant_id: entry.merchant_id, error: error.message });
+ console.error(`FAILED to delete ${entry.merchant_id}: ${error.message}`);
+ }
+ });
+
+ await writeChain;
+ console.log(`\ndone: deleted=${deletedCount} failed=${failures.length} remaining_in_manifest=${manifest.length}`);
+}
+
+// ---------------------------------------------------------------------------
+
+async function main() {
+ const cfg = loadConfig();
+ const mode = process.argv.includes("--mode=cleanup") ? "cleanup" : "provision";
+ const recorder = new FixtureRecorder(path.join(path.dirname(resolvePath(cfg.output)),"fixtures.sqlite"),{ kind: mode });
+ setFixtureRecorder(recorder);
+ try {
+ if (mode === "cleanup") await cleanup(cfg);
+ else await provision(cfg);
+ recorder.close();
+ } catch (error) { recorder.close(error); throw error; }
+ finally { setFixtureRecorder(null); }
+}
+
+if (process.argv[1] && import.meta.url === pathToFileURL(path.resolve(process.argv[1])).href) {
+ main().catch((error) => { console.error(error.stack || error.message); process.exitCode = 1; });
+}
diff --git a/loadtest/k6/scenario-mix/reconcile.mjs b/loadtest/k6/scenario-mix/reconcile.mjs
new file mode 100644
index 0000000000..05fb6dbe62
--- /dev/null
+++ b/loadtest/k6/scenario-mix/reconcile.mjs
@@ -0,0 +1,85 @@
+import { DatabaseSync } from "node:sqlite";
+import { createReadStream, createWriteStream } from "node:fs";
+import { once } from "node:events";
+import path from "node:path";
+
+// Streaming RFC4180 parser: quoted commas/newlines and escaped quotes survive chunk boundaries.
+export async function* csvRows(file) {
+ let field = "", row = [], quoted = false, closedQuote = false, first = true, skipLF = false;
+ for await (const chunk of createReadStream(file,{ encoding: "utf8" })) {
+ for (const character of chunk) {
+ if (first) { first = false; if (character === "\uFEFF") continue; }
+ if (skipLF) { skipLF = false; if (character === "\n") continue; }
+ if (quoted) {
+ if (character === '"') { quoted = false; closedQuote = true; } else field += character;
+ } else if (closedQuote && character === '"') {
+ quoted = true; closedQuote = false; field += '"';
+ } else if (character === ",") {
+ row.push(field); field = ""; closedQuote = false;
+ } else if (character === "\n" || character === "\r") {
+ row.push(field); yield row; row = []; field = ""; closedQuote = false; skipLF = character === "\r";
+ } else if (character === '"' && !field && !closedQuote) {
+ quoted = true;
+ } else {
+ if (closedQuote || character === '"') throw new Error("Invalid CSV quoting");
+ field += character;
+ }
+ if (field.length > 1024 * 1024) throw new Error("CSV field exceeds 1 MiB");
+ }
+ }
+ if (quoted) throw new Error("Unterminated CSV quote");
+ if (field || row.length || closedQuote) { row.push(field); yield row; }
+}
+const escaped = (value) => `"${String(value ?? "").replaceAll('"','""')}"`;
+
+export async function reconcile({ db: file, csv, output, allowIncomplete = false, runId = null }) {
+ if (path.resolve(csv) === path.resolve(output) || path.resolve(file) === path.resolve(output)) throw new Error("Reconciliation output must differ from its inputs");
+ const db = new DatabaseSync(file,{ readOnly: true });
+ let out;
+ try {
+ const runs = db.prepare("SELECT * FROM runs").all();
+ const run = runId ? runs.find((r) => r.run_id === runId) : runs.length === 1 ? runs[0] : null;
+ if (!run) throw new Error("Specify --run-id when the database contains multiple runs, or check the supplied run ID");
+ if (!allowIncomplete && (run.recording_state !== "complete" || run.enqueued !== run.persisted)) throw new Error("Recording is incomplete; use --allow-incomplete to inspect partial data");
+ db.exec("PRAGMA temp_store=FILE; CREATE TEMP TABLE csv_rows(row_number INTEGER PRIMARY KEY,payment_id TEXT NOT NULL,status TEXT NOT NULL)");
+ const insert = db.prepare("INSERT INTO csv_rows VALUES(?,?,?)");
+ let header = false, number = 0, count = 0;
+ db.exec("BEGIN");
+ for await (const row of csvRows(csv)) {
+ number++;
+ if (row.length === 1 && row[0] === "") continue;
+ if (!header) {
+ if (row.length !== 2 || row[0] !== "payment_id" || row[1] !== "status") throw new Error("CSV header must be payment_id,status");
+ header = true; continue;
+ }
+ if (row.length !== 2 || !row[0] || !row[1]) throw new Error(`Invalid CSV row ${number}: payment_id and status are required`);
+ insert.run(number,row[0],row[1]); count++;
+ if (count % 10000 === 0) { db.exec("COMMIT; BEGIN"); }
+ }
+ db.exec("COMMIT");
+ if (!header || !count) throw new Error("CSV must contain a header and at least one payment");
+ db.exec("CREATE INDEX temp.csv_payment_id ON csv_rows(payment_id); CREATE TEMP TABLE csv_groups AS SELECT payment_id,COUNT(*) AS n,COUNT(DISTINCT status) AS statuses FROM csv_rows GROUP BY payment_id; CREATE UNIQUE INDEX temp.csv_group_id ON csv_groups(payment_id)");
+ const query = db.prepare(`SELECT c.row_number,c.payment_id,c.status AS csv_status,p.status AS recorded_status,
+ CASE WHEN g.n>1 AND g.statuses>1 THEN 'conflicting_duplicate' WHEN g.n>1 THEN 'duplicate'
+ WHEN p.payment_id IS NULL THEN 'missing' WHEN p.status IS NOT c.status THEN 'mismatch' ELSE 'match' END AS result
+ FROM csv_rows c JOIN csv_groups g USING(payment_id)
+ LEFT JOIN payments p ON p.run_id=? AND p.payment_id=c.payment_id ORDER BY c.row_number`);
+ const summary = { match: 0, mismatch: 0, missing: 0, duplicate: 0, conflicting_duplicate: 0 };
+ out = createWriteStream(output,{ flags: "wx", mode: 0o600 });
+ // Attach an error listener immediately; a later drain/finish wait also observes errors.
+ let outputError;
+ out.on("error",(error) => { outputError = error; });
+ async function write(text) {
+ if (outputError) throw outputError;
+ if (!out.write(text)) await once(out,"drain");
+ }
+ await write("row_number,payment_id,csv_status,recorded_status,result\n");
+ for (const row of query.iterate(run.run_id)) {
+ summary[row.result]++;
+ await write([row.row_number,row.payment_id,row.csv_status,row.recorded_status,row.result].map(escaped).join(",")+"\n");
+ }
+ const finished = once(out,"finish"); out.end(); await finished;
+ return { run_id: run.run_id, recording_state: run.recording_state, summary,
+ exitCode: Object.entries(summary).some(([key,n]) => key !== "match" && n > 0) ? 2 : 0 };
+ } finally { if (out && !out.writableFinished) out.destroy(); db.close(); }
+}
diff --git a/loadtest/k6/scenario-mix/record.mjs b/loadtest/k6/scenario-mix/record.mjs
new file mode 100644
index 0000000000..c95d34276f
--- /dev/null
+++ b/loadtest/k6/scenario-mix/record.mjs
@@ -0,0 +1,42 @@
+// Node fixture response extraction. Go load capture uses the same SQLite schema.
+// No request headers/card data or successful raw bodies are retained.
+import {diagnosticText,diagnosticBody,diagnosticUrl} from './diagnostics.mjs';
+export function responseRecord(context, method, url, request, response, text, latencyMs, transportError = null, parsedBody = undefined) {
+ let body = {};
+ let parseError = null;
+ if (parsedBody !== undefined) body = parsedBody;
+ else if (text) {
+ try { body = JSON.parse(text); } catch (_) { parseError = "invalid_json_response"; }
+ }
+ if (!body || typeof body !== "object") body = {};
+ const operation = context.operation;
+ const isCustomer = operation === "customer_create";
+ const isPayment = /^(payment_create|payment_confirm|baseline_create|baseline_confirm|baseline_poll)$/.test(operation);
+ const baseline = operation.startsWith("baseline_");
+ const role = context.role || (baseline ? "baseline" : "measured");
+ const pathId = /\/payments\/([^/?]+)(?:\/|\?|$)/.exec(url)?.[1];
+ const customerId = (isCustomer ? body.id || body.customer_id : body.customer_id)
+ || request?.customer_id || context.customer_id || null;
+ const paymentId = isPayment ? body.payment_id || pathId || (operation === "payment_confirm" ? context.payment_id : null) || null : context.payment_id || null;
+ const apiStatus = Number(response?.status || 0);
+ const failed = apiStatus < 200 || apiStatus >= 300;
+ const headers = response?.headers || {};
+ let requestId = null;
+ for (const key of Object.keys(headers)) {
+ if (["x-request-id", "request-id", "request_id"].includes(key.toLowerCase())) {
+ requestId = Array.isArray(headers[key]) ? headers[key][0] : headers[key];
+ break;
+ }
+ }
+ const message = transportError || (failed ? body.error?.message || (typeof body.error === "string" ? body.error : null) || body.message || response?.error || (parseError ? "non_json_error_response" : `HTTP ${apiStatus}`) : parseError);
+ return {
+ flow_id: context.flow_id, merchant_id: context.merchant_id || null,
+ operation, role, observed_at: Date.now(), method, url:diagnosticUrl(url),
+ customer_id: customerId, merchant_reference_id: body.merchant_reference_id || request?.merchant_reference_id || null,
+ payment_id: paymentId, amount: Number.isSafeInteger(body.amount) ? body.amount : Number.isSafeInteger(request?.amount) ? request.amount : null,
+ status: isPayment && typeof body.status === "string" ? body.status : null,
+ api_status_code: apiStatus, request_id: requestId || null, latency_ms: latencyMs,
+ message: message == null ? null : diagnosticText(message), error_body: failed&&text ? diagnosticBody(text) : null,
+ entity_type: isCustomer ? "customer" : isPayment ? "payment" : null,
+ };
+}
diff --git a/loadtest/k6/scenario-mix/recorder/Dockerfile b/loadtest/k6/scenario-mix/recorder/Dockerfile
new file mode 100644
index 0000000000..1f99617755
--- /dev/null
+++ b/loadtest/k6/scenario-mix/recorder/Dockerfile
@@ -0,0 +1,10 @@
+FROM golang:1.24.4-bookworm AS build
+WORKDIR /recorder
+COPY go.mod go.sum ./
+RUN go mod download
+COPY . .
+RUN CGO_ENABLED=1 go build -mod=readonly -trimpath -o /k6-sqlite ./cmd/k6-sqlite
+FROM debian:bookworm-slim
+RUN apt-get update && apt-get install -y --no-install-recommends ca-certificates && rm -rf /var/lib/apt/lists/*
+COPY --from=build /k6-sqlite /usr/local/bin/k6-sqlite
+ENTRYPOINT ["k6-sqlite"]
diff --git a/loadtest/k6/scenario-mix/recorder/build.sh b/loadtest/k6/scenario-mix/recorder/build.sh
new file mode 100755
index 0000000000..0185163ef4
--- /dev/null
+++ b/loadtest/k6/scenario-mix/recorder/build.sh
@@ -0,0 +1,7 @@
+#!/usr/bin/env bash
+set -euo pipefail
+cd -- "$(dirname -- "${BASH_SOURCE[0]}")"
+# Pinned k6 and SQLite dependencies (including transitives) live in go.mod/go.sum.
+# CI and the build container use Go 1.24.4. No xk6 installation is required.
+mkdir -p ../bin
+CGO_ENABLED=1 GOTOOLCHAIN=go1.24.4 go build -mod=readonly -trimpath -o ../bin/k6-sqlite ./cmd/k6-sqlite
diff --git a/loadtest/k6/scenario-mix/recorder/capture.go b/loadtest/k6/scenario-mix/recorder/capture.go
new file mode 100644
index 0000000000..5f31d1d328
--- /dev/null
+++ b/loadtest/k6/scenario-mix/recorder/capture.go
@@ -0,0 +1,179 @@
+package recorder
+
+import (
+ "fmt"
+ "math"
+ "regexp"
+ "strconv"
+ "strings"
+ "time"
+
+ "github.com/grafana/sobek"
+ k6http "go.k6.io/k6/js/modules/k6/http"
+)
+
+// Reading the native Response avoids repeatedly exporting its headers/timings and
+// 20 record fields across the JS bridge. JSON() reuses k6's own JSON cache; Export
+// on its Go map returns the underlying map, rather than copying its properties.
+type Captured struct {
+ CustomerID *string `js:"customer_id"`
+ PaymentID *string `js:"payment_id"`
+ EntityType *string `js:"entity_type"`
+ Role string `js:"role"`
+ RequestID *string `js:"request_id"`
+}
+
+// parsedBody reuses k6's cached JSON export and accepts only object bodies.
+// JavaScript parse exceptions become malformed results; unrelated panics are
+// re-raised so recorder defects are not mistaken for invalid server responses.
+func parsedBody(response *k6http.Response) (body map[string]interface{}, malformed bool) {
+ defer func() {
+ if panicValue := recover(); panicValue != nil {
+ switch panicValue.(type) {
+ case *sobek.Exception, *sobek.Object:
+ body = nil
+ malformed = true
+ default:
+ panic(panicValue)
+ }
+ }
+ }()
+ body, _ = response.JSON().Export().(map[string]interface{})
+ return body, false
+}
+
+// stringField returns a nonempty string property, or nil for missing, empty,
+// or differently typed values, including when body is nil.
+func stringField(body map[string]interface{}, key string) *string {
+ if value, ok := body[key].(string); ok && value != "" {
+ return &value
+ }
+ return nil
+}
+
+// complete resolves a reserved attempt from the native k6 response, capturing
+// HTTP timing, HS-only latency, entity IDs, connector attribution, and errors.
+// A missing response uses elapsed wall time; the returned IDs are available only
+// after the record is accepted by the writer, not necessarily persisted.
+func complete(id uint64, response *k6http.Response, transportError string) (Captured, error) {
+ w, err := current()
+ if err != nil {
+ return Captured{}, err
+ }
+ w.mu.Lock()
+ r, ok := w.pending[id]
+ w.mu.Unlock()
+ if !ok {
+ return Captured{}, fmt.Errorf("unknown HTTP attempt %d", id)
+ }
+ started := r.LatencyMS
+ r.ObservedAt = time.Now().UnixMilli()
+ r.LatencyMS = float64(r.ObservedAt) - started
+ var body map[string]interface{}
+ malformed := false
+ if response != nil {
+ r.APIStatusCode = response.Status
+ r.LatencyMS = response.Timings.Duration
+ for key, value := range response.Headers {
+ switch strings.ToLower(key) {
+ case "x-hs-latency":
+ r.ServerLatencyMS = parseServerLatency(value)
+ case "x-request-id", "request-id", "request_id":
+ r.RequestID = strPointer(value)
+ }
+ }
+ failed := r.APIStatusCode < 200 || r.APIStatusCode >= 300
+ text, _ := response.Body.(string)
+ if raw, ok := response.Body.([]byte); ok {
+ text = string(raw)
+ }
+ if failed && text != "" {
+ r.ErrorBody = strPointer(text)
+ }
+ // Successful non-entity steps need only metadata. Their JSON is parsed by the
+ // scenario if needed; entity/error responses share that same cached parse.
+ if text != "" && (r.EntityType != nil || failed) {
+ body, malformed = parsedBody(response)
+ }
+ if r.Operation == "payment_confirm" || r.Operation == "baseline_confirm" {
+ r.Connector = stringField(body, "connector")
+ r.MerchantConnectorID = stringField(body, "merchant_connector_id")
+ }
+ if failed {
+ message := fmt.Sprintf("HTTP %d", r.APIStatusCode)
+ if malformed {
+ message = "non_json_error_response"
+ }
+ if response.Error != "" {
+ message = response.Error
+ }
+ if value := stringField(body, "message"); value != nil {
+ message = *value
+ }
+ if value := stringField(body, "error"); value != nil {
+ message = *value
+ }
+ if nested, ok := body["error"].(map[string]interface{}); ok {
+ if value := stringField(nested, "message"); value != nil {
+ message = *value
+ }
+ }
+ r.Message = strPointer(message)
+ } else if malformed {
+ r.Message = strPointer("invalid_json_response")
+ }
+ }
+ if response == nil && transportError == "" {
+ r.Message = strPointer("no_http_response")
+ }
+ if transportError != "" {
+ r.Message = strPointer(transportError)
+ }
+ if r.EntityType != nil {
+ if *r.EntityType == "customer" {
+ if value := stringField(body, "id"); value != nil {
+ r.CustomerID = value
+ } else if value := stringField(body, "customer_id"); value != nil {
+ r.CustomerID = value
+ }
+ if value := stringField(body, "merchant_reference_id"); value != nil {
+ r.MerchantReferenceID = value
+ }
+ } else if *r.EntityType == "payment" {
+ if value := stringField(body, "payment_id"); value != nil {
+ r.PaymentID = value
+ }
+ if value := stringField(body, "customer_id"); value != nil {
+ r.CustomerID = value
+ }
+ if value := stringField(body, "status"); value != nil {
+ r.Status = value
+ }
+ if value, ok := body["amount"].(float64); ok && math.Abs(value) <= 9007199254740991 && math.Trunc(value) == value {
+ amount := int64(value)
+ r.Amount = &amount
+ }
+ }
+ }
+ if err = w.Finish(id, r); err != nil {
+ return Captured{}, err
+ }
+ return Captured{r.CustomerID, r.PaymentID, r.EntityType, r.Role, r.RequestID}, nil
+}
+
+var latencyMilliseconds = regexp.MustCompile(`^[0-9]+(\.[0-9]+)?$`)
+
+// parseServerLatency accepts a trimmed, nonnegative decimal x-hs-latency
+// value in milliseconds, including zero. Missing, malformed, or overflowing
+// values return nil so unavailable latency is not reported as zero.
+func parseServerLatency(header string) *float64 {
+ text := strings.TrimSpace(header)
+ if !latencyMilliseconds.MatchString(text) {
+ return nil
+ }
+ value, err := strconv.ParseFloat(text, 64)
+ if err != nil || math.IsInf(value, 0) {
+ return nil
+ }
+ return &value
+}
diff --git a/loadtest/k6/scenario-mix/recorder/capture_test.go b/loadtest/k6/scenario-mix/recorder/capture_test.go
new file mode 100644
index 0000000000..be8d800331
--- /dev/null
+++ b/loadtest/k6/scenario-mix/recorder/capture_test.go
@@ -0,0 +1,17 @@
+package recorder
+
+import "testing"
+
+func TestServerLatencyHeader(t *testing.T) {
+ for text, want := range map[string]float64{"0": 0, " 12.5 ": 12.5} {
+ got := parseServerLatency(text)
+ if got == nil || *got != want {
+ t.Fatalf("%q: %v", text, got)
+ }
+ }
+ for _, text := range []string{"", "true", "NaN", "Infinity", "-1", "10ms", "1e2"} {
+ if parseServerLatency(text) != nil {
+ t.Fatalf("accepted invalid latency %q", text)
+ }
+ }
+}
diff --git a/loadtest/k6/scenario-mix/recorder/cmd/k6-sqlite/main.go b/loadtest/k6/scenario-mix/recorder/cmd/k6-sqlite/main.go
new file mode 100644
index 0000000000..3d490434d7
--- /dev/null
+++ b/loadtest/k6/scenario-mix/recorder/cmd/k6-sqlite/main.go
@@ -0,0 +1,10 @@
+package main
+
+import (
+ "go.k6.io/k6/cmd"
+ _ "hyperswitch.local/loadtest-recorder"
+)
+
+// main runs the standard k6 CLI with the recorder registered by the blank
+// import, enabling scenarios to select the sqlite-recorder output.
+func main() { cmd.Execute() }
diff --git a/loadtest/k6/scenario-mix/recorder/control.go b/loadtest/k6/scenario-mix/recorder/control.go
new file mode 100644
index 0000000000..8069479a32
--- /dev/null
+++ b/loadtest/k6/scenario-mix/recorder/control.go
@@ -0,0 +1,439 @@
+package recorder
+
+import (
+ "context"
+ "crypto/subtle"
+ "encoding/json"
+ "errors"
+ "math"
+ "net"
+ "net/http"
+ "os"
+ "sync"
+ "time"
+)
+
+type controlStage struct {
+ Target float64 `json:"target_rps"`
+ Seconds float64 `json:"duration_seconds"`
+}
+type controlLoad struct {
+ Rate float64 `json:"total_rps"`
+ Duration float64 `json:"duration_seconds"`
+ Start float64 `json:"start_rps"`
+ Stages []controlStage `json:"stages"`
+}
+type admission struct {
+ ctx context.Context
+ ready chan bool
+}
+type controlFlow struct {
+ Weight float64
+ Requests chan admission
+ Credit float64
+ Started uint64
+}
+type controlSnapshot struct {
+ State string `json:"state"`
+ FaultGate bool `json:"fault_gate"`
+ Active float64 `json:"active_seconds"`
+ Wall float64 `json:"wall_seconds"`
+ InFlight uint64 `json:"in_flight"`
+ Dropped uint64 `json:"dropped"`
+ Offered float64 `json:"offered_tps"`
+ Started uint64 `json:"started_flows"`
+ FlowStarts map[string]uint64 `json:"flow_starts"`
+}
+type loadControl struct {
+ mu sync.Mutex
+ load controlLoad
+ flows map[string]*controlFlow
+ state string
+ started, last time.Time
+ active float64
+ faultGate bool
+ faultCycle bool
+ gateAt float64
+ gateRate float64
+ inFlight, dropped uint64
+ stop chan struct{}
+ done chan struct{}
+ server *http.Server
+ file string
+ onDone func()
+}
+
+// newLoadControl validates load metadata and creates weighted admission queues,
+// a bearer-authenticated loopback HTTP endpoint, and the scheduling goroutine.
+// It writes endpoint discovery before serving; the active clock starts on enter.
+func newLoadControl(metadata map[string]interface{}, file, token string, onDone func()) (*loadControl, error) {
+ if token == "" {
+ return nil, errors.New("console control token is required")
+ }
+ raw, _ := json.Marshal(metadata["load"])
+ var load controlLoad
+ if err := json.Unmarshal(raw, &load); err != nil {
+ return nil, err
+ }
+ if load.Start < 0 {
+ return nil, errors.New("console start rate must be nonnegative")
+ }
+ if len(load.Stages) > 0 {
+ load.Duration = 0
+ for _, s := range load.Stages {
+ if s.Target <= 0 || s.Seconds <= 0 {
+ return nil, errors.New("invalid console stage")
+ }
+ load.Duration += s.Seconds
+ }
+ var loadFields map[string]interface{}
+ _ = json.Unmarshal(raw, &loadFields)
+ if _, explicitStart := loadFields["start_rps"]; !explicitStart {
+ load.Start = load.Stages[0].Target
+ }
+ } else if load.Rate <= 0 || load.Duration <= 0 {
+ return nil, errors.New("console control requires positive rate and duration")
+ }
+ c := &loadControl{load: load, flows: map[string]*controlFlow{}, state: "idle", file: file, stop: make(chan struct{}), done: make(chan struct{}), onDone: onDone}
+ if entries, ok := metadata["scenarios"].([]interface{}); ok {
+ for _, raw := range entries {
+ entry := raw.(map[string]interface{})
+ name := entry["name"].(string)
+ weight := entry["weight"].(float64)
+ if weight > 0 {
+ c.flows[name] = &controlFlow{Weight: weight, Requests: make(chan admission, 100000)}
+ }
+ }
+ }
+ listener, err := net.Listen("tcp", "127.0.0.1:0")
+ if err != nil {
+ return nil, err
+ }
+ c.server = &http.Server{ReadHeaderTimeout: 5 * time.Second, Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if subtle.ConstantTimeCompare([]byte(r.Header.Get("Authorization")), []byte("Bearer "+token)) != 1 {
+ http.Error(w, "unauthorized", 401)
+ return
+ }
+ if r.URL.Path != "/control" {
+ http.NotFound(w, r)
+ return
+ }
+ if r.Method == "POST" {
+ var body struct {
+ Action string `json:"action"`
+ UntilActiveSeconds *float64 `json:"until_active_seconds"`
+ }
+ if json.NewDecoder(http.MaxBytesReader(w, r.Body, 1024)).Decode(&body) != nil {
+ http.Error(w, "invalid action", 400)
+ return
+ }
+ if err := c.action(body.Action, body.UntilActiveSeconds); err != nil {
+ http.Error(w, err.Error(), 409)
+ return
+ }
+ } else if r.Method != "GET" {
+ http.Error(w, "method not allowed", 405)
+ return
+ }
+ w.Header().Set("Content-Type", "application/json")
+ _ = json.NewEncoder(w).Encode(c.snapshot())
+ })}
+ if err := c.writeFile(map[string]interface{}{"endpoint": "http://" + listener.Addr().String() + "/control", "state": "idle"}); err != nil {
+ listener.Close()
+ return nil, err
+ }
+ go func() { _ = c.server.Serve(listener) }()
+ go c.loop()
+ return c, nil
+}
+
+// writeFile publishes controller discovery or status through a private temporary
+// file and rename, so readers do not observe partially written JSON.
+func (c *loadControl) writeFile(value interface{}) error {
+ raw, _ := json.Marshal(value)
+ if err := os.WriteFile(c.file+".tmp", raw, 0600); err != nil {
+ return err
+ }
+ return os.Rename(c.file+".tmp", c.file)
+}
+
+// rate returns the configured rate at the current active time, interpolating
+// linear stages. Callers must hold c.mu when the controller is running; pause
+// and fault gating are handled by callers rather than by this calculation.
+func (c *loadControl) rate() float64 {
+ if len(c.load.Stages) == 0 {
+ return c.load.Rate
+ }
+ t := c.active
+ start := c.load.Start
+ for _, s := range c.load.Stages {
+ if t <= s.Seconds {
+ return start + (s.Target-start)*t/s.Seconds
+ }
+ t -= s.Seconds
+ start = s.Target
+ }
+ return start
+}
+
+// offeredBetween integrates configured traffic over an active-time interval.
+// Each linear ramp contributes its exact area, avoiding endpoint-rate estimates
+// when scheduler ticks are delayed. Callers hold c.mu during live scheduling.
+func (c *loadControl) offeredBetween(from, to float64) float64 {
+ if len(c.load.Stages) == 0 {
+ return c.load.Rate * (to - from)
+ }
+ area, offset, start := 0.0, 0.0, c.load.Start
+ for _, stage := range c.load.Stages {
+ a, b := math.Max(from, offset), math.Min(to, offset+stage.Seconds)
+ if b > a {
+ first := start + (stage.Target-start)*(a-offset)/stage.Seconds
+ last := start + (stage.Target-start)*(b-offset)/stage.Seconds
+ area += (first + last) / 2 * (b - a)
+ }
+ offset += stage.Seconds
+ start = stage.Target
+ if offset >= to {
+ break
+ }
+ }
+ return area
+}
+
+// snapshot copies controller state and per-flow admission totals under c.mu.
+// Wall time includes pauses and gates; offered TPS is zero outside running state.
+func (c *loadControl) snapshot() controlSnapshot {
+ c.mu.Lock()
+ defer c.mu.Unlock()
+ wall := 0.0
+ if !c.started.IsZero() {
+ wall = time.Since(c.started).Seconds()
+ }
+ rate := c.rate()
+ if c.state != "running" {
+ rate = 0
+ }
+ starts, total := make(map[string]uint64, len(c.flows)), uint64(0)
+ for name, flow := range c.flows {
+ starts[name] = flow.Started
+ total += flow.Started
+ }
+ return controlSnapshot{State: c.state, FaultGate: c.faultGate, Active: c.active, Wall: wall, InFlight: c.inFlight, Dropped: c.dropped, Offered: rate, Started: total, FlowStarts: starts}
+}
+
+// action applies a validated pause, resume, or fault-cycle transition under
+// c.mu. Fault gates freeze active time while traffic continues; release can
+// set the next recovery boundary, and recover can skip to an explicit boundary
+// without manufacturing catch-up traffic. Invalid transitions return an error.
+func (c *loadControl) action(action string, until ...*float64) error {
+ c.mu.Lock()
+ defer c.mu.Unlock()
+ var gateAt *float64
+ if len(until) > 0 {
+ gateAt = until[0]
+ }
+ switch action {
+ case "gate":
+ if c.state != "running" {
+ return errors.New("only a running load can enter a fault gate")
+ }
+ if !c.faultGate {
+ c.gateRate = c.rate()
+ c.faultGate = true
+ c.faultCycle = true
+ c.gateAt = 0
+ c.last = time.Now()
+ }
+ case "release":
+ if c.state != "running" {
+ return errors.New("only a running load can be released from a fault gate")
+ }
+ if c.faultGate {
+ if gateAt != nil {
+ if *gateAt <= c.active || *gateAt > c.load.Duration {
+ return errors.New("release boundary must be after the active clock and within the load duration")
+ }
+ c.gateAt = *gateAt
+ } else {
+ c.gateAt = 0
+ }
+ c.faultGate = false
+ c.last = time.Now()
+ }
+ case "recover":
+ if c.state != "running" {
+ return errors.New("only a running load can finish a fault cycle")
+ }
+ if gateAt != nil {
+ if math.IsNaN(*gateAt) || math.IsInf(*gateAt, 0) || *gateAt < c.active || *gateAt > c.load.Duration {
+ return errors.New("recovery boundary must be at or after the active clock and within the load duration")
+ }
+ c.active = *gateAt
+ }
+ c.faultGate = false
+ c.faultCycle = false
+ c.gateAt = 0
+ c.last = time.Now()
+ case "pause":
+ if c.state != "running" || c.faultGate {
+ return errors.New("only running loads can pause")
+ }
+ c.state = "pausing"
+ if c.inFlight == 0 {
+ c.state = "paused"
+ }
+ case "resume":
+ if c.state != "paused" {
+ return errors.New("only paused loads can resume")
+ }
+ c.state = "running"
+ c.last = time.Now()
+ default:
+ return errors.New("unknown control action")
+ }
+ return nil
+}
+
+// enter registers a VU waiting for its named flow's next admission slot.
+// It starts an idle controller and blocks until admitted, cancelled, or stopped;
+// a true result must be paired with leave after the flow finishes.
+func (c *loadControl) enter(ctx context.Context, name string) bool {
+ c.mu.Lock()
+ f := c.flows[name]
+ if c.state == "idle" {
+ c.started = time.Now()
+ c.last = c.started
+ c.state = "running"
+ }
+ c.mu.Unlock()
+ if f == nil {
+ return false
+ }
+ req := admission{ctx: ctx, ready: make(chan bool, 1)}
+ select {
+ case f.Requests <- req:
+ case <-ctx.Done():
+ return false
+ case <-c.stop:
+ return false
+ }
+ select {
+ case ok := <-req.ready:
+ return ok
+ case <-ctx.Done():
+ return false
+ case <-c.stop:
+ return false
+ }
+}
+
+// leave decrements in-flight work under c.mu and completes a pending pause
+// when the last admitted flow has drained.
+func (c *loadControl) leave() {
+ c.mu.Lock()
+ defer c.mu.Unlock()
+ if c.inFlight > 0 {
+ c.inFlight--
+ }
+ if c.state == "pausing" && c.inFlight == 0 {
+ c.state = "paused"
+ }
+}
+
+// step advances one scheduling tick, distributing integrated offered traffic
+// using fractional per-flow credit. Slots without a waiting VU are dropped,
+// not backlogged; fault gates keep traffic flowing with active time frozen.
+// It returns true only after duration, fault recovery, and draining are complete.
+func (c *loadControl) step(now time.Time) bool {
+ c.mu.Lock()
+ defer c.mu.Unlock()
+ if c.state == "running" {
+ delta := now.Sub(c.last).Seconds()
+ if delta < 0 {
+ return false
+ }
+ c.last = now
+ offered := c.gateRate * delta
+ if !c.faultGate {
+ remaining := c.load.Duration - c.active
+ if c.gateAt > c.active && c.gateAt-c.active < remaining {
+ remaining = c.gateAt - c.active
+ }
+ if delta > remaining {
+ delta = remaining
+ }
+ offered = c.offeredBetween(c.active, c.active+delta)
+ c.active += delta
+ if c.gateAt > 0 && c.active >= c.gateAt-1e-9 {
+ c.active = c.gateAt
+ c.gateRate = c.rate()
+ c.gateAt = 0
+ c.faultGate = true
+ c.faultCycle = true
+ }
+ }
+ for _, f := range c.flows {
+ f.Credit += offered * f.Weight / 100
+ slots := int(math.Floor(f.Credit + 1e-9))
+ f.Credit -= float64(slots)
+ if f.Credit < 0 && f.Credit > -1e-9 {
+ f.Credit = 0
+ }
+ for i := 0; i < slots; i++ {
+ delivered := false
+ for !delivered {
+ select {
+ case req := <-f.Requests:
+ if req.ctx.Err() != nil {
+ continue
+ }
+ c.inFlight++
+ f.Started++
+ req.ready <- true
+ delivered = true
+ default:
+ c.dropped++
+ delivered = true
+ }
+ }
+ }
+ }
+ if !c.faultGate && !c.faultCycle && c.active >= c.load.Duration {
+ c.state = "draining"
+ }
+ }
+ if c.state == "draining" && c.inFlight == 0 {
+ c.state = "completed"
+ return true
+ }
+ return false
+}
+
+// loop drives admission at millisecond ticks until stopped or fully drained.
+// On completion it publishes final controller state and invokes onDone once.
+func (c *loadControl) loop() {
+ defer close(c.done)
+ ticker := time.NewTicker(time.Millisecond)
+ defer ticker.Stop()
+ for {
+ select {
+ case now := <-ticker.C:
+ if c.step(now) {
+ _ = c.writeFile(c.snapshot())
+ c.onDone()
+ return
+ }
+ case <-c.stop:
+ return
+ }
+ }
+}
+
+// close stops scheduling, waits for the loop to exit, closes the control HTTP
+// server, and publishes the final snapshot. It must be called only once.
+func (c *loadControl) close() {
+ close(c.stop)
+ <-c.done
+ _ = c.server.Close()
+ _ = c.writeFile(c.snapshot())
+}
diff --git a/loadtest/k6/scenario-mix/recorder/control_test.go b/loadtest/k6/scenario-mix/recorder/control_test.go
new file mode 100644
index 0000000000..f75cd13910
--- /dev/null
+++ b/loadtest/k6/scenario-mix/recorder/control_test.go
@@ -0,0 +1,233 @@
+package recorder
+
+import (
+ "context"
+ "math"
+ "testing"
+ "time"
+)
+
+func TestRejectedFailoverSkipsToNextStageWithoutCatchupTraffic(t *testing.T) {
+ now := time.Now()
+ c := &loadControl{load: controlLoad{Duration: 80, Stages: []controlStage{{Target: 5, Seconds: 60}, {Target: 10, Seconds: 20}}}, flows: map[string]*controlFlow{}, state: "running", active: 20, started: now, last: now}
+ if err := c.action("gate"); err != nil {
+ t.Fatal(err)
+ }
+ for _, invalid := range []float64{19, 81, math.NaN(), math.Inf(1)} {
+ if err := c.action("recover", &invalid); err == nil {
+ t.Fatal("invalid skip boundary accepted")
+ }
+ }
+ end := 60.0
+ if err := c.action("recover", &end); err != nil {
+ t.Fatal(err)
+ }
+ if c.active != 60 || c.faultGate || c.faultCycle {
+ t.Fatal("did not move directly to next stage")
+ }
+ if c.inFlight != 0 || c.dropped != 0 {
+ t.Fatal("skipping manufactured traffic")
+ }
+}
+
+func TestControlPauseDrainsAndFreezesAdmission(t *testing.T) {
+ now := time.Now()
+ f := &controlFlow{Weight: 100, Requests: make(chan admission, 10)}
+ c := &loadControl{load: controlLoad{Rate: 10, Duration: 3}, flows: map[string]*controlFlow{"guest": f}, state: "running", started: now, last: now}
+ request := admission{ctx: context.Background(), ready: make(chan bool, 1)}
+ f.Requests <- request
+ c.step(now.Add(110 * time.Millisecond))
+ if c.inFlight != 1 {
+ t.Fatal("did not admit flow")
+ }
+ if s := c.snapshot(); s.Started != 1 || s.FlowStarts["guest"] != 1 {
+ t.Fatal("started counters must include admitted flows before responses return")
+ }
+ if err := c.action("pause"); err != nil {
+ t.Fatal(err)
+ }
+ if c.state != "pausing" {
+ t.Fatal("must drain before paused")
+ }
+ if err := c.action("resume"); err == nil {
+ t.Fatal("resume while pausing allowed")
+ }
+ credit := f.Credit
+ active := c.active
+ c.step(now.Add(time.Second))
+ if c.active != active {
+ t.Fatal("paused clock advanced")
+ }
+ c.leave()
+ if c.state != "paused" || c.inFlight != 0 {
+ t.Fatal("did not reach paused")
+ }
+ if err := c.action("resume"); err != nil {
+ t.Fatal(err)
+ }
+ if f.Credit != credit {
+ t.Fatal("resume discarded already accrued fractional credit")
+ }
+ if c.state != "running" {
+ t.Fatal("did not resume")
+ }
+ c.active = 3
+ c.state = "draining"
+ if !c.step(time.Now()) || c.state != "completed" {
+ t.Fatal("did not complete after drain")
+ }
+}
+
+func TestControlDropsUnavailableSlotsAndPreservesRampClock(t *testing.T) {
+ now := time.Now()
+ c := &loadControl{load: controlLoad{Start: 0, Duration: 2, Stages: []controlStage{{Target: 10, Seconds: 2}}}, flows: map[string]*controlFlow{"guest": {Weight: 100, Requests: make(chan admission, 1)}}, state: "running", started: now, last: now}
+ c.step(now.Add(time.Second))
+ if c.rate() != 5 || c.dropped != 2 {
+ t.Fatal("ramp or dropped admission counters incorrect")
+ }
+ if c.snapshot().Started != 0 {
+ t.Fatal("dropped admissions must not count as started flows")
+ }
+ active := c.active
+ c.step(now.Add(-time.Second))
+ if c.active != active {
+ t.Fatal("stale ticker moved active clock backwards")
+ }
+ if err := c.action("pause"); err != nil {
+ t.Fatal(err)
+ }
+ if err := c.action("pause"); err == nil {
+ t.Fatal("second pause accepted")
+ }
+ c.step(now.Add(10 * time.Second))
+ if c.active != active {
+ t.Fatal("pause consumed ramp duration")
+ }
+}
+
+func TestControlFractionalWeightsDeliverWholeFinalSlots(t *testing.T) {
+ now := time.Now()
+ flows := map[string]*controlFlow{}
+ for name, weight := range map[string]float64{"cit": 50, "sdk": 30, "guest": 20} {
+ f := &controlFlow{Weight: weight, Requests: make(chan admission, 100)}
+ for i := 0; i < 100; i++ {
+ f.Requests <- admission{ctx: context.Background(), ready: make(chan bool, 1)}
+ }
+ flows[name] = f
+ }
+ c := &loadControl{load: controlLoad{Rate: 10, Duration: 3}, flows: flows, state: "running", started: now, last: now}
+ for i := 1; i <= 3000; i++ {
+ c.step(now.Add(time.Duration(i) * time.Millisecond))
+ c.inFlight = 0
+ }
+ for name, want := range map[string]int{"cit": 15, "sdk": 9, "guest": 6} {
+ if got := 100 - len(flows[name].Requests); got != want {
+ t.Fatalf("%s: got %d, want %d", name, got, want)
+ }
+ }
+ if c.dropped != 0 {
+ t.Fatal("unexpected drops")
+ }
+}
+
+func TestFaultGateFreezesStageClockButKeepsTrafficFlowing(t *testing.T) {
+ now := time.Now()
+ f := &controlFlow{Weight: 100, Requests: make(chan admission, 100)}
+ for i := 0; i < 100; i++ {
+ f.Requests <- admission{ctx: context.Background(), ready: make(chan bool, 1)}
+ }
+ c := &loadControl{load: controlLoad{Rate: 10, Duration: 30}, flows: map[string]*controlFlow{"guest": f}, state: "running", started: now, last: now}
+ c.step(now.Add(time.Second))
+ if err := c.action("gate"); err != nil {
+ t.Fatal(err)
+ }
+ gateStarted := c.last
+ active := c.active
+ c.step(gateStarted.Add(2 * time.Second))
+ if c.active != active {
+ t.Fatal("fault setup consumed configured stage time")
+ }
+ if got := 100 - len(f.Requests); got != 30 {
+ t.Fatalf("traffic stopped during fault gate: admitted %d, want 30", got)
+ }
+ if snapshot := c.snapshot(); !snapshot.FaultGate || snapshot.State != "running" || snapshot.Offered != 10 {
+ t.Fatalf("unexpected gated snapshot: %+v", snapshot)
+ }
+ if err := c.action("release"); err != nil {
+ t.Fatal(err)
+ }
+ released := c.last
+ c.step(released.Add(3 * time.Second))
+ if c.active != active+3 {
+ t.Fatalf("confirmed outage did not consume configured time: got %v", c.active)
+ }
+ if err := c.action("gate"); err != nil {
+ t.Fatal(err)
+ }
+ recoveryStarted := c.last
+ c.step(recoveryStarted.Add(2 * time.Second))
+ if c.active != active+3 {
+ t.Fatal("recovery consumed time before the next stage")
+ }
+ if err := c.action("recover"); err != nil {
+ t.Fatal(err)
+ }
+}
+
+func TestFinalFaultStageCannotCompleteBeforeVerifiedRecovery(t *testing.T) {
+ now := time.Now()
+ c := &loadControl{load: controlLoad{Rate: 1, Duration: 1}, flows: map[string]*controlFlow{}, state: "running", started: now, last: now}
+ if err := c.action("gate"); err != nil {
+ t.Fatal(err)
+ }
+ if err := c.action("release"); err != nil {
+ t.Fatal(err)
+ }
+ released := c.last
+ c.step(released.Add(time.Second))
+ if c.active != 1 || c.state != "running" {
+ t.Fatalf("final fault stage completed before recovery: active=%v state=%s", c.active, c.state)
+ }
+ if err := c.action("gate"); err != nil {
+ t.Fatal(err)
+ }
+ if err := c.action("recover"); err != nil {
+ t.Fatal(err)
+ }
+ if !c.step(c.last.Add(time.Millisecond)) || c.state != "completed" {
+ t.Fatalf("load did not complete after verified recovery: %s", c.state)
+ }
+}
+
+func TestRecoveryGatePreventsTheNextStageFromStartingEarly(t *testing.T) {
+ now := time.Now()
+ c := &loadControl{load: controlLoad{Start: 1, Duration: 30, Stages: []controlStage{{Target: 1, Seconds: 20}, {Target: 5, Seconds: 10}}}, flows: map[string]*controlFlow{}, state: "running", started: now, last: now}
+ c.step(now.Add(10 * time.Second))
+ if err := c.action("gate"); err != nil {
+ t.Fatal(err)
+ }
+ boundary := 20.0
+ invalid := 31.0
+ if err := c.action("release", &invalid); err == nil || !c.faultGate {
+ t.Fatal("invalid release must preserve the fault gate")
+ }
+ if err := c.action("release", &boundary); err != nil {
+ t.Fatal(err)
+ }
+ released := c.last
+ c.step(released.Add(15 * time.Second))
+ if c.active != boundary || !c.faultGate {
+ t.Fatalf("load passed the fault-stage boundary before recovery: active=%v faultGate=%v", c.active, c.faultGate)
+ }
+ if got := c.rate(); got != 1 {
+ t.Fatalf("next ramp started before recovery verification: rate=%v", got)
+ }
+ if err := c.action("recover"); err != nil {
+ t.Fatal(err)
+ }
+ recovered := c.last
+ c.step(recovered.Add(time.Second))
+ if c.active != boundary+1 || c.rate() <= 1 {
+ t.Fatalf("next ramp did not begin after recovery: active=%v rate=%v", c.active, c.rate())
+ }
+}
diff --git a/loadtest/k6/scenario-mix/recorder/customer.sql b/loadtest/k6/scenario-mix/recorder/customer.sql
new file mode 100644
index 0000000000..2f62420cf0
--- /dev/null
+++ b/loadtest/k6/scenario-mix/recorder/customer.sql
@@ -0,0 +1,8 @@
+INSERT INTO customers
+(run_id,customer_id,merchant_id,merchant_reference_id,api_status_code,request_id,message,observed_at,response_event_id)
+VALUES (?,?,?,?,?,?,?,?,?)
+ON CONFLICT(run_id,customer_id) DO UPDATE SET
+ merchant_reference_id=COALESCE(excluded.merchant_reference_id,customers.merchant_reference_id),
+ api_status_code=excluded.api_status_code,request_id=excluded.request_id,
+ message=excluded.message,observed_at=excluded.observed_at,response_event_id=excluded.response_event_id
+WHERE excluded.observed_at > customers.observed_at OR (excluded.observed_at = customers.observed_at AND excluded.response_event_id > customers.response_event_id)
diff --git a/loadtest/k6/scenario-mix/recorder/diagnostics.go b/loadtest/k6/scenario-mix/recorder/diagnostics.go
new file mode 100644
index 0000000000..033cc964cd
--- /dev/null
+++ b/loadtest/k6/scenario-mix/recorder/diagnostics.go
@@ -0,0 +1,98 @@
+package recorder
+
+import (
+ "encoding/json"
+ "net/url"
+ "regexp"
+ "strings"
+)
+
+var diagnosticSecret = regexp.MustCompile(`(?i)(api[_ -]?key|client[_ -]?secret|authorization|password|access[_ -]?token|card[_ -]?(?:number|cvc)|cvc|cvv)(["']?\s*[=:]\s*)("[^"]*"|'[^']*'|[^\s;,]+)`)
+var diagnosticBearer = regexp.MustCompile(`(?i)\bBearer\s+[A-Za-z0-9._~+/=-]+`)
+var diagnosticCard = regexp.MustCompile(`\b(?:\d[ -]?){13,19}\b`)
+var diagnosticQuery = regexp.MustCompile(`(?i)key|secret|token|password|cvc|cvv|card`)
+
+// diagnosticText redacts common credential, bearer-token, and card-number
+// patterns, then bounds retained text to 512 runes. This is best-effort
+// filtering for diagnostic strings, not a general sensitive-data detector.
+func diagnosticText(value string) string {
+ value = diagnosticBearer.ReplaceAllString(value, "Bearer [redacted]")
+ value = diagnosticSecret.ReplaceAllString(value, "${1}${2}[redacted]")
+ value = diagnosticCard.ReplaceAllString(value, "[redacted]")
+ text := []rune(value)
+ if len(text) > 512 {
+ return string(text[:512])
+ }
+ return value
+}
+
+// diagnosticProjection retains only error, code, type, and message fields
+// from nested JSON objects, sanitizing string leaves. Unsupported values and
+// objects beyond depth three become nil rather than retaining arbitrary bodies.
+func diagnosticProjection(value interface{}, depth int) interface{} {
+ if text, ok := value.(string); ok {
+ return diagnosticText(text)
+ }
+ object, ok := value.(map[string]interface{})
+ if !ok || depth > 3 {
+ return nil
+ }
+ result := map[string]interface{}{}
+ for _, key := range []string{"error", "code", "type", "message"} {
+ if field, ok := object[key]; ok {
+ result[key] = diagnosticProjection(field, depth+1)
+ }
+ }
+ return result
+}
+
+// diagnosticBody produces a bounded JSON error projection for persistence.
+// It omits oversized or non-JSON input and replaces projections exceeding
+// the output limit with a fixed diagnostic message.
+func diagnosticBody(text string) string {
+ if len(text) > 65536 {
+ return "[oversized error response omitted]"
+ }
+ var value interface{}
+ if json.Unmarshal([]byte(text), &value) != nil {
+ return "[non-JSON error response omitted]"
+ }
+ data, err := json.Marshal(diagnosticProjection(value, 0))
+ if err != nil || len(data) > 4096 {
+ return `{"message":"Error diagnostic exceeded limit"}`
+ }
+ return string(data)
+}
+
+// sanitizeDiagnostics returns a record with filtered error text and body,
+// URL user information removed, and sensitive-looking query values redacted.
+// Malformed URLs fall back to bounded text filtering; other record fields
+// are preserved, so callers must still avoid capturing request secrets.
+func sanitizeDiagnostics(r Record) Record {
+ if r.Message != nil {
+ text := diagnosticText(*r.Message)
+ r.Message = &text
+ }
+ if r.ErrorBody != nil {
+ text := diagnosticBody(*r.ErrorBody)
+ r.ErrorBody = &text
+ }
+ if u, err := url.Parse(r.URL); err == nil {
+ u.User = nil
+ query := u.Query()
+ changed := false
+ for key := range query {
+ if diagnosticQuery.MatchString(key) {
+ query.Set(key, "[redacted]")
+ changed = true
+ }
+ }
+ if changed {
+ u.RawQuery = query.Encode()
+ }
+ r.URL = u.String()
+ } else {
+ r.URL = strings.TrimSpace(diagnosticText(r.URL))
+ }
+ return r
+}
diff --git a/loadtest/k6/scenario-mix/recorder/diagnostics_test.go b/loadtest/k6/scenario-mix/recorder/diagnostics_test.go
new file mode 100644
index 0000000000..7ff3ea0772
--- /dev/null
+++ b/loadtest/k6/scenario-mix/recorder/diagnostics_test.go
@@ -0,0 +1,24 @@
+package recorder
+
+import (
+ "strings"
+ "testing"
+)
+
+func TestErrorDiagnosticsExcludeSensitiveFields(t *testing.T) {
+ raw := `{"error":{"code":"PAYMENT_FAILED","message":"Invalid card 4242424242424242; api_key=private-key","metadata":{"password":"private-password"}},"client_secret":"private-client-secret"}`
+ message := "Authorization: Bearer private-token"
+ r := sanitizeDiagnostics(Record{URL: "http://router/confirm?client_secret=private-client-secret", Message: &message, ErrorBody: &raw})
+ result := r.URL + *r.Message + *r.ErrorBody
+ for _, secret := range []string{"4242424242424242", "private-key", "private-password", "private-client-secret", "private-token"} {
+ if strings.Contains(result, secret) {
+ t.Fatalf("retained sensitive diagnostic: %s", secret)
+ }
+ }
+ if !strings.Contains(*r.ErrorBody, "PAYMENT_FAILED") {
+ t.Fatal("lost diagnostic code")
+ }
+ if strings.Contains(diagnosticBody("<html>raw-secret</html>"), "raw-secret") {
+ t.Fatal("retained raw non-JSON body")
+ }
+}
diff --git a/loadtest/k6/scenario-mix/recorder/event.sql b/loadtest/k6/scenario-mix/recorder/event.sql
new file mode 100644
index 0000000000..b569fef126
--- /dev/null
+++ b/loadtest/k6/scenario-mix/recorder/event.sql
@@ -0,0 +1,5 @@
+INSERT INTO request_events
+(run_id,attempt_id,flow_id,merchant_id,operation,role,observed_at,method,url,customer_id,
+ merchant_reference_id,payment_id,amount,status,api_status_code,request_id,
+ latency_ms,message,error_body,entity_type,server_latency_ms,requested_connector,selected_connector_account,connector,merchant_connector_id)
+VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)
diff --git a/loadtest/k6/scenario-mix/recorder/extension.go b/loadtest/k6/scenario-mix/recorder/extension.go
new file mode 100644
index 0000000000..37f72426bc
--- /dev/null
+++ b/loadtest/k6/scenario-mix/recorder/extension.go
@@ -0,0 +1,287 @@
+package recorder
+
+import (
+ "encoding/json"
+ "errors"
+ "fmt"
+ "strings"
+ "sync"
+ "time"
+
+ "go.k6.io/k6/errext"
+ "go.k6.io/k6/js/modules"
+ "go.k6.io/k6/metrics"
+ "go.k6.io/k6/output"
+)
+
+var active struct {
+ sync.RWMutex
+ writer *Writer
+ last *Stats
+ control *loadControl
+}
+
+// init registers the JavaScript module and output extension under the names
+// used by scenarios and the k6 --out flag.
+func init() {
+ modules.Register("k6/x/sqlite-recorder", &module{})
+ output.RegisterExtension("sqlite-recorder", newOutput)
+}
+
+type module struct{}
+type instance struct{ vu modules.VU }
+
+// NewModuleInstance binds the module to a virtual user so admission waits
+// can observe that VU's cancellation context.
+func (*module) NewModuleInstance(vu modules.VU) modules.Instance { return &instance{vu: vu} }
+
+// Exports exposes recording, admission control, and statistics to scenarios.
+// The attribution version lets scripts detect connector-aware recorder support.
+func (i *instance) Exports() modules.Exports {
+ return modules.Exports{Default: map[string]interface{}{"connectorAttribution": 1, "record": record, "begin": begin, "finish": finish, "complete": complete, "stats": snapshot, "enter": i.enter, "leave": leave}}
+}
+
+// enter waits for admission through the active load controller. It returns
+// false when control is unavailable or the VU is cancelled before admission.
+func (i *instance) enter(name string) bool {
+ active.RLock()
+ c := active.control
+ active.RUnlock()
+ return c != nil && c.enter(i.vu.Context(), name)
+}
+
+// leave releases one admitted flow when a controller exists, allowing pause
+// and completion to finish draining in-flight work.
+func leave() {
+ active.RLock()
+ c := active.control
+ active.RUnlock()
+ if c != nil {
+ c.leave()
+ }
+}
+
+// current reads the active writer under the shared lock and rejects recording
+// when k6 has not started the sqlite-recorder output.
+func current() (*Writer, error) {
+ active.RLock()
+ defer active.RUnlock()
+ if active.writer == nil {
+ return nil, errors.New("SQLite recorder not started; use --out sqlite-recorder")
+ }
+ return active.writer, nil
+}
+
+// record queues an already assembled response projection on the active writer.
+// Writer availability, capacity, and persistence failures propagate to the caller.
+func record(r Record) error {
+ w, err := current()
+ if err != nil {
+ return err
+ }
+ return w.Enqueue(r)
+}
+
+// snapshot returns current recorder counters, or the final retained counters
+// after shutdown. It fails when no run has produced statistics.
+func snapshot() (Stats, error) {
+ active.RLock()
+ defer active.RUnlock()
+ if active.writer != nil {
+ return active.writer.Snapshot(), nil
+ }
+ if active.last != nil {
+ return *active.last, nil
+ }
+ return Stats{}, errors.New("SQLite recorder has no run")
+}
+
+type sqliteOutput struct {
+ params output.Params
+ writer *Writer
+ stop func(error)
+ monitorStop chan struct{}
+ monitorDone chan struct{}
+ progressFile string
+ progress *progressCollector
+ control *loadControl
+}
+
+// newOutput constructs the k6 output without opening resources; Start performs
+// environment validation and initializes recording.
+func newOutput(params output.Params) (output.Output, error) {
+ return &sqliteOutput{params: params}, nil
+}
+
+// Description supplies the human-readable output name shown by k6.
+func (*sqliteOutput) Description() string { return "buffered SQLite response recorder" }
+
+// SetTestRunStopCallback stores k6's abort callback for recorder failures and
+// load-duration completion; k6 installs it before Start.
+func (o *sqliteOutput) SetTestRunStopCallback(stop func(error)) { o.stop = stop }
+
+// Start opens the run database, publishes the active writer, and optionally
+// starts authenticated load control and periodic progress reporting. Required
+// paths and run metadata come from the output environment; setup errors fail startup.
+func (o *sqliteOutput) Start() error {
+ file := o.params.Environment["SQLITE_RECORDER_DB"]
+ runID := o.params.Environment["SQLITE_RECORDER_RUN_ID"]
+ if file == "" || runID == "" {
+ return errors.New("SQLITE_RECORDER_DB and SQLITE_RECORDER_RUN_ID are required")
+ }
+ metadata := map[string]interface{}{}
+ if raw := o.params.Environment["SQLITE_RECORDER_METADATA"]; raw != "" {
+ if err := json.Unmarshal([]byte(raw), &metadata); err != nil {
+ return err
+ }
+ }
+ w, err := NewWriter(file, runID, DefaultSettings(), metadata)
+ if err != nil {
+ return err
+ }
+ w.SetStop(o.stop)
+ o.writer = w
+ o.progressFile = o.params.Environment["SQLITE_RECORDER_PROGRESS_FILE"]
+ if o.progressFile != "" {
+ o.progress = newProgressCollector(metadata)
+ }
+ active.Lock()
+ active.writer = w
+ active.Unlock()
+ if file := o.params.Environment["SQLITE_RECORDER_CONTROL_FILE"]; file != "" {
+ c, err := newLoadControl(metadata, file, o.params.Environment["SQLITE_RECORDER_CONTROL_TOKEN"], func() { o.stop(errors.New("console active load duration completed")) })
+ if err != nil {
+ _ = w.Close(err)
+ return err
+ }
+ o.control = c
+ active.Lock()
+ active.control = c
+ active.Unlock()
+ }
+ o.monitorStop = make(chan struct{})
+ o.monitorDone = make(chan struct{})
+ go func() {
+ defer close(o.monitorDone)
+ interval := 10 * time.Second
+ if o.progressFile != "" {
+ interval = time.Second
+ }
+ ticker := time.NewTicker(interval)
+ defer ticker.Stop()
+ for {
+ select {
+ case <-o.monitorStop:
+ return
+ case <-ticker.C:
+ if o.progressFile != "" {
+ o.writeProgress()
+ continue
+ }
+ raw, _ := json.Marshal(w.Snapshot())
+ fmt.Fprintf(o.params.StdErr, "SQLite recorder progress: %s\n", raw)
+ }
+ }
+ }()
+ return nil
+}
+
+// AddMetricSamples forwards k6 samples to live aggregation when a progress
+// file was configured; database request capture uses the JavaScript API instead.
+func (o *sqliteOutput) AddMetricSamples(samples []metrics.SampleContainer) {
+ if o.progress != nil {
+ o.progress.add(samples)
+ }
+}
+
+// Stop finalizes recording when k6 supplies no test error, using the same
+// drain and resource cleanup path as StopWithTestError.
+func (o *sqliteOutput) Stop() error { return o.StopWithTestError(nil) }
+
+// StopWithTestError stops progress polling, drains and closes the writer, then
+// publishes final telemetry and releases load control. A controller-completed run
+// with no in-flight work clears the stop error before completeness is evaluated.
+func (o *sqliteOutput) StopWithTestError(err error) error {
+ if o.writer == nil {
+ return nil
+ }
+ close(o.monitorStop)
+ <-o.monitorDone
+ if o.control != nil && o.control.snapshot().State == "completed" && o.control.snapshot().InFlight == 0 {
+ err = nil
+ }
+ result := o.writer.Close(recordingError(err))
+ o.writeProgress()
+ if o.control != nil {
+ o.control.close()
+ }
+ stats := o.writer.Snapshot()
+ raw, _ := json.Marshal(stats)
+ fmt.Fprintf(o.params.StdErr, "SQLite recorder: %s\n", raw)
+ active.Lock()
+ active.writer = nil
+ active.control = nil
+ active.last = &stats
+ active.Unlock()
+ return result
+}
+
+// recordingError excludes thresholds evaluated after a finished test from
+// recording completeness. Early threshold aborts and other interruptions remain
+// errors because they may have truncated the captured workload.
+func recordingError(err error) error {
+ var reason errext.HasAbortReason
+ if errors.As(err, &reason) && reason.AbortReason() == errext.AbortedByThresholdsAfterTestEnd {
+ return nil
+ }
+ return err
+}
+
+// begin reserves an HTTP attempt before execution and classifies baseline and
+// entity operations. started is a Unix-millisecond timestamp temporarily stored
+// in LatencyMS; optional connectors identify the requested connector and MCA.
+func begin(flowID string, merchantID *string, operation, method, url string, customerID, reference, paymentID *string, amount *int64, started int64, connectors ...string) (uint64, error) {
+ w, err := current()
+ if err != nil {
+ return 0, err
+ }
+ role := "measured"
+ if strings.HasPrefix(operation, "baseline_") {
+ role = "baseline"
+ }
+ var entity *string
+ if operation == "customer_create" {
+ entity = strPointer("customer")
+ }
+ switch operation {
+ case "payment_create", "payment_confirm", "baseline_create", "baseline_confirm", "baseline_poll":
+ entity = strPointer("payment")
+ if i := strings.Index(url, "/payments/"); i >= 0 {
+ id := strings.SplitN(strings.SplitN(url[i+len("/payments/"):], "/", 2)[0], "?", 2)[0]
+ if id != "" {
+ paymentID = &id
+ }
+ } else if operation == "payment_create" || operation == "baseline_create" {
+ paymentID = nil
+ }
+ }
+ var requested, selected *string
+ if len(connectors) > 0 && connectors[0] != "" {
+ requested = &connectors[0]
+ }
+ if len(connectors) > 1 && connectors[1] != "" {
+ selected = &connectors[1]
+ }
+ return w.Begin(Record{RequestedConnector: requested, SelectedConnectorAccount: selected, FlowID: flowID, MerchantID: merchantID, Operation: operation, Role: role, Method: method, URL: url,
+ CustomerID: customerID, MerchantReferenceID: reference, PaymentID: paymentID, Amount: amount, ObservedAt: time.Now().UnixMilli(), LatencyMS: float64(started), EntityType: entity})
+}
+
+// finish submits an explicitly assembled result for a reserved attempt.
+// The writer rejects unknown or previously finished attempt IDs.
+func finish(id uint64, r Record) error {
+ w, err := current()
+ if err != nil {
+ return err
+ }
+ return w.Finish(id, r)
+}
diff --git a/loadtest/k6/scenario-mix/recorder/go.mod b/loadtest/k6/scenario-mix/recorder/go.mod
new file mode 100644
index 0000000000..04e33a6866
--- /dev/null
+++ b/loadtest/k6/scenario-mix/recorder/go.mod
@@ -0,0 +1,99 @@
+module hyperswitch.local/loadtest-recorder
+
+go 1.24.0
+
+require go.k6.io/k6 v1.0.0
+
+require (
+ buf.build/gen/go/gogo/protobuf/protocolbuffers/go v1.36.5-20210810001428-4df00b267f94.1 // indirect
+ buf.build/gen/go/prometheus/prometheus/protocolbuffers/go v1.36.5-20240802094132-5b212ab78fb7.1 // indirect
+ github.com/Azure/go-ntlmssp v0.0.0-20221128193559-754e69321358 // indirect
+ github.com/Masterminds/semver/v3 v3.3.1 // indirect
+ github.com/PuerkitoBio/goquery v1.9.2 // indirect
+ github.com/Soontao/goHttpDigestClient v0.0.0-20170320082612-6d28bb1415c5 // indirect
+ github.com/andybalholm/brotli v1.1.1 // indirect
+ github.com/andybalholm/cascadia v1.3.2 // indirect
+ github.com/beorn7/perks v1.0.1 // indirect
+ github.com/bufbuild/protocompile v0.14.1 // indirect
+ github.com/cenkalti/backoff/v4 v4.3.0 // indirect
+ github.com/cespare/xxhash/v2 v2.3.0 // indirect
+ github.com/chromedp/cdproto v0.0.0-20240919203636-12af5e8a671f // indirect
+ github.com/chromedp/sysutil v1.0.0 // indirect
+ github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f // indirect
+ github.com/dlclark/regexp2 v1.11.4 // indirect
+ github.com/evanw/esbuild v0.25.3 // indirect
+ github.com/fatih/color v1.18.0 // indirect
+ github.com/fsnotify/fsnotify v1.10.1 // indirect
+ github.com/go-logr/logr v1.4.2 // indirect
+ github.com/go-logr/stdr v1.2.2 // indirect
+ github.com/go-sourcemap/sourcemap v2.1.4+incompatible // indirect
+ github.com/golang/protobuf v1.5.4 // indirect
+ github.com/google/pprof v0.0.0-20250317173921-a4b03ec1a45e // indirect
+ github.com/google/uuid v1.6.0 // indirect
+ github.com/gorilla/websocket v1.5.3 // indirect
+ github.com/grafana/k6build v0.5.11 // indirect
+ github.com/grafana/k6deps v0.2.6 // indirect
+ github.com/grafana/k6provider v0.1.15 // indirect
+ github.com/grafana/sobek v0.0.0-20250320150027-203dc85b6d98 // indirect
+ github.com/grafana/xk6-dashboard v0.7.5 // indirect
+ github.com/grafana/xk6-redis v0.3.3 // indirect
+ github.com/grpc-ecosystem/go-grpc-middleware v1.4.0 // indirect
+ github.com/grpc-ecosystem/grpc-gateway/v2 v2.26.1 // indirect
+ github.com/inconshreveable/mousetrap v1.0.0 // indirect
+ github.com/influxdata/influxdb1-client v0.0.0-20190402204710-8ff2fc3824fc // indirect
+ github.com/jhump/protoreflect v1.17.0 // indirect
+ github.com/josharian/intern v1.0.0 // indirect
+ github.com/klauspost/compress v1.18.0 // indirect
+ github.com/mailru/easyjson v0.9.0 // indirect
+ github.com/mattn/go-colorable v0.1.14 // indirect
+ github.com/mattn/go-isatty v0.0.20 // indirect
+ github.com/mattn/go-sqlite3 v1.14.24
+ github.com/matttproud/golang_protobuf_extensions v1.0.4 // indirect
+ github.com/mstoykov/atlas v0.0.0-20220811071828-388f114305dd // indirect
+ github.com/mstoykov/envconfig v1.5.0 // indirect
+ github.com/mstoykov/k6-taskqueue-lib v0.1.3 // indirect
+ github.com/nu7hatch/gouuid v0.0.0-20131221200532-179d4d0c4d8d // indirect
+ github.com/pkg/browser v0.0.0-20210911075715-681adbf594b8 // indirect
+ github.com/prometheus/client_golang v1.16.0 // indirect
+ github.com/prometheus/client_model v0.4.0 // indirect
+ github.com/prometheus/common v0.42.0 // indirect
+ github.com/prometheus/procfs v0.10.1 // indirect
+ github.com/r3labs/sse/v2 v2.10.0 // indirect
+ github.com/redis/go-redis/v9 v9.0.5 // indirect
+ github.com/serenize/snaker v0.0.0-20201027110005-a7ad2135616e // indirect
+ github.com/sirupsen/logrus v1.9.3 // indirect
+ github.com/spf13/afero v1.1.2 // indirect
+ github.com/spf13/cobra v1.4.0 // indirect
+ github.com/spf13/pflag v1.0.5 // indirect
+ github.com/tidwall/gjson v1.18.0 // indirect
+ github.com/tidwall/match v1.1.1 // indirect
+ github.com/tidwall/pretty v1.2.1 // indirect
+ go.opentelemetry.io/auto/sdk v1.1.0 // indirect
+ go.opentelemetry.io/otel v1.35.0 // indirect
+ go.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetricgrpc v1.35.0 // indirect
+ go.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetrichttp v1.35.0 // indirect
+ go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.35.0 // indirect
+ go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.35.0 // indirect
+ go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.35.0 // indirect
+ go.opentelemetry.io/otel/metric v1.35.0 // indirect
+ go.opentelemetry.io/otel/sdk v1.35.0 // indirect
+ go.opentelemetry.io/otel/sdk/metric v1.35.0 // indirect
+ go.opentelemetry.io/otel/trace v1.35.0 // indirect
+ go.opentelemetry.io/proto/otlp v1.5.0 // indirect
+ golang.org/x/crypto v0.37.0 // indirect
+ golang.org/x/crypto/x509roots/fallback v0.0.0-20250414110644-0091fc8e7c69 // indirect
+ golang.org/x/net v0.39.0 // indirect
+ golang.org/x/sync v0.13.0 // indirect
+ golang.org/x/sys v0.32.0 // indirect
+ golang.org/x/term v0.31.0 // indirect
+ golang.org/x/text v0.24.0 // indirect
+ golang.org/x/time v0.11.0 // indirect
+ google.golang.org/genproto/googleapis/api v0.0.0-20250218202821-56aae31c358a // indirect
+ google.golang.org/genproto/googleapis/rpc v0.0.0-20250218202821-56aae31c358a // indirect
+ google.golang.org/grpc v1.71.1 // indirect
+ google.golang.org/protobuf v1.36.6 // indirect
+ gopkg.in/cenkalti/backoff.v1 v1.1.0 // indirect
+ gopkg.in/guregu/null.v3 v3.3.0 // indirect
+ gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7 // indirect
+ gopkg.in/yaml.v3 v3.0.1 // indirect
+)
diff --git a/loadtest/k6/scenario-mix/recorder/go.sum b/loadtest/k6/scenario-mix/recorder/go.sum
new file mode 100644
index 0000000000..8774672007
--- /dev/null
+++ b/loadtest/k6/scenario-mix/recorder/go.sum
@@ -0,0 +1,362 @@
+buf.build/gen/go/gogo/protobuf/protocolbuffers/go v1.36.5-20210810001428-4df00b267f94.1 h1:msc7tmde/S7g2xOxfMYsTKjWQsfDI8kNkKCvklq2AhM=
+buf.build/gen/go/gogo/protobuf/protocolbuffers/go v1.36.5-20210810001428-4df00b267f94.1/go.mod h1:mUoXP7Apxz01oxVlxIFxqw2LVx60pAp78uBFjUXkmXc=
+buf.build/gen/go/prometheus/prometheus/protocolbuffers/go v1.36.5-20240802094132-5b212ab78fb7.1 h1:ImDF97CnEaa0J3KR9nPnE8vJpiIr5wfDjvQijyv3cJ0=
+buf.build/gen/go/prometheus/prometheus/protocolbuffers/go v1.36.5-20240802094132-5b212ab78fb7.1/go.mod h1:P36ReP+oIZKZEkukwNbbppm+rwn3QgG9dsfRGcLiy0E=
+cloud.google.com/go v0.26.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw=
+github.com/Azure/go-ntlmssp v0.0.0-20221128193559-754e69321358 h1:mFRzDkZVAjdal+s7s0MwaRv9igoPqLRdzOLzw/8Xvq8=
+github.com/Azure/go-ntlmssp v0.0.0-20221128193559-754e69321358/go.mod h1:chxPXzSsl7ZWRAuOIE23GDNzjWuZquvFlgA8xmpunjU=
+github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU=
+github.com/Masterminds/semver/v3 v3.3.1 h1:QtNSWtVZ3nBfk8mAOu/B6v7FMJ+NHTIgUPi7rj+4nv4=
+github.com/Masterminds/semver/v3 v3.3.1/go.mod h1:4V+yj/TJE1HU9XfppCwVMZq3I84lprf4nC11bSS5beM=
+github.com/PuerkitoBio/goquery v1.9.2 h1:4/wZksC3KgkQw7SQgkKotmKljk0M6V8TUvA8Wb4yPeE=
+github.com/PuerkitoBio/goquery v1.9.2/go.mod h1:GHPCaP0ODyyxqcNoFGYlAprUFH81NuRPd0GX3Zu2Mvk=
+github.com/Soontao/goHttpDigestClient v0.0.0-20170320082612-6d28bb1415c5 h1:k+1+doEm31k0rRjCjLnGG3YRkuO9ljaEyS2ajZd6GK8=
+github.com/Soontao/goHttpDigestClient v0.0.0-20170320082612-6d28bb1415c5/go.mod h1:5Q4+CyR7+Q3VMG8f78ou+QSX/BNUNUx5W48eFRat8DQ=
+github.com/andybalholm/brotli v1.1.1 h1:PR2pgnyFznKEugtsUo0xLdDop5SKXd5Qf5ysW+7XdTA=
+github.com/andybalholm/brotli v1.1.1/go.mod h1:05ib4cKhjx3OQYUY22hTVd34Bc8upXjOLL2rKwwZBoA=
+github.com/andybalholm/cascadia v1.3.2 h1:3Xi6Dw5lHF15JtdcmAHD3i1+T8plmv7BQ/nsViSLyss=
+github.com/andybalholm/cascadia v1.3.2/go.mod h1:7gtRlve5FxPPgIgX36uWBX58OdBsSS6lUvCFb+h7KvU=
+github.com/benbjohnson/clock v1.1.0/go.mod h1:J11/hYXuz8f4ySSvYwY0FKfm+ezbsZBKZxNJlLklBHA=
+github.com/beorn7/perks v1.0.1 h1:VlbKKnNfV8bJzeqoa4cOKqO6bYr3WgKZxO8Z16+hsOM=
+github.com/beorn7/perks v1.0.1/go.mod h1:G2ZrVWU2WbWT9wwq4/hrbKbnv/1ERSJQ0ibhJ6rlkpw=
+github.com/bsm/ginkgo/v2 v2.7.0 h1:ItPMPH90RbmZJt5GtkcNvIRuGEdwlBItdNVoyzaNQao=
+github.com/bsm/ginkgo/v2 v2.7.0/go.mod h1:AiKlXPm7ItEHNc/2+OkrNG4E0ITzojb9/xWzvQ9XZ9w=
+github.com/bsm/gomega v1.26.0 h1:LhQm+AFcgV2M0WyKroMASzAzCAJVpAxQXv4SaI9a69Y=
+github.com/bsm/gomega v1.26.0/go.mod h1:JyEr/xRbxbtgWNi8tIEVPUYZ5Dzef52k01W3YH0H+O0=
+github.com/bufbuild/protocompile v0.14.1 h1:iA73zAf/fyljNjQKwYzUHD6AD4R8KMasmwa/FBatYVw=
+github.com/bufbuild/protocompile v0.14.1/go.mod h1:ppVdAIhbr2H8asPk6k4pY7t9zB1OU5DoEw9xY/FUi1c=
+github.com/cenkalti/backoff/v4 v4.3.0 h1:MyRJ/UdXutAwSAT+s3wNd7MfTIcy71VQueUuFK343L8=
+github.com/cenkalti/backoff/v4 v4.3.0/go.mod h1:Y3VNntkOUPxTVeUxJ/G5vcM//AlwfmyYozVcomhLiZE=
+github.com/census-instrumentation/opencensus-proto v0.2.1/go.mod h1:f6KPmirojxKA12rnyqOA5BBL4O983OfeGPqjHWSTneU=
+github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs=
+github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=
+github.com/chromedp/cdproto v0.0.0-20240919203636-12af5e8a671f h1:dEjjp+iN34En5Pl9XIi978DmR2/CMwuOxoPWtiHixKQ=
+github.com/chromedp/cdproto v0.0.0-20240919203636-12af5e8a671f/go.mod h1:GKljq0VrfU4D5yc+2qA6OVr8pmO/MBbPEWqWQ/oqGEs=
+github.com/chromedp/sysutil v1.0.0 h1:+ZxhTpfpZlmchB58ih/LBHX52ky7w2VhQVKQMucy3Ic=
+github.com/chromedp/sysutil v1.0.0/go.mod h1:kgWmDdq8fTzXYcKIBqIYvRRTnYb9aNS9moAV0xufSww=
+github.com/client9/misspell v0.3.4/go.mod h1:qj6jICC3Q7zFZvVWo7KLAzC3yx5G7kyvSDkc90ppPyw=
+github.com/cncf/udpa/go v0.0.0-20191209042840-269d4d468f6f/go.mod h1:M8M6+tZqaGXZJjfX53e64911xZQV5JYwmTeXPW+k8Sc=
+github.com/cpuguy83/go-md2man/v2 v2.0.1/go.mod h1:tgQtvFlXSQOSOSIRvRPT7W67SCa46tRHOmNcaadrF8o=
+github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
+github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
+github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
+github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f h1:lO4WD4F/rVNCu3HqELle0jiPLLBs70cWOduZpkS1E78=
+github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f/go.mod h1:cuUVRXasLTGF7a8hSLbxyZXjz+1KgoB3wDUb6vlszIc=
+github.com/dlclark/regexp2 v1.11.4 h1:rPYF9/LECdNymJufQKmri9gV604RvvABwgOA8un7yAo=
+github.com/dlclark/regexp2 v1.11.4/go.mod h1:DHkYz0B9wPfa6wondMfaivmHpzrQ3v9q8cnmRbL6yW8=
+github.com/envoyproxy/go-control-plane v0.9.0/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4=
+github.com/envoyproxy/go-control-plane v0.9.1-0.20191026205805-5f8ba28d4473/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4=
+github.com/envoyproxy/go-control-plane v0.9.4/go.mod h1:6rpuAdCZL397s3pYoYcLgu1mIlRU8Am5FuJP05cCM98=
+github.com/envoyproxy/protoc-gen-validate v0.1.0/go.mod h1:iSmxcyjqTsJpI2R4NaDN7+kN2VEUnK/pcBlmesArF7c=
+github.com/evanw/esbuild v0.25.3 h1:4JKyUsm/nHDhpxis4IyWXAi8GiyTwG1WdEp6OhGVE8U=
+github.com/evanw/esbuild v0.25.3/go.mod h1:D2vIQZqV/vIf/VRHtViaUtViZmG7o+kKmlBfVQuRi48=
+github.com/fatih/color v1.18.0 h1:S8gINlzdQ840/4pfAwic/ZE0djQEH3wM94VfqLTZcOM=
+github.com/fatih/color v1.18.0/go.mod h1:4FelSpRwEGDpQ12mAdzqdOukCy4u8WUtOY6lkT/6HfU=
+github.com/fsnotify/fsnotify v1.10.1 h1:b0/UzAf9yR5rhf3RPm9gf3ehBPpf0oZKIjtpKrx59Ho=
+github.com/fsnotify/fsnotify v1.10.1/go.mod h1:TLheqan6HD6GBK6PrDWyDPBaEV8LspOxvPSjC+bVfgo=
+github.com/go-kit/log v0.1.0/go.mod h1:zbhenjAZHb184qTLMA9ZjW7ThYL0H2mk7Q6pNt4vbaY=
+github.com/go-logfmt/logfmt v0.5.0/go.mod h1:wCYkCAKZfumFQihp8CzCvQ3paCTfi41vtzG1KdI/P7A=
+github.com/go-logr/logr v1.2.2/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A=
+github.com/go-logr/logr v1.4.2 h1:6pFjapn8bFcIbiKo3XT4j/BhANplGihG6tvd+8rYgrY=
+github.com/go-logr/logr v1.4.2/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY=
+github.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag=
+github.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE=
+github.com/go-sourcemap/sourcemap v2.1.4+incompatible h1:a+iTbH5auLKxaNwQFg0B+TCYl6lbukKPc7b5x0n1s6Q=
+github.com/go-sourcemap/sourcemap v2.1.4+incompatible/go.mod h1:F8jJfvm2KbVjc5NqelyYJmf/v5J0dwNLS2mL4sNA1Jg=
+github.com/go-stack/stack v1.8.0/go.mod h1:v0f6uXyyMGvRgIKkXu+yp6POWl0qKG85gN/melR3HDY=
+github.com/gogo/protobuf v1.3.2/go.mod h1:P1XiOD3dCwIKUDQYPy72D8LYyHL2YPYrpS2s69NZV8Q=
+github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b/go.mod h1:SBH7ygxi8pfUlaOkMMuAQtPIUF8ecWP5IEl/CR7VP2Q=
+github.com/golang/mock v1.1.1/go.mod h1:oTYuIxOrZwtPieC+H1uAHpcLFnEyAGVDL/k47Jfbm0A=
+github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U=
+github.com/golang/protobuf v1.3.2/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U=
+github.com/golang/protobuf v1.3.3/go.mod h1:vzj43D7+SQXF/4pzW/hwtAqwc6iTitCiVSaWz5lYuqw=
+github.com/golang/protobuf v1.5.4 h1:i7eJL8qZTpSEXOPTxNKhASYpMn+8e5Q6AdndVa1dWek=
+github.com/golang/protobuf v1.5.4/go.mod h1:lnTiLA8Wa4RWRcIUkrtSVa5nRhsEGBg48fD6rSs7xps=
+github.com/google/go-cmp v0.2.0/go.mod h1:oXzfMopK8JAjlY9xF4vHSVASa0yLyX7SntLO5aqRK0M=
+github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
+github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=
+github.com/google/pprof v0.0.0-20250317173921-a4b03ec1a45e h1:ijClszYn+mADRFY17kjQEVQ1XRhq2/JR1M3sGqeJoxs=
+github.com/google/pprof v0.0.0-20250317173921-a4b03ec1a45e/go.mod h1:boTsfXsheKC2y+lKOCMpSfarhxDeIzfZG1jqGcPl3cA=
+github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
+github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
+github.com/gorilla/websocket v1.5.3 h1:saDtZ6Pbx/0u+bgYQ3q96pZgCzfhKXGPqt7kZ72aNNg=
+github.com/gorilla/websocket v1.5.3/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE=
+github.com/grafana/k6build v0.5.11 h1:nuYV5DOMz5PEU8/XFRcDcfgzxUlLujeYNkU7NVEbdfc=
+github.com/grafana/k6build v0.5.11/go.mod h1:SA6/5cnnCLQ99IpFrqVfcuO+SxCRo/yLGtcnj3bfpII=
+github.com/grafana/k6deps v0.2.6 h1:T9t5pGnL4697SJ6fCF36fNCNSFSH/kDBI9Do/W+5TqA=
+github.com/grafana/k6deps v0.2.6/go.mod h1:y+pBsBemOJHML6ObuJFVgcNgO9RSfRvBklltI194aTE=
+github.com/grafana/k6foundry v0.4.6 h1:fFgR72Pw0dzo8wVWyggu35SGGjdt31Dktil1bDE1MCM=
+github.com/grafana/k6foundry v0.4.6/go.mod h1:eLsr0whhH+5Y1y7YpDxJi3Jv5wHMuf+80vdRyMH10pg=
+github.com/grafana/k6provider v0.1.15 h1:aUStpqDMEnEL9aGCcSKmpcreHRZsr8IELna+ttKMOYI=
+github.com/grafana/k6provider v0.1.15/go.mod h1:tnyPNxenfF0G5JWVXQixk7QUJIn2FbZneDfvgocttNs=
+github.com/grafana/sobek v0.0.0-20250320150027-203dc85b6d98 h1:DqWI8D/A8GABIIjukZVNr0Sj4sBeewK2TmbTyiqUAZk=
+github.com/grafana/sobek v0.0.0-20250320150027-203dc85b6d98/go.mod h1:FmcutBFPLiGgroH42I4/HBahv7GxVjODcVWFTw1ISes=
+github.com/grafana/xk6-dashboard v0.7.5 h1:TcILyffT/Ea/XD7xG1jMA5lwtusOPRbEQsQDHmO30Mk=
+github.com/grafana/xk6-dashboard v0.7.5/go.mod h1:Y75F8xmgCraKT+pBzFH6me9AyH5PkXD+Bxo1dm6Il/M=
+github.com/grafana/xk6-redis v0.3.3 h1:9QiS4OUjYMzvriGzbqrhCn9i/kENmCkibZE+xCJSdPk=
+github.com/grafana/xk6-redis v0.3.3/go.mod h1:YL1qfBZXW4o2aAF6/gRa/N9oGoumUg7cJzzCHLxoCOw=
+github.com/grpc-ecosystem/go-grpc-middleware v1.4.0 h1:UH//fgunKIs4JdUbpDl1VZCDaL56wXCB/5+wF6uHfaI=
+github.com/grpc-ecosystem/go-grpc-middleware v1.4.0/go.mod h1:g5qyo/la0ALbONm6Vbp88Yd8NsDy6rZz+RcrMPxvld8=
+github.com/grpc-ecosystem/grpc-gateway/v2 v2.26.1 h1:e9Rjr40Z98/clHv5Yg79Is0NtosR5LXRvdr7o/6NwbA=
+github.com/grpc-ecosystem/grpc-gateway/v2 v2.26.1/go.mod h1:tIxuGz/9mpox++sgp9fJjHO0+q1X9/UOWd798aAm22M=
+github.com/inconshreveable/mousetrap v1.0.0 h1:Z8tu5sraLXCXIcARxBp/8cbvlwVa7Z1NHg9XEKhtSvM=
+github.com/inconshreveable/mousetrap v1.0.0/go.mod h1:PxqpIevigyE2G7u3NXJIT2ANytuPF1OarO4DADm73n8=
+github.com/influxdata/influxdb1-client v0.0.0-20190402204710-8ff2fc3824fc h1:KpMgaYJRieDkHZJWY3LMafvtqS/U8xX6+lUN+OKpl/Y=
+github.com/influxdata/influxdb1-client v0.0.0-20190402204710-8ff2fc3824fc/go.mod h1:qj24IKcXYK6Iy9ceXlo3Tc+vtHo9lIhSX5JddghvEPo=
+github.com/jhump/protoreflect v1.17.0 h1:qOEr613fac2lOuTgWN4tPAtLL7fUSbuJL5X5XumQh94=
+github.com/jhump/protoreflect v1.17.0/go.mod h1:h9+vUUL38jiBzck8ck+6G/aeMX8Z4QUY/NiJPwPNi+8=
+github.com/josharian/intern v1.0.0 h1:vlS4z54oSdjm0bgjRigI+G1HpF+tI+9rE5LLzOg8HmY=
+github.com/josharian/intern v1.0.0/go.mod h1:5DoeVV0s6jJacbCEi61lwdGj/aVlrQvzHFFd8Hwg//Y=
+github.com/kisielk/errcheck v1.5.0/go.mod h1:pFxgyoBC7bSaBwPgfKdkLd5X25qrDl4LWUI2bnpBCr8=
+github.com/kisielk/gotool v1.0.0/go.mod h1:XhKaO+MFFWcvkIS/tQcRk01m1F5IRFswLeQ+oQHNcck=
+github.com/klauspost/compress v1.18.0 h1:c/Cqfb0r+Yi+JtIEq73FWXVkRonBlf0CRNYc8Zttxdo=
+github.com/klauspost/compress v1.18.0/go.mod h1:2Pp+KzxcywXVXMr50+X0Q/Lsb43OQHYWRCY2AiWywWQ=
+github.com/konsorten/go-windows-terminal-sequences v1.0.1/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ=
+github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo=
+github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=
+github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=
+github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ=
+github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI=
+github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
+github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=
+github.com/mailru/easyjson v0.9.0 h1:PrnmzHw7262yW8sTBwxi1PdJA3Iw/EKBa8psRf7d9a4=
+github.com/mailru/easyjson v0.9.0/go.mod h1:1+xMtQp2MRNVL/V1bOzuP3aP8VNwRW55fQUto+XFtTU=
+github.com/mattn/go-colorable v0.1.14 h1:9A9LHSqF/7dyVVX6g0U9cwm9pG3kP9gSzcuIPHPsaIE=
+github.com/mattn/go-colorable v0.1.14/go.mod h1:6LmQG8QLFO4G5z1gPvYEzlUgJ2wF+stgPZH1UqBm1s8=
+github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=
+github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
+github.com/mattn/go-sqlite3 v1.14.24 h1:tpSp2G2KyMnnQu99ngJ47EIkWVmliIizyZBfPrBWDRM=
+github.com/mattn/go-sqlite3 v1.14.24/go.mod h1:Uh1q+B4BYcTPb+yiD3kU8Ct7aC0hY9fxUwlHK0RXw+Y=
+github.com/matttproud/golang_protobuf_extensions v1.0.4 h1:mmDVorXM7PCGKw94cs5zkfA9PSy5pEvNWRP0ET0TIVo=
+github.com/matttproud/golang_protobuf_extensions v1.0.4/go.mod h1:BSXmuO+STAnVfrANrmjBb36TMTDstsz7MSK+HVaYKv4=
+github.com/mccutchen/go-httpbin v1.1.2-0.20190116014521-c5cb2f4802fa h1:lx8ZnNPwjkXSzOROz0cg69RlErRXs+L3eDkggASWKLo=
+github.com/mccutchen/go-httpbin v1.1.2-0.20190116014521-c5cb2f4802fa/go.mod h1:fhpOYavp5g2K74XDl/ao2y4KvhqVtKlkg1e+0UaQv7I=
+github.com/mstoykov/atlas v0.0.0-20220811071828-388f114305dd h1:AC3N94irbx2kWGA8f/2Ks7EQl2LxKIRQYuT9IJDwgiI=
+github.com/mstoykov/atlas v0.0.0-20220811071828-388f114305dd/go.mod h1:9vRHVuLCjoFfE3GT06X0spdOAO+Zzo4AMjdIwUHBvAk=
+github.com/mstoykov/envconfig v1.5.0 h1:E2FgWf73BQt0ddgn7aoITkQHmgwAcHup1s//MsS5/f8=
+github.com/mstoykov/envconfig v1.5.0/go.mod h1:vk/d9jpexY2Z9Bb0uB4Ndesss1Sr0Z9ZiGUrg5o9VGk=
+github.com/mstoykov/k6-taskqueue-lib v0.1.3 h1:sdiSc5NEK/qpQkTQe505vgRYQocZevdO9ON+yMudFqo=
+github.com/mstoykov/k6-taskqueue-lib v0.1.3/go.mod h1:e9R2vtLFHCKT+CMiEjTJVMQiJAi17M1KiXXRs7FYc6w=
+github.com/nu7hatch/gouuid v0.0.0-20131221200532-179d4d0c4d8d h1:VhgPp6v9qf9Agr/56bj7Y/xa04UccTW04VP0Qed4vnQ=
+github.com/nu7hatch/gouuid v0.0.0-20131221200532-179d4d0c4d8d/go.mod h1:YUTz3bUH2ZwIWBy3CJBeOBEugqcmXREj14T+iG/4k4U=
+github.com/nxadm/tail v1.4.11 h1:8feyoE3OzPrcshW5/MJ4sGESc5cqmGkGCWlco4l0bqY=
+github.com/nxadm/tail v1.4.11/go.mod h1:OTaG3NK980DZzxbRq6lEuzgU+mug70nY11sMd4JXXHc=
+github.com/onsi/ginkgo v1.16.5 h1:8xi0RTUf59SOSfEtZMvwTvXYMzG4gV23XVHOZiXNtnE=
+github.com/onsi/ginkgo v1.16.5/go.mod h1:+E8gABHa3K6zRBolWtd+ROzc/U5bkGt0FwiG042wbpU=
+github.com/onsi/gomega v1.33.0 h1:snPCflnZrpMsy94p4lXVEkHo12lmPnc3vY5XBbreexE=
+github.com/onsi/gomega v1.33.0/go.mod h1:+925n5YtiFsLzzafLUHzVMBpvvRAzrydIBiSIxjX3wY=
+github.com/opentracing/opentracing-go v1.1.0/go.mod h1:UkNAQd3GIcIGf0SeVgPpRdFStlNbqXla1AfSYxPUl2o=
+github.com/pkg/browser v0.0.0-20210911075715-681adbf594b8 h1:KoWmjvw+nsYOo29YJK9vDA65RGE3NrOnUtO7a+RF9HU=
+github.com/pkg/browser v0.0.0-20210911075715-681adbf594b8/go.mod h1:HKlIX3XHQyzLZPlr7++PzdhaXEj94dEiJgZDTsxEqUI=
+github.com/pkg/errors v0.8.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
+github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
+github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
+github.com/prometheus/client_golang v1.16.0 h1:yk/hx9hDbrGHovbci4BY+pRMfSuuat626eFsHb7tmT8=
+github.com/prometheus/client_golang v1.16.0/go.mod h1:Zsulrv/L9oM40tJ7T815tM89lFEugiJ9HzIqaAx4LKc=
+github.com/prometheus/client_model v0.0.0-20190812154241-14fe0d1b01d4/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA=
+github.com/prometheus/client_model v0.4.0 h1:5lQXD3cAg1OXBf4Wq03gTrXHeaV0TQvGfUooCfx1yqY=
+github.com/prometheus/client_model v0.4.0/go.mod h1:oMQmHW1/JoDwqLtg57MGgP/Fb1CJEYF2imWWhWtMkYU=
+github.com/prometheus/common v0.42.0 h1:EKsfXEYo4JpWMHH5cg+KOUWeuJSov1Id8zGR8eeI1YM=
+github.com/prometheus/common v0.42.0/go.mod h1:xBwqVerjNdUDjgODMpudtOMwlOwf2SaTr1yjz4b7Zbc=
+github.com/prometheus/procfs v0.10.1 h1:kYK1Va/YMlutzCGazswoHKo//tZVlFpKYh+PymziUAg=
+github.com/prometheus/procfs v0.10.1/go.mod h1:nwNm2aOCAYw8uTR/9bWRREkZFxAUcWzPHWJq+XBB/FM=
+github.com/r3labs/sse/v2 v2.10.0 h1:hFEkLLFY4LDifoHdiCN/LlGBAdVJYsANaLqNYa1l/v0=
+github.com/r3labs/sse/v2 v2.10.0/go.mod h1:Igau6Whc+F17QUgML1fYe1VPZzTV6EMCnYktEmkNJ7I=
+github.com/redis/go-redis/v9 v9.0.5 h1:CuQcn5HIEeK7BgElubPP8CGtE0KakrnbBSTLjathl5o=
+github.com/redis/go-redis/v9 v9.0.5/go.mod h1:WqMKv5vnQbRuZstUwxQI195wHy+t4PuXDOjzMvcuQHk=
+github.com/rogpeppe/go-internal v1.13.1 h1:KvO1DLK/DRN07sQ1LQKScxyZJuNnedQ5/wKSR38lUII=
+github.com/rogpeppe/go-internal v1.13.1/go.mod h1:uMEvuHeurkdAXX61udpOXGD/AzZDWNMNyH2VO9fmH0o=
+github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM=
+github.com/serenize/snaker v0.0.0-20201027110005-a7ad2135616e h1:zWKUYT07mGmVBH+9UgnHXd/ekCK99C8EbDSAt5qsjXE=
+github.com/serenize/snaker v0.0.0-20201027110005-a7ad2135616e/go.mod h1:Yow6lPLSAXx2ifx470yD/nUe22Dv5vBvxK/UK9UUTVs=
+github.com/sirupsen/logrus v1.4.2/go.mod h1:tLMulIdttU9McNUspp0xgXVQah82FyeX6MwdIuYE2rE=
+github.com/sirupsen/logrus v1.9.3 h1:dueUQJ1C2q9oE3F7wvmSGAaVtTmUizReu6fjN8uqzbQ=
+github.com/sirupsen/logrus v1.9.3/go.mod h1:naHLuLoDiP4jHNo9R0sCBMtWGeIprob74mVsIT4qYEQ=
+github.com/spf13/afero v1.1.2 h1:m8/z1t7/fwjysjQRYbP0RD+bUIF/8tJwPdEZsI83ACI=
+github.com/spf13/afero v1.1.2/go.mod h1:j4pytiNVoe2o6bmDsKpLACNPDBIoEAkihy7loJ1B0CQ=
+github.com/spf13/cobra v1.4.0 h1:y+wJpx64xcgO1V+RcnwW0LEHxTKRi2ZDPSBjWnrg88Q=
+github.com/spf13/cobra v1.4.0/go.mod h1:Wo4iy3BUC+X2Fybo0PDqwJIv3dNRiZLHQymsfxlB84g=
+github.com/spf13/pflag v1.0.5 h1:iy+VFUOCP1a+8yFto/drg2CJ5u0yRoB7fZw3DKv/JXA=
+github.com/spf13/pflag v1.0.5/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=
+github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
+github.com/stretchr/objx v0.1.1/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
+github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs=
+github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
+github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4=
+github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
+github.com/stretchr/testify v1.10.0 h1:Xv5erBjTwe/5IxqUQTdXv5kgmIvbHo3QQyRwhJsOfJA=
+github.com/stretchr/testify v1.10.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
+github.com/tidwall/gjson v1.18.0 h1:FIDeeyB800efLX89e5a8Y0BNH+LOngJyGrIWxG2FKQY=
+github.com/tidwall/gjson v1.18.0/go.mod h1:/wbyibRr2FHMks5tjHJ5F8dMZh3AcwJEMf5vlfC0lxk=
+github.com/tidwall/match v1.1.1 h1:+Ho715JplO36QYgwN9PGYNhgZvoUSc9X2c80KVTi+GA=
+github.com/tidwall/match v1.1.1/go.mod h1:eRSPERbgtNPcGhD8UCthc6PmLEQXEWd3PRB5JTxsfmM=
+github.com/tidwall/pretty v1.2.0/go.mod h1:ITEVvHYasfjBbM0u2Pg8T2nJnzm8xPwvNhhsoaGGjNU=
+github.com/tidwall/pretty v1.2.1 h1:qjsOFOWWQl+N3RsoF5/ssm1pHmJJwhjlSbZ51I6wMl4=
+github.com/tidwall/pretty v1.2.1/go.mod h1:ITEVvHYasfjBbM0u2Pg8T2nJnzm8xPwvNhhsoaGGjNU=
+github.com/xyproto/randomstring v1.0.5 h1:YtlWPoRdgMu3NZtP45drfy1GKoojuR7hmRcnhZqKjWU=
+github.com/xyproto/randomstring v1.0.5/go.mod h1:rgmS5DeNXLivK7YprL0pY+lTuhNQW3iGxZ18UQApw/E=
+github.com/yuin/goldmark v1.1.27/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74=
+github.com/yuin/goldmark v1.2.1/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74=
+github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY=
+go.k6.io/k6 v1.0.0 h1:m03ILf6kubhhM0h8NTc6J6ifqW8ljX6a2PFOiH7WWBw=
+go.k6.io/k6 v1.0.0/go.mod h1:7yI5PDHfF68jrSXJnqsaD6muxFt+3Ru+bjBCJW8KAcs=
+go.opentelemetry.io/auto/sdk v1.1.0 h1:cH53jehLUN6UFLY71z+NDOiNJqDdPRaXzTel0sJySYA=
+go.opentelemetry.io/auto/sdk v1.1.0/go.mod h1:3wSPjt5PWp2RhlCcmmOial7AvC4DQqZb7a7wCow3W8A=
+go.opentelemetry.io/otel v1.35.0 h1:xKWKPxrxB6OtMCbmMY021CqC45J+3Onta9MqjhnusiQ=
+go.opentelemetry.io/otel v1.35.0/go.mod h1:UEqy8Zp11hpkUrL73gSlELM0DupHoiq72dR+Zqel/+Y=
+go.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetricgrpc v1.35.0 h1:QcFwRrZLc82r8wODjvyCbP7Ifp3UANaBSmhDSFjnqSc=
+go.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetricgrpc v1.35.0/go.mod h1:CXIWhUomyWBG/oY2/r/kLp6K/cmx9e/7DLpBuuGdLCA=
+go.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetrichttp v1.35.0 h1:0NIXxOCFx+SKbhCVxwl3ETG8ClLPAa0KuKV6p3yhxP8=
+go.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetrichttp v1.35.0/go.mod h1:ChZSJbbfbl/DcRZNc9Gqh6DYGlfjw4PvO1pEOZH1ZsE=
+go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.35.0 h1:1fTNlAIJZGWLP5FVu0fikVry1IsiUnXjf7QFvoNN3Xw=
+go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.35.0/go.mod h1:zjPK58DtkqQFn+YUMbx0M2XV3QgKU0gS9LeGohREyK4=
+go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.35.0 h1:m639+BofXTvcY1q8CGs4ItwQarYtJPOWmVobfM1HpVI=
+go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.35.0/go.mod h1:LjReUci/F4BUyv+y4dwnq3h/26iNOeC3wAIqgvTIZVo=
+go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.35.0 h1:xJ2qHD0C1BeYVTLLR9sX12+Qb95kfeD/byKj6Ky1pXg=
+go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.35.0/go.mod h1:u5BF1xyjstDowA1R5QAO9JHzqK+ublenEW/dyqTjBVk=
+go.opentelemetry.io/otel/metric v1.35.0 h1:0znxYu2SNyuMSQT4Y9WDWej0VpcsxkuklLa4/siN90M=
+go.opentelemetry.io/otel/metric v1.35.0/go.mod h1:nKVFgxBZ2fReX6IlyW28MgZojkoAkJGaE8CpgeAU3oE=
+go.opentelemetry.io/otel/sdk v1.35.0 h1:iPctf8iprVySXSKJffSS79eOjl9pvxV9ZqOWT0QejKY=
+go.opentelemetry.io/otel/sdk v1.35.0/go.mod h1:+ga1bZliga3DxJ3CQGg3updiaAJoNECOgJREo9KHGQg=
+go.opentelemetry.io/otel/sdk/metric v1.35.0 h1:1RriWBmCKgkeHEhM7a2uMjMUfP7MsOF5JpUCaEqEI9o=
+go.opentelemetry.io/otel/sdk/metric v1.35.0/go.mod h1:is6XYCUMpcKi+ZsOvfluY5YstFnhW0BidkR+gL+qN+w=
+go.opentelemetry.io/otel/trace v1.35.0 h1:dPpEfJu1sDIqruz7BHFG3c7528f6ddfSWfFDVt/xgMs=
+go.opentelemetry.io/otel/trace v1.35.0/go.mod h1:WUk7DtFp1Aw2MkvqGdwiXYDZZNvA/1J8o6xRXLrIkyc=
+go.opentelemetry.io/proto/otlp v1.5.0 h1:xJvq7gMzB31/d406fB8U5CBdyQGw4P399D1aQWU/3i4=
+go.opentelemetry.io/proto/otlp v1.5.0/go.mod h1:keN8WnHxOy8PG0rQZjJJ5A2ebUoafqWp0eVQ4yIXvJ4=
+go.uber.org/atomic v1.7.0/go.mod h1:fEN4uk6kAWBTFdckzkM89CLk9XfWZrxpCo0nPH17wJc=
+go.uber.org/goleak v1.1.10/go.mod h1:8a7PlsEVH3e/a/GLqe5IIrQx6GzcnRmZEufDUTk4A7A=
+go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto=
+go.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE=
+go.uber.org/multierr v1.6.0/go.mod h1:cdWPpRnG4AhwMwsgIHip0KRBQjJy5kYEpYjJxpXp9iU=
+go.uber.org/zap v1.18.1/go.mod h1:xg/QME4nWcxGxrpdeYfq7UvYrLh66cuVKdrbD1XF/NI=
+golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
+golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
+golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=
+golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc=
+golang.org/x/crypto v0.37.0 h1:kJNSjF/Xp7kU0iB2Z+9viTPMW4EqqsrywMXLJOOsXSE=
+golang.org/x/crypto v0.37.0/go.mod h1:vg+k43peMZ0pUMhYmVAWysMK35e6ioLh3wB8ZCAfbVc=
+golang.org/x/crypto/x509roots/fallback v0.0.0-20250414110644-0091fc8e7c69 h1:yMbJozT8oiQBENoJ9L7TCSZb6wJJAMDUnoIaHHvoEss=
+golang.org/x/crypto/x509roots/fallback v0.0.0-20250414110644-0091fc8e7c69/go.mod h1:lxN5T34bK4Z/i6cMaU7frUU57VkDXFD4Kamfl/cp9oU=
+golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA=
+golang.org/x/lint v0.0.0-20181026193005-c67002cb31c3/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE=
+golang.org/x/lint v0.0.0-20190227174305-5b3e6a55c961/go.mod h1:wehouNa3lNwaWXcvxsM5YxQ5yQlVC4a0KAMCusXpPoU=
+golang.org/x/lint v0.0.0-20190313153728-d0100b6bd8b3/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc=
+golang.org/x/lint v0.0.0-20190930215403-16217165b5de/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc=
+golang.org/x/mod v0.2.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA=
+golang.org/x/mod v0.3.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA=
+golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4=
+golang.org/x/mod v0.8.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs=
+golang.org/x/mod v0.23.0 h1:Zb7khfcRGKk+kqfxFaP5tZqCnDZMjC5VtUBs87Hr6QM=
+golang.org/x/mod v0.23.0/go.mod h1:6SkKJ3Xj0I0BrPOZoBy3bdMptDDU9oJrpohJ3eWZ1fY=
+golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
+golang.org/x/net v0.0.0-20180826012351-8a410e7b638d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
+golang.org/x/net v0.0.0-20190213061140-3a22650c66bd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
+golang.org/x/net v0.0.0-20190311183353-d8887717615a/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
+golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
+golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
+golang.org/x/net v0.0.0-20191116160921-f9c825593386/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
+golang.org/x/net v0.0.0-20200226121028-0de0cce0169b/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
+golang.org/x/net v0.0.0-20201021035429-f5854403a974/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU=
+golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg=
+golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c=
+golang.org/x/net v0.6.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs=
+golang.org/x/net v0.9.0/go.mod h1:d48xBJpPfHeWQsugry2m+kC02ZBRGRgulfHnEXEuWns=
+golang.org/x/net v0.39.0 h1:ZCu7HMWDxpXpaiKdhzIfaltL9Lp31x/3fCP11bc6/fY=
+golang.org/x/net v0.39.0/go.mod h1:X7NRbYVEA+ewNkCNyJ513WmMdQ3BineSwVtN2zD/d+E=
+golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U=
+golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
+golang.org/x/sync v0.0.0-20181108010431-42b317875d0f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
+golang.org/x/sync v0.0.0-20181221193216-37e7f081c4d4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
+golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
+golang.org/x/sync v0.0.0-20190911185100-cd5d95a43a6e/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
+golang.org/x/sync v0.0.0-20201020160332-67f06af15bc9/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
+golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
+golang.org/x/sync v0.1.0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
+golang.org/x/sync v0.13.0 h1:AauUjRAJ9OSnvULf/ARrrVywoJDy0YS2AwQ98I37610=
+golang.org/x/sync v0.13.0/go.mod h1:1dzgHSNfp02xaA81J2MS99Qcpr2w7fw1gpm99rleRqA=
+golang.org/x/sys v0.0.0-20180830151530-49385e6e1522/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
+golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
+golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
+golang.org/x/sys v0.0.0-20190422165155-953cdadca894/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
+golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
+golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
+golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
+golang.org/x/sys v0.0.0-20210616045830-e2b7044e8c71/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
+golang.org/x/sys v0.0.0-20211025201205-69cdffdb9359/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
+golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
+golang.org/x/sys v0.0.0-20220715151400-c0bba94af5f8/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
+golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
+golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
+golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
+golang.org/x/sys v0.7.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
+golang.org/x/sys v0.32.0 h1:s77OFDvIQeibCmezSnk/q6iAfkdiQaJi4VzroCFrN20=
+golang.org/x/sys v0.32.0/go.mod h1:BJP2sWEmIv4KK5OTEluFJCKSidICx8ciO85XgH3Ak8k=
+golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
+golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8=
+golang.org/x/term v0.5.0/go.mod h1:jMB1sMXY+tzblOD4FWmEbocvup2/aLOaQEp7JmGp78k=
+golang.org/x/term v0.7.0/go.mod h1:P32HKFT3hSsZrRxla30E9HqToFYAQPCMs/zFMBUFqPY=
+golang.org/x/term v0.31.0 h1:erwDkOK1Msy6offm1mOgvspSkslFnIGsFnxOKoufg3o=
+golang.org/x/term v0.31.0/go.mod h1:R4BeIy7D95HzImkxGkTW1UQTtP54tio2RyHz7PwK0aw=
+golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
+golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
+golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ=
+golang.org/x/text v0.7.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8=
+golang.org/x/text v0.9.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8=
+golang.org/x/text v0.24.0 h1:dd5Bzh4yt5KYA8f9CJHCP4FB4D51c2c6JvN37xJJkJ0=
+golang.org/x/text v0.24.0/go.mod h1:L8rBsPeo2pSS+xqN0d5u2ikmjtmoJbDBT1b7nHvFCdU=
+golang.org/x/time v0.11.0 h1:/bpjEDfN9tkoN/ryeYHnv5hcMlc8ncjMcM4XBk5NWV0=
+golang.org/x/time v0.11.0/go.mod h1:CDIdPxbZBQxdj6cxyCIdrNogrJKMJ7pr37NYpMcMDSg=
+golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
+golang.org/x/tools v0.0.0-20190114222345-bf090417da8b/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
+golang.org/x/tools v0.0.0-20190226205152-f727befe758c/go.mod h1:9Yl7xja0Znq3iFh3HoIrodX9oNMXvdceNzlUR8zjMvY=
+golang.org/x/tools v0.0.0-20190311212946-11955173bddd/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs=
+golang.org/x/tools v0.0.0-20190524140312-2c0ae7006135/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q=
+golang.org/x/tools v0.0.0-20191108193012-7d206e10da11/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
+golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
+golang.org/x/tools v0.0.0-20200619180055-7c47624df98f/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE=
+golang.org/x/tools v0.0.0-20210106214847-113979e3529a/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA=
+golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc=
+golang.org/x/tools v0.6.0/go.mod h1:Xwgl3UAJ/d3gWutnCtw505GrjyAbvKui8lOU390QaIU=
+golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
+golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
+golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
+golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
+google.golang.org/appengine v1.1.0/go.mod h1:EbEs0AVv82hx2wNQdGPgUI5lhzA/G0D9YwlJXL52JkM=
+google.golang.org/appengine v1.4.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4=
+google.golang.org/genproto v0.0.0-20180817151627-c66870c02cf8/go.mod h1:JiN7NxoALGmiZfu7CAH4rXhgtRTLTxftemlI0sWmxmc=
+google.golang.org/genproto v0.0.0-20190819201941-24fa4b261c55/go.mod h1:DMBHOl98Agz4BDEuKkezgsaosCRResVns1a3J2ZsMNc=
+google.golang.org/genproto v0.0.0-20200423170343-7949de9c1215/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c=
+google.golang.org/genproto/googleapis/api v0.0.0-20250218202821-56aae31c358a h1:nwKuGPlUAt+aR+pcrkfFRrTU1BVrSmYyYMxYbUIVHr0=
+google.golang.org/genproto/googleapis/api v0.0.0-20250218202821-56aae31c358a/go.mod h1:3kWAYMk1I75K4vykHtKt2ycnOgpA6974V7bREqbsenU=
+google.golang.org/genproto/googleapis/rpc v0.0.0-20250218202821-56aae31c358a h1:51aaUVRocpvUOSQKM6Q7VuoaktNIaMCLuhZB6DKksq4=
+google.golang.org/genproto/googleapis/rpc v0.0.0-20250218202821-56aae31c358a/go.mod h1:uRxBH1mhmO8PGhU89cMcHaXKZqO+OfakD8QQO0oYwlQ=
+google.golang.org/grpc v1.19.0/go.mod h1:mqu4LbDTu4XGKhr4mRzUsmM4RtVoemTSY81AxZiDr8c=
+google.golang.org/grpc v1.23.0/go.mod h1:Y5yQAOtifL1yxbo5wqy6BxZv8vAUGQwXBOALyacEbxg=
+google.golang.org/grpc v1.25.1/go.mod h1:c3i+UQWmh7LiEpx4sFZnkU36qjEYZ0imhYfXVyQciAY=
+google.golang.org/grpc v1.27.0/go.mod h1:qbnxyOmOxrQa7FizSgH+ReBfzJrCY1pSN7KXBS8abTk=
+google.golang.org/grpc v1.29.1/go.mod h1:itym6AZVZYACWQqET3MqgPpjcuV5QH3BxFS3IjizoKk=
+google.golang.org/grpc v1.71.1 h1:ffsFWr7ygTUscGPI0KKK6TLrGz0476KUvvsbqWK0rPI=
+google.golang.org/grpc v1.71.1/go.mod h1:H0GRtasmQOh9LkFoCPDu3ZrwUtD1YGE+b2vYBYd/8Ec=
+google.golang.org/protobuf v1.36.6 h1:z1NpPI8ku2WgiWnf+t9wTPsn6eP1L7ksHUlkfLvd9xY=
+google.golang.org/protobuf v1.36.6/go.mod h1:jduwjTPXsFjZGTmRluh+L6NjiWu7pchiJ2/5YcXBHnY=
+gopkg.in/cenkalti/backoff.v1 v1.1.0 h1:Arh75ttbsvlpVA7WtVpH4u9h6Zl46xuptxqLxPiSo4Y=
+gopkg.in/cenkalti/backoff.v1 v1.1.0/go.mod h1:J6Vskwqd+OMVJl8C33mmtxTBs2gyzfv7UDAkHu8BrjI=
+gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
+gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
+gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=
+gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=
+gopkg.in/guregu/null.v3 v3.3.0 h1:8j3ggqq+NgKt/O7mbFVUFKUMWN+l1AmT5jQmJ6nPh2c=
+gopkg.in/guregu/null.v3 v3.3.0/go.mod h1:E4tX2Qe3h7QdL+uZ3a0vqvYwKQsRSQKM5V4YltdgH9Y=
+gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7 h1:uRGJdciOHaEIrze2W8Q3AKkepLTh2hOroT7a+7czfdQ=
+gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7/go.mod h1:dt/ZhP58zS4L8KSrWDmTeBkI65Dw0HsyUHuEVlX15mw=
+gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
+gopkg.in/yaml.v2 v2.2.8/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
+gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY=
+gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ=
+gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
+gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
+gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
+gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
+honnef.co/go/tools v0.0.0-20190102054323-c2f93a96b099/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4=
+honnef.co/go/tools v0.0.0-20190523083050-ea95bdfd59fc/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4=
diff --git a/loadtest/k6/scenario-mix/recorder/payment.sql b/loadtest/k6/scenario-mix/recorder/payment.sql
new file mode 100644
index 0000000000..4f6cde423e
--- /dev/null
+++ b/loadtest/k6/scenario-mix/recorder/payment.sql
@@ -0,0 +1,9 @@
+INSERT INTO payments
+(run_id,payment_id,merchant_id,customer_id,amount,status,role,api_status_code,request_id,message,observed_at,response_event_id)
+VALUES (?,?,?,?,?,?,?,?,?,?,?,?)
+ON CONFLICT(run_id,payment_id) DO UPDATE SET
+ customer_id=COALESCE(excluded.customer_id,payments.customer_id),
+ amount=COALESCE(excluded.amount,payments.amount),status=COALESCE(excluded.status,payments.status),
+ api_status_code=excluded.api_status_code,request_id=excluded.request_id,
+ message=excluded.message,observed_at=excluded.observed_at,response_event_id=excluded.response_event_id
+WHERE excluded.observed_at > payments.observed_at OR (excluded.observed_at = payments.observed_at AND excluded.response_event_id > payments.response_event_id)
diff --git a/loadtest/k6/scenario-mix/recorder/progress.go b/loadtest/k6/scenario-mix/recorder/progress.go
new file mode 100644
index 0000000000..e276ec13bd
--- /dev/null
+++ b/loadtest/k6/scenario-mix/recorder/progress.go
@@ -0,0 +1,244 @@
+package recorder
+
+import (
+ "encoding/json"
+ "math"
+ "os"
+ "sort"
+ "strings"
+ "sync"
+ "time"
+
+ "go.k6.io/k6/metrics"
+)
+
+// Live telemetry contains counters and one bounded latency window, never responses.
+type flowProgress struct {
+ ServerP99 *float64 `json:"server_p99_ms"`
+ ServerSamples []float64 `json:"server_samples_ms,omitempty"`
+ serverLatencies []float64
+ Successes uint64 `json:"successes"`
+ Failures uint64 `json:"failures"`
+ TPS float64 `json:"tps"`
+ P90 *float64 `json:"p90_ms"`
+ P99 *float64 `json:"p99_ms"`
+ windowSuccess uint64
+ latencies []float64
+}
+type connectorProgress struct {
+ Assigned uint64 `json:"assigned"`
+ Confirmed uint64 `json:"confirmed"`
+ Successes uint64 `json:"successes"`
+}
+type liveProgress struct {
+ ServerP99 *float64 `json:"server_p99_ms"`
+ ServerSamples []float64 `json:"server_samples_ms,omitempty"`
+ P99 *float64 `json:"p99_ms"`
+ Elapsed float64 `json:"elapsed_seconds"`
+ Iterations uint64 `json:"iterations"`
+ Dropped uint64 `json:"dropped"`
+ HTTPAttempts uint64 `json:"http_attempts"`
+ HTTPErrors uint64 `json:"http_errors"`
+ ConfirmHTTPAttempts uint64 `json:"confirm_http_attempts"`
+ ConfirmHTTPErrors uint64 `json:"confirm_http_errors"`
+ SuccessfulTPS float64 `json:"successful_tps"`
+ Recorder Stats `json:"recorder"`
+ Connectors map[string]*connectorProgress `json:"connectors,omitempty"`
+ Flows map[string]*flowProgress `json:"flows"`
+ Control *controlSnapshot `json:"control,omitempty"`
+}
+type progressCollector struct {
+ mu sync.Mutex
+ started, previous time.Time
+ state liveProgress
+ latencies []float64
+ serverLatencies []float64
+}
+
+// newProgressCollector initializes run counters and per-flow buckets from
+// scenario metadata. Unknown flow names are not added during sample collection.
+func newProgressCollector(metadata map[string]interface{}) *progressCollector {
+ p := &progressCollector{started: time.Now(), previous: time.Now()}
+ p.state.Flows = map[string]*flowProgress{}
+ p.state.Connectors = map[string]*connectorProgress{}
+ if scenarios, ok := metadata["scenarios"].([]interface{}); ok {
+ for _, raw := range scenarios {
+ if f, ok := raw.(map[string]interface{}); ok {
+ if name, ok := f["name"].(string); ok {
+ p.state.Flows[name] = &flowProgress{}
+ }
+ }
+ }
+ }
+ return p
+}
+
+// add aggregates k6 counters and payment-confirm latency samples under p.mu.
+// Latency buffers retain at most 8,192 samples per window; only configured flow
+// names contribute per-flow totals, preventing phase metrics from double counting.
+func (p *progressCollector) add(containers []metrics.SampleContainer) {
+ p.mu.Lock()
+ defer p.mu.Unlock()
+ for _, container := range containers {
+ for _, sample := range container.GetSamples() {
+ name := sample.Metric.Name
+ switch name {
+ case "connector_assigned", "connector_confirmed", "connector_succeeded":
+ if sample.Tags != nil {
+ if connector, ok := sample.Tags.Get("connector"); ok && connector != "" {
+ c := p.state.Connectors[connector]
+ if c == nil {
+ c = &connectorProgress{}
+ p.state.Connectors[connector] = c
+ }
+ switch name {
+ case "connector_assigned":
+ c.Assigned += uint64(sample.Value)
+ case "connector_confirmed":
+ c.Confirmed += uint64(sample.Value)
+ case "connector_succeeded":
+ c.Successes += uint64(sample.Value)
+ }
+ }
+ }
+ case "payment_confirm_server_latency_ms":
+ if sample.Value >= 0 && !math.IsNaN(sample.Value) && !math.IsInf(sample.Value, 0) && len(p.serverLatencies) < 8192 {
+ p.serverLatencies = append(p.serverLatencies, sample.Value)
+ }
+ case "payment_confirm_latency_ms":
+ if len(p.latencies) < 8192 {
+ p.latencies = append(p.latencies, sample.Value)
+ }
+ case "iterations":
+ p.state.Iterations += uint64(sample.Value)
+ case "dropped_iterations":
+ p.state.Dropped += uint64(sample.Value)
+ case "http_reqs":
+ p.state.HTTPAttempts += uint64(sample.Value)
+ if sample.Tags != nil {
+ if operation, ok := sample.Tags.Get("operation"); ok && operation == "payment_confirm" {
+ p.state.ConfirmHTTPAttempts += uint64(sample.Value)
+ }
+ }
+ case "http_req_failed":
+ if sample.Value > 0 {
+ p.state.HTTPErrors++
+ if sample.Tags != nil {
+ if operation, ok := sample.Tags.Get("operation"); ok && operation == "payment_confirm" {
+ p.state.ConfirmHTTPErrors++
+ }
+ }
+ }
+ default:
+ if strings.HasPrefix(name, "scenario_success_") {
+ if f := p.state.Flows[strings.TrimPrefix(name, "scenario_success_")]; f != nil {
+ f.Successes += uint64(sample.Value)
+ f.windowSuccess += uint64(sample.Value)
+ }
+ }
+ if strings.HasPrefix(name, "scenario_failure_") {
+ if f := p.state.Flows[strings.TrimPrefix(name, "scenario_failure_")]; f != nil {
+ f.Failures += uint64(sample.Value)
+ }
+ }
+ if strings.HasPrefix(name, "payment_confirm_server_ms_") {
+ if f := p.state.Flows[strings.TrimPrefix(name, "payment_confirm_server_ms_")]; f != nil && sample.Value >= 0 && !math.IsNaN(sample.Value) && !math.IsInf(sample.Value, 0) && len(f.serverLatencies) < 8192 {
+ f.serverLatencies = append(f.serverLatencies, sample.Value)
+ }
+ }
+ if strings.HasPrefix(name, "payment_confirm_ms_") {
+ if f := p.state.Flows[strings.TrimPrefix(name, "payment_confirm_ms_")]; f != nil && len(f.latencies) < 8192 {
+ f.latencies = append(f.latencies, sample.Value)
+ }
+ }
+ }
+ }
+ }
+}
+
+// bytes serializes live progress with the supplied recorder counters.
+// Cumulative counts are retained, while TPS deltas and latency buffers reset
+// after each publication; empty windows emit unavailable latency rather than zero.
+func (p *progressCollector) bytes(stats Stats) []byte {
+ p.mu.Lock()
+ defer p.mu.Unlock()
+ now := time.Now()
+ seconds := now.Sub(p.previous).Seconds()
+ p.previous = now
+ p.state.Elapsed = now.Sub(p.started).Seconds()
+ p.state.Recorder = stats
+ p.state.SuccessfulTPS = 0
+ p.state.ServerP99 = serverPercentile(p.serverLatencies)
+ p.state.ServerSamples = p.serverLatencies
+ p.serverLatencies = p.serverLatencies[:0]
+ p.state.P99 = nil
+ if len(p.latencies) > 0 {
+ sort.Float64s(p.latencies)
+ value := p.latencies[int(float64(len(p.latencies)-1)*0.99)]
+ p.state.P99 = &value
+ p.latencies = p.latencies[:0]
+ }
+ for _, f := range p.state.Flows {
+ f.TPS = float64(f.windowSuccess) / seconds
+ f.windowSuccess = 0
+ p.state.SuccessfulTPS += f.TPS
+ f.ServerP99 = serverPercentile(f.serverLatencies)
+ f.ServerSamples = f.serverLatencies
+ f.serverLatencies = f.serverLatencies[:0]
+ f.P90 = nil
+ f.P99 = nil
+ if len(f.latencies) > 0 {
+ sort.Float64s(f.latencies)
+ value := f.latencies[int(float64(len(f.latencies)-1)*0.9)]
+ f.P90 = &value
+ p99 := f.latencies[int(float64(len(f.latencies)-1)*0.99)]
+ f.P99 = &p99
+ f.latencies = f.latencies[:0]
+ }
+ }
+ raw, _ := json.Marshal(p.state)
+ return raw
+}
+
+// writeProgress combines live metrics with recorder and optional controller
+// state, then atomically replaces the progress file. Controller counters override
+// k6 scheduling totals; write failures fail the recorder rather than leaving
+// telemetry loss unreported.
+func (o *sqliteOutput) writeProgress() {
+ if o.progressFile == "" {
+ return
+ }
+ raw := o.progress.bytes(o.writer.Snapshot())
+ if o.control != nil {
+ var state liveProgress
+ _ = json.Unmarshal(raw, &state)
+ snapshot := o.control.snapshot()
+ state.Control = &snapshot
+ state.Elapsed = snapshot.Wall
+ state.Dropped = snapshot.Dropped
+ state.Iterations = 0
+ for _, flow := range state.Flows {
+ state.Iterations += flow.Successes + flow.Failures
+ }
+ raw, _ = json.Marshal(state)
+ }
+ if err := os.WriteFile(o.progressFile+".tmp", raw, 0600); err != nil {
+ o.writer.fail(err)
+ return
+ }
+ if err := os.Rename(o.progressFile+".tmp", o.progressFile); err != nil {
+ o.writer.fail(err)
+ }
+}
+
+// serverPercentile sorts the supplied window in place and returns its p99
+// using the lower indexed sample at floor((n-1)*0.99). Empty windows return nil;
+// this live estimate is not a percentile over the entire recorded run.
+func serverPercentile(values []float64) *float64 {
+ if len(values) == 0 {
+ return nil
+ }
+ sort.Float64s(values)
+ value := values[int(float64(len(values)-1)*.99)]
+ return &value
+}
diff --git a/loadtest/k6/scenario-mix/recorder/progress_test.go b/loadtest/k6/scenario-mix/recorder/progress_test.go
new file mode 100644
index 0000000000..6180999541
--- /dev/null
+++ b/loadtest/k6/scenario-mix/recorder/progress_test.go
@@ -0,0 +1,87 @@
+package recorder
+
+import (
+ "encoding/json"
+ "go.k6.io/k6/metrics"
+ "testing"
+)
+
+func TestProgressHTTPDisplayCountsPaymentConfirmOnly(t *testing.T) {
+ p := newProgressCollector(map[string]interface{}{})
+ r := metrics.NewRegistry()
+ for _, operation := range []string{"pm_session_confirm", "payment_create", "payment_confirm"} {
+ tags := r.RootTagSet().With("operation", operation)
+ p.add([]metrics.SampleContainer{metrics.Samples{
+ {TimeSeries: metrics.TimeSeries{Metric: r.MustNewMetric("http_reqs", metrics.Counter), Tags: tags}, Value: 10},
+ {TimeSeries: metrics.TimeSeries{Metric: r.MustNewMetric("http_req_failed", metrics.Rate), Tags: tags}, Value: 1},
+ }})
+ }
+ if p.state.HTTPAttempts != 30 || p.state.HTTPErrors != 3 || p.state.ConfirmHTTPAttempts != 10 || p.state.ConfirmHTTPErrors != 1 {
+ t.Fatalf("wrong HTTP counters: %+v", p.state)
+ }
+}
+
+func TestProgressCountsSuccessesWithoutDoubleCountingPhases(t *testing.T) {
+ p := newProgressCollector(map[string]interface{}{"scenarios": []interface{}{map[string]interface{}{"name": "guest"}}})
+ r := metrics.NewRegistry()
+ samples := metrics.Samples{}
+ for name, value := range map[string]float64{"scenario_success_guest": 10, "scenario_success_guest_p1": 10, "scenario_failure_guest": 2, "iterations": 12, "http_reqs": 40, "http_req_failed": 1, "payment_confirm_ms_guest": 123} {
+ samples = append(samples, metrics.Sample{TimeSeries: metrics.TimeSeries{Metric: r.MustNewMetric(name, metrics.Counter)}, Value: value})
+ }
+ p.add([]metrics.SampleContainer{samples})
+ var result liveProgress
+ if err := json.Unmarshal(p.bytes(Stats{Enqueued: 40, Persisted: 39}), &result); err != nil {
+ t.Fatal(err)
+ }
+ if result.Flows["guest"].Successes != 10 || result.Flows["guest"].Failures != 2 || result.Iterations != 12 {
+ t.Fatalf("wrong counters: %+v", result)
+ }
+ if result.Flows["guest"].P90 == nil || *result.Flows["guest"].P90 != 123 {
+ t.Fatal("latency missing")
+ }
+ if result.Recorder.Persisted != 39 {
+ t.Fatal("recorder snapshot missing")
+ }
+}
+
+func TestProgressLatencyWindowIsBoundedAndResets(t *testing.T) {
+ p := newProgressCollector(map[string]interface{}{"scenarios": []interface{}{map[string]interface{}{"name": "guest"}}})
+ r := metrics.NewRegistry()
+ metric := r.MustNewMetric("payment_confirm_ms_guest", metrics.Trend)
+ samples := make(metrics.Samples, 20000)
+ for i := range samples {
+ samples[i] = metrics.Sample{TimeSeries: metrics.TimeSeries{Metric: metric}, Value: float64(i)}
+ }
+ p.add([]metrics.SampleContainer{samples})
+ if len(p.state.Flows["guest"].latencies) != 8192 {
+ t.Fatal("unbounded latency window")
+ }
+ p.bytes(Stats{})
+ if len(p.state.Flows["guest"].latencies) != 0 {
+ t.Fatal("window did not reset")
+ }
+}
+
+func TestServerLatencyWindowPreservesZeroAndResets(t *testing.T) {
+ p := newProgressCollector(map[string]interface{}{"scenarios": []interface{}{map[string]interface{}{"name": "guest"}}})
+ r := metrics.NewRegistry()
+ for _, name := range []string{"payment_confirm_server_latency_ms", "payment_confirm_server_ms_guest"} {
+ metric := r.MustNewMetric(name, metrics.Trend)
+ for _, value := range []float64{0, 10, 30} {
+ p.add([]metrics.SampleContainer{metrics.Samples{{TimeSeries: metrics.TimeSeries{Metric: metric}, Value: value}}})
+ }
+ }
+ var result liveProgress
+ if err := json.Unmarshal(p.bytes(Stats{}), &result); err != nil {
+ t.Fatal(err)
+ }
+ if result.ServerP99 == nil || *result.ServerP99 != 10 || result.Flows["guest"].ServerP99 == nil || *result.Flows["guest"].ServerP99 != 10 || len(result.ServerSamples) != 3 || result.ServerSamples[0] != 0 {
+ t.Fatalf("wrong server latency: %+v", result)
+ }
+ if err := json.Unmarshal(p.bytes(Stats{}), &result); err != nil {
+ t.Fatal(err)
+ }
+ if result.ServerP99 != nil || result.Flows["guest"].ServerP99 != nil {
+ t.Fatal("missing samples reported as latency")
+ }
+}
diff --git a/loadtest/k6/scenario-mix/recorder/schema.sql b/loadtest/k6/scenario-mix/recorder/schema.sql
new file mode 100644
index 0000000000..1fdbc67c50
--- /dev/null
+++ b/loadtest/k6/scenario-mix/recorder/schema.sql
@@ -0,0 +1,32 @@
+PRAGMA journal_mode=WAL;
+PRAGMA synchronous=FULL;
+PRAGMA busy_timeout=5000;
+CREATE TABLE IF NOT EXISTS runs (
+ run_id TEXT PRIMARY KEY, recording_state TEXT NOT NULL DEFAULT 'incomplete',
+ started_at INTEGER NOT NULL, ended_at INTEGER, enqueued INTEGER NOT NULL DEFAULT 0,
+ persisted INTEGER NOT NULL DEFAULT 0, error TEXT, metadata TEXT NOT NULL DEFAULT '{}'
+);
+CREATE TABLE IF NOT EXISTS request_events (
+ event_id INTEGER PRIMARY KEY, run_id TEXT NOT NULL, attempt_id INTEGER NOT NULL, flow_id TEXT NOT NULL,
+ merchant_id TEXT, operation TEXT NOT NULL, role TEXT NOT NULL,
+ observed_at INTEGER NOT NULL, method TEXT NOT NULL, url TEXT NOT NULL,
+ customer_id TEXT, merchant_reference_id TEXT, payment_id TEXT, amount INTEGER,
+ status TEXT, api_status_code INTEGER NOT NULL, request_id TEXT,
+ latency_ms REAL NOT NULL, message TEXT, error_body TEXT, entity_type TEXT, server_latency_ms REAL, requested_connector TEXT, selected_connector_account TEXT, connector TEXT, merchant_connector_id TEXT
+);
+CREATE TABLE IF NOT EXISTS customers (
+ run_id TEXT NOT NULL, customer_id TEXT NOT NULL, merchant_id TEXT,
+ merchant_reference_id TEXT, api_status_code INTEGER NOT NULL, request_id TEXT,
+ message TEXT, observed_at INTEGER NOT NULL, response_event_id INTEGER NOT NULL,
+ PRIMARY KEY (run_id, customer_id)
+);
+CREATE TABLE IF NOT EXISTS payments (
+ run_id TEXT NOT NULL, payment_id TEXT NOT NULL, merchant_id TEXT, customer_id TEXT,
+ amount INTEGER, status TEXT, role TEXT NOT NULL, api_status_code INTEGER NOT NULL,
+ request_id TEXT, message TEXT, observed_at INTEGER NOT NULL, response_event_id INTEGER NOT NULL,
+ PRIMARY KEY (run_id, payment_id)
+);
+
+CREATE INDEX IF NOT EXISTS requests_payment ON request_events(payment_id,merchant_id,event_id);
+CREATE INDEX IF NOT EXISTS requests_operation ON request_events(operation,event_id);
+CREATE INDEX IF NOT EXISTS requests_http ON request_events(api_status_code,event_id);
diff --git a/loadtest/k6/scenario-mix/recorder/writer.go b/loadtest/k6/scenario-mix/recorder/writer.go
new file mode 100644
index 0000000000..7e4be9a388
--- /dev/null
+++ b/loadtest/k6/scenario-mix/recorder/writer.go
@@ -0,0 +1,434 @@
+package recorder
+
+import (
+ "database/sql"
+ _ "embed"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "os"
+ "sync"
+ "time"
+
+ _ "github.com/mattn/go-sqlite3"
+)
+
+//go:embed schema.sql
+var schemaSQL string
+
+//go:embed event.sql
+var eventSQL string
+
+//go:embed customer.sql
+var customerSQL string
+
+//go:embed payment.sql
+var paymentSQL string
+
+var errQueueFull = errors.New("SQLite recording queue exhausted; run is incomplete")
+
+// Record contains only response projections, never request headers or card data.
+type Record struct {
+ AttemptID uint64 `json:"attempt_id" js:"attempt_id"`
+ FlowID string `json:"flow_id" js:"flow_id"`
+ MerchantID *string `json:"merchant_id" js:"merchant_id"`
+ Operation string `json:"operation" js:"operation"`
+ Role string `json:"role" js:"role"`
+ ObservedAt int64 `json:"observed_at" js:"observed_at"`
+ Method string `json:"method" js:"method"`
+ URL string `json:"url" js:"url"`
+ CustomerID *string `json:"customer_id" js:"customer_id"`
+ MerchantReferenceID *string `json:"merchant_reference_id" js:"merchant_reference_id"`
+ PaymentID *string `json:"payment_id" js:"payment_id"`
+ Amount *int64 `json:"amount" js:"amount"`
+ Status *string `json:"status" js:"status"`
+ APIStatusCode int `json:"api_status_code" js:"api_status_code"`
+ RequestID *string `json:"request_id" js:"request_id"`
+ RequestedConnector *string `json:"requested_connector" js:"requested_connector"`
+ SelectedConnectorAccount *string `json:"selected_connector_account" js:"selected_connector_account"`
+ Connector *string `json:"connector" js:"connector"`
+ MerchantConnectorID *string `json:"merchant_connector_id" js:"merchant_connector_id"`
+ ServerLatencyMS *float64 `json:"server_latency_ms" js:"server_latency_ms"`
+ LatencyMS float64 `json:"latency_ms" js:"latency_ms"`
+ Message *string `json:"message" js:"message"`
+ ErrorBody *string `json:"error_body" js:"error_body"`
+ EntityType *string `json:"entity_type" js:"entity_type"`
+ size int64
+}
+
+// bytes estimates a record's buffered footprint from fixed overhead and string
+// lengths. It enforces the recorder's byte budget, rather than measuring Go heap use.
+func (r *Record) bytes() int64 {
+ n := int64(384 + len(r.FlowID) + len(r.Operation) + len(r.Role) + len(r.Method) + len(r.URL))
+ for _, s := range []*string{r.MerchantID, r.CustomerID, r.MerchantReferenceID, r.PaymentID, r.Status, r.RequestID, r.Message, r.ErrorBody, r.EntityType, r.RequestedConnector, r.SelectedConnectorAccount, r.Connector, r.MerchantConnectorID} {
+ if s != nil {
+ n += int64(len(*s))
+ }
+ }
+ return n
+}
+
+type Settings struct {
+ BatchSize, MaxEvents int
+ MaxBytes int64
+ FlushInterval time.Duration
+}
+
+// DefaultSettings bounds buffered recording to 100,000 events and 64 MiB
+// of estimated payload, flushing batches of 1,000 events or every 50 milliseconds.
+func DefaultSettings() Settings { return Settings{1000, 100000, 64 << 20, 50 * time.Millisecond} }
+
+type Stats struct {
+ Attempts uint64 `json:"attempts" js:"attempts"`
+ PendingEvents int `json:"pending_events" js:"pending_events"`
+ PendingBytes int64 `json:"pending_bytes" js:"pending_bytes"`
+ Enqueued uint64 `json:"enqueued" js:"enqueued"`
+ Persisted uint64 `json:"persisted" js:"persisted"`
+ QueueEvents int `json:"queue_events" js:"queue_events"`
+ QueueBytes int64 `json:"queue_bytes" js:"queue_bytes"`
+ PeakEvents int `json:"peak_events" js:"peak_events"`
+ PeakBytes int64 `json:"peak_bytes" js:"peak_bytes"`
+ MaxCommitMS float64 `json:"max_commit_ms" js:"max_commit_ms"`
+ Error string `json:"error,omitempty" js:"error"`
+}
+
+type Writer struct {
+ db *sql.DB
+ runID string
+ settings Settings
+ queue chan *Record
+ done chan struct{}
+ mu sync.Mutex
+ stats Stats
+ err error
+ closed bool
+ closing bool
+ pending map[uint64]Record
+ stop func(error)
+ metadata map[string]interface{}
+}
+
+// NewWriter exclusively creates a private database for one run, initializes
+// the schema and metadata, and starts a single batching goroutine. Invalid
+// limits or an existing file fail initialization instead of overwriting prior data.
+func NewWriter(file, runID string, settings Settings, metadata map[string]interface{}) (*Writer, error) {
+ if settings.BatchSize < 1 || settings.MaxEvents < 1 || settings.MaxBytes < 1 || settings.FlushInterval <= 0 {
+ return nil, errors.New("invalid recorder settings")
+ }
+ // A database belongs to one generator/run. Never overwrite an earlier run.
+ f, err := os.OpenFile(file, os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0600)
+ if err != nil {
+ return nil, err
+ }
+ if err = f.Close(); err != nil {
+ return nil, err
+ }
+ db, err := sql.Open("sqlite3", file)
+ if err != nil {
+ return nil, err
+ }
+ db.SetMaxOpenConns(1)
+ if _, err = db.Exec(schemaSQL); err != nil {
+ db.Close()
+ return nil, err
+ }
+ if metadata == nil {
+ metadata = map[string]interface{}{}
+ }
+ raw, _ := json.Marshal(metadata)
+ if _, err = db.Exec("INSERT INTO runs(run_id,started_at,metadata) VALUES(?,?,?)", runID, time.Now().UnixMilli(), string(raw)); err != nil {
+ db.Close()
+ return nil, err
+ }
+ w := &Writer{db: db, runID: runID, settings: settings, queue: make(chan *Record, settings.MaxEvents), done: make(chan struct{}), metadata: metadata, pending: make(map[uint64]Record)}
+ go w.loop()
+ return w, nil
+}
+
+// fail latches the first recorder error and updates diagnostic counters.
+// It invokes the registered abort callback outside the mutex, avoiding lock
+// re-entry while ensuring subsequent failures do not trigger duplicate aborts.
+func (w *Writer) fail(err error) {
+ w.mu.Lock()
+ first := w.err == nil
+ if first {
+ w.err = err
+ w.stats.Error = err.Error()
+ }
+ stop := w.stop
+ w.mu.Unlock()
+ if first && stop != nil {
+ stop(err)
+ }
+}
+
+// SetStop installs the test-abort callback used by subsequent recorder failures.
+// Register it before producers begin so capacity or database errors can stop k6.
+func (w *Writer) SetStop(stop func(error)) { w.mu.Lock(); w.stop = stop; w.mu.Unlock() }
+
+// Enqueue accepts a completed record within the shared pending-and-queued
+// event and byte limits. It fails the run on exhaustion rather than silently
+// dropping data; capacity accounting includes batches awaiting commit.
+func (w *Writer) Enqueue(r Record) error {
+ r = sanitizeDiagnostics(r)
+ r.size = r.bytes()
+ w.mu.Lock()
+ if w.err != nil {
+ err := w.err
+ w.mu.Unlock()
+ return err
+ }
+ if w.closed {
+ w.mu.Unlock()
+ return errors.New("recorder already closed")
+ }
+ if w.stats.QueueEvents+w.stats.PendingEvents >= w.settings.MaxEvents || w.stats.QueueBytes+w.stats.PendingBytes+r.size > w.settings.MaxBytes {
+ w.mu.Unlock()
+ err := errQueueFull
+ w.fail(err)
+ return err
+ }
+ w.stats.Enqueued++
+ w.stats.QueueEvents++
+ w.stats.QueueBytes += r.size
+ if w.stats.QueueEvents > w.stats.PeakEvents {
+ w.stats.PeakEvents = w.stats.QueueEvents
+ }
+ if w.stats.QueueBytes > w.stats.PeakBytes {
+ w.stats.PeakBytes = w.stats.QueueBytes
+ }
+ // Count includes in-flight batches, so the buffered send is guaranteed to fit.
+ w.queue <- &r
+ w.mu.Unlock()
+ return nil
+}
+
+// Snapshot returns a mutex-protected copy of recorder counters without
+// waiting for queued writes to reach SQLite.
+func (w *Writer) Snapshot() Stats { w.mu.Lock(); defer w.mu.Unlock(); return w.stats }
+
+// loop is the sole batch consumer, flushing on size, interval, or queue close.
+// Queue exhaustion still drains accepted records; database failures stop further
+// commits and leave the run incomplete.
+func (w *Writer) loop() {
+ defer close(w.done)
+ ticker := time.NewTicker(w.settings.FlushInterval)
+ defer ticker.Stop()
+ batch := make([]*Record, 0, w.settings.BatchSize)
+ flush := func() {
+ if len(batch) == 0 {
+ return
+ }
+ w.mu.Lock()
+ fatal := w.err
+ w.mu.Unlock()
+ // Queue exhaustion still drains all accepted events. Database errors cannot.
+ if fatal != nil && !errors.Is(fatal, errQueueFull) {
+ return
+ }
+ if err := w.commit(batch); err != nil {
+ w.fail(err)
+ return
+ }
+ batch = batch[:0]
+ }
+ for {
+ select {
+ case r, ok := <-w.queue:
+ if !ok {
+ flush()
+ return
+ }
+ batch = append(batch, r)
+ if len(batch) >= w.settings.BatchSize {
+ flush()
+ if len(batch) != 0 {
+ return
+ }
+ }
+ case <-ticker.C:
+ flush()
+ if len(batch) != 0 {
+ return
+ }
+ }
+ }
+}
+
+// commit writes request events, entity projections, and persisted counters
+// in one SQLite transaction. Queue accounting is released only after commit;
+// any statement failure rolls back the batch and propagates to the writer loop.
+func (w *Writer) commit(batch []*Record) error {
+ start := time.Now()
+ tx, err := w.db.Begin()
+ if err != nil {
+ return err
+ }
+ defer tx.Rollback() // no-op after commit
+ insert, err := tx.Prepare(eventSQL)
+ if err != nil {
+ return err
+ }
+ defer insert.Close()
+ customer, err := tx.Prepare(customerSQL)
+ if err != nil {
+ return err
+ }
+ defer customer.Close()
+ payment, err := tx.Prepare(paymentSQL)
+ if err != nil {
+ return err
+ }
+ defer payment.Close()
+ var bytes int64
+ for _, r := range batch {
+ result, err := insert.Exec(w.runID, r.AttemptID, r.FlowID, r.MerchantID, r.Operation, r.Role, r.ObservedAt, r.Method, r.URL, r.CustomerID, r.MerchantReferenceID, r.PaymentID, r.Amount, r.Status, r.APIStatusCode, r.RequestID, r.LatencyMS, r.Message, r.ErrorBody, r.EntityType, r.ServerLatencyMS, r.RequestedConnector, r.SelectedConnectorAccount, r.Connector, r.MerchantConnectorID)
+ if err != nil {
+ return err
+ }
+ id, err := result.LastInsertId()
+ if err != nil {
+ return err
+ }
+ if r.EntityType != nil && *r.EntityType == "customer" && r.CustomerID != nil {
+ if _, err = customer.Exec(w.runID, r.CustomerID, r.MerchantID, r.MerchantReferenceID, r.APIStatusCode, r.RequestID, r.Message, r.ObservedAt, id); err != nil {
+ return err
+ }
+ }
+ if r.EntityType != nil && *r.EntityType == "payment" && r.PaymentID != nil {
+ if _, err = payment.Exec(w.runID, r.PaymentID, r.MerchantID, r.CustomerID, r.Amount, r.Status, r.Role, r.APIStatusCode, r.RequestID, r.Message, r.ObservedAt, id); err != nil {
+ return err
+ }
+ }
+ bytes += r.size
+ }
+ w.mu.Lock()
+ persisted := w.stats.Persisted + uint64(len(batch))
+ enqueued := w.stats.Enqueued
+ w.mu.Unlock()
+ if _, err = tx.Exec("UPDATE runs SET enqueued=?,persisted=? WHERE run_id=?", enqueued, persisted, w.runID); err != nil {
+ return err
+ }
+ if err = tx.Commit(); err != nil {
+ return err
+ }
+ w.mu.Lock()
+ w.stats.Persisted = persisted
+ w.stats.QueueEvents -= len(batch)
+ w.stats.QueueBytes -= bytes
+ ms := float64(time.Since(start).Microseconds()) / 1000
+ if ms > w.stats.MaxCommitMS {
+ w.stats.MaxCommitMS = ms
+ }
+ w.mu.Unlock()
+ return nil
+}
+
+// Begin reserves bounded capacity and assigns an attempt ID before an HTTP
+// request starts. Pending attempts share limits with queued records; unfinished
+// attempts become explicit transport-failure events during Close.
+func (w *Writer) Begin(r Record) (uint64, error) {
+ r.size = r.bytes()
+ w.mu.Lock()
+ if w.err != nil {
+ err := w.err
+ w.mu.Unlock()
+ return 0, err
+ }
+ if w.closed || w.closing {
+ w.mu.Unlock()
+ return 0, errors.New("recorder closing")
+ }
+ if w.stats.QueueEvents+w.stats.PendingEvents >= w.settings.MaxEvents || w.stats.QueueBytes+w.stats.PendingBytes+r.size > w.settings.MaxBytes {
+ w.mu.Unlock()
+ w.fail(errQueueFull)
+ return 0, errQueueFull
+ }
+ w.stats.Attempts++
+ r.AttemptID = w.stats.Attempts
+ w.pending[r.AttemptID] = r
+ w.stats.PendingEvents++
+ w.stats.PendingBytes += r.size
+ w.mu.Unlock()
+ return r.AttemptID, nil
+}
+
+// Finish consumes an attempt reservation exactly once and enqueues its result
+// with the original attempt ID. Unknown or duplicate IDs fail; a result that
+// exceeds remaining queue capacity propagates the recorder failure.
+func (w *Writer) Finish(id uint64, r Record) error {
+ r = sanitizeDiagnostics(r)
+ w.mu.Lock()
+ pending, ok := w.pending[id]
+ if !ok {
+ w.mu.Unlock()
+ return errors.New("unknown/already recorded HTTP attempt")
+ }
+ delete(w.pending, id)
+ w.stats.PendingEvents--
+ w.stats.PendingBytes -= pending.size
+ w.mu.Unlock()
+ r.AttemptID = id
+ return w.Enqueue(r)
+}
+
+// Close blocks new attempt reservations, records pending attempts as interrupted,
+// and drains accepted records before finalizing run metadata and closing SQLite.
+// Test errors, recorder errors, or counter mismatches mark recording incomplete;
+// call it after producers stop, as concurrent finalization is not supported.
+func (w *Writer) Close(testErr error) error {
+ w.mu.Lock()
+ w.closing = true
+ pending := w.pending
+ w.pending = make(map[uint64]Record)
+ w.stats.PendingEvents = 0
+ w.stats.PendingBytes = 0
+ w.mu.Unlock()
+ if len(pending) > 0 && testErr == nil {
+ testErr = errors.New("unfinished HTTP attempts at shutdown")
+ }
+ for _, r := range pending {
+ r.APIStatusCode = 0
+ r.ObservedAt = time.Now().UnixMilli()
+ r.Message = strPointer("request interrupted before response was recorded")
+ r.LatencyMS = float64(r.ObservedAt) - r.LatencyMS
+ _ = w.Enqueue(r) // recording failures already mark the run incomplete
+ }
+ w.mu.Lock()
+ if !w.closed {
+ w.closed = true
+ close(w.queue)
+ }
+ w.mu.Unlock()
+ <-w.done
+ stats := w.Snapshot()
+ state := "complete"
+ w.mu.Lock()
+ err := w.err
+ w.mu.Unlock()
+ if err == nil {
+ err = testErr
+ }
+ if err != nil || stats.Enqueued != stats.Persisted || (stats.Attempts > 0 && stats.Attempts != stats.Enqueued) {
+ state = "incomplete"
+ }
+ w.metadata["recorder"] = stats
+ raw, _ := json.Marshal(w.metadata)
+ var message interface{}
+ if err != nil {
+ message = err.Error()
+ }
+ _, updateErr := w.db.Exec("UPDATE runs SET recording_state=?,ended_at=?,enqueued=?,persisted=?,error=?,metadata=? WHERE run_id=?", state, time.Now().UnixMilli(), stats.Enqueued, stats.Persisted, message, string(raw), w.runID)
+ closeErr := w.db.Close()
+ if err != nil {
+ return fmt.Errorf("recording incomplete: %w", err)
+ }
+ if updateErr != nil {
+ return updateErr
+ }
+ return closeErr
+}
+
+// strPointer wraps a string for nullable record fields, preserving the
+// distinction between an absent value and an explicitly supplied empty string.
+func strPointer(s string) *string { return &s }
diff --git a/loadtest/k6/scenario-mix/recorder/writer_test.go b/loadtest/k6/scenario-mix/recorder/writer_test.go
new file mode 100644
index 0000000000..47b5f8e86f
--- /dev/null
+++ b/loadtest/k6/scenario-mix/recorder/writer_test.go
@@ -0,0 +1,240 @@
+package recorder
+
+import (
+ "database/sql"
+ "errors"
+ "fmt"
+ "path/filepath"
+ "sync"
+ "testing"
+ "time"
+
+ "go.k6.io/k6/errext"
+)
+
+func TestRecordingCompletenessIndependentOfFinalThresholds(t *testing.T) {
+ for _, reason := range []errext.AbortReason{errext.AbortedByThresholdsAfterTestEnd, errext.AbortedByThreshold, errext.AbortedByUser, errext.AbortedByScriptError} {
+ err := errext.WithAbortReasonIfNone(errors.New("test failed"), reason)
+ if (recordingError(err) == nil) != (reason == errext.AbortedByThresholdsAfterTestEnd) {
+ t.Fatalf("unexpected recording classification for %v", reason)
+ }
+ }
+}
+
+func str(s string) *string { return &s }
+func paymentRecord(id, status string) Record {
+ return Record{FlowID: "flow", Operation: "payment_confirm", Role: "measured", ObservedAt: time.Now().UnixMilli(), Method: "POST", URL: "http://test/payments/" + id + "/confirm", PaymentID: str(id), Status: str(status), APIStatusCode: 200, EntityType: str("payment")}
+}
+func TestConcurrentDrain(t *testing.T) {
+ file := filepath.Join(t.TempDir(), "run.sqlite")
+ w, err := NewWriter(file, "run", DefaultSettings(), nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+ var wg sync.WaitGroup
+ for vu := 0; vu < 8; vu++ {
+ wg.Add(1)
+ go func(vu int) {
+ defer wg.Done()
+ for i := 0; i < 200; i++ {
+ id := fmt.Sprintf("pay-%d-%d", vu, i)
+ attempt, err := w.Begin(paymentRecord(id, "processing"))
+ if err != nil {
+ t.Error(err)
+ return
+ }
+ if err := w.Finish(attempt, paymentRecord(id, "processing")); err != nil {
+ t.Error(err)
+ return
+ }
+ attempt, err = w.Begin(paymentRecord(id, "succeeded"))
+ if err != nil {
+ t.Error(err)
+ return
+ }
+ if err := w.Finish(attempt, paymentRecord(id, "succeeded")); err != nil {
+ t.Error(err)
+ return
+ }
+ }
+ }(vu)
+ }
+ wg.Wait()
+ if err := w.Close(nil); err != nil {
+ t.Fatal(err)
+ }
+ stats := w.Snapshot()
+ if stats.Enqueued != 3200 || stats.Persisted != 3200 || stats.QueueEvents != 0 {
+ t.Fatalf("%+v", stats)
+ }
+ db, err := sql.Open("sqlite3", file)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer db.Close()
+ var count int
+ if err = db.QueryRow("SELECT COUNT(*) FROM payments WHERE status='succeeded'").Scan(&count); err != nil || count != 1600 {
+ t.Fatalf("count=%d err=%v", count, err)
+ }
+}
+func TestByteQueueExhaustionAbortsAndMarksIncomplete(t *testing.T) {
+ settings := DefaultSettings()
+ settings.MaxBytes = 1
+ file := filepath.Join(t.TempDir(), "run.sqlite")
+ w, err := NewWriter(file, "run", settings, nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+ called := false
+ w.SetStop(func(error) { called = true })
+ if err = w.Enqueue(paymentRecord("pay", "succeeded")); err == nil {
+ t.Fatal("expected queue error")
+ }
+ if !called {
+ t.Fatal("test-wide abort not called")
+ }
+ if err = w.Close(nil); err == nil {
+ t.Fatal("expected incomplete close")
+ }
+ db, _ := sql.Open("sqlite3", file)
+ defer db.Close()
+ var state string
+ if err = db.QueryRow("SELECT recording_state FROM runs").Scan(&state); err != nil || state != "incomplete" {
+ t.Fatalf("state=%s err=%v", state, err)
+ }
+}
+func TestDatabaseFailureAndGracefulAbort(t *testing.T) {
+ t.Run("write failure", func(t *testing.T) {
+ file := filepath.Join(t.TempDir(), "run.sqlite")
+ w, err := NewWriter(file, "run", DefaultSettings(), nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if _, err = w.db.Exec("DROP TABLE payments"); err != nil {
+ t.Fatal(err)
+ }
+ if err = w.Enqueue(paymentRecord("pay", "succeeded")); err != nil {
+ t.Fatal(err)
+ }
+ if err = w.Close(nil); err == nil {
+ t.Fatal("expected write failure")
+ }
+ if w.Snapshot().Persisted != 0 {
+ t.Fatal("failed transaction partially committed")
+ }
+ })
+ t.Run("disk full", func(t *testing.T) {
+ file := filepath.Join(t.TempDir(), "run.sqlite")
+ w, err := NewWriter(file, "run", DefaultSettings(), nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+ var pages int
+ if err = w.db.QueryRow("PRAGMA page_count").Scan(&pages); err != nil {
+ t.Fatal(err)
+ }
+ if _, err = w.db.Exec(fmt.Sprintf("PRAGMA max_page_count=%d", pages)); err != nil {
+ t.Fatal(err)
+ }
+ r := paymentRecord("pay", "failed")
+ // Raw error bodies are now deliberately projected and bounded. Exercise
+ // SQLite disk exhaustion with an unrelated large event field instead.
+ r.FlowID = string(make([]byte, 1<<20))
+ if err = w.Enqueue(r); err != nil {
+ t.Fatal(err)
+ }
+ if err = w.Close(nil); err == nil {
+ t.Fatal("expected SQLITE_FULL")
+ }
+ })
+ t.Run("graceful interrupt drains", func(t *testing.T) {
+ file := filepath.Join(t.TempDir(), "run.sqlite")
+ w, err := NewWriter(file, "run", DefaultSettings(), nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+ for i := 0; i < 10; i++ {
+ if err = w.Enqueue(paymentRecord(fmt.Sprint(i), "succeeded")); err != nil {
+ t.Fatal(err)
+ }
+ }
+ if err = w.Close(errors.New("interrupted")); err == nil {
+ t.Fatal("expected incomplete abort")
+ }
+ if w.Snapshot().Persisted != 10 {
+ t.Fatal("graceful abort lost accepted events")
+ }
+ })
+}
+func TestRefusesExistingDatabase(t *testing.T) {
+ file := filepath.Join(t.TempDir(), "run.sqlite")
+ w, err := NewWriter(file, "run", DefaultSettings(), nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err = w.Close(nil); err != nil {
+ t.Fatal(err)
+ }
+ if _, err = NewWriter(file, "new", DefaultSettings(), nil); err == nil {
+ t.Fatal("overwrote previous run")
+ }
+}
+func BenchmarkWriter(b *testing.B) {
+ settings := DefaultSettings()
+ settings.MaxEvents = 1000000
+ settings.MaxBytes = 256 << 20
+ w, err := NewWriter(filepath.Join(b.TempDir(), "run.sqlite"), "bench", settings, nil)
+ if err != nil {
+ b.Fatal(err)
+ }
+ b.ResetTimer()
+ for i := 0; i < b.N; i++ {
+ r := paymentRecord(fmt.Sprint(i), "succeeded")
+ r.FlowID = "00000000-0000-0000-0000-000000000000:nomod_saved_card:100:123456"
+ r.MerchantID = str("loadtest_mix_0001")
+ r.CustomerID = str("cus_00000000000000000000000000000000")
+ r.MerchantReferenceID = str("customer_mix_nomod_saved_card_123456_100_1787303017640")
+ r.RequestID = str("00000000-0000-0000-0000-000000000000")
+ r.LatencyMS = 3.5
+ amount := int64(1000)
+ r.Amount = &amount
+ if err = w.Enqueue(r); err != nil {
+ b.Fatal(err)
+ }
+ }
+ if err = w.Close(nil); err != nil {
+ b.Fatal(err)
+ }
+ b.StopTimer()
+ b.ReportMetric(float64(b.N)/b.Elapsed().Seconds(), "events/s")
+}
+
+func TestInterruptedAttemptIsRecorded(t *testing.T) {
+ file := filepath.Join(t.TempDir(), "run.sqlite")
+ w, err := NewWriter(file, "run", DefaultSettings(), nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+ r := paymentRecord("pay", "processing")
+ r.Status = nil
+ r.LatencyMS = float64(time.Now().UnixMilli())
+ if _, err = w.Begin(r); err != nil {
+ t.Fatal(err)
+ }
+ if err = w.Close(errors.New("SIGTERM")); err == nil {
+ t.Fatal("expected incomplete run")
+ }
+ db, _ := sql.Open("sqlite3", file)
+ defer db.Close()
+ var status int
+ var message string
+ if err = db.QueryRow("SELECT api_status_code,message FROM request_events").Scan(&status, &message); err != nil {
+ t.Fatal(err)
+ }
+ if status != 0 || message != "request interrupted before response was recorded" {
+ t.Fatalf("status=%d message=%s", status, message)
+ }
+ if w.Snapshot().Enqueued != 1 || w.Snapshot().Persisted != 1 {
+ t.Fatal("interrupted attempt lost")
+ }
+}
diff --git a/loadtest/k6/scenario-mix/recording-client.js b/loadtest/k6/scenario-mix/recording-client.js
new file mode 100644
index 0000000000..613d268c2e
--- /dev/null
+++ b/loadtest/k6/scenario-mix/recording-client.js
@@ -0,0 +1,4 @@
+// The load CLI substitutes this module with k6/x/sqlite-recorder in its generated script.
+// Plain k6 remains available for existing unrecorded experiments and inspect.
+if (__ENV.SQLITE_RECORDER_REQUIRED) throw new Error("Use the load command with the custom k6-sqlite binary");
+export default { record() {}, stats() { return {}; } };
diff --git a/loadtest/k6/scenario-mix/run.mjs b/loadtest/k6/scenario-mix/run.mjs
new file mode 100644
index 0000000000..0c32acd949
--- /dev/null
+++ b/loadtest/k6/scenario-mix/run.mjs
@@ -0,0 +1,176 @@
+#!/usr/bin/env node
+import {normalizeConnectorPlan} from '../../console/src/connector-config.mjs';
+import {normalizePaymentFlows,assertSupportedPaymentFlows} from '../../console/src/payment-flows.mjs';
+import {requireSupportedEnvironment} from '../../console/src/environments.mjs';
+import { mkdir, readFile, writeFile, rename, access, unlink } from "node:fs/promises";
+import { createHash, randomUUID } from "node:crypto";
+import { spawn } from "node:child_process";
+import { fileURLToPath, pathToFileURL } from "node:url";
+import path from "node:path";
+import { DatabaseSync } from "node:sqlite";
+import { loadConfig, provision, setFixtureRecorder } from "./provision-merchants.mjs";
+import { FixtureRecorder } from "./sqlite.mjs";
+import { configureSuperposition } from "./superposition.mjs";
+import { reconcile } from "./reconcile.mjs";
+
+const root = path.dirname(fileURLToPath(import.meta.url));
+const digest = (text) => createHash("sha256").update(text).digest("hex");
+async function atomicJson(file,value) {
+ await writeFile(`${file}.tmp`,JSON.stringify(value,null,2),{ mode: 0o600 });
+ await rename(`${file}.tmp`,file);
+}
+
+export async function fixtures(configPath,output,{onProgress=async()=>{},connectorAccounts=null}={}) {
+ const cfg = loadConfig(configPath);
+ if(connectorAccounts)cfg.connectors=connectorAccounts;
+ output = path.resolve(output);
+ await mkdir(output,{ recursive: true, mode: 0o700 });
+ const manifestFile = path.join(output,"manifest.json");
+ cfg.output = path.join(output,"merchants.json");
+ const identity = digest(JSON.stringify({ router:cfg.router,prefix:cfg.merchant_id_prefix,count:cfg.merchant_count,organization:cfg.organization_id,connector:cfg.connectors?.map(c=>c.connector_name).sort()||cfg.connectorAccounts?.map(c=>c.connector).sort()||cfg.connector }));
+ let previous;
+ try { previous = JSON.parse(await readFile(manifestFile,"utf8")); } catch (error) { if (error.code !== "ENOENT") throw error; }
+ if (previous && previous.identity !== identity) throw new Error("Fixture provisioning identity changed; use a new output directory");
+ const manifest = { schema_version: 1, identity, state: "creating", router: cfg.router };
+ await atomicJson(manifestFile,manifest);
+ const recorder = new FixtureRecorder(path.join(output,"fixtures.sqlite"),{ kind: "fixtures", identity });
+ setFixtureRecorder(recorder);
+ let setup={stage:"merchants",superposition:{status:cfg.superposition?"pending":"skipped"}};
+ const report=async changes=>{setup={...setup,...changes};await onProgress(setup);};
+ try {
+ await report({stage:"merchants"});
+ const result = await provision(cfg);
+ await report({stage:"superposition"});
+ const superposition = await configureSuperposition(cfg.superposition,recorder,result.merchants,result.organization_id,superposition=>report({superposition}));
+ const merchantData = await readFile(cfg.output,"utf8");
+ recorder.metadata.superposition = superposition;
+ recorder.close();
+ await atomicJson(manifestFile,{ ...manifest, state: "ready", ready_at: new Date().toISOString(),
+ organization_id: result.organization_id, merchant_count: result.merchants.length,
+ merchants_sha256: digest(merchantData), superposition });
+ await report({stage:"ready"});
+ return { manifest: manifestFile, merchant_count: result.merchants.length };
+ } catch (error) {
+ await report({stage:"failed",failedStage:setup.stage}).catch(()=>{});
+ try { recorder.close(error); } catch (_) { /* initial error is authoritative */ }
+ await atomicJson(manifestFile,{ ...manifest,state: "failed",error: error.message });
+ throw error;
+ } finally { setFixtureRecorder(null); }
+}
+
+export async function load(configPath,fixturePath,output,binary = path.join(root,"bin/k6-sqlite"),{ recording = true, telemetry = false, timing = false } = {}) {
+ const config = JSON.parse(await readFile(configPath,"utf8"));
+ if(config.environment)requireSupportedEnvironment(config.environment);
+ if(config.connectors)config.connectors=normalizeConnectorPlan(config.connectors);
+ config.scenarios=normalizePaymentFlows(config.scenarios);assertSupportedPaymentFlows(config.scenarios);
+ fixturePath = path.resolve(fixturePath); output = path.resolve(output); binary = path.resolve(binary);
+ const manifest = JSON.parse(await readFile(path.join(fixturePath,"manifest.json"),"utf8"));
+ if (manifest.schema_version !== 1 || manifest.state !== "ready") throw new Error("Load requires a ready fixture manifest");
+ const merchantsFile = path.join(fixturePath,"merchants.json");
+ const merchants = await readFile(merchantsFile,"utf8");
+ if (digest(merchants) !== manifest.merchants_sha256) throw new Error("Fixture credentials changed since readiness verification; rerun fixtures");
+ if(config.connectors)for(const merchant of JSON.parse(merchants))for(const row of config.connectors.mix)if(!merchant.connector_accounts?.[row.connector]&&!(row.connector==='stripe_test'&&config.connectors.mix.length===1&&merchant.merchant_connector_id))throw new Error(`Fixture is missing ${row.connector}; create compatible fixtures first`);
+ if (config.services?.router?.replace(/\/$/,"") !== manifest.router) throw new Error("Load router must match fixture router");
+ await access(binary);
+ await mkdir(output,{ recursive: true,mode: 0o700 });
+ const database = path.join(output,"results.sqlite");
+ try { await access(database); throw new Error("Run database already exists; use a new output directory"); } catch (error) { if (error.code !== "ENOENT") throw error; }
+ config.merchant_pool = { file: merchantsFile }; delete config.merchant;
+ const generatedConfig = path.join(output,"load-config.json");
+ await atomicJson(generatedConfig,config);
+ // Preserve the original plain-k6 entrypoint. The recorded variant imports the native extension.
+ const source = (await readFile(path.join(root,"scenario-mix.js"),"utf8"))
+ .replace('"./recording-client.js"','"k6/x/sqlite-recorder"')
+ .replace("'./connectors.mjs'",JSON.stringify(path.join(root,'connectors.mjs')))
+ .replace('"./server-latency.mjs"',JSON.stringify(path.join(root,'server-latency.mjs')));
+ const script = path.join(output,"scenario-mix.generated.js");
+ await writeFile(script,source,{ mode: 0o600 });
+ const runId = randomUUID();
+ const metadata = { fixtures_sha256: digest(JSON.stringify(manifest)), load_config_sha256: digest(JSON.stringify(config)),
+ environment:config.environment??null,mode: config.mode ?? null, profile:config.profile ?? null,fixture_set:config.fixtureSet ?? null,
+ offered_tps:config.load.total_rps ?? Math.max(config.load.start_rps || 0,...(config.load.stages || []).map(s=>s.target_rps)),
+ superposition: manifest.superposition, load: config.load, scenarios: config.scenarios };
+ // Smoke tests reuse the recorder output's bounded metrics collector without
+ // calling its response-recording API. Its temporary database is removed
+ // below, leaving only the lightweight progress samples used by the UI.
+ const args = ["run",...((recording || telemetry) ? ["--out","sqlite-recorder"] : []),script];
+ const timingArgs = process.platform === 'darwin' ? ['-l','-p',binary,...args]
+ : ['-f','real %e\nuser %U\nsys %S\nmax_rss_kb %M',binary,...args];
+ const child = spawn(timing ? "/usr/bin/time" : binary,timing ? timingArgs : args,{
+ detached: process.platform !== "win32",
+ stdio: timing ? ["inherit","inherit","pipe"] : "inherit", env: { ...process.env, RECORDING_DISABLED: recording ? "" : "1", SQLITE_RECORDER_REQUIRED: recording ? "1" : "",
+ SCENARIO_MIX_CONFIG: generatedConfig, OUTPUT_DIR: output,SUMMARY_OUTPUT: "summary.json",
+ SQLITE_RECORDER_DB: database,SQLITE_RECORDER_RUN_ID: runId,SQLITE_RECORDER_METADATA: JSON.stringify(metadata) },
+ });
+ let stderr = "";
+ if (timing) child.stderr.on("data",(chunk) => { stderr += chunk; process.stderr.write(chunk); });
+ const signals = ["SIGINT","SIGTERM"];
+ const forward = (signal) => {
+ try { if (process.platform === "win32") child.kill(signal); else process.kill(-child.pid,signal); }
+ catch (error) { if (error.code !== "ESRCH") throw error; }
+ };
+ const handlers = signals.map((signal) => { const handler = () => forward(signal); process.on(signal,handler); return handler; });
+ if (process.env.K6_PID_FILE) await atomicJson(process.env.K6_PID_FILE,{ pid:child.pid });
+ let code;
+ try {
+ code = await new Promise((resolve,reject) => { child.once("error",reject); child.once("close",(exitCode) => resolve(exitCode ?? 1)); });
+ } finally { signals.forEach((signal,i) => process.removeListener(signal,handlers[i])); }
+ const cpu = timing ? Object.fromEntries([...stderr.matchAll(/^(real|user|sys)\s+(\d+(?:\.\d+)?)$/gm)].map((m) => [m[1],Number(m[2])])) : null;
+ if (cpu) {
+ const rss = /(?:^max_rss_kb (\d+)|^\s*(\d+)\s+maximum resident set size)/m.exec(stderr);
+ cpu.max_rss_kb = rss ? Number(rss[1] || rss[2]) / (rss[1] ? 1 : 1024) : null;
+ }
+ if(process.env.SQLITE_RECORDER_CONTROL_FILE) {
+ const control=JSON.parse(await readFile(process.env.SQLITE_RECORDER_CONTROL_FILE,'utf8'));
+ if(control.state==='completed') {
+ const summary=JSON.parse(await readFile(path.join(output,'summary.json'),'utf8'));
+ const failedThreshold=Object.values(summary.metrics || {}).some(metric=>Object.values(metric.thresholds || {}).some(threshold=>threshold.ok===false));
+ code=failedThreshold?99:0;
+ }
+ }
+ if (!recording) {
+ if(telemetry)await Promise.all([database,`${database}-wal`,`${database}-shm`].map(file=>unlink(file).catch(error=>{if(error.code!=='ENOENT')throw error;})));
+ return { run_id: runId, exitCode: code,cpu };
+ }
+ const quote = (value) => `'${String(value).replaceAll("'", "'\\''")}'`;
+ if (!process.env.LOADTEST_CONSOLE_JOB) console.log(`\nReconcile this run (replace payments.csv with your CSV):\nnode ${quote(path.join(root,"run.mjs"))} reconcile --db ${quote(database)} --csv payments.csv --output ${quote(path.join(output,"reconciliation.csv"))}\n`);
+ try { await access(database); } catch(error) { if(error.code==='ENOENT')throw new Error(`k6 exited ${code} before recording initialized; see Diagnostics`);throw error; }
+ const db = new DatabaseSync(database,{ readOnly: true });
+ try {
+ const run = db.prepare("SELECT * FROM runs WHERE run_id=?").get(runId);
+ if (!run || run.recording_state !== "complete" || run.enqueued !== run.persisted) throw new Error(`Run ${runId} has incomplete recording`);
+ } finally { db.close(); }
+ return { run_id: runId, database,exitCode: code,cpu };
+}
+
+function argumentsFor(command,args) {
+ const allowed = { fixtures:["config","output"],load:["config","fixtures","output","k6"],
+ reconcile:["db","csv","output","run-id","allow-incomplete"] }[command];
+ if (!allowed) throw new Error("Usage: node run.mjs fixtures|load|reconcile --help");
+ const values = {};
+ for (let i=0;i<args.length;i++) {
+ if (args[i] === "--help") return null;
+ const key = args[i].replace(/^--/,"");
+ if (!args[i].startsWith("--") || !allowed.includes(key) || key in values) throw new Error(`Invalid or duplicate argument: ${args[i]}`);
+ if (key === "allow-incomplete") { values[key] = true; continue; }
+ if (!args[i+1] || args[i+1].startsWith("--")) throw new Error(`Missing value for --${key}`);
+ values[key] = args[++i];
+ }
+ const required = command === "fixtures" ? ["config","output"] : command === "load" ? ["config","fixtures","output"] : ["db","csv","output"];
+ for (const key of required) if (!values[key]) throw new Error(`--${key} is required`);
+ return values;
+}
+export async function main(args = process.argv.slice(2)) {
+ const command = args[0]; const flags = argumentsFor(command,args.slice(1));
+ if (!flags) {
+ console.log("fixtures --config provision.json --output fixtures/\nload --config load.json --fixtures fixtures/ --output run/ [--k6 binary]\nreconcile --db run/results.sqlite --csv payments.csv --output reconciliation.csv [--run-id id] [--allow-incomplete]");
+ return;
+ }
+ const result = command === "fixtures" ? await fixtures(flags.config,flags.output)
+ : command === "load" ? await load(flags.config,flags.fixtures,flags.output,flags.k6)
+ : await reconcile({ db:flags.db,csv:flags.csv,output:flags.output,runId:flags["run-id"],allowIncomplete:flags["allow-incomplete"] });
+ console.log(JSON.stringify(result,null,2)); process.exitCode = result.exitCode || 0;
+}
+if (process.argv[1] && import.meta.url === pathToFileURL(path.resolve(process.argv[1])).href) {
+ main().catch((error) => { console.error(error.stack || error.message); process.exitCode = 1; });
+}
diff --git a/loadtest/k6/scenario-mix/scenario-mix.js b/loadtest/k6/scenario-mix/scenario-mix.js
new file mode 100644
index 0000000000..50b0b0eaa6
--- /dev/null
+++ b/loadtest/k6/scenario-mix/scenario-mix.js
@@ -0,0 +1,1316 @@
+import {connectorSchedule,selectedConnector,connectorRouting,connectorBrowserInfo,connectorTestCard} from './connectors.mjs';
+/**
+ * scenario-mix.js — a single k6 load test that mixes all payment scenarios
+ * with configurable traffic percentages (example: 50% guest, 40% CIT
+ * off-session, 10% metadata-changed).
+ *
+ * Scenario catalogue and request semantics are defined here (see
+ * the payment-flow definitions below), but unlike
+ * the runner there is no separate fixture stage: every iteration is
+ * self-contained — it creates everything it needs (customer, payment-method
+ * session, saved card, payment) and times each step individually.
+ *
+ * Usage:
+ * cp config.example.json config.json # fill in endpoints + credentials
+ * k6 run scenario-mix.js
+ * or:
+ * SCENARIO_MIX_CONFIG=/path/to/config.json k6 run scenario-mix.js
+ *
+ * Load shape: either flat (load.total_rps for load.duration_seconds) or a
+ * stepped ramp (load.phases, same knobs as the phase settings) that
+ * holds each RPS level and reports per-phase percentiles — useful for finding
+ * the application's maximum sustainable RPS.
+ */
+import http from "k6/http";
+import {serverLatency,latencyHeaders} from "./server-latency.mjs";
+import { sleep } from "k6";
+import { Counter, Trend } from "k6/metrics";
+import exec from "k6/execution";
+import encoding from "k6/encoding";
+import recorder from "./recording-client.js";
+
+// ---------------------------------------------------------------------------
+// Configuration loading and validation (fails fast, before any traffic)
+// ---------------------------------------------------------------------------
+
+const configPath = __ENV.SCENARIO_MIX_CONFIG || "./config.json";
+// Directory prefix for every file this script writes itself (SUMMARY_OUTPUT).
+// Defaults to "output" (checked into the repo alongside this script) rather
+// than cwd, so a plain `k6 run scenario-mix.js` doesn't scatter files loose
+// next to the source. k6 VU/init code can't create directories — the actual
+// file write happens in k6's Go runtime after handleSummary returns, and it
+// fails outright if the directory doesn't already exist — so a non-default
+// OUTPUT_DIR must be created ahead of time (`mkdir -p "$OUTPUT_DIR"`) before
+// running. Same constraint applies to any path passed to --console-output or
+// --out web-dashboard=export=..., which are k6 CLI flags this script has no
+// control over; see README "Collecting everything into one output directory".
+const outputDir = __ENV.OUTPUT_DIR || "output";
+const recordingEnabled = Boolean(__ENV.SQLITE_RECORDER_REQUIRED) && !__ENV.RECORDING_DISABLED;
+
+function joinPath(dir, file) {
+ if (!dir) return file;
+ return dir.endsWith("/") ? `${dir}${file}` : `${dir}/${file}`;
+}
+
+function fail(message) {
+ throw new Error(`scenario-mix: ${message}`);
+}
+
+let config;
+try {
+ config = JSON.parse(open(configPath));
+} catch (error) {
+ fail(`cannot read config at "${configPath}" (set SCENARIO_MIX_CONFIG): ${error}`);
+}
+
+
+
+// Payment-flow behavior table used by the console engine.
+const SCENARIOS = {
+ // No customer and no saved card; modular sessions use volatile storage.
+ guest: { requiresCustomer: false, setupFutureUsage: null, storageType: "volatile" },
+ // Customer-initiated save-card flows, vaulted inline at confirm.
+ cit_on_session: { requiresCustomer: true, setupFutureUsage: "on_session", storageType: "persistent" },
+ cit_off_session: { requiresCustomer: true, setupFutureUsage: "off_session", storageType: "persistent" },
+ // Payment-to-vault: the session stays volatile, acceptance is recorded, and
+ // the card is promoted to persistent storage after authorization.
+ ptv_on_session: { requiresCustomer: true, setupFutureUsage: "on_session", storageType: "volatile", modularOnly: true },
+ ptv_off_session: { requiresCustomer: true, setupFutureUsage: "off_session", storageType: "volatile", modularOnly: true },
+ // Saves a card in the iteration's baseline step, then the measured confirm
+ // resubmits the same PAN with changed metadata (expiry/holder name) to
+ // exercise vault metadata replacement. Non-modular only.
+ cit_metadata_changed: { requiresCustomer: true, requiresSavedCard: true, metadataChanged: true, setupFutureUsage: "off_session", storageType: "persistent" },
+ // Replicates the Hyperswitch SDK's pre-confirm calls (payment method list,
+ // wallet session tokens, BIN eligibility check) ahead of a guest-style
+ // confirm. Router (non_modular) only — the v2/modular payment-method
+ // service does not expose 1:1 equivalents of these endpoints yet.
+ sdk_checkout: { requiresCustomer: false, setupFutureUsage: null, storageType: "volatile", sdkFlow: true },
+ // Merchant-initiated transaction: the customer is not present. A baseline
+ // step first saves a card via a CIT confirm (off_session, like
+ // cit_metadata_changed), then the measured request is a single
+ // POST /payments with confirm:true, off_session:true, and
+ // recurring_details.payment_method_id pointing at the saved payment
+ // method — no card data on the wire, no separate payment_create call.
+ // Mirrors cypress-tests' create-pm-id-mit.json / MandatesUsingPMID flow.
+ // Non-modular only (router recurring-payments API).
+ mit: { requiresCustomer: true, requiresSavedCard: true, setupFutureUsage: null, storageType: "persistent", nonModularOnly: true, mitFlow: true },
+ // Returning-customer checkout: a baseline step first saves a card via a
+ // CIT confirm (off_session, like cit_metadata_changed/mit), then the
+ // measured request creates a fresh payment intent and calls the combined
+ // payment-method-list endpoint (GET /payments/{payment_id}/client — the
+ // same SDK-facing call sdk_checkout's payment_method_list step makes) to
+ // obtain the saved card's payment_token from its customer_payment_methods,
+ // then confirms with that token — no card data on the wire for the
+ // measured confirm. Mirrors cypress-tests' 14-SaveCardFlow.cy.js
+ // (listCustomerPMCallTest + saveCardConfirmCallTest), adapted to the
+ // combined list endpoint. Non-modular only, and needs
+ // merchant.publishable_key for the SDK Authorization header, same as
+ // sdk_checkout.
+ saved_card_checkout: { requiresCustomer: true, requiresSavedCard: true, savedCardCheckout: true, setupFutureUsage: null, storageType: "persistent", nonModularOnly: true },
+};
+
+// Payment statuses considered a successful measured confirm (workload.js).
+const SUCCESS_STATUSES = new Set(["succeeded", "requires_capture", "processing"]);
+
+function numberOr(value, fallback) {
+ if (value === undefined || value === null) return fallback;
+ const parsed = Number(value);
+ if (!Number.isFinite(parsed)) fail(`expected a number, got "${value}"`);
+ return parsed;
+}
+
+function statusCode(response) {
+ return response.status || "invalid";
+}
+
+function buildPlan(entry, index) {
+ if (!entry || typeof entry !== "object") fail(`scenarios[${index}] must be an object`);
+ const name = String(entry.name || "");
+ if (!/^[A-Za-z0-9_]+$/.test(name)) {
+ fail(`scenarios[${index}]: "name" must be non-empty and use only letters, digits and underscores (it becomes part of metric names), got "${entry.name}"`);
+ }
+ const merchantPath = "modular";
+ const scenarioName = String(entry.scenario || "").toLowerCase();
+ const scenario = SCENARIOS[scenarioName];
+ if (!scenario) {
+ fail(`scenario "${name}": unknown scenario "${entry.scenario}" (known: ${Object.keys(SCENARIOS).join(", ")})`);
+ }
+ if ((scenario.metadataChanged || scenario.nonModularOnly) && Number(entry.weight)>0) {
+ fail(`scenario "${name}": ${scenarioName} is not yet supported by the payment-method service`);
+ }
+ const weight = numberOr(entry.weight, NaN);
+ if (!(weight >= 0)) fail(`scenario "${name}": weight must be a number >= 0`);
+ return {
+ name,
+ weight,
+ merchantPath,
+ scenarioName,
+ usesPmService: merchantPath === "modular",
+ ...scenario,
+ };
+}
+
+const load = config.load || {};
+const paymentConfig = config.payment || {};
+const connectorSlots=connectorSchedule(config.connectors);
+if(recordingEnabled&&config.connectors&&recorder.connectorAttribution!==1)fail("Rebuild k6-sqlite to enable connector attribution before running this scenario");
+
+const requestTimeoutMs = numberOr(load.request_timeout_ms, 40000);
+if (!(requestTimeoutMs >= 100)) fail("load.request_timeout_ms must be >= 100");
+const thinkTimeMs = numberOr(load.think_time_ms, 0);
+if (thinkTimeMs < 0) fail("load.think_time_ms must be >= 0");
+const preAllocatedVusMultiplier = numberOr(load.pre_allocated_vus_multiplier, 3);
+// Each iteration is a multi-request flow (up to ~6 sequential requests) and
+// flow duration balloons as the system saturates — exactly when VU headroom
+// matters, so keep the ceiling generous. It is a ceiling: VUs beyond
+// preAllocatedVUs are only used when needed.
+const maxVusMultiplier = numberOr(load.max_vus_multiplier, 10);
+if (!(maxVusMultiplier >= preAllocatedVusMultiplier && preAllocatedVusMultiplier > 0)) {
+ fail("load VU multipliers must satisfy 0 < pre_allocated_vus_multiplier <= max_vus_multiplier");
+}
+
+// Flat mode: fixed load.total_rps for load.duration_seconds.
+// Ramp mode: load.phases describes ONE continuous ramping-arrival-rate curve
+// (hold at starting_rps, smoothly ramp to target_rps, hold at target_rps) -
+// a single persistent k6 scenario per traffic entry for the whole test.
+//
+// 2026-09-24: restructured from the previous discrete-step design (a brand
+// new constant-arrival-rate scenario, with its own fresh VU pool and
+// connections, spun up at every phase boundary). That design was root-
+// caused as the trigger for a k6-client-side connection-establishment
+// failure burst: two full 1000 TPS runs both aborted within ~40s of the
+// transition into the final (highest-rate) phase specifically, while
+// server-side p95 latency (Envoy/router/PMM) stayed completely flat
+// through the whole test both times - ruling out any real hyperswitch-side
+// cause and pointing at the burst of brand-new VUs/connections created at
+// each phase boundary (up to ~3000 at once, across 3 scenarios) as the
+// actual trigger. ramping-arrival-rate keeps ONE VU pool/connection set
+// alive for the scenario's entire lifetime and interpolates smoothly
+// between stages instead of jumping in discrete steps, eliminating that
+// churn at the design level (not just raising a failure-count threshold).
+//
+// load.stages generalizes the same single-executor design to any number of
+// stages (e.g. calibration -> ramp -> hold -> ramp -> hold, which load.phases'
+// one-ramp shape cannot express): an ordered list of
+// { name, target_rps, duration_seconds }, still ONE ramping-arrival-rate
+// scenario per traffic entry. Each stage's target_rps is the rate reached at
+// the END of that stage, interpolated linearly from the previous stage's
+// target (k6 semantics); a stage whose target equals the previous one is a
+// flat hold. load.start_rps (default: first stage's target_rps) is the rate
+// at t=0, so a first stage with the same target is a flat hold from the start.
+// load.phases is converted to the equivalent stage list below, so the
+// executor/summary code has a single path.
+let rampPlan = null;
+let flatTotalRps = null;
+let flatDurationSeconds = null;
+if (load.stages !== undefined) {
+ if (load.phases !== undefined || load.total_rps !== undefined || load.duration_seconds !== undefined) {
+ fail("load.stages cannot be combined with load.phases, load.total_rps or load.duration_seconds");
+ }
+ if (!Array.isArray(load.stages) || !load.stages.length) fail("load.stages must be a non-empty array");
+ const stages = load.stages.map((stage, index) => {
+ if (!stage || typeof stage !== "object") fail(`load.stages[${index}] must be an object`);
+ const targetRps = numberOr(stage.target_rps, NaN);
+ if (!(targetRps > 0)) fail(`load.stages[${index}].target_rps must be a number > 0`);
+ const durationSeconds = numberOr(stage.duration_seconds, NaN);
+ if (!(durationSeconds >= 1)) fail(`load.stages[${index}].duration_seconds must be >= 1`);
+ return { name: String(stage.name || `stage_${index + 1}`), targetRps, durationSeconds };
+ });
+ const startRps = numberOr(load.start_rps, stages[0].targetRps);
+ if (!(startRps >= 0)) fail("load.start_rps must be a number >= 0");
+ rampPlan = {
+ startRps,
+ stages,
+ strict: true,
+ totalSeconds: stages.reduce((sum, stage) => sum + stage.durationSeconds, 0),
+ peakRps: Math.max(startRps, ...stages.map((stage) => stage.targetRps)),
+ };
+} else if (load.phases && typeof load.phases === "object") {
+ if (load.total_rps !== undefined || load.duration_seconds !== undefined) {
+ fail("load.total_rps and load.duration_seconds cannot be combined with load.phases");
+ }
+ const startRps = numberOr(load.phases.starting_rps, NaN);
+ if (!(startRps > 0)) fail("load.phases.starting_rps must be a number > 0");
+ const targetRps = numberOr(load.phases.target_rps, startRps);
+ if (startRps > targetRps) fail("load.phases.starting_rps cannot exceed load.phases.target_rps");
+ // initial_hold_seconds/final_hold_seconds keep their existing names/
+ // semantics from the previous design. hold_seconds (no initial_/final_
+ // prefix) is accepted as a fallback for initial_hold_seconds only, for
+ // continuity with older configs; it no longer sizes anything else since
+ // there are no more discrete ramp steps to hold.
+ const initialHoldSeconds = numberOr(load.phases.initial_hold_seconds, numberOr(load.phases.hold_seconds, NaN));
+ if (!(initialHoldSeconds >= 1)) fail("load.phases.initial_hold_seconds (or hold_seconds) must be >= 1");
+ const finalHoldSeconds = numberOr(load.phases.final_hold_seconds, initialHoldSeconds);
+ if (!(finalHoldSeconds >= 1)) fail("load.phases.final_hold_seconds must be >= 1");
+ // New knob replacing step_rps: the ramp is one smooth interpolation from
+ // starting_rps to target_rps over this many seconds, not a staircase of
+ // step_rps-sized jumps each held for hold_seconds.
+ const rampDurationSeconds = numberOr(load.phases.ramp_duration_seconds, startRps < targetRps ? NaN : 0);
+ if (startRps < targetRps && !(rampDurationSeconds >= 1)) {
+ fail("load.phases.ramp_duration_seconds must be >= 1 when target_rps exceeds starting_rps");
+ }
+ const idleSeconds = numberOr(load.phases.idle_seconds, 0);
+ if (idleSeconds < 0) fail("load.phases.idle_seconds must be >= 0");
+ const legacyStages = [{ name: "initial_hold", targetRps: startRps, durationSeconds: initialHoldSeconds }];
+ if (targetRps > startRps) legacyStages.push({ name: "ramp", targetRps, durationSeconds: rampDurationSeconds });
+ legacyStages.push({ name: "final_hold", targetRps, durationSeconds: finalHoldSeconds });
+ rampPlan = {
+ startRps,
+ targetRps,
+ initialHoldSeconds,
+ rampDurationSeconds,
+ finalHoldSeconds,
+ idleSeconds,
+ stages: legacyStages,
+ strict: false,
+ // Same window formula the summary always used for load.phases, kept as-is
+ // so legacy configs print identical numbers.
+ totalSeconds: initialHoldSeconds + rampDurationSeconds + finalHoldSeconds,
+ peakRps: targetRps,
+ };
+} else {
+ flatTotalRps = numberOr(load.total_rps, NaN);
+ if (!(flatTotalRps > 0)) {
+ fail("load.total_rps must be a number > 0 (or configure load.phases for a stepped ramp)");
+ }
+ flatDurationSeconds = numberOr(load.duration_seconds, NaN);
+ if (!(flatDurationSeconds >= 1)) fail("load.duration_seconds must be >= 1");
+}
+
+const loadDescription = rampPlan
+ ? (rampPlan.strict
+ ? `stages: start ${rampPlan.startRps} rps -> ${rampPlan.stages.map((stage) => `${stage.name} ${stage.targetRps} rps/${stage.durationSeconds}s`).join(" -> ")} (total ${rampPlan.totalSeconds}s)`
+ : `ramp: hold ${rampPlan.startRps} rps x ${rampPlan.initialHoldSeconds}s -> ramp to ${rampPlan.targetRps} rps over ${rampPlan.rampDurationSeconds}s -> hold ${rampPlan.targetRps} rps x ${rampPlan.finalHoldSeconds}s (total ${rampPlan.totalSeconds}s)`)
+ : `total_rps=${flatTotalRps} | duration=${flatDurationSeconds}s`;
+
+const entries = Array.isArray(config.scenarios) ? config.scenarios : [];
+if (!entries.length) fail("scenarios must contain at least one entry");
+const plans = entries.map(buildPlan);
+const seenNames = new Set();
+for (const plan of plans) {
+ if (seenNames.has(plan.name)) fail(`duplicate scenario name "${plan.name}"`);
+ seenNames.add(plan.name);
+}
+const weightSum = plans.reduce((sum, plan) => sum + plan.weight, 0);
+if (Math.abs(weightSum - 100) > 1e-6) {
+ fail(`scenario weights must add up to 100 (got ${weightSum})`);
+}
+const enabledPlans = plans.filter((plan) => plan.weight > 0);
+if (!enabledPlans.length) fail("at least one scenario must have weight > 0");
+
+const services = config.services || {};
+const targetHeaders = config.target_headers || {};
+const merchant = config.merchant || {};
+const merchantPoolConfig = config.merchant_pool || null;
+
+if (!services.router) fail("services.router is required");
+const routerUrl = services.router.replace(/\/$/, "");
+// Customers are created through the payment-method service even for
+// non-modular scenarios, matching the runner's fixture stage. Known
+// tradeoff (explicit choice, 2026-09-15): a customer created this way is
+// v2-native, and a card saved for it via a non-modular (v1) CIT confirm
+// only becomes usable for MIT through Router's async
+// PaymentMethodModularForwardCompatWorkflow process-tracker job
+// (crates/router/src/core/payment_methods.rs:704-724) — there's no inline
+// path for this direction. Running mit immediately after its baseline
+// confirm can race that job and intermittently fail with IR_39 ("no
+// eligible connector found for token-based MIT payment"); accepted as a
+// known limitation rather than adding retry/delay logic here.
+const needsModularPm = enabledPlans.some((plan) => plan.usesPmService || plan.requiresCustomer);
+// The modular path needs it for payment-method-session confirm auth;
+// sdk_checkout and saved_card_checkout both need it to build the SDK
+// Authorization header (see sdkAuthorizationHeader()) for the combined
+// payment-method-list call.
+const needsPublishableKey = enabledPlans.some((plan) => plan.usesPmService || plan.sdkFlow || plan.savedCardCheckout);
+let modularPmUrl = null;
+if (needsModularPm) {
+ if (!services.modular_pm) {
+ fail("services.modular_pm is required: an enabled scenario uses the modular path or creates customers through the payment-method service");
+ }
+ modularPmUrl = services.modular_pm.replace(/\/$/, "");
+}
+
+// merchant_pool: an array of { merchant_id, api_key, publishable_key,
+// profile_id } entries (see provision-merchants.mjs), one picked at random
+// per iteration (pickMerchant() below) so traffic spreads evenly across
+// every merchant in the pool over the run — independent of VU/executor
+// topology, unlike trying to synthesize a cross-scenario global counter.
+// Falls back to the single top-level `merchant` block when merchant_pool
+// isn't configured (unchanged single-merchant behavior).
+let merchantPool = null;
+if (merchantPoolConfig) {
+ if (!merchantPoolConfig.file) fail("merchant_pool.file is required when merchant_pool is set");
+ let raw;
+ try {
+ raw = open(merchantPoolConfig.file);
+ } catch (error) {
+ fail(`cannot read merchant_pool.file at "${merchantPoolConfig.file}": ${error}`);
+ }
+ let parsed;
+ try {
+ parsed = JSON.parse(raw);
+ } catch (error) {
+ fail(`merchant_pool.file "${merchantPoolConfig.file}" is not valid JSON: ${error}`);
+ }
+ if (!Array.isArray(parsed) || !parsed.length) {
+ fail(`merchant_pool.file "${merchantPoolConfig.file}" must be a non-empty JSON array`);
+ }
+ parsed.forEach((entry, index) => {
+ if (!entry || !entry.api_key || !entry.profile_id) {
+ fail(`merchant_pool.file "${merchantPoolConfig.file}": entry [${index}] must have api_key and profile_id`);
+ }
+ if (needsPublishableKey && !entry.publishable_key) {
+ fail(`merchant_pool.file "${merchantPoolConfig.file}": entry [${index}] is missing publishable_key, required by the modular path and/or sdk_checkout`);
+ }
+ });
+ merchantPool = parsed;
+} else {
+ if (!merchant.api_key) fail("merchant.api_key is required (or configure merchant_pool)");
+ if (!merchant.profile_id) fail("merchant.profile_id is required (set on every payment create, or configure merchant_pool)");
+ if (needsPublishableKey && !merchant.publishable_key) {
+ fail("merchant.publishable_key is required for the modular merchant path (payment-method session confirm) and for sdk_checkout (SDK Authorization header), or configure merchant_pool");
+ }
+}
+
+function pickMerchant() {
+ if (!merchantPool) return merchant;
+ return merchantPool[Math.floor(Math.random() * merchantPool.length)];
+}
+
+if (!paymentConfig.card || !paymentConfig.card.card_number) fail("payment.card with card_number is required");
+const cardPool = Array.isArray(paymentConfig.card_pool) && paymentConfig.card_pool.length
+ ? paymentConfig.card_pool
+ : [paymentConfig.card];
+for (const [index, card] of cardPool.entries()) {
+ if (!card || !card.card_number) fail(`payment.card_pool[${index}] requires card_number`);
+}
+const metadataChangedUsed = enabledPlans.some((plan) => plan.metadataChanged);
+if (metadataChangedUsed && (!paymentConfig.metadata_update || typeof paymentConfig.metadata_update !== "object")) {
+ fail("payment.metadata_update is required when cit_metadata_changed is enabled");
+}
+const metadataUpdate = paymentConfig.metadata_update || {};
+
+const paymentAmount = numberOr(paymentConfig.amount, 1000);
+const paymentCurrency = paymentConfig.currency || "USD";
+const sessionExpiry = numberOr(paymentConfig.session_expiry, 900);
+// mit's single create+confirm call passes a return_url the way cypress-tests'
+// MIT fixtures do, even though an off_session recurring charge won't
+// normally redirect anywhere.
+const mitReturnUrl = paymentConfig.return_url || "https://example.com";
+
+// Wallets requested by sdk_checkout's session call (POST /payments/session_tokens).
+// Empty is valid and is the default — most test merchants have no wallet connectors.
+const sdkConfig = config.sdk || {};
+const sdkWallets = Array.isArray(sdkConfig.wallets) ? sdkConfig.wallets : [];
+
+// ---------------------------------------------------------------------------
+// k6 options: one constant-arrival-rate executor per traffic entry. The split
+// is deterministic: rate = total_rps * weight / 100.
+// ---------------------------------------------------------------------------
+
+const scenarios = {};
+const planByName = {};
+
+function rateFor(plan, phaseRps) {
+ return (phaseRps * plan.weight) / 100;
+}
+
+// constant-arrival-rate requires an integer iteration count; fractional
+// rates are expressed with a longer timeUnit (0.5/s -> 1 iteration / 2s).
+function arrivalRate(ratePerSecond) {
+ const rounded = Math.round(ratePerSecond * 1e6) / 1e6;
+ for (let timeUnitSeconds = 1; timeUnitSeconds <= 36000; timeUnitSeconds += 1) {
+ const iterations = rounded * timeUnitSeconds;
+ const nearest = Math.round(iterations);
+ if (nearest >= 1 && Math.abs(iterations - nearest) < 1e-9) {
+ return { rate: nearest, timeUnit: `${timeUnitSeconds}s` };
+ }
+ }
+ fail(`cannot express rate ${ratePerSecond}/s as an integer arrival rate`);
+}
+
+// Flat-mode only now (ramp mode uses rampingExecutor below) - a single
+// constant-arrival-rate scenario for the whole flat-RPS test.
+function executor(name, plan, ratePerSecond, durationSeconds) {
+ const arrival = arrivalRate(ratePerSecond);
+ const preAllocatedVUs = Math.max(1, Math.ceil(ratePerSecond * preAllocatedVusMultiplier));
+ scenarios[name] = {
+ executor: "constant-arrival-rate",
+ exec: "runScenario",
+ rate: arrival.rate,
+ timeUnit: arrival.timeUnit,
+ duration: `${durationSeconds}s`,
+ preAllocatedVUs,
+ maxVUs: Math.max(preAllocatedVUs, Math.ceil(ratePerSecond * maxVusMultiplier)),
+ // An iteration runs several sequential requests; allow ramp-down to cover
+ // roughly a worst-case full flow.
+ gracefulStop: `${Math.ceil((requestTimeoutMs * 8) / 1000)}s`,
+ env: { SCENARIO_NAME: plan.name },
+ tags: { traffic_scenario: plan.name },
+ };
+}
+
+// Ramp mode: ONE ramping-arrival-rate scenario per traffic entry, alive for
+// the whole test - hold at startRps, smoothly ramp to targetRps, hold at
+// targetRps. preAllocatedVUs/maxVUs are sized off the PEAK rate (targetRps)
+// since the same pool must cover the scenario's busiest moment; raising
+// load.pre_allocated_vus_multiplier gives this pool more headroom allocated
+// up front (at scenario start, not reactively mid-ramp) - the second half
+// of this session's fix, alongside the single-scenario restructure itself.
+//
+// Stage rates are integers per scenario. load.phases keeps its historical
+// Math.max(1, round(...)) clamp; load.stages (rp.strict) instead refuses to
+// run when a stage's per-scenario rates round to 0 or no longer add up to the
+// stage's total, rather than silently inflating a low-rate stage.
+function stageRate(plan, rp, rps) {
+ const rate = Math.round(rateFor(plan, rps));
+ return rp.strict ? rate : Math.max(1, rate);
+}
+
+function validateStageRates(rp) {
+ for (const rps of [rp.startRps, ...rp.stages.map((stage) => stage.targetRps)]) {
+ let sum = 0;
+ for (const plan of enabledPlans) {
+ const rate = stageRate(plan, rp, rps);
+ if (rate < 1 && rps !== 0) {
+ fail(`${rps} rps gives scenario "${plan.name}" (weight ${plan.weight}%) an arrival rate of ${rate}/s; raise that stage's rate or weight`);
+ }
+ sum += rate;
+ }
+ if (sum !== rps) {
+ fail(`${rps} rps splits across the enabled scenarios into integer rates summing to ${sum}, not ${rps}; use a rate that divides evenly by the weights`);
+ }
+ }
+}
+
+function rampingExecutor(name, plan, rp) {
+ const startRate = stageRate(plan, rp, rp.startRps);
+ const peakRate = stageRate(plan, rp, rp.peakRps);
+ const preAllocatedVUs = Math.max(1, Math.ceil(peakRate * preAllocatedVusMultiplier));
+ const stages = rp.stages.map((stage) => ({
+ target: stageRate(plan, rp, stage.targetRps),
+ duration: `${stage.durationSeconds}s`,
+ }));
+ scenarios[name] = {
+ executor: "ramping-arrival-rate",
+ exec: "runScenario",
+ startRate,
+ timeUnit: "1s",
+ preAllocatedVUs,
+ maxVUs: Math.max(preAllocatedVUs, Math.ceil(peakRate * maxVusMultiplier)),
+ stages,
+ gracefulStop: `${Math.ceil((requestTimeoutMs * 8) / 1000)}s`,
+ env: { SCENARIO_NAME: plan.name },
+ tags: { traffic_scenario: plan.name },
+ };
+}
+
+if (rampPlan) {
+ if (rampPlan.strict && !__ENV.SQLITE_RECORDER_CONTROL_FILE) validateStageRates(rampPlan);
+ for (const plan of enabledPlans) {
+ rampingExecutor(plan.name, plan, rampPlan);
+ }
+} else {
+ for (const plan of enabledPlans) {
+ executor(plan.name, plan, rateFor(plan, flatTotalRps), flatDurationSeconds);
+ }
+}
+for (const plan of enabledPlans) planByName[plan.name] = plan;
+// Console runs use native Go admission pacing and a persistent VU pool. The
+// CLI keeps k6's arrival-rate executors. No HTTP round trip occurs per flow.
+if (__ENV.SQLITE_RECORDER_CONTROL_FILE) {
+ const peak = rampPlan ? rampPlan.peakRps : flatTotalRps;
+ for (const plan of enabledPlans) {
+ const vus = Math.max(1,Math.ceil(rateFor(plan,peak)*maxVusMultiplier));
+ scenarios[plan.name] = {executor:'externally-controlled',exec:'runScenario',duration:'0s',vus,maxVUs:vus,
+ env:{SCENARIO_NAME:plan.name},tags:{traffic_scenario:plan.name}};
+ }
+}
+
+export const options = {
+ scenarios,
+ thresholds: config.thresholds && typeof config.thresholds === "object" ? config.thresholds : {},
+ summaryTrendStats: ["count", "avg", "med", "p(75)", "p(90)", "p(99)", "max"],
+};
+
+// ---------------------------------------------------------------------------
+// Metrics: per-scenario Trends so the summary splits percentiles per traffic
+// entry, plus one cross-scenario confirm trend and success/failure counters.
+// ---------------------------------------------------------------------------
+
+const connectorAssigned=new Counter("connector_assigned");
+const connectorConfirmed=new Counter("connector_confirmed");
+const connectorSucceeded=new Counter("connector_succeeded");
+const globalPaymentConfirm = new Trend("payment_confirm_latency_ms", true);
+const globalServerConfirm = new Trend("payment_confirm_server_latency_ms", true);
+
+function stepNames(plan) {
+ const steps = [];
+ if (plan.requiresCustomer) steps.push("customer_create");
+ if (plan.usesPmService) steps.push("pm_session_create");
+ if (plan.requiresSavedCard) steps.push("baseline_create", "baseline_confirm");
+ // mit's measured request is a single POST /payments with confirm:true —
+ // there is no separate payment_create call to time.
+ if (!plan.mitFlow) steps.push("payment_create");
+ if (plan.sdkFlow) steps.push("payment_method_list", "session", "eligibility");
+ // saved_card_checkout calls the same combined list endpoint as
+ // sdk_checkout's payment_method_list step, but on its own (no session/
+ // eligibility calls) — see Step 4c in runFlow().
+ if (plan.savedCardCheckout) steps.push("payment_method_list");
+ if (plan.usesPmService) steps.push("pm_session_confirm");
+ steps.push("payment_confirm");
+ return steps;
+}
+
+for (const plan of enabledPlans) {
+ plan.trends = {};
+ for (const step of stepNames(plan)) {
+ plan.trends[step] = new Trend(`${step}_ms_${plan.name}`, true);
+ }
+ plan.serverConfirmTrend = new Trend(`payment_confirm_server_ms_${plan.name}`, true);
+ plan.trends.total_flow = new Trend(`total_flow_ms_${plan.name}`, true);
+ plan.successCounter = new Counter(`scenario_success_${plan.name}`);
+ plan.failureCounter = new Counter(`scenario_failure_${plan.name}`);
+ // 2026-09-24: per-phase (_p<N>) breakdown removed along with the discrete-
+ // step scenario design (see the ramp-mode parsing block's comment above) -
+ // there's no longer a discrete phase boundary to slice metrics by under
+ // ramping-arrival-rate's continuous interpolation. plan.phases stays null
+ // in both modes now; the aggregate trends/counters above (and the whole-
+ // scenario achieved-TPS reporting in handleSummary) are what's left.
+ plan.phases = null;
+}
+
+// ---------------------------------------------------------------------------
+// Request helpers shared by the supported payment flows.
+// ---------------------------------------------------------------------------
+
+function json(response) {
+ try { return response.json(); } catch (_) { return {}; }
+}
+
+function requestParams(headers, operation) {
+ return { headers, timeout: `${requestTimeoutMs}ms`, redirects: 0, tags: { operation, name: operation } };
+}
+
+// VU-local flow context. Every request, including polling, passes through here.
+let flowContext = null;
+let lastEvent = null;
+function request(method, url, body, headers, operation) {
+ if(method==='POST'&&['payment_confirm','baseline_confirm'].includes(operation)&&flowContext?.connectorChoice)body={...(config.connectors?.mode==='real'?{browser_info:connectorBrowserInfo(paymentConfig.browser_info)}:{}),...body,...connectorRouting(flowContext.connectorChoice)};
+ const started = Date.now();
+ let response;
+ let transportError;
+ let attemptId = null;
+ if (recordingEnabled) {
+ // Primitive arguments avoid constructing/exporting a second response object per call.
+ try { attemptId = recorder.begin(flowContext.flow_id,flowContext.merchant_id || null,operation,method,url,
+ body?.customer_id || flowContext.customer_id || null,body?.merchant_reference_id || null,
+ flowContext.payment_id || null,Number.isSafeInteger(body?.amount) ? body.amount : null,started,flowContext.connectorChoice?.connector||"",flowContext.connectorChoice?.merchant_connector_id||""); } catch (error) {
+ exec.test.abort(`SQLite recorder cannot begin request: ${error.message || error}`); throw error;
+ }
+ }
+ try {
+ response = http.request(method,url,body === null ? null : JSON.stringify(body),requestParams(headers,operation));
+ } catch (error) { transportError = error; }
+ if (!recordingEnabled) { if (transportError) throw transportError; return response; }
+ let record;
+ try { record = recorder.complete(attemptId,response || null,transportError?.message || ""); } catch (error) {
+ // runScenario catches ordinary flow errors; recorder failures must stop every VU.
+ exec.test.abort(`SQLite recording failed: ${error.message || error}`); throw error;
+ }
+ lastEvent = { attempt_id: attemptId, flow_id: flowContext.flow_id, operation, request_id: record.request_id };
+ if (record.entity_type === "customer" && record.customer_id) flowContext.customer_id = record.customer_id;
+ if (record.entity_type === "payment" && record.payment_id && record.role === "measured") flowContext.payment_id = record.payment_id;
+ if (transportError) throw transportError;
+ return response;
+}
+function post(url, body, headers, operation) { return request("POST",url,body,headers,operation); }
+function get(url, headers, operation) { return request("GET",url,null,headers,operation); }
+
+function apiKeyHeaders(merchant) {
+ return {
+ ...latencyHeaders(targetHeaders.router),
+ "api-key": merchant.api_key,
+ "content-type": "application/json",
+ };
+}
+
+function modularApiKeyHeaders(merchant) {
+ return {
+ ...(targetHeaders.modular_pm || {}),
+ Authorization: `api-key=${merchant.api_key}`,
+ "x-profile-id": merchant.profile_id,
+ "content-type": "application/json",
+ };
+}
+
+function modularSessionHeaders(merchant, clientSecret) {
+ return {
+ ...(targetHeaders.modular_pm || {}),
+ Authorization: `publishable-key=${merchant.publishable_key},client-secret=${clientSecret}`,
+ "x-profile-id": merchant.profile_id,
+ "content-type": "application/json",
+ };
+}
+
+// Base64 (standard, padded) of comma-separated key=value pairs, decoded by
+// SdkAuthorization::decode (crates/hyperswitch_domain_models/src/sdk_auth.rs).
+// Replicates the Authorization header the Hyperswitch SDK sends on
+// payment_method_list / session / eligibility once it holds a payment_id and
+// client_secret from payment create.
+function sdkAuthorizationHeader(merchant, payment) {
+ const parts = [
+ `profile_id=${merchant.profile_id}`,
+ `publishable_key=${merchant.publishable_key}`,
+ `client_secret=${payment.client_secret}`,
+ `payment_id=${payment.payment_id}`,
+ ];
+ return encoding.b64encode(parts.join(","));
+}
+
+function sdkAuthHeaders(merchant, payment) {
+ return {
+ ...latencyHeaders(targetHeaders.router),
+ Authorization: sdkAuthorizationHeader(merchant, payment),
+ "content-type": "application/json",
+ };
+}
+
+function customerAcceptance() {
+ return {
+ acceptance_type: "online",
+ accepted_at: new Date().toISOString(),
+ online: { ip_address: "127.0.0.1", user_agent: "k6-scenario-mix" },
+ };
+}
+
+function pickCard(iteration) {
+ return cardPool[iteration % cardPool.length];
+}
+
+function paymentCreateBody(merchant, plan, customerId, description) {
+ return {
+ amount: paymentAmount,
+ currency: paymentCurrency,
+ confirm: false,
+ capture_method: "automatic",
+ profile_id: merchant.profile_id,
+ session_expiry: sessionExpiry,
+ description,
+ ...(customerId ? { customer_id: customerId } : {}),
+ ...(plan.setupFutureUsage ? { setup_future_usage: plan.setupFutureUsage } : {}),
+ };
+}
+
+// mit's measured request: a single create+confirm call against a previously
+// saved payment method, no card data on the wire. Mirrors cypress-tests'
+// create-pm-id-mit.json fixture and the recurring_details.payment_method_id
+// flow it exercises (cypress-tests/cypress/e2e/spec/Payment/20-MandatesUsingPMID.cy.js).
+// Router requires confirm:true, off_session:true and customer_id together
+// with recurring_details (validate_recurring_mandate in
+// crates/router/src/core/payments/operations/payment_confirm.rs).
+function mitConfirmBody(merchant, customerId, savedPaymentMethodId, description) {
+ return {
+ amount: paymentAmount,
+ currency: paymentCurrency,
+ confirm: true,
+ capture_method: "automatic",
+ profile_id: merchant.profile_id,
+ session_expiry: sessionExpiry,
+ description,
+ customer_id: customerId,
+ off_session: true,
+ recurring_details: { type: "payment_method_id", data: savedPaymentMethodId },
+ return_url: mitReturnUrl,
+ };
+}
+
+// One JSON record per failed iteration, via console.error. k6 VU code cannot
+// write files directly (open() is read-only, init-stage only), so the way to
+// get a durable failures file is k6's own console-output redirection: run
+// with `k6 run --console-output=failures.log` (or `K6_CONSOLE_OUTPUT=failures.log`)
+// and every console.error call below lands there as its own line instead of
+// the terminal — see README "Logging failures to a file".
+function logFailure(merchant, plan, phaseInfo, reason, response, errorMessage, flowMs) {
+ // SQLite preserves every failure. Per-flow terminal output can throttle a failure storm.
+ if (recordingEnabled && load.log_failures !== true) return;
+ const record = {
+ time: new Date().toISOString(),
+ scenario: plan.name,
+ merchant_path: plan.merchantPath,
+ scenario_type: plan.scenarioName,
+ // Only meaningful (and present) in merchant_pool mode — the single
+ // top-level `merchant` config block has no merchant_id field.
+ merchant_id: merchant.merchant_id,
+ phase: phaseInfo ? phaseInfo.index : undefined,
+ vu: __VU,
+ iteration: exec.scenario.iterationInTest,
+ reason,
+ // Wall-clock age of the iteration at the moment it failed, so a post-hoc
+ // report can bucket the failure by when the flow STARTED (time - flow_ms),
+ // the same basis RECON success lines use (ts - flow_ms).
+ flow_ms: flowMs,
+ };
+ if (response) {
+ record.status = response.status;
+ record.url = response.url;
+ record.error = response.error || undefined;
+ record.event = lastEvent;
+ // Without the SQLite recorder the console line is the only record of a failure, so keep the
+ // response headers/body there (with the recorder they live in SQLite, see request()).
+ if (!recordingEnabled) {
+ record.headers = response.headers;
+ record.body = response.body;
+ }
+ // payment_id when the failing request carries one (confirm/retrieve URLs,
+ // or a create response body), so failures can be reconciled against the
+ // database the same way RECON success lines are.
+ const urlMatch = /\/payments\/(pay_[A-Za-z0-9_]+)/.exec(response.url || "");
+ if (urlMatch) {
+ record.payment_id = urlMatch[1];
+ } else {
+ try {
+ const parsedBody = JSON.parse(response.body);
+ if (parsedBody && parsedBody.payment_id) record.payment_id = parsedBody.payment_id;
+ } catch (_) { /* non-JSON error body: no payment_id to record */ }
+ }
+ }
+ if (errorMessage) record.error_message = errorMessage;
+ console.error(JSON.stringify(record));
+}
+
+function failIteration(merchant, plan, startedAt, reason, phaseInfo, response, errorMessage) {
+ plan.failureCounter.add(1, { reason });
+ if (phaseInfo) phaseInfo.failureCounter.add(1, { reason });
+ plan.trends.total_flow.add(Date.now() - startedAt);
+ logFailure(merchant, plan, phaseInfo, reason, response, errorMessage, Date.now() - startedAt);
+}
+
+// Card persistence can complete shortly after a successful confirm. Poll the
+// payment until the saved payment method surfaces (fixtures.js behavior).
+function findSavedPaymentMethod(merchant, paymentId) {
+ for (let attempt = 0; attempt < 50; attempt += 1) {
+ const response = get(`${routerUrl}/payments/${paymentId}`, apiKeyHeaders(merchant), "baseline_poll");
+ const paymentMethodId = json(response).payment_method_id;
+ if (paymentMethodId) return paymentMethodId;
+ sleep(0.1);
+ }
+ return null;
+}
+
+// ---------------------------------------------------------------------------
+// Measured traffic
+// ---------------------------------------------------------------------------
+
+// Runs once, after init and immediately before the first scenario starts, so
+// this line is the closest wall-clock anchor to t=0 of the load curve. An
+// orchestrator scheduling faults/stage windows against the curve should use
+// it rather than the moment it launched k6 (init + VU pre-allocation shift
+// the two by seconds). One line per host; both hosts of a split run print
+// their own, and the gap between them is the cross-host start skew.
+export function setup() {
+ console.log(`RUNSTART ts=${new Date().toISOString()} epoch_ms=${Date.now()}`);
+}
+
+export function runScenario() {
+ const plan = planByName[__ENV.SCENARIO_NAME];
+ const controlled = Boolean(__ENV.SQLITE_RECORDER_CONTROL_FILE);
+ if (controlled && !recorder.enter(plan.name)) return;
+ const phaseInfo = plan.phases ? plan.phases[Number(__ENV.PHASE_INDEX || 0)] : null;
+ const startedAt = Date.now();
+ // Resolved once per iteration (not per request) so every request in the
+ // flow — and a mid-flow exception's failure record — uses the same
+ // merchant, and so a merchant_pool run is a uniform-random pick over the
+ // whole pool per iteration rather than per request.
+ let merchant;
+ try {
+ merchant = pickMerchant();
+ flowContext = { flow_id: `${__ENV.SQLITE_RECORDER_RUN_ID || "unrecorded"}:${exec.scenario.name}:${__VU}:${exec.scenario.iterationInTest}`,
+ merchant_id: merchant.merchant_id, customer_id: null, payment_id: null,connectorChoice:selectedConnector(connectorSlots,exec.scenario.iterationInTest,merchant) };
+ if(flowContext.connectorChoice)connectorAssigned.add(1,{connector:flowContext.connectorChoice.connector});
+ lastEvent = null;
+ // Never let an unexpected exception kill an iteration invisibly: k6 would
+ // count it as complete with no success/failure recorded, silently
+ // understating the failure rate.
+ runFlow(merchant, plan, phaseInfo, startedAt);
+ } catch (error) {
+ failIteration(merchant, plan, startedAt, `exception_${(error && error.name) || "error"}`, phaseInfo, null, error && error.message);
+ } finally { if (controlled) recorder.leave(); }
+}
+
+function runFlow(merchant, plan, phaseInfo, startedAt) {
+ const iteration = exec.scenario.iterationInTest;
+ const defaultCard = pickCard(iteration);
+ const card = config.connectors?.mode==='real'?connectorTestCard(flowContext.connectorChoice?.connector,defaultCard,paymentConfig.connector_cards):defaultCard;
+
+ // Step 1: customer (CIT and saved-card scenarios only; guests skip this).
+ // Always through the payment-method service, regardless of merchant_path
+ // — explicit choice (2026-09-15) accepting that mit/cit_metadata_changed's
+ // baseline card save (v1 confirm) then relies on Router's async
+ // PaymentMethodModularForwardCompatWorkflow process-tracker job to make
+ // the card usable for the measured MIT/recurring confirm; no inline path
+ // exists for that sync, so running the measured request immediately after
+ // the baseline can race it and intermittently return IR_39.
+ let customerId = null;
+ if (plan.requiresCustomer) {
+ const reference = `customer_mix_${plan.name}_${iteration}_${__VU}_${Date.now()}`;
+ const response = post(
+ `${modularPmUrl}/customers`,
+ {
+ merchant_reference_id: reference,
+ name: "Loadtest User",
+ phone: "6168205362",
+ email: `${reference}@example.com`,
+ phone_country_code: "+1",
+ },
+ modularApiKeyHeaders(merchant),
+ "customer_create",
+ );
+ plan.trends.customer_create.add(response.timings.duration);
+ const body = json(response);
+ customerId = body.id || body.customer_id;
+ if (response.status < 200 || response.status >= 300 || !customerId) {
+ failIteration(merchant, plan, startedAt, `customer_create_${statusCode(response)}`, phaseInfo, response);
+ return;
+ }
+ }
+
+ // Step 2: payment-method session (modular merchant path only).
+ let pmSessionId = null;
+ let pmSessionClientSecret = null;
+ if (plan.usesPmService) {
+ const response = post(
+ `${modularPmUrl}/payment-method-sessions`,
+ {
+ ...(customerId ? { customer_id: customerId } : {}),
+ expires_in: sessionExpiry,
+ storage_type: plan.storageType,
+ },
+ modularApiKeyHeaders(merchant),
+ "pm_session_create",
+ );
+ plan.trends.pm_session_create.add(response.timings.duration);
+ const body = json(response);
+ pmSessionId = body.id;
+ pmSessionClientSecret = body.client_secret;
+ if (response.status < 200 || response.status >= 300 || !pmSessionId || !pmSessionClientSecret) {
+ failIteration(merchant, plan, startedAt, `pm_session_create_${statusCode(response)}`, phaseInfo, response);
+ return;
+ }
+ }
+
+ // Step 3: baseline saved card (cit_metadata_changed, mit,
+ // saved_card_checkout). The measured confirm later either resubmits the
+ // same PAN with changed metadata (cit_metadata_changed), charges the saved
+ // payment_method_id directly (mit), or looks the card back up through the
+ // combined payment-method-list endpoint (saved_card_checkout, Step 4c
+ // below).
+ let savedPaymentMethodId = null;
+ // Payment token the measured confirm's `payment_token` field uses —
+ // sourced from either Step 4c below (saved_card_checkout) or the modular
+ // pm-session confirm (Step 5).
+ let token = null;
+ if (plan.requiresSavedCard) {
+ const createResponse = post(
+ `${routerUrl}/payments`,
+ paymentCreateBody(merchant, plan, customerId, `scenario-mix baseline ${plan.merchantPath}:${plan.scenarioName}`),
+ apiKeyHeaders(merchant),
+ "baseline_create",
+ );
+ plan.trends.baseline_create.add(createResponse.timings.duration);
+ const baseline = json(createResponse);
+ if (createResponse.status < 200 || createResponse.status >= 300 || !baseline.payment_id) {
+ failIteration(merchant, plan, startedAt, `baseline_create_${statusCode(createResponse)}`, phaseInfo, createResponse);
+ return;
+ }
+ const confirmResponse = post(
+ `${routerUrl}/payments/${baseline.payment_id}/confirm`,
+ {
+ payment_method: "card",
+ payment_method_type: "credit",
+ payment_method_data: { card },
+ // The baseline must finish storing the card before measured traffic.
+ setup_future_usage: "off_session",
+ customer_acceptance: customerAcceptance(),
+ },
+ apiKeyHeaders(merchant),
+ "baseline_confirm",
+ );
+ plan.trends.baseline_confirm.add(confirmResponse.timings.duration);
+ savedPaymentMethodId = json(confirmResponse).payment_method_id
+ || findSavedPaymentMethod(merchant, baseline.payment_id);
+ if (confirmResponse.status < 200 || confirmResponse.status >= 300 || !savedPaymentMethodId) {
+ failIteration(merchant, plan, startedAt, `baseline_confirm_${statusCode(confirmResponse)}`, phaseInfo, confirmResponse);
+ return;
+ }
+ }
+
+ // Optional settling pause between preparation and the measured requests.
+ if (thinkTimeMs > 0) sleep(thinkTimeMs / 1000);
+
+ // Step 4: create the payment that the measured confirm operates on. mit
+ // skips this — its measured step is a single create+confirm call (Step 6).
+ let payment = null;
+ if (!plan.mitFlow) {
+ const createResponse = post(
+ `${routerUrl}/payments`,
+ paymentCreateBody(merchant, plan, customerId, `scenario-mix ${plan.merchantPath}:${plan.scenarioName}`),
+ apiKeyHeaders(merchant),
+ "payment_create",
+ );
+ plan.trends.payment_create.add(createResponse.timings.duration);
+ payment = json(createResponse);
+ if (createResponse.status < 200 || createResponse.status >= 300 || !payment.payment_id) {
+ failIteration(merchant, plan, startedAt, `payment_create_${statusCode(createResponse)}`, phaseInfo, createResponse);
+ return;
+ }
+ }
+
+ // Step 4b: SDK pre-confirm calls (sdk_checkout only) — replicates what the
+ // Hyperswitch SDK does between intent creation and confirm: list available
+ // payment methods, fetch wallet session tokens, and run an eligibility
+ // check for the card the shopper is about to submit.
+ if (plan.sdkFlow) {
+ const pmListResponse = get(
+ `${routerUrl}/payments/${payment.payment_id}/client`,
+ sdkAuthHeaders(merchant, payment),
+ "payment_method_list",
+ );
+ plan.trends.payment_method_list.add(pmListResponse.timings.duration);
+ if (pmListResponse.status < 200 || pmListResponse.status >= 300) {
+ failIteration(merchant, plan, startedAt, `payment_method_list_${statusCode(pmListResponse)}`, phaseInfo, pmListResponse);
+ return;
+ }
+
+ const sessionResponse = post(
+ `${routerUrl}/payments/session_tokens`,
+ { payment_id: payment.payment_id, client_secret: payment.client_secret, wallets: sdkWallets },
+ sdkAuthHeaders(merchant, payment),
+ "session",
+ );
+ plan.trends.session.add(sessionResponse.timings.duration);
+ if (sessionResponse.status < 200 || sessionResponse.status >= 300) {
+ failIteration(merchant, plan, startedAt, `session_${statusCode(sessionResponse)}`, phaseInfo, sessionResponse);
+ return;
+ }
+
+ const eligibilityResponse = post(
+ `${routerUrl}/payments/${payment.payment_id}/eligibility`,
+ {
+ payment_method_type: "card",
+ payment_method_subtype: "credit",
+ payment_method_data: { card },
+ },
+ sdkAuthHeaders(merchant, payment),
+ "eligibility",
+ );
+ plan.trends.eligibility.add(eligibilityResponse.timings.duration);
+ if (eligibilityResponse.status < 200 || eligibilityResponse.status >= 300) {
+ failIteration(merchant, plan, startedAt, `eligibility_${statusCode(eligibilityResponse)}`, phaseInfo, eligibilityResponse);
+ return;
+ }
+ }
+
+ // Step 4c: combined payment-method list (saved_card_checkout only) — the
+ // same GET /payments/{id}/client endpoint sdk_checkout's payment_method_list
+ // step calls, but here the intent carries a customer_id, so the response's
+ // customer_payment_methods includes the card saved in the baseline step;
+ // its payment_token is what the measured confirm below spends. Mirrors
+ // cypress-tests' listCustomerPMCallTest, adapted to the combined list
+ // endpoint per SDK usage rather than the merchant-facing
+ // /customers/{id}/payment_methods endpoint.
+ if (plan.savedCardCheckout) {
+ const response = get(
+ `${routerUrl}/payments/${payment.payment_id}/client`,
+ sdkAuthHeaders(merchant, payment),
+ "payment_method_list",
+ );
+ plan.trends.payment_method_list.add(response.timings.duration);
+ token = json(response).customer_payment_methods?.[0]?.payment_token;
+ let listResponse = response;
+ // A 2xx with an empty customer_payment_methods means the baseline's v1
+ // CIT confirm hasn't synced into the v2 payment-method store this
+ // endpoint reads from yet — the same async
+ // PaymentMethodModularForwardCompatWorkflow race called out for mit's
+ // IR_39 above, just surfacing here as an empty list instead of a hard
+ // error. Poll briefly rather than failing on the first empty response
+ // (mirrors findSavedPaymentMethod above, and the "wait a moment and
+ // re-send this request" the nomod-saved-card-scenario Postman
+ // collection's own test script calls out for this exact request).
+ if (listResponse.status >= 200 && listResponse.status < 300 && !token) {
+ for (let attempt = 0; attempt < 50 && !token; attempt += 1) {
+ sleep(0.1);
+ listResponse = get(`${routerUrl}/payments/${payment.payment_id}/client`, sdkAuthHeaders(merchant, payment), "payment_method_list_poll");
+ token = json(listResponse).customer_payment_methods?.[0]?.payment_token;
+ }
+ }
+ if (listResponse.status < 200 || listResponse.status >= 300 || !token) {
+ failIteration(merchant, plan, startedAt, `payment_method_list_${statusCode(listResponse)}`, phaseInfo, listResponse);
+ return;
+ }
+ }
+
+ // Step 5: confirm the payment-method session to obtain a payment token
+ // (modular merchant path only).
+ if (plan.usesPmService) {
+ const body = {
+ payment_method_data: { card },
+ payment_method_type: "card",
+ payment_method_subtype: "credit",
+ };
+ // PM Modular persists a session-backed card only after recording the
+ // customer's acceptance. Guest sessions intentionally remain volatile.
+ if (plan.setupFutureUsage) body.customer_acceptance = customerAcceptance();
+ const response = post(
+ `${modularPmUrl}/payment-method-sessions/${pmSessionId}/confirm`,
+ body,
+ modularSessionHeaders(merchant, pmSessionClientSecret),
+ "pm_session_confirm",
+ );
+ plan.trends.pm_session_confirm.add(response.timings.duration);
+ const pmBody = json(response);
+ token = pmBody.associated_payment_methods?.[0]?.payment_method_token;
+ if (token && typeof token === "object") token = token.data;
+ if (response.status < 200 || response.status >= 300 || !token) {
+ failIteration(merchant, plan, startedAt, `pm_session_confirm_${statusCode(response)}`, phaseInfo, response);
+ return;
+ }
+ }
+
+ // Step 6: measured payment confirm. mit is a single create+confirm call
+ // against the saved payment method (no payment.payment_id to confirm
+ // against, no card data) rather than confirming the Step 4 intent.
+ let confirmResponse;
+ if (plan.mitFlow) {
+ confirmResponse = post(
+ `${routerUrl}/payments`,
+ mitConfirmBody(merchant, customerId, savedPaymentMethodId, `scenario-mix ${plan.merchantPath}:${plan.scenarioName}`),
+ apiKeyHeaders(merchant),
+ "payment_confirm",
+ );
+ } else {
+ const measuredCard = plan.metadataChanged ? { ...card, ...metadataUpdate } : card;
+ let confirmBody;
+ if (plan.savedCardCheckout) {
+ // Repeat-customer confirm: payment_token references the locker-held
+ // PAN, payment_method_data.card_token supplies the fresh CVC (never
+ // stored server-side) plus the holder name — the currently-recommended
+ // shape (api_models::payments' top-level `card_cvc` field is being
+ // deprecated in favor of `payment_method_data.card_token`). This is a
+ // different request shape from the modular pm-session token confirm
+ // below on purpose: it's what drives router's make_pm_data /
+ // retrieve_payment_method_with_token merge (CardToken + locker PAN),
+ // not a bare payment_token + payment_method_type pair.
+ confirmBody = {
+ payment_token: token,
+ payment_method: "card",
+ payment_method_data: {
+ card_token: {
+ card_holder_name: card.card_holder_name,
+ card_cvc: card.card_cvc,
+ },
+ },
+ };
+ } else if (plan.usesPmService) {
+ confirmBody = { payment_token: token, payment_method: "card", payment_method_type: "credit" };
+ } else {
+ confirmBody = { payment_method: "card", payment_method_type: "credit", payment_method_data: { card: measuredCard } };
+ }
+ if (plan.setupFutureUsage) {
+ confirmBody.setup_future_usage = plan.setupFutureUsage;
+ confirmBody.customer_acceptance = customerAcceptance();
+ }
+ confirmResponse = post(
+ `${routerUrl}/payments/${payment.payment_id}/confirm`,
+ confirmBody,
+ apiKeyHeaders(merchant),
+ "payment_confirm",
+ );
+ }
+ plan.trends.payment_confirm.add(confirmResponse.timings.duration);
+ globalPaymentConfirm.add(confirmResponse.timings.duration);
+ const serverMs=serverLatency(confirmResponse.headers);
+ if (phaseInfo) phaseInfo.confirmTrend.add(confirmResponse.timings.duration);
+ const confirmedConnector=json(confirmResponse).connector;
+ if(confirmedConnector)connectorConfirmed.add(1,{connector:confirmedConnector});
+ const status = json(confirmResponse).status || "failed";
+ const succeeded = confirmResponse.status >= 200
+ && confirmResponse.status < 300
+ && SUCCESS_STATUSES.has(status);
+ if (!succeeded) {
+ failIteration(merchant, plan, startedAt, `payment_confirm_${statusCode(confirmResponse)}_${status}`, phaseInfo, confirmResponse);
+ return;
+ }
+ if(serverMs!==null){globalServerConfirm.add(serverMs);plan.serverConfirmTrend.add(serverMs);}
+ if(confirmedConnector)connectorSucceeded.add(1,{connector:confirmedConnector});
+ plan.successCounter.add(1);
+ if (phaseInfo) phaseInfo.successCounter.add(1);
+ // Payment-id-level success record for post-hoc reconciliation against
+ // AlloyDB (scripts/alloydb-reconcile-ledger.sh in the hyperswitch-infra
+ // repo). `payment` is null for mitFlow (single-call create+confirm, no
+ // separate create step) - fall back to the confirm response body's own
+ // payment_id, which is always present on a successful confirm either way.
+ const reconPaymentId = (payment && payment.payment_id) || json(confirmResponse).payment_id || "unknown";
+ // merchant_id only meaningful in merchant_pool mode (empty string in
+ // single-merchant mode, matching logFailure's own merchant_id field above)
+ // - lets a per-merchant success/failure breakdown be computed straight
+ // from this console log, same source as everything else, no separate
+ // metric-tag plumbing needed (TC-09).
+ if (!__ENV.LOADTEST_CONSOLE_JOB) console.log(`RECON payment_id=${reconPaymentId} status=${confirmResponse.status} merchant_id=${merchant.merchant_id || ""} confirm_ms=${confirmResponse.timings.duration.toFixed(1)} flow_ms=${Date.now() - startedAt} ts=${new Date().toISOString()}`);
+ plan.trends.total_flow.add(Date.now() - startedAt);
+}
+
+// ---------------------------------------------------------------------------
+// Summary: per-scenario percentile table plus optional full JSON export.
+// ---------------------------------------------------------------------------
+
+function metricValues(data, name) {
+ const metric = data.metrics[name];
+ return metric ? metric.values : null;
+}
+
+function countOf(values) {
+ return values ? values.count : 0;
+}
+
+// The custom summary output replaces k6's default end-of-test summary, so it
+// must surface the signals that say whether the test itself was valid:
+// dropped_iterations > 0 means the client could not sustain the requested
+// rate (raise the VU multipliers and rerun — numbers below are unreliable).
+function globalSummaryRow(data) {
+ const droppedCount = countOf(metricValues(data, "dropped_iterations"));
+ const httpFailed = metricValues(data, "http_req_failed");
+ const failedRate = httpFailed ? (httpFailed.rate * 100).toFixed(2) : "0.00";
+ const warning = droppedCount > 0
+ ? " WARNING: reports at the requested rate were NOT all achieved; raise VU multipliers and rerun"
+ : "";
+ const peak = peakIterationRateRaw(data);
+ const peakStr = peak === null ? "-" : `${peak.toFixed(2)}/s`;
+ return `global | iterations=${countOf(metricValues(data, "iterations"))} | peak_iteration_rate=${peakStr} | dropped_iterations=${droppedCount}${warning} | http_reqs=${countOf(metricValues(data, "http_reqs"))} | http_req_failed=${failedRate}%`;
+}
+
+// The highest iteration rate (all iterations, success or failure — same
+// thing k6's own "Iteration Rate" dashboard tile measures) sustained across
+// the run: in ramp mode, the max over phases of (that phase's total
+// iterations across every scenario / that phase's hold_seconds); in flat
+// mode, the single sustained rate across the whole run. This intentionally
+// counts every iteration, not just successes — it answers "how many
+// flows/sec did this actually push," distinct from achieved TPS above
+// (business-success throughput). It only reflects handleSummary's final
+// aggregate, not a live per-second trace — k6 doesn't expose a live-readable
+// iteration counter from VU code, and the web dashboard's live/exported
+// charts are a separate output plugin this script has no way to add panels
+// to (see README), so this can only ever show up in the stdout summary and
+// SUMMARY_OUTPUT below, never inside timeseries.html itself.
+// 2026-09-24: simplified alongside the per-phase removal above - ramp mode
+// no longer has discrete phases to take a max over, so this is just the
+// whole-scenario average iteration rate in both modes now (in ramp mode,
+// that UNDERSTATES the true peak near target_rps, since it's averaged over
+// the whole hold+ramp+hold window - a real limitation of losing the
+// per-phase breakdown, noted here rather than silently hidden).
+function peakIterationRateRaw(data) {
+ const totalIterationsAt = (suffix) => enabledPlans.reduce((sum, plan) => sum
+ + countOf(metricValues(data, `scenario_success_${plan.name}${suffix}`))
+ + countOf(metricValues(data, `scenario_failure_${plan.name}${suffix}`)), 0);
+ const windowSeconds = rampPlan
+ ? rampPlan.totalSeconds
+ : flatDurationSeconds;
+ return achievedTpsRaw(totalIterationsAt(""), windowSeconds);
+}
+
+function fmt(values, key) {
+ if (!values || values[key] === undefined || values.count === 0) return "-";
+ return values[key].toFixed(2);
+}
+
+// Achieved TPS is successful transactions / wall-clock window — distinct
+// from "target rps" (the offered/requested iteration rate): if any measured
+// confirms fail or iterations are dropped, achieved TPS falls below target.
+// Raw numeric form (null when the window is unknown) feeds both the text
+// table below and the synthetic gauge metrics injected for the HTML report;
+// k6's own Counter.rate can't be reused for this because in ramp mode it
+// divides by the whole test's wall-clock time, not a single phase's
+// hold_seconds.
+function achievedTpsRaw(successCount, windowSeconds) {
+ return windowSeconds > 0 ? successCount / windowSeconds : null;
+}
+
+function achievedTps(successCount, windowSeconds) {
+ const raw = achievedTpsRaw(successCount, windowSeconds);
+ return raw === null ? "-" : raw.toFixed(2);
+}
+
+// SUMMARY_OUTPUT's JSON dump only contains whatever is in data.metrics;
+// achieved TPS is a value this script derives (success count / window)
+// rather than something k6 tracks natively, so it has no metric to show
+// without this. handleSummary's `data` is a plain, still-mutable JS object
+// at this point (not yet serialized), so adding entries here is enough for
+// JSON.stringify(data) below to pick them up. Shape is k6's gauge format:
+// values.value/min/max (min/max just mirror value — there's only one sample).
+function injectAchievedTpsMetrics(data) {
+ const setGauge = (name, value) => {
+ data.metrics[name] = { type: "gauge", contains: "default", values: { value, min: value, max: value } };
+ };
+ const windowSeconds = rampPlan
+ ? rampPlan.totalSeconds
+ : flatDurationSeconds;
+ for (const plan of enabledPlans) {
+ const successValues = metricValues(data, `scenario_success_${plan.name}`);
+ const tps = achievedTpsRaw(countOf(successValues), windowSeconds);
+ if (tps !== null) setGauge(`achieved_tps_${plan.name}`, tps);
+ }
+ const peak = peakIterationRateRaw(data);
+ if (peak !== null) setGauge("peak_iteration_rate", peak);
+}
+
+// 2026-09-24: handles both modes now (was flat-only; the ramp-mode
+// per-phase table above is gone along with the discrete-step design).
+// "target rps" is the scenario's peak rate (target_rps in ramp mode, the
+// flat rate otherwise); "achieved tps" is averaged over the whole
+// hold+ramp+hold window in ramp mode, which understates the true peak near
+// target_rps - see peakIterationRateRaw's comment for the same caveat.
+function summaryRow(data, plan) {
+ const confirmValues = metricValues(data, `payment_confirm_ms_${plan.name}`);
+ const flowValues = metricValues(data, `total_flow_ms_${plan.name}`);
+ const successValues = metricValues(data, `scenario_success_${plan.name}`);
+ const failureValues = metricValues(data, `scenario_failure_${plan.name}`);
+ const successCount = successValues ? successValues.count : 0;
+ const targetRate = rampPlan ? rateFor(plan, rampPlan.peakRps) : rateFor(plan, flatTotalRps);
+ const windowSeconds = rampPlan
+ ? rampPlan.totalSeconds
+ : flatDurationSeconds;
+ return [
+ plan.name,
+ String(plan.weight),
+ targetRate.toFixed(2),
+ achievedTps(successCount, windowSeconds),
+ fmt(confirmValues, "med"),
+ fmt(confirmValues, "p(90)"),
+ fmt(confirmValues, "p(99)"),
+ fmt(flowValues, "med"),
+ fmt(flowValues, "p(90)"),
+ String(successCount),
+ failureValues ? String(failureValues.count) : "0",
+ ].join(" | ");
+}
+
+export function handleSummary(data) {
+ injectAchievedTpsMetrics(data);
+ const header = `scenario-mix | config=${configPath} | ${loadDescription}`;
+ const rows = [header, globalSummaryRow(data)];
+ if (!__ENV.RECORDING_DISABLED && __ENV.SQLITE_RECORDER_REQUIRED) rows.push(`recorder: ${JSON.stringify(recorder.stats())}`);
+ const columns = [
+ "scenario", "weight%", "target rps", "achieved tps",
+ "confirm p50", "confirm p90", "confirm p99",
+ "flow p50", "flow p90",
+ "success", "failure",
+ ];
+ rows.push(columns.join(" | "));
+ rows.push(columns.map((column) => "-".repeat(column.length)).join(" | "));
+ for (const plan of enabledPlans) rows.push(summaryRow(data, plan));
+ const output = { stdout: `\n${rows.join("\n")}\n` };
+ if (__ENV.SUMMARY_OUTPUT) {
+ output[joinPath(outputDir, __ENV.SUMMARY_OUTPUT)] = JSON.stringify(data, null, 2);
+ }
+ return output;
+}
diff --git a/loadtest/k6/scenario-mix/server-latency.mjs b/loadtest/k6/scenario-mix/server-latency.mjs
new file mode 100644
index 0000000000..5aa7d7f565
--- /dev/null
+++ b/loadtest/k6/scenario-mix/server-latency.mjs
@@ -0,0 +1,11 @@
+// The router reports internal processing milliseconds when requested with true.
+export function serverLatency(headers) {
+ const entry=Object.entries(headers||{}).find(([name])=>name.toLowerCase()==='x-hs-latency');
+ if(!entry||typeof entry[1]!=='string')return null;
+ const text=entry[1].trim();
+ if(!/^\d+(?:\.\d+)?$/.test(text))return null;
+ const value=Number(text);return Number.isFinite(value)?value:null;
+}
+export function latencyHeaders(headers) {
+ return {...Object.fromEntries(Object.entries(headers||{}).filter(([name])=>name.toLowerCase()!=='x-hs-latency')),'x-hs-latency':'true'};
+}
diff --git a/loadtest/k6/scenario-mix/sqlite.mjs b/loadtest/k6/scenario-mix/sqlite.mjs
new file mode 100644
index 0000000000..f460f0125f
--- /dev/null
+++ b/loadtest/k6/scenario-mix/sqlite.mjs
@@ -0,0 +1,66 @@
+import { DatabaseSync } from "node:sqlite";
+import { readFileSync } from "node:fs";
+import { randomUUID } from "node:crypto";
+import { responseRecord } from "./record.mjs";
+
+export const sql = (name) => readFileSync(new URL(`./recorder/${name}.sql`, import.meta.url), "utf8");
+export class FixtureRecorder {
+ constructor(file, metadata = {}) {
+ this.db = new DatabaseSync(file);
+ this.db.exec(sql("schema"));
+ const columns=this.db.prepare("PRAGMA table_info(request_events)").all().map(c=>c.name);
+ for(const column of ["requested_connector","selected_connector_account","connector","merchant_connector_id"])if(!columns.includes(column))this.db.exec(`ALTER TABLE request_events ADD COLUMN ${column} TEXT`);
+ this.runId = randomUUID();
+ this.count = 0;
+ this.metadata = metadata;
+ this.db.prepare("INSERT INTO runs(run_id,started_at,metadata) VALUES(?,?,?)").run(this.runId, Date.now(), JSON.stringify(metadata));
+ this.insert = this.db.prepare(sql("event"));
+ this.customer = this.db.prepare(sql("customer"));
+ this.payment = this.db.prepare(sql("payment"));
+ }
+ record(e) {
+ this.db.exec("BEGIN IMMEDIATE");
+ try {
+ const id = this.insert.run(this.runId,this.count+1,e.flow_id,e.merchant_id,e.operation,e.role,e.observed_at,e.method,e.url,
+ e.customer_id,e.merchant_reference_id,e.payment_id,e.amount,e.status,e.api_status_code,e.request_id,e.latency_ms,
+ e.message,e.error_body,e.entity_type,e.server_latency_ms??null,e.requested_connector??null,e.selected_connector_account??null,e.connector??null,e.merchant_connector_id??null).lastInsertRowid;
+ if (e.entity_type === "customer" && e.customer_id) this.customer.run(this.runId,e.customer_id,e.merchant_id,e.merchant_reference_id,e.api_status_code,e.request_id,e.message,e.observed_at,id);
+ if (e.entity_type === "payment" && e.payment_id) this.payment.run(this.runId,e.payment_id,e.merchant_id,e.customer_id,e.amount,e.status,e.role,e.api_status_code,e.request_id,e.message,e.observed_at,id);
+ this.db.prepare("UPDATE runs SET enqueued=?,persisted=? WHERE run_id=?").run(this.count+1,this.count+1,this.runId);
+ this.db.exec("COMMIT");
+ this.count += 1;
+ return id;
+ } catch (error) {
+ try { this.db.exec("ROLLBACK"); } catch (_) { /* SQLite may already have rolled back */ }
+ error.recordingFatal = true; throw error;
+ }
+ }
+ close(error = null) {
+ this.db.prepare("UPDATE runs SET recording_state=?,ended_at=?,error=?,metadata=? WHERE run_id=?")
+ .run(error ? "incomplete" : "complete",Date.now(),error ? String(error) : null,JSON.stringify(this.metadata),this.runId);
+ this.db.close();
+ }
+}
+
+export async function recordedFetch(recorder, url, options = {}, context = {}) {
+ const start = performance.now();
+ let response;
+ let text = "";
+ let transportError;
+ try {
+ response = await fetch(url, { redirect: "manual", ...options, signal: options.signal || AbortSignal.timeout(30000) });
+ text = await response.clone().text();
+ } catch (error) { transportError = error; }
+ if (recorder) {
+ let request = {};
+ try { request = JSON.parse(options.body || "{}"); } catch (_) { /* non-JSON request */ }
+ const scrub=value=>{if(typeof value==='string'&&value.length>=4)text=text.replaceAll(value,'[redacted]');else if(value&&typeof value==='object')Object.values(value).forEach(scrub);};
+ if(request.connector_account_details)scrub(request.connector_account_details);
+ if(request.metadata)scrub(request.metadata);
+ recorder.record(responseRecord({ flow_id: context.flow_id || randomUUID(), ...context }, options.method || "GET",url,request,
+ response ? { status: response.status, headers: Object.fromEntries(response.headers) } : null,text,
+ performance.now() - start,transportError?.message));
+ }
+ if (transportError) throw transportError;
+ return response;
+}
diff --git a/loadtest/k6/scenario-mix/superposition.mjs b/loadtest/k6/scenario-mix/superposition.mjs
new file mode 100644
index 0000000000..8dd5574b0c
--- /dev/null
+++ b/loadtest/k6/scenario-mix/superposition.mjs
@@ -0,0 +1,98 @@
+import { isDeepStrictEqual } from "node:util";
+import { recordedFetch } from "./sqlite.mjs";
+import { progress } from "./progress.mjs";
+
+function validate(config) {
+ if (!config || typeof config.defaults !== "object" || !config.defaults || Array.isArray(config.defaults)) throw new Error("superposition.defaults must be a flag/value object");
+ for (const key of ["endpoint", "token", "organization_id", "workspace_id"]) {
+ if (typeof config[key] !== "string" || !config[key]) throw new Error(`superposition.${key} is required`);
+ }
+ if (!Number.isSafeInteger(config.concurrency ?? 20) || (config.concurrency ?? 20) < 1) throw new Error("superposition.concurrency must be a positive integer");
+ if (!Number.isFinite(config.refresh_interval_seconds) || config.refresh_interval_seconds < 0) throw new Error("superposition.refresh_interval_seconds must specify the deployed service polling interval");
+ if (!Number.isFinite(config.poll_interval_seconds ?? 5) || (config.poll_interval_seconds ?? 5) < 0.25 || (config.poll_interval_seconds ?? 5) > 60) throw new Error("superposition.poll_interval_seconds must be between 0.25 and 60 seconds");
+ if (!['authorization','x-superposition-access'].includes(config.access_header ?? 'authorization')) throw new Error("superposition.access_header must be authorization or x-superposition-access");
+}
+
+function authenticationHeaders(config) {
+ return (config.access_header ?? 'authorization') === 'x-superposition-access'
+ ? { 'x-superposition-access': config.token }
+ : { Authorization: `Bearer ${config.token}` };
+}
+
+export async function configureSuperposition(config, recorder, merchants, organizationId, onProgress = async () => {}) {
+ if (!config) return null;
+ validate(config);
+ await onProgress({status:"applying"});
+ const headers = { "content-type": "application/json", ...authenticationHeaders(config),
+ "x-org-id": config.organization_id, "x-workspace": config.workspace_id };
+ const base = config.endpoint.replace(/\/$/, "");
+ async function call(method, route, body, merchantId = null) {
+ const response = await recordedFetch(recorder,`${base}${route}`, { method, headers, ...(body === undefined ? {} : { body: JSON.stringify(body) }) },
+ { operation: `superposition_${method}_${route.split("?")[0]}`, merchant_id: merchantId, role: "fixture" });
+ if (!response.ok) throw new Error(`Superposition ${method} ${route}: HTTP ${response.status}: ${await response.text()}`);
+ return { body: await response.json(), version: response.headers.get("x-config-version") };
+ }
+ // Discover every key before changing anything. PATCH only the value, preserving schema/functions.
+ const current = new Map();
+ for (const key of Object.keys(config.defaults)) {
+ const existing = await call("GET",`/default-config/${encodeURIComponent(key)}`);
+ current.set(key,existing.body.value);
+ }
+ for (const [key,value] of Object.entries(config.defaults)) {
+ if (isDeepStrictEqual(current.get(key),value)) continue;
+ await call("PATCH",`/default-config/${encodeURIComponent(key)}`,{ value, change_reason: "scenario-mix fixture defaults" });
+ }
+ let version = null;
+ async function verify(label) {
+ const bar = progress(label, merchants.length);
+ let completed = 0;
+ let cursor = 0;
+ let failure;
+ async function worker() {
+ while (!failure && cursor < merchants.length) {
+ const merchant = merchants[cursor++];
+ try {
+ const resolved = await call("POST","/config/resolve",{ context: {
+ ...(config.context || {}), organization_id: organizationId, merchant_id: merchant.merchant_id, profile_id: merchant.profile_id,
+ } },merchant.merchant_id);
+ for (const [key,value] of Object.entries(config.defaults)) {
+ if (!isDeepStrictEqual(resolved.body[key],value)) throw new Error(`Superposition override conflict for ${merchant.merchant_id}: ${key}`);
+ }
+ if (!resolved.version) throw new Error("Superposition response lacks x-config-version; cannot verify a stable configuration");
+ if (version !== null && version !== resolved.version) throw new Error("Superposition configuration changed during fixture verification; rerun fixtures");
+ version = resolved.version;
+ bar.update(++completed);
+ } catch (error) { failure ||= error; }
+ }
+ }
+ try {
+ await Promise.all(Array.from({ length: Math.min(config.concurrency ?? 20,merchants.length) },worker));
+ } finally { bar.finish(); }
+ if (failure) throw failure;
+ }
+ await onProgress({status:"resolving"});
+ await verify("Resolve flags");
+ if (config.refresh_interval_seconds > 0) console.log(`Waiting ${config.refresh_interval_seconds}s for Superposition service refresh before readiness verification...`);
+ const deadline = Date.now() + config.refresh_interval_seconds * 1000;
+ await onProgress({status:"waiting",remainingSeconds:config.refresh_interval_seconds,totalSeconds:config.refresh_interval_seconds});
+ if (config.refresh_interval_seconds > 0) {
+ const seconds = config.refresh_interval_seconds;
+ const bar = progress("Service refresh", seconds);
+ try {
+ while (Date.now() < deadline) {
+ await new Promise((resolve) => setTimeout(resolve,Math.min((config.poll_interval_seconds ?? 5)*1000,deadline-Date.now())));
+ const remaining = Math.max(0,Math.ceil((deadline-Date.now())/1000));
+ bar.update(seconds-remaining, `${remaining}s remaining`);
+ await onProgress({status:"waiting",remainingSeconds:remaining,totalSeconds:seconds});
+ }
+ } finally { bar.finish(); }
+ }
+ // A progress callback can cross the deadline after the last timer tick.
+ // Always publish the terminal countdown before entering verification.
+ await onProgress({status:"waiting",remainingSeconds:0,totalSeconds:config.refresh_interval_seconds});
+ await onProgress({status:"verifying",remainingSeconds:0});
+ await verify("Verify refreshed flags");
+ await onProgress({status:"complete",remainingSeconds:0});
+ return { organization_id: config.organization_id, workspace_id: config.workspace_id,
+ defaults: config.defaults, version, refresh_interval_seconds: config.refresh_interval_seconds,poll_interval_seconds:config.poll_interval_seconds ?? 5 };
+}
diff --git a/loadtest/k6/scenario-mix/test/diagnostics.test.mjs b/loadtest/k6/scenario-mix/test/diagnostics.test.mjs
new file mode 100644
index 0000000000..3bda974067
--- /dev/null
+++ b/loadtest/k6/scenario-mix/test/diagnostics.test.mjs
@@ -0,0 +1,11 @@
+import test from 'node:test';
+import assert from 'node:assert/strict';
+import {responseRecord} from '../record.mjs';
+test('error projections keep useful diagnostics without echoed secrets or card data',()=>{
+ const body=JSON.stringify({error:{code:'PAYMENT_FAILED',message:'Invalid card 4242424242424242; api_key=private-key',metadata:{password:'private-password'}},card_number:'4242424242424242',client_secret:'private-client-secret'});
+ const record=responseRecord({operation:'payment_confirm'},'POST','http://router/payments/fake/confirm',{}, {status:400},body,1);
+ assert.match(record.error_body,/PAYMENT_FAILED/);
+ assert.doesNotMatch(JSON.stringify(record),/4242424242424242|private-key|private-password|private-client-secret/);
+ const html=responseRecord({operation:'payment_confirm'},'POST','http://router/confirm',{}, {status:500},'<html>raw-secret</html>',1);
+ assert.doesNotMatch(html.error_body,/raw-secret/);
+});
diff --git a/loadtest/k6/scenario-mix/test/fixtures.test.mjs b/loadtest/k6/scenario-mix/test/fixtures.test.mjs
new file mode 100644
index 0000000000..eee0b1e69f
--- /dev/null
+++ b/loadtest/k6/scenario-mix/test/fixtures.test.mjs
@@ -0,0 +1,212 @@
+import test from 'node:test';
+import assert from 'node:assert/strict';
+import { mkdtemp, writeFile, readFile } from 'node:fs/promises';
+import { DatabaseSync } from 'node:sqlite';
+import path from 'node:path';
+import os from 'node:os';
+import { fixtures,load } from '../run.mjs';
+import { FixtureRecorder } from '../sqlite.mjs';
+import { configureSuperposition } from '../superposition.mjs';
+
+import { mockServer } from "./mock-server.mjs";
+
+const temporary = () => mkdtemp(path.join(os.tmpdir(),'loadtest-fixtures-'));
+async function configuration(dir,url,extras={}) {
+ const cfg={router:url,admin_api_key:'admin-test',merchant_count:2,concurrency:2,merchant_id_prefix:'test',retry:{attempts:1,backoff_ms:1},
+ connector:{connector_name:'stripe',connector_account_details:{auth_type:'HeaderKey',api_key:'test-key'},business_country:'US',business_label:'default'},
+ superposition:{endpoint:url,token:'sp-test',organization_id:'sp-org',workspace_id:'test',refresh_interval_seconds:0,defaults:{flag:true}},...extras};
+ const file=path.join(dir,'provision.json');await writeFile(file,JSON.stringify(cfg));return file;
+}
+test('fixtures are recorded, ready, and resumable without minting extra API keys',async() => {
+ const {server,state,url}=await mockServer(); const dir=await temporary();state.requireAdminAuthorization=true;
+ try {
+ const cfg=await configuration(dir,url),output=path.join(dir,'fixtures');
+ const setup=[];await fixtures(cfg,output,{onProgress:value=>setup.push(structuredClone(value))});const keys=state.keys;
+ assert.equal(setup[0].stage,"merchants");assert.equal(setup.at(-1).stage,"ready");assert.ok(setup.some(s=>s.superposition.status==="applying"));assert.ok(setup.some(s=>s.superposition.status==="verifying"));
+ const patches=state.patches;
+ await fixtures(cfg,output); assert.equal(state.keys,keys);assert.equal(state.patches,patches);
+ const manifest=JSON.parse(await readFile(path.join(output,'manifest.json'),'utf8'));
+ assert.equal(manifest.state,'ready');assert.equal(manifest.merchant_count,2);assert.equal(manifest.superposition.version,'v1');
+ const db=new DatabaseSync(path.join(output,'fixtures.sqlite'),{readOnly:true});
+ assert.equal(db.prepare('SELECT COUNT(*) n FROM request_events').get().n,state.requests);
+ assert.equal(db.prepare("SELECT COUNT(*) n FROM runs WHERE recording_state='complete'").get().n,2);db.close();
+ } finally {server.close();}
+});
+test('Superposition changes only default values and skips unchanged defaults',async() => {
+ const {server,state,url}=await mockServer();const dir=await temporary(),recorder=new FixtureRecorder(path.join(dir,'fixtures.sqlite'));
+ const cfg={endpoint:url,token:'token',organization_id:'sp-org',workspace_id:'test',refresh_interval_seconds:0,defaults:{flag:true}};
+ try {
+ state.default=false;
+ await configureSuperposition(cfg,recorder,[{merchant_id:'m',profile_id:'p'}],'o');assert.equal(state.patches,1);
+ await configureSuperposition(cfg,recorder,[{merchant_id:'m',profile_id:'p'}],'o');assert.equal(state.patches,1);
+ } finally {recorder.close();server.close();}
+});
+
+test('Superposition supports its access header authentication mode',async()=>{
+ const requests=[];const server=(await import('node:http')).createServer((req,res)=>{requests.push(req.headers);res.writeHead(200,{'content-type':'application/json','x-config-version':'v1'});res.end(req.url==='/config/resolve'?'{"flag":true}':'{"value":true}');});
+ await new Promise(resolve=>server.listen(0,'127.0.0.1',resolve));const recorder=new FixtureRecorder(path.join(await temporary(),'fixtures.sqlite'));
+ try{await configureSuperposition({endpoint:`http://127.0.0.1:${server.address().port}`,token:'access-token',access_header:'x-superposition-access',organization_id:'org',workspace_id:'dev',refresh_interval_seconds:0,defaults:{flag:true}},recorder,[{merchant_id:'m',profile_id:'p'}],'org');assert.ok(requests.every(headers=>headers['x-superposition-access']==='access-token'&&!headers.authorization));}
+ finally{recorder.close();server.close();}
+});
+test('partial connector failure resumes using checkpointed API keys and invalidates readiness',async() => {
+ const {server,state,url}=await mockServer();const dir=await temporary();
+ try {
+ const cfg=await configuration(dir,url),output=path.join(dir,'fixtures');state.failConnector=true;
+ await assert.rejects(fixtures(cfg,output),/fixtures failed/);assert.equal(state.keys,2);
+ assert.equal(JSON.parse(await readFile(path.join(output,'manifest.json'),'utf8')).state,'failed');
+ state.failConnector=false;await fixtures(cfg,output);assert.equal(state.keys,2);
+ } finally {server.close();}
+});
+test('Superposition rejects unknown flags before writes and detects context conflicts',async() => {
+ const {server,state,url}=await mockServer();const dir=await temporary(),recorder=new FixtureRecorder(path.join(dir,'fixtures.sqlite'));
+ const cfg={endpoint:url,token:'token',organization_id:'sp-org',workspace_id:'test',refresh_interval_seconds:0,defaults:{flag:true,unknown:true}};
+ try {
+ await assert.rejects(configureSuperposition(cfg,recorder,[{merchant_id:'m',profile_id:'p'}],'o'),/404/);assert.equal(state.patches,0);
+ cfg.defaults={flag:true};state.conflict=true;
+ await assert.rejects(configureSuperposition(cfg,recorder,[{merchant_id:'m',profile_id:'p'}],'o'),/override conflict/);
+ } finally {recorder.close();server.close();}
+});
+test('recorded k6 load covers supported payment-service flows and drains every response', {skip: !process.env.K6_SQLITE_BINARY},async() => {
+ const {server,state,url}=await mockServer();const dir=await temporary();
+ try {
+ const cfg=await configuration(dir,url),output=path.join(dir,'fixtures');await fixtures(cfg,output);
+ const before=state.requests;
+ const scenarios=[['guest',20],['cit_on_session',15],['cit_off_session',20],['ptv_on_session',15],['ptv_off_session',15],['sdk_checkout',15]]
+ .map(([scenario,weight],i)=>({name:`s${i}`,scenario,merchant_path:'modular',weight}));
+ const config={services:{router:url,modular_pm:`${url}/v2`},load:{total_rps:20,duration_seconds:2},payment:{amount:100,currency:'USD',card:{card_number:'4242424242424242',card_exp_month:'10',card_exp_year:'35',card_cvc:'123'},metadata_update:{card_exp_month:'11'}},scenarios};
+ const configPath=path.join(dir,'load.json');await writeFile(configPath,JSON.stringify(config));
+ const result=await load(configPath,output,path.join(dir,'run'),process.env.K6_SQLITE_BINARY);assert.equal(result.exitCode,0);
+ const summary=JSON.parse(await readFile(path.join(dir,'run','summary.json'),'utf8'));
+ assert.ok(summary.metrics.http_reqs.values.count>100);
+ assert.equal(summary.metrics.payment_confirm_server_latency_ms.values['p(99)'],12);assert.ok(state.latencyOptIns>0);
+ const db=new DatabaseSync(result.database,{readOnly:true});
+ const events=db.prepare('SELECT COUNT(*) n FROM request_events').get().n;
+ assert.equal(events,state.requests-before);assert.ok(events>100);
+ assert.equal(db.prepare('SELECT MIN(api_status_code) n FROM request_events').get().n,200);
+ assert.equal(db.prepare("SELECT MIN(server_latency_ms) n FROM request_events WHERE operation='payment_confirm'").get().n,12);
+ assert.ok(db.prepare('SELECT AVG(latency_ms) n FROM request_events').get().n>0);
+ const operations=db.prepare('SELECT DISTINCT operation FROM request_events').all().map(r=>r.operation);
+ for(const operation of ['customer_create','pm_session_create','pm_session_confirm','payment_create','payment_confirm','payment_method_list','session','eligibility']) assert.ok(operations.includes(operation),operation);
+ assert.ok(db.prepare("SELECT COUNT(*) n FROM payments WHERE status='succeeded'").get().n>0);
+ assert.equal(db.prepare('SELECT recording_state FROM runs').get().recording_state,'complete');db.close();
+ } finally {server.close();}
+});
+
+test('final threshold failure returns nonzero while fully persisted recording stays complete', {skip: !process.env.K6_SQLITE_BINARY},async() => {
+ const {server,url}=await mockServer();const dir=await temporary();
+ try {
+ const cfg=await configuration(dir,url),output=path.join(dir,'fixtures');await fixtures(cfg,output);
+ const config={services:{router:url,modular_pm:`${url}/v2`},load:{total_rps:2,duration_seconds:1},
+ payment:{amount:100,currency:'USD',card:{card_number:'4242424242424242',card_exp_month:'10',card_exp_year:'35',card_cvc:'123'}},
+ scenarios:[{name:'guest',merchant_path:'non_modular',scenario:'guest',weight:100}],thresholds:{http_req_failed:['rate<0']}};
+ const configPath=path.join(dir,'load.json');await writeFile(configPath,JSON.stringify(config));
+ const result=await load(configPath,output,path.join(dir,'run'),process.env.K6_SQLITE_BINARY);
+ assert.equal(result.exitCode,99);
+ const db=new DatabaseSync(result.database,{readOnly:true});
+ const run=db.prepare('SELECT recording_state,enqueued,persisted FROM runs').get();
+ assert.equal(run.recording_state,'complete');assert.equal(run.enqueued,run.persisted);db.close();
+ } finally {server.close();}
+});
+
+test('native capture preserves non-2xx bodies and tolerates malformed entity JSON', {skip: !process.env.K6_SQLITE_BINARY},async()=>{
+ const {server,state,url}=await mockServer();const dir=await temporary();
+ try {
+ const cfg=await configuration(dir,url),fixtureOutput=path.join(dir,'fixtures');await fixtures(cfg,fixtureOutput);
+ const config={services:{router:url,modular_pm:`${url}/v2`},load:{total_rps:4,duration_seconds:1},
+ payment:{amount:100,currency:'USD',card:{card_number:'4242424242424242'}},
+ scenarios:[{name:'customer_error',scenario:'cit_off_session',merchant_path:'non_modular',weight:100}]};
+ const file=path.join(dir,'load.json');await writeFile(file,JSON.stringify(config));
+ for(const mode of ['errorCustomers','malformedCustomers']) {
+ state.errorCustomers=mode==='errorCustomers';state.malformedCustomers=mode==='malformedCustomers';
+ const result=await load(file,fixtureOutput,path.join(dir,mode),process.env.K6_SQLITE_BINARY);
+ assert.equal(result.exitCode,0);
+ const db=new DatabaseSync(result.database,{readOnly:true});
+ const events=db.prepare('SELECT * FROM request_events').all();assert.ok(events.length>=4);
+ for(const event of events) {
+ assert.equal(event.api_status_code,mode==='errorCustomers'?422:200);
+ assert.equal(event.message,mode==='errorCustomers'?'invalid customer':'invalid_json_response');
+ if(mode==='errorCustomers') assert.match(event.error_body,/invalid customer/);
+ assert.ok(event.merchant_reference_id);assert.equal(event.customer_id,null);
+ }
+ assert.equal(db.prepare('SELECT COUNT(*) n FROM customers').get().n,0);db.close();
+ }
+ } finally {server.close();}
+});
+
+test('Superposition refresh countdown precedes final readiness verification',async()=>{
+ const {server,url}=await mockServer(),dir=await temporary();
+ try{
+ const file=await configuration(dir,url),cfg=JSON.parse(await readFile(file,'utf8'));cfg.superposition.refresh_interval_seconds=1;cfg.superposition.poll_interval_seconds=.25;await writeFile(file,JSON.stringify(cfg));
+ const updates=[];await fixtures(file,path.join(dir,'fixtures'),{onProgress:value=>updates.push(structuredClone(value))});
+ const waiting=updates.filter(s=>s.superposition.status==='waiting');assert.equal(waiting[0].superposition.remainingSeconds,1);assert.equal(waiting.at(-1).superposition.remainingSeconds,0);assert.ok(waiting.length>=4);
+ assert.ok(updates.findIndex(s=>s.superposition.status==='verifying')>updates.findIndex(s=>s.superposition.status==='waiting'));assert.equal(updates.at(-1).stage,'ready');
+ }finally{server.close();}
+});
+
+test('controlled smoke counts starts before delayed responses and preserves failed checks', {skip:!process.env.K6_SQLITE_BINARY},async()=>{
+ const {server,state,url}=await mockServer(),dir=await temporary(),oldControl=process.env.SQLITE_RECORDER_CONTROL_FILE,oldProgress=process.env.SQLITE_RECORDER_PROGRESS_FILE,oldToken=process.env.SQLITE_RECORDER_CONTROL_TOKEN;
+ try{
+ const fixturePath=path.join(dir,'fixtures');await fixtures(await configuration(dir,url),fixturePath);
+ const config={services:{router:url,modular_pm:`${url}/v2`},load:{total_rps:2,duration_seconds:3},payment:{amount:100,currency:'USD',card:{card_number:'4242424242424242'}},scenarios:[{name:'guest',scenario:'guest',merchant_path:'non_modular',weight:100}]},file=path.join(dir,'load.json');await writeFile(file,JSON.stringify(config));
+ const output=path.join(dir,'delayed');process.env.SQLITE_RECORDER_CONTROL_FILE=path.join(output,'control.json');process.env.SQLITE_RECORDER_PROGRESS_FILE=path.join(output,'progress.json');state.delayPayments=4000;process.env.SQLITE_RECORDER_CONTROL_TOKEN='delayed-test-token';
+ const pending=load(file,fixturePath,output,process.env.K6_SQLITE_BINARY,{recording:false,telemetry:true});let observed=false;
+ for(let attempt=0;attempt<80;attempt++){
+ const p=JSON.parse(await readFile(process.env.SQLITE_RECORDER_PROGRESS_FILE,'utf8').catch(()=>'{}'));
+ if(p.control?.started_flows>=2){assert.equal(p.flows.guest.successes,0);assert.equal(p.control.flow_starts.guest,p.control.started_flows);assert.equal(p.control.in_flight,p.control.started_flows);observed=true;break;}
+ await new Promise(resolve=>setTimeout(resolve,50));
+ }
+ const result=await pending;assert.ok(observed,'admissions must be visible while HTTP is blocked');assert.equal(result.exitCode,0);
+ const final=JSON.parse(await readFile(process.env.SQLITE_RECORDER_PROGRESS_FILE,'utf8'));assert.equal(final.control.state,'completed');assert.equal(final.control.started_flows,6);assert.equal(final.flows.guest.successes,6);assert.equal(final.control.in_flight,0);
+ await assert.rejects(readFile(path.join(output,'results.sqlite')),error=>error.code==='ENOENT');
+ state.delayPayments=0;config.thresholds={http_req_failed:['rate<0']};await writeFile(file,JSON.stringify(config));const failedOutput=path.join(dir,'failed');process.env.SQLITE_RECORDER_CONTROL_FILE=path.join(failedOutput,'control.json');process.env.SQLITE_RECORDER_PROGRESS_FILE=path.join(failedOutput,'progress.json');
+ assert.equal((await load(file,fixturePath,failedOutput,process.env.K6_SQLITE_BINARY,{recording:false,telemetry:true})).exitCode,99);
+ }finally{server.close();if(oldControl==null)delete process.env.SQLITE_RECORDER_CONTROL_FILE;else process.env.SQLITE_RECORDER_CONTROL_FILE=oldControl;if(oldProgress==null)delete process.env.SQLITE_RECORDER_PROGRESS_FILE;else process.env.SQLITE_RECORDER_PROGRESS_FILE=oldProgress;if(oldToken==null)delete process.env.SQLITE_RECORDER_CONTROL_TOKEN;else process.env.SQLITE_RECORDER_CONTROL_TOKEN=oldToken;}
+});
+
+test('multi-connector fixture -> explicit routing -> recorder -> telemetry -> results', {skip:!process.env.K6_SQLITE_BINARY},async()=>{
+ const {server,url,state}=await mockServer();const dir=await temporary();
+ state.requireBrowserInfo=true;
+ try{
+ const plan={mode:'real',mix:[{connector:'stripe',weight:70},{connector:'adyen',weight:30}]};
+ const cfg=await configuration(dir,url,{connectorPlan:plan}),fixturePath=path.join(dir,'fixtures');
+ const accounts=['stripe','adyen'].map(connector_name=>({connector_name,connector_account_details:{auth_type:'HeaderKey',api_key:'secret-fixture-only'},business_country:'US',business_label:'default',test_mode:true}));
+ await fixtures(cfg,fixturePath,{connectorAccounts:accounts});
+ const merchants=JSON.parse(await readFile(path.join(fixturePath,'merchants.json'),'utf8'));assert.equal(merchants.length,2);
+ for(const merchant of merchants)assert.deepEqual(Object.keys(merchant.connector_accounts).sort(),['adyen','stripe']);
+ const keys=state.keys;await fixtures(cfg,fixturePath,{connectorAccounts:accounts});assert.equal(state.keys,keys);
+ const config={connectors:plan,services:{router:url,modular_pm:`${url}/v2`},load:{total_rps:20,duration_seconds:2},payment:{amount:100,currency:'USD',card:{card_number:'4242424242424242',card_exp_month:'10',card_exp_year:'35',card_cvc:'123'}},scenarios:[{name:'guest',scenario:'guest',merchant_path:'modular',weight:100}]};
+ const file=path.join(dir,'load.json');await writeFile(file,JSON.stringify(config));const output=path.join(dir,'run');const oldProgress=process.env.SQLITE_RECORDER_PROGRESS_FILE;process.env.SQLITE_RECORDER_PROGRESS_FILE=path.join(output,'progress.json');let result;try{result=await load(file,fixturePath,output,process.env.K6_SQLITE_BINARY);}finally{if(oldProgress===undefined)delete process.env.SQLITE_RECORDER_PROGRESS_FILE;else process.env.SQLITE_RECORDER_PROGRESS_FILE=oldProgress;}assert.equal(result.exitCode,0);
+ const db=new DatabaseSync(result.database,{readOnly:true});
+ const captured=db.prepare("SELECT requested_connector,connector,selected_connector_account,merchant_connector_id,server_latency_ms,latency_ms FROM request_events WHERE operation='payment_confirm'").all();
+ assert.ok(captured.length>=38);assert.ok(captured.every(r=>r.requested_connector===r.connector&&r.selected_connector_account===r.merchant_connector_id&&r.server_latency_ms===12));assert.equal(new Set(captured.map(r=>r.connector)).size,2);db.close();
+ const {connectorResults}=await import('../../../console/server/connector-results.mjs');const tally=connectorResults(output,plan);assert.equal(tally.rows.length,2);assert.equal(tally.unattributedConfirmations,0);assert.equal(tally.rows.reduce((s,r)=>s+r.confirmations,0),captured.length);
+ const progress=JSON.parse(await readFile(path.join(output,'progress.json'),'utf8'));assert.ok(progress.connectors.stripe.confirmed>0);assert.ok(progress.connectors.adyen.confirmed>0);
+ const artifacts=await Promise.all(['config.json','load-config.json','summary.json'].map(name=>readFile(path.join(output,name),'utf8').catch(()=>'')));assert.ok(artifacts.every(s=>!s.includes('secret-fixture-only')));
+ }finally{server.close();}
+});
+
+test('multi-connector setup resumes a partly-created merchant without duplicate accounts',async()=>{
+ const {server,url,state}=await mockServer();const dir=await temporary();
+ try{
+ const file=await configuration(dir,url),output=path.join(dir,'fixtures');
+ const accounts=['stripe','adyen'].map(connector_name=>({connector_name,connector_account_details:{auth_type:'HeaderKey',api_key:'fixture-credential'},business_country:'US',business_label:'default'}));
+ state.failConnectorName='adyen';await assert.rejects(()=>fixtures(file,output,{connectorAccounts:accounts}));const keys=state.keys;
+ for(const rows of state.connectors.values())assert.equal(rows.length,1);
+ state.failConnectorName=null;await fixtures(file,output,{connectorAccounts:accounts.map(c=>({...c,connector_account_details:{auth_type:'HeaderKey',api_key:'corrected-credential'}}))});
+ assert.equal(state.keys,keys);for(const rows of state.connectors.values())assert.equal(rows.length,2);
+ const manifest=JSON.parse(await readFile(path.join(output,'manifest.json'),'utf8'));assert.equal(manifest.state,'ready');
+ }finally{server.close();}
+});
+
+test('console credential accounts use the merchant business details, including saved fixture retries',async()=>{
+ const {provisionConnectorAccounts,resolveConnectorAccounts,connectorSecretStore}=await import('../../../console/server/connector-fixtures.mjs');
+ const {server,url}=await mockServer(),dir=await temporary();
+ try{
+ const plan={mode:'real',mix:[{connector:'stripe',weight:100}]};
+ const refs=provisionConnectorAccounts(plan,{stripe:{credentials:{api_key:'fixture-test-key'}}},dir);
+ const accounts=resolveConnectorAccounts(refs,dir);
+ await fixtures(await configuration(dir,url,{merchant_count:1}),path.join(dir,'fixtures'),{connectorAccounts:accounts});
+ const legacy=[{connector:'stripe',credentialRef:connectorSecretStore(dir).put({...accounts[0],business_label:'loadtest'})}];
+ assert.equal(resolveConnectorAccounts(legacy,dir)[0].business_label,'default');
+ }finally{server.close();}
+});
diff --git a/loadtest/k6/scenario-mix/test/mock-server.mjs b/loadtest/k6/scenario-mix/test/mock-server.mjs
new file mode 100644
index 0000000000..1677f6416a
--- /dev/null
+++ b/loadtest/k6/scenario-mix/test/mock-server.mjs
@@ -0,0 +1,60 @@
+import { createServer } from "node:http";
+import { once } from "node:events";
+
+export async function mockServer({baselinePolls=1,listPolls=1} = {}) {
+ const state = {accounts:new Map(),connectors:new Map(),keys:0,patches:0,default:true,conflict:false,failConnector:false,requests:0,polls:new Map(),errorCustomers:false,malformedCustomers:false,latencyOptIns:0,routed:[]};
+ const server = createServer(async(req,res) => {
+ state.requests++;
+ if(req.headers['x-hs-latency']==='true')state.latencyOptIns++;
+ let text=''; for await (const chunk of req) text+=chunk;
+ const body = text ? JSON.parse(text) : {};
+ const url = new URL(req.url,'http://localhost');
+ const send = (status,data) => {res.writeHead(status,{'content-type':'application/json','x-request-id':`r-${state.requests}`,'x-config-version':'v1',...(req.headers['x-hs-latency']==='true'?{'x-hs-latency':'12'}:{})});res.end(JSON.stringify(data));};
+ if(state.requireAdminAuthorization&&(url.pathname==='/organization'||url.pathname.startsWith('/accounts')||url.pathname.startsWith('/api_keys/'))&&req.headers.authorization!=='admin-api-key=admin-test')return send(400,{error:{message:'Missing required param: Authorization'}});
+ if(url.pathname==='/organization') return send(200,{organization_id:'org-1'});
+ if(url.pathname==='/accounts' && req.method==='POST') {
+ if(state.accounts.has(body.merchant_id)) return send(409,{error:{message:'exists'}});
+ const account={merchant_id:body.merchant_id,organization_id:body.organization_id,default_profile:`pro-${body.merchant_id}`,publishable_key:'pk-test',primary_business_details:body.primary_business_details};
+ state.accounts.set(body.merchant_id,account); return send(200,account);
+ }
+ if(url.pathname.startsWith('/accounts/')) return send(200,state.accounts.get(url.pathname.split('/')[2]));
+ if(url.pathname.startsWith('/api_keys/')) {state.keys++;return send(200,{api_key:`key-${state.keys}`});}
+ if(url.pathname.endsWith('/connectors')) {
+ const merchant=url.pathname.split('/')[2];
+ if(req.method==='GET') return send(200,state.connectors.get(merchant)||[]);
+ if(body.business_country&&body.business_label&&!state.accounts.get(merchant)?.primary_business_details?.some(d=>d.country===body.business_country&&d.business===body.business_label))return send(400,{error:{message:'business_details are not configured in the merchant account'}});
+ if(state.failConnector||state.failConnectorName===body.connector_name) return send(500,{error:{message:'connector unavailable'}});
+ const connector={merchant_connector_id:`mca-${merchant}-${body.connector_name}`,connector_label:`${body.connector_name}_${body.business_country}_${body.business_label}`};
+ const existing=state.connectors.get(merchant)||[];if(existing.some(c=>c.connector_label===connector.connector_label))return send(400,{error:{message:'already exists'}});
+ state.connectors.set(merchant,[...existing,connector]);return send(200,connector);
+ }
+ if(url.pathname==='/default-config/unknown') return send(404,{error:{message:'unknown flag'}});
+ if(url.pathname.startsWith('/default-config/')) {
+ if(req.method==='PATCH') {state.patches++;state.default=body.value;}
+ return send(200,{key:'flag',value:state.default,schema:{type:'boolean'}});
+ }
+ if(url.pathname==='/config/resolve') return send(200,{flag:state.conflict?false:state.default});
+ // Local target for recorded k6 integration; IDs always unique.
+ if(url.pathname==='/v2/customers') {
+ if(state.errorCustomers) return send(422,{error:{message:'invalid customer'}});
+ if(state.malformedCustomers) {res.writeHead(200,{'content-type':'application/json','x-request-id':'malformed-test'});res.end('not-json');return;}
+ return send(200,{id:`cus-${state.requests}`});
+ }
+ if(url.pathname==='/v2/payment-method-sessions') return send(200,{id:`pms-${state.requests}`,client_secret:'secret-test'});
+ if(url.pathname.startsWith('/v2/payment-method-sessions/')) return send(200,{associated_payment_methods:[{payment_method_token:'token-test'}]});
+ if(url.pathname==='/payments' && req.method==='POST') {const id=`pay-${state.requests}`;if(state.delayPayments)await new Promise(resolve=>setTimeout(resolve,state.delayPayments));return send(200,{payment_id:id,customer_id:body.customer_id,amount:body.amount,status:body.confirm?'succeeded':'requires_payment_method',client_secret:'secret-test'});}
+ if(url.pathname.endsWith('/confirm')){if(state.requireBrowserInfo&&body.routing?.data?.connector==='adyen'&&['accept_header','language','screen_height','screen_width','color_depth','user_agent','time_zone','java_enabled'].some(k=>body.browser_info?.[k]==null))return send(400,{error:{message:'Missing required param: browser_info'}});if(body.routing)state.routed.push(body.routing);return send(200,{payment_id:url.pathname.split('/')[2],status:'succeeded',connector:body.routing?.data?.connector,merchant_connector_id:body.routing?.data?.merchant_connector_id});}
+ if(url.pathname.endsWith('/client')) {
+ const n=state.polls.get(url.pathname)||0;state.polls.set(url.pathname,n+1);
+ return send(200,{customer_payment_methods:n<listPolls?[]:[{payment_token:'token-test'}]});
+ }
+ if(url.pathname==='/payments/session_tokens' || url.pathname.endsWith('/eligibility')) return send(200,{});
+ if(url.pathname.startsWith('/payments/')) {
+ const n=state.polls.get(url.pathname)||0;state.polls.set(url.pathname,n+1);
+ return send(200,{payment_id:url.pathname.split('/')[2],...(n<baselinePolls?{}:{payment_method_id:'pm-test'}),status:'succeeded'});
+ }
+ return send(404,{error:{message:'unknown route'}});
+ });
+ server.listen(0,'127.0.0.1');await once(server,'listening');
+ return {server,state,url:`http://127.0.0.1:${server.address().port}`};
+}
diff --git a/loadtest/k6/scenario-mix/test/server-latency.test.mjs b/loadtest/k6/scenario-mix/test/server-latency.test.mjs
new file mode 100644
index 0000000000..ef12a1b5ee
--- /dev/null
+++ b/loadtest/k6/scenario-mix/test/server-latency.test.mjs
@@ -0,0 +1,10 @@
+import test from 'node:test';import assert from 'node:assert/strict';
+import {serverLatency,latencyHeaders} from '../server-latency.mjs';
+test('server latency parses case-insensitive milliseconds and preserves zero',()=>{
+ assert.equal(serverLatency({'X-Hs-Latency':' 123.5 '}),123.5);assert.equal(serverLatency({'x-hs-latency':'0'}),0);
+ for(const value of ['', 'true','NaN','Infinity','-1','10ms',null,10])assert.equal(serverLatency({'x-hs-latency':value}),null);
+ assert.equal(serverLatency({}),null);
+});
+test('router latency opt-in replaces conflicting casing and keeps other headers',()=>{
+ assert.deepEqual(latencyHeaders({'X-HS-LATENCY':'false','x-feature':'test'}),{'x-feature':'test','x-hs-latency':'true'});
+});
diff --git a/loadtest/k6/scenario-mix/test/storage.test.mjs b/loadtest/k6/scenario-mix/test/storage.test.mjs
new file mode 100644
index 0000000000..f64cb994fb
--- /dev/null
+++ b/loadtest/k6/scenario-mix/test/storage.test.mjs
@@ -0,0 +1,84 @@
+import test from 'node:test';
+import assert from 'node:assert/strict';
+import { mkdtemp, writeFile, readFile } from 'node:fs/promises';
+import os from 'node:os';
+import path from 'node:path';
+import { DatabaseSync } from 'node:sqlite';
+import { FixtureRecorder, recordedFetch } from '../sqlite.mjs';
+import { responseRecord } from '../record.mjs';
+import { reconcile, csvRows } from '../reconcile.mjs';
+
+const temp = () => mkdtemp(path.join(os.tmpdir(),'loadtest-storage-'));
+function record(operation,body,request={},context={},status=200,text=null) {
+ return responseRecord({ flow_id:'flow-1',merchant_id:'merchant-1',operation,...context },'POST','http://local/payments',request,
+ { status,headers:{'X-Request-Id':'request-123'} },text ?? JSON.stringify(body),12.5);
+}
+test('records fields, errors, malformed bodies and transport failures without retaining successful raw bodies',() => {
+ const customer = record('customer_create',{id:'cus-1'},{merchant_reference_id:'ref-1'});
+ assert.equal(customer.customer_id,'cus-1'); assert.equal(customer.request_id,'request-123');
+ assert.equal(customer.merchant_reference_id,'ref-1'); assert.equal(customer.error_body,null);
+ const failure = record('payment_create',{error:{message:'invalid amount'}},{amount:3},{},422);
+ assert.equal(failure.payment_id,null); assert.equal(failure.message,'invalid amount');
+ assert.match(failure.error_body,/invalid amount/);
+ assert.equal(record('payment_confirm',{}, {}, {}, 200,'garbage').message,'invalid_json_response');
+ const transport = responseRecord({flow_id:'f',operation:'payment_create'},'POST','http://local/payments',{},null,'',5,'timeout');
+ assert.equal(transport.api_status_code,0); assert.equal(transport.message,'timeout');
+});
+test('SQLite preserves event history and latest known payment status, including baseline role',async() => {
+ const dir = await temp(), file = path.join(dir,'results.sqlite');
+ const recorder = new FixtureRecorder(file);
+ recorder.record(record('baseline_create',{payment_id:'baseline',status:'requires_payment_method',amount:100}));
+ recorder.record(record('payment_create',{payment_id:'pay-1',status:'requires_payment_method',amount:100,customer_id:'cus-1'}));
+ recorder.record(record('payment_confirm',{payment_id:'pay-1',status:'succeeded'}));
+ recorder.record(record('payment_confirm',{error:{message:'unavailable'}},{},{payment_id:'pay-1'},500));
+ // A confirm URL supplies payment ID even when its error body has none.
+ recorder.record(responseRecord({flow_id:'f',operation:'payment_confirm'},'POST','http://local/payments/pay-1/confirm',{},
+ {status:500,headers:{}},'{"error":{"message":"unavailable"}}',2));
+ const stale=record('payment_confirm',{payment_id:'pay-1',status:'processing'});stale.observed_at=1;recorder.record(stale);
+ recorder.close();
+ const db = new DatabaseSync(file,{readOnly:true});
+ const payment = db.prepare("SELECT * FROM payments WHERE payment_id='pay-1'").get();
+ assert.equal(payment.status,'succeeded'); assert.equal(payment.amount,100); assert.equal(payment.customer_id,'cus-1');
+ assert.equal(payment.api_status_code,500); assert.equal(payment.message,'unavailable');
+ assert.equal(db.prepare("SELECT role FROM payments WHERE payment_id='baseline'").get().role,'baseline');
+ assert.equal(db.prepare('SELECT COUNT(*) n FROM request_events').get().n,6);
+ assert.equal(db.prepare('SELECT recording_state FROM runs').get().recording_state,'complete');
+ db.close();
+});
+test('reconciliation handles matches, missing IDs, mismatches and duplicate/conflicting input',async() => {
+ const dir = await temp(), file = path.join(dir,'results.sqlite'), csv = path.join(dir,'input.csv'), output = path.join(dir,'result.csv');
+ const recorder = new FixtureRecorder(file);
+ recorder.record(record('payment_confirm',{payment_id:'pay-1',status:'succeeded'})); recorder.close();
+ await writeFile(csv,'payment_id,status\r\npay-1,succeeded\r\nmissing,failed\r\npay-2,failed\r\npay-2,succeeded\r\npay-3,failed\r\npay-3,failed\r\n');
+ const result = await reconcile({db:file,csv,output});
+ assert.equal(result.exitCode,2); assert.deepEqual(result.summary,{match:1,mismatch:0,missing:1,duplicate:2,conflicting_duplicate:2});
+ assert.match(await readFile(output,'utf8'),/conflicting_duplicate/);
+ await writeFile(csv,'payment_id,status\npay-1,failed\n');
+ assert.equal((await reconcile({db:file,csv,output:path.join(dir,'mismatch.csv')})).summary.mismatch,1);
+});
+test('incomplete databases require an explicit override; invalid CSV fails',async() => {
+ const dir = await temp(), file = path.join(dir,'results.sqlite'),csv = path.join(dir,'input.csv');
+ const recorder = new FixtureRecorder(file); recorder.close(new Error('interrupted'));
+ await writeFile(csv,'payment_id,status\nmissing,failed\n');
+ await assert.rejects(reconcile({db:file,csv,output:path.join(dir,'out.csv')}),/incomplete/);
+ assert.equal((await reconcile({db:file,csv,output:path.join(dir,'partial.csv'),allowIncomplete:true})).summary.missing,1);
+ await writeFile(csv,'status,payment_id\nfailed,missing\n');
+ await assert.rejects(reconcile({db:file,csv,output:path.join(dir,'bad.csv'),allowIncomplete:true}),/header/);
+});
+test('CSV parser handles quotes, embedded newlines, UTF-8 and chunk boundaries',async() => {
+ const dir = await temp(),csv = path.join(dir,'input.csv');
+ const long = 'é'.repeat(40000);
+ await writeFile(csv,`\uFEFFpayment_id,status\r\n"${long}","a,b\nwith ""quote"""\r\n`);
+ const rows = []; for await (const row of csvRows(csv)) rows.push(row);
+ assert.deepEqual(rows,[['payment_id','status'],[long,'a,b\nwith "quote"']]);
+ await writeFile(csv,'payment_id,status\n"unterminated');
+ await assert.rejects(async()=> { for await(const _ of csvRows(csv)) {} },/Unterminated/);
+});
+test('transport attempts are captured before fetch errors propagate',async() => {
+ const dir = await temp(),file = path.join(dir,'fixtures.sqlite');
+ const recorder = new FixtureRecorder(file);
+ await assert.rejects(recordedFetch(recorder,'http://127.0.0.1:1',{},{operation:'fixture_GET'}));
+ recorder.close();
+ const db = new DatabaseSync(file,{readOnly:true});
+ assert.equal(db.prepare('SELECT COUNT(*) n FROM request_events WHERE api_status_code=0').get().n,1); db.close();
+});
diff --git a/loadtest/loadtest.config.example.json b/loadtest/loadtest.config.example.json
new file mode 100644
index 0000000000..68d3061149
--- /dev/null
+++ b/loadtest/loadtest.config.example.json
@@ -0,0 +1,102 @@
+{
+ "output": "artifacts/local",
+ "fixtures": {
+ "router": "http://127.0.0.1:8080",
+ "admin_api_key": "${ROUTER_ADMIN_API_KEY}",
+ "merchant_id_prefix": "loadtest_local",
+ "concurrency": 20,
+ "connector": {
+ "connector_name": "stripe_test",
+ "connector_account_details": {
+ "auth_type": "HeaderKey",
+ "api_key": "local-test"
+ },
+ "test_mode": true,
+ "business_country": "US",
+ "business_label": "default"
+ },
+ "superposition": {
+ "endpoint": "http://127.0.0.1:8082",
+ "token": "${SUPERPOSITION_TOKEN}",
+ "access_header": "x-superposition-access",
+ "organization_id": "localorg",
+ "workspace_id": "dev",
+ "refresh_interval_seconds": 300,
+ "poll_interval_seconds": 5,
+ "defaults": {
+ "system.should_call_pm_modular_service": true,
+ "system.payment_method_integration_type": "pay_then_vault",
+ "vaulting.should_trigger_fingerprint_migration": true
+ }
+ },
+ "retry": {
+ "attempts": 3,
+ "backoff_ms": 500
+ }
+ },
+ "services": {
+ "router": "http://127.0.0.1:8080",
+ "modular_pm": "http://127.0.0.1:8081/v2"
+ },
+ "target_headers": {
+ "router": {},
+ "modular_pm": {}
+ },
+ "load": {
+ "total_rps": 10,
+ "duration_seconds": 60,
+ "request_timeout_ms": 40000,
+ "think_time_ms": 0,
+ "pre_allocated_vus_multiplier": 3,
+ "max_vus_multiplier": 10
+ },
+ "payment": {
+ "amount": 1000,
+ "currency": "USD",
+ "session_expiry": 900,
+ "card": {
+ "card_number": "4242424242424242",
+ "card_exp_month": "10",
+ "card_exp_year": "35",
+ "card_holder_name": "Load Test",
+ "card_cvc": "123"
+ },
+ "card_pool": [],
+ "metadata_update": {
+ "card_exp_month": "11",
+ "card_exp_year": "36",
+ "card_holder_name": "Updated Load Test"
+ }
+ },
+ "sdk": {
+ "wallets": []
+ },
+ "scenarios": [
+ {
+ "name": "cit_off",
+ "merchant_path": "modular",
+ "scenario": "cit_off_session",
+ "weight": 50
+ },
+ {
+ "name": "sdk",
+ "merchant_path": "modular",
+ "scenario": "sdk_checkout",
+ "weight": 30
+ },
+ {
+ "name": "guest",
+ "merchant_path": "modular",
+ "scenario": "guest",
+ "weight": 20
+ }
+ ],
+ "thresholds": {
+ "http_req_failed": [
+ "rate<0.01"
+ ],
+ "dropped_iterations": [
+ "count==0"
+ ]
+ }
+}
diff --git a/loadtest/loadtest.sh b/loadtest/loadtest.sh
deleted file mode 100644
index d3b03bba03..0000000000
--- a/loadtest/loadtest.sh
+++ /dev/null
@@ -1,85 +0,0 @@
-#!/bin/bash
-
-run_loadtest() {
- docker compose down
- docker compose up k6
-}
-
-print_details() {
- echo "-----------------------------------"
- echo "RUN NAME: $1"
- echo " SCRIPT: $2"
- echo "-----------------------------------"
-}
-
-exit_if_baseline_file_not_exist() {
- if ! [ -e "./k6/benchmark/baseline_$1.json" ]
- then
- echo "baseline_$1.json file not exist to compare."
- exit 1
- fi
-}
-
-while getopts r:s:ca flag
-do
- case "${flag}" in
- r) run_name=${OPTARG};;
- s) script=${OPTARG};;
- c) compare=true;;
- a) all_script=true;;
- *) echo "usage: $0 [-r] [-c] [-s]" >&2
- exit 1;;
- esac
-done
-
-# if script is empty, `-s` not specified, use "health"
-if [ -z "$script" ]
-then
- script=health
-fi
-
-if ! [ -e "./k6/$script.js" ] && [ -z "$all_script" ]
-then
- echo "$script.js not exist."
- exit 1
-fi
-
-# if compare is specified using `-c` flag, create run name using commit number
-if [ "$compare" = true ]
-then
- run_name=$(git show -s --format=%h)
- # make sure baseline file exist for specified parameter before starting the loadtest
- if [ "$all_script" = true ]
- then
- for scriptname in ./k6/*.js
- do
- filename=$(basename "$scriptname" | cut -f 1 -d '.')
- exit_if_baseline_file_not_exist "$filename"
- done
- else
- exit_if_baseline_file_not_exist "$script"
- fi
-else
- # if run name is empty, `-r` not specified, use "baseline"
- if [ -z "$run_name" ]
- then
- run_name=baseline
- fi
-fi
-
-export LOADTEST_RUN_NAME=$run_name
-
-if [ "$all_script" = true ]
-then
- for script in ./k6/*.js
- do
- script=$(basename "$script")
- print_details "$run_name" "$script"
- export LOADTEST_K6_SCRIPT=$script
- run_loadtest
- done
-else
- print_details "$run_name" "$script.js"
- export LOADTEST_K6_SCRIPT="$script.js"
- run_loadtest
-fi
diff --git a/loadtest/protocol/worker-v1.schema.json b/loadtest/protocol/worker-v1.schema.json
new file mode 100644
index 0000000000..258286986f
--- /dev/null
+++ b/loadtest/protocol/worker-v1.schema.json
@@ -0,0 +1,9 @@
+{
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
+ "$id": "https://hyperswitch.io/loadtest/worker-v1.schema.json",
+ "title": "Hyperswitch load worker protocol v1",
+ "$defs": {
+ "capacity": {"type":"object","required":["capacityTps","capacityVus"],"properties":{"capacityTps":{"type":"integer","minimum":1},"capacityVus":{"type":"integer","minimum":1}}},
+ "command": {"type":"object","required":["id","revision","kind","payload"],"properties":{"id":{"type":"string","format":"uuid"},"runId":{"type":["string","null"]},"revision":{"type":"integer","minimum":1},"kind":{"enum":["prepare","start","pause","resume","stop","upload"]},"payload":{"type":"object"}}}
+ }
+}
diff --git a/loadtest/worker/Dockerfile b/loadtest/worker/Dockerfile
new file mode 100644
index 0000000000..c0aa1f86e2
--- /dev/null
+++ b/loadtest/worker/Dockerfile
@@ -0,0 +1,18 @@
+FROM golang:1.24.4-bookworm AS recorder
+WORKDIR /recorder
+COPY loadtest/k6/scenario-mix/recorder/go.mod loadtest/k6/scenario-mix/recorder/go.sum ./
+RUN go mod download
+COPY loadtest/k6/scenario-mix/recorder/ ./
+RUN CGO_ENABLED=1 go build -mod=readonly -trimpath -o /k6-sqlite ./cmd/k6-sqlite
+
+FROM node:24.19.0-bookworm-slim
+RUN apt-get update && apt-get install -y --no-install-recommends ca-certificates tini && rm -rf /var/lib/apt/lists/*
+WORKDIR /opt/hyperswitch/loadtest
+COPY loadtest/worker ./worker
+COPY loadtest/k6/scenario-mix ./k6/scenario-mix
+COPY loadtest/console/src/connector-config.mjs loadtest/console/src/connector-catalog.json loadtest/console/src/payment-flows.mjs loadtest/console/src/environments.mjs ./console/src/
+COPY --from=recorder /k6-sqlite /usr/local/bin/k6-sqlite
+RUN useradd --create-home worker && mkdir /data && chown worker:worker /data
+USER worker
+ENV LOADTEST_ROOT=/opt/hyperswitch/loadtest LOADTEST_WORKER_DATA_DIR=/data K6_BINARY=/usr/local/bin/k6-sqlite
+ENTRYPOINT ["/usr/bin/tini","--","node","worker/agent.mjs"]
diff --git a/loadtest/worker/Dockerfile.dockerignore b/loadtest/worker/Dockerfile.dockerignore
new file mode 100644
index 0000000000..f2ef4b6083
--- /dev/null
+++ b/loadtest/worker/Dockerfile.dockerignore
@@ -0,0 +1,17 @@
+**
+!loadtest/
+!loadtest/worker/
+!loadtest/worker/*.mjs
+!loadtest/k6/
+!loadtest/k6/scenario-mix/
+!loadtest/k6/scenario-mix/*.mjs
+!loadtest/k6/scenario-mix/scenario-mix.js
+!loadtest/k6/scenario-mix/recording-client.js
+!loadtest/k6/scenario-mix/recorder/
+!loadtest/k6/scenario-mix/recorder/**
+!loadtest/console/
+!loadtest/console/src/
+!loadtest/console/src/connector-config.mjs
+!loadtest/console/src/connector-catalog.json
+!loadtest/console/src/payment-flows.mjs
+!loadtest/console/src/environments.mjs
diff --git a/loadtest/worker/agent.mjs b/loadtest/worker/agent.mjs
new file mode 100644
index 0000000000..13cef61c12
--- /dev/null
+++ b/loadtest/worker/agent.mjs
@@ -0,0 +1,44 @@
+#!/usr/bin/env node
+import os from 'node:os';
+import {readFile,writeFile,mkdir} from 'node:fs/promises';
+import path from 'node:path';
+import {WorkerExecutor} from './executor.mjs';
+
+const server=String(process.env.LOADTEST_CONTROL_PLANE_URL||'').replace(/\/$/,'');
+const enrollmentToken=process.env.LOADTEST_WORKER_ENROLLMENT_TOKEN||'';
+const stateDir=path.resolve(process.env.LOADTEST_WORKER_DATA_DIR||'.worker-data'),stateFile=path.join(stateDir,'identity.json');
+if(!server)throw new Error('LOADTEST_CONTROL_PLANE_URL is required');
+function networkError(error){
+ const cause=error?.cause,detail=[cause?.code,cause?.message].filter(Boolean).join(' · ');
+ return detail?`${error.message} (${detail})`:error.message;
+}
+const request=async(url,options={})=>{let response;const {raw=false,...fetchOptions}=options;try{response=await fetch(server+url,{...fetchOptions,headers:{'content-type':'application/json',...(fetchOptions.headers||{})},signal:AbortSignal.timeout(15000)});}catch(error){throw new Error(`Cannot reach control plane at ${server}: ${networkError(error)}`);}const text=await response.text(),body=raw?text:(text?JSON.parse(text):{});if(!response.ok)throw new Error(body.error||`Control plane returned ${response.status}`);return body;};
+let identity;try{identity=JSON.parse(await readFile(stateFile,'utf8'));}catch(e){if(e.code!=='ENOENT')throw e;}
+if(!identity){
+ for(;;)try{identity=await request('/api/worker/v1/enroll',{method:'POST',headers:{authorization:`Bearer ${enrollmentToken}`},body:JSON.stringify({name:process.env.LOADTEST_WORKER_NAME||os.hostname(),capacityTps:Number(process.env.LOADTEST_WORKER_TPS||250),capacityVus:Number(process.env.LOADTEST_WORKER_VUS||2500),version:'1',labels:{platform:process.platform,arch:process.arch}})});break;}catch(e){console.error(`Enrollment pending: ${e.message}`);await new Promise(resolve=>setTimeout(resolve,3000));}
+ await mkdir(stateDir,{recursive:true,mode:0o700});await writeFile(stateFile,JSON.stringify(identity,null,2)+'\n',{mode:0o600});
+}
+let revision=Number(identity.revision||0),stopping=false,pollMs=Number(process.env.LOADTEST_WORKER_POLL_MS||1000);if(!Number.isInteger(pollMs)||pollMs<250||pollMs>10000)throw new Error('LOADTEST_WORKER_POLL_MS must be 250–10000 milliseconds');
+const headers={authorization:`Bearer ${identity.token}`};
+const executor=new WorkerExecutor({server,identity,request:(url,options={})=>request(url,{...options,headers:{...headers,...(options.headers||{})}}),dataDir:stateDir});
+await executor.recover();
+async function cycle(){
+ await request(`/api/worker/v1/workers/${identity.id}/heartbeat`,{method:'POST',headers,body:JSON.stringify({...await executor.state(),version:'1'})});
+ const commands=await request(`/api/worker/v1/workers/${identity.id}/commands?after=${revision}`,{headers});
+ for(const command of commands){
+ let result,error;try{
+ if(command.kind==='prepare')result=await executor.prepare(command);
+ else if(command.kind==='start'){result=await executor.start(command);const run=executor.runs.get(command.runId);run.done.then(async()=>{if(run.status==='recorded'){run.status='uploading';await executor.persist(command.runId,run);await executor.upload(command.runId,headers);run.status='complete';await executor.persist(command.runId,run);}}).catch(async e=>{run.status='failed';run.log=(run.log||'')+'\n'+e.message;await executor.persist(command.runId,run);});}
+ else if(['pause','resume','gate','release','recover','stop'].includes(command.kind))result=await executor.control(command);
+ else if(command.kind==='upload')result=await executor.upload(command.runId,headers);
+ else throw new Error('Unsupported command');
+ }catch(e){error=e.message;}
+ await request(`/api/worker/v1/workers/${identity.id}/commands/${command.id}/ack`,{method:'POST',headers,body:JSON.stringify({ok:!error,result:error?{error}:result})});
+ revision=Math.max(revision,command.revision);
+ identity.revision=revision;await writeFile(stateFile,JSON.stringify(identity,null,2)+'\n',{mode:0o600});
+ }
+}
+let lastContact=Date.now();
+process.once('SIGINT',()=>stopping=true);process.once('SIGTERM',()=>stopping=true);
+while(!stopping){try{await cycle();lastContact=Date.now();}catch(e){console.error(e.message);if(Date.now()-lastContact>=30000)await executor.shutdown();}await new Promise(resolve=>setTimeout(resolve,pollMs));}
+await executor.shutdown();
diff --git a/loadtest/worker/executor.mjs b/loadtest/worker/executor.mjs
new file mode 100644
index 0000000000..2bca3c3ecc
--- /dev/null
+++ b/loadtest/worker/executor.mjs
@@ -0,0 +1,78 @@
+import {createHash,randomUUID} from 'node:crypto';
+import {spawn} from 'node:child_process';
+import {createReadStream} from 'node:fs';
+import {mkdir,readFile,writeFile,readdir,stat} from 'node:fs/promises';
+import path from 'node:path';
+
+const digest=value=>createHash('sha256').update(value).digest('hex');
+const wait=ms=>new Promise(resolve=>setTimeout(resolve,ms));
+export function shardLoadConfig(input,{offeredTps,totalTps}){
+ const config=structuredClone(input),fraction=Number(offeredTps)/Number(totalTps);
+ if(!(fraction>0&&fraction<=1))throw new Error('Worker shard fraction is invalid');
+ if(Array.isArray(config.load?.stages)){
+ config.load.stages=config.load.stages.map(stage=>({...stage,target_rps:Math.max(.001,Number(stage.target_rps)*fraction)}));
+ config.load.start_rps=Math.max(0,Number(config.load.start_rps||0)*fraction);
+ }else if(config.load?.phases){
+ config.load.phases={...config.load.phases,starting_rps:Number(config.load.phases.starting_rps)*fraction,target_rps:Number(config.load.phases.target_rps)*fraction};
+ }else config.load.total_rps=Number(offeredTps);
+ config.load.pre_allocated_vus_multiplier=Number(config.load.pre_allocated_vus_multiplier||3);config.load.max_vus_multiplier=Number(config.load.max_vus_multiplier||10);
+ return config;
+}
+export class WorkerExecutor{
+ constructor({server,identity,request,dataDir,loadtestRoot=path.resolve(process.env.LOADTEST_ROOT||path.join(import.meta.dirname,'..'))}){this.server=server;this.identity=identity;this.request=request;this.dataDir=dataDir;this.loadtestRoot=loadtestRoot;this.runs=new Map();}
+ async persist(runId,run){await writeFile(path.join(run.directory,'worker-state.json'),JSON.stringify({runId,status:run.status,exitCode:run.exitCode,bundleId:run.bundleId})+'\n',{mode:0o600});}
+ async recover(){for(const entry of await readdir(path.join(this.dataDir,'runs'),{withFileTypes:true}).catch(e=>e.code==='ENOENT'?[]:Promise.reject(e))){if(!entry.isDirectory())continue;const directory=path.join(this.dataDir,'runs',entry.name);try{const state=JSON.parse(await readFile(path.join(directory,'worker-state.json'),'utf8')),status=['ready','complete'].includes(state.status)?state.status:'failed',run={directory,fixtures:path.join(directory,'fixtures'),output:path.join(directory,'output'),status,exitCode:state.exitCode,bundleId:state.bundleId,child:null,log:status==='failed'?'Worker agent restarted during execution':''};this.runs.set(state.runId,run);await this.persist(state.runId,run);}catch{}}
+ }
+ async prepare(command){
+ const existing=this.runs.get(command.runId);if(existing&&!['failed'].includes(existing.status)){if(existing.bundleId&&existing.bundleId!==command.payload.bundleId)throw new Error('Run was already prepared from a different bundle');return {runId:command.runId,status:existing.status};}
+ const {bundleId,sha256}=command.payload,body=await this.request(`/api/worker/v1/workers/${this.identity.id}/bundles/${bundleId}`,{raw:true});
+ if(digest(body)!==sha256)throw new Error('Worker bundle checksum mismatch');const bundle=JSON.parse(body),directory=path.join(this.dataDir,'runs',bundle.runId),fixtures=path.join(directory,'fixtures'),output=path.join(directory,'output');
+ await mkdir(fixtures,{recursive:true,mode:0o700});await mkdir(output,{recursive:true,mode:0o700});
+ const config=shardLoadConfig(bundle.config,command.payload);
+ await Promise.all([writeFile(path.join(directory,'config.json'),JSON.stringify(config,null,2),{mode:0o600}),writeFile(path.join(fixtures,'manifest.json'),JSON.stringify(bundle.manifest),{mode:0o600}),writeFile(path.join(fixtures,'merchants.json'),JSON.stringify(bundle.merchants),{mode:0o600})]);
+ const run={directory,fixtures,output,status:'ready',child:null,bundleId};this.runs.set(bundle.runId,run);await this.persist(bundle.runId,run);return {runId:bundle.runId,status:'ready'};
+ }
+ async start(command){
+ const run=this.runs.get(command.runId);if(!run)throw new Error('Run is not prepared');if(run.status!=='ready'){if(['running','pausing','paused','draining','recorded','uploading','complete'].includes(run.status))return {runId:command.runId,status:run.status};throw new Error('Run is not prepared');}const delay=Number(command.payload.startAt||0)-Date.now();if(delay>0)await wait(delay);
+ const binary=process.env.K6_BINARY||path.join(this.loadtestRoot,'k6/scenario-mix/bin/k6-sqlite'),entry=path.join(this.loadtestRoot,'k6/scenario-mix/run.mjs');
+ run.status='running';run.controlToken=randomUUID();await this.persist(command.runId,run);run.child=spawn(process.execPath,[entry,'load','--config',path.join(run.directory,'config.json'),'--fixtures',run.fixtures,'--output',run.output,'--k6',binary],{stdio:['ignore','pipe','pipe'],env:{...process.env,LOADTEST_CONSOLE_JOB:'1',K6_PID_FILE:path.join(run.directory,'k6-pid.json'),SQLITE_RECORDER_CONTROL_TOKEN:run.controlToken,SQLITE_RECORDER_CONTROL_FILE:path.join(run.output,'control.json'),SQLITE_RECORDER_PROGRESS_FILE:path.join(run.output,'progress.json')}});
+ run.log='';for(const stream of [run.child.stdout,run.child.stderr])stream.on('data',chunk=>run.log=(run.log+chunk).slice(-100000));
+ run.done=new Promise(resolve=>run.child.once('close',async code=>{run.exitCode=code??1;run.status=[0,99].includes(run.exitCode)?'recorded':'failed';await this.persist(command.runId,run);resolve(run);}));return {runId:command.runId,status:'running'};
+ }
+ async control(command){
+ const run=this.runs.get(command.runId);if(!run)throw new Error('Run does not exist');
+ const delay=Number(command.payload?.effectiveAt||0)-Date.now();if(delay>0)await wait(delay);
+ if(command.kind==='stop'){
+ if(!run.child&&run.status==='ready'){run.status='failed';run.log='Cancelled before load started';await this.persist(command.runId,run);}
+ else if(!['complete','failed','recorded','uploading'].includes(run.status)){run.child?.kill('SIGTERM');run.status='draining';}
+ return {status:run.status};
+ }
+ if((command.kind==='pause'&&run.status==='paused')||(command.kind==='resume'&&run.status==='running'))return {state:run.status};
+ const control=JSON.parse(await readFile(path.join(run.output,'control.json'),'utf8')),response=await fetch(control.endpoint,{method:'POST',headers:{authorization:`Bearer ${run.controlToken}`,'content-type':'application/json'},body:JSON.stringify({action:command.kind,...command.payload}),signal:AbortSignal.timeout(5000)});
+ if(!response.ok)throw new Error(await response.text());const state=await response.json();run.status=state.state==='paused'?'paused':state.state==='pausing'?'pausing':'running';return state;
+ }
+ async state(){const active=[...this.runs.entries()].find(([,run])=>!['complete','failed'].includes(run.status));if(active){let progress={};try{progress=JSON.parse(await readFile(path.join(active[1].output,'progress.json'),'utf8'));}catch{}return {runId:active[0],runStatus:active[1].status,status:['recorded'].includes(active[1].status)?'uploading':active[1].status,progress:{...progress,exitCode:active[1].exitCode}};}const finished=[...this.runs.entries()].at(-1);return finished?{runId:finished[0],runStatus:finished[1].status,status:'idle',progress:{exitCode:finished[1].exitCode},error:finished[1].status==='failed'?finished[1].log:null}:{status:'idle'};}
+ async shutdown(){
+ const active=[...this.runs.entries()].filter(([,run])=>!['complete','failed','recorded','uploading'].includes(run.status));
+ for(const [runId] of active)await this.control({runId,kind:'stop',payload:{}});
+ let timer;
+ try{await Promise.race([Promise.all(active.map(([,run])=>run.done)),new Promise(resolve=>{timer=setTimeout(resolve,10000);})]);}finally{clearTimeout(timer);}
+ for(const [,run] of active)if(run.child&&run.child.exitCode===null&&run.child.signalCode===null){
+ // run.mjs owns this detached k6 process group and is still waiting for it.
+ const child=JSON.parse(await readFile(path.join(run.directory,'k6-pid.json'),'utf8').catch(()=>'null'));
+ if(Number.isSafeInteger(child?.pid)&&child.pid>1)try{process.kill(-child.pid,'SIGKILL');}catch(error){if(error.code!=='ESRCH')throw error;}
+ run.child.kill('SIGKILL');
+ }
+ await Promise.all(active.map(([,run])=>run.done));
+ }
+ async upload(runId,headers){
+ const run=this.runs.get(runId);if(!run)throw new Error('Run does not exist');
+ for(const name of ['results.sqlite','summary.json','progress.json']){
+ const file=path.join(run.output,name);let info;
+ try{info=await stat(file);}catch(error){if(error.code==='ENOENT'&&name==='progress.json')continue;throw error;}
+ const response=await fetch(`${this.server}/api/worker/v1/workers/${this.identity.id}/runs/${runId}/artifacts/${name}`,{method:'PUT',headers:{...headers,'content-type':name.endsWith('.json')?'application/json':'application/octet-stream','content-length':String(info.size)},body:createReadStream(file),duplex:'half'});
+ await response.body?.cancel();if(!response.ok)throw new Error(`Artifact upload failed (${response.status})`);
+ }
+ return {uploaded:true};
+ }
+}
diff --git a/scripts/add_connector.sh b/scripts/add_connector.sh
index 4d91029b0c..0ea892cc1f 100755
--- a/scripts/add_connector.sh
+++ b/scripts/add_connector.sh
@@ -47,7 +47,7 @@ cd $SCRIPT/..
# Remove template files if already created for this connector
rm -rf $conn/$payment_gateway $conn/$payment_gateway.rs
-git checkout $conn.rs $src/types/api/connector_mapping.rs $src/configs/settings.rs config/development.toml config/docker_compose.toml config/config.example.toml loadtest/config/development.toml crates/api_models/src/connector_enums.rs crates/euclid/src/enums.rs crates/api_models/src/routing.rs $src/core/payments/flows.rs crates/common_enums/src/connector_enums.rs crates/common_enums/src/connector_enums.rs-e $src/types/connector_transformers.rs $src/core/admin.rs
+git checkout $conn.rs $src/types/api/connector_mapping.rs $src/configs/settings.rs config/development.toml config/docker_compose.toml config/config.example.toml crates/api_models/src/connector_enums.rs crates/euclid/src/enums.rs crates/api_models/src/routing.rs $src/core/payments/flows.rs crates/common_enums/src/connector_enums.rs crates/common_enums/src/connector_enums.rs-e $src/types/connector_transformers.rs $src/core/admin.rs
# Add enum for this connector in required places
previous_connector=''
@@ -58,7 +58,7 @@ sed -i'' -e "s/};/ ${payment_gateway}::${payment_gateway_camelcase},\n};/" $conn
sed -i'' -e "/pub use hyperswitch_connectors::connectors::{/ s/{/{\n ${payment_gateway}, ${payment_gateway}::${payment_gateway_camelcase},/" $src/connector.rs
sed -i'' -e "s|$previous_connector_camelcase \(.*\)|$previous_connector_camelcase \1\n\t\t\tRoutableConnectors::${payment_gateway_camelcase} => euclid_enums::Connector::${payment_gateway_camelcase},|" crates/api_models/src/routing.rs
sed -i'' -e "s/pub $previous_connector: \(.*\)/pub $previous_connector: \1\n\tpub ${payment_gateway}: ConnectorParams,/" crates/hyperswitch_interfaces/src/configs.rs
-sed -i'' -e "s|$previous_connector.base_url \(.*\)|$previous_connector.base_url \1\n${payment_gateway}.base_url = \"$base_url\"|" config/development.toml config/docker_compose.toml config/config.example.toml loadtest/config/development.toml config/deployments/integration_test.toml config/deployments/production.toml config/deployments/sandbox.toml
+sed -i'' -e "s|$previous_connector.base_url \(.*\)|$previous_connector.base_url \1\n${payment_gateway}.base_url = \"$base_url\"|" config/development.toml config/docker_compose.toml config/config.example.toml config/deployments/integration_test.toml config/deployments/production.toml config/deployments/sandbox.toml
sed -i '' -e "s/\(pub enum Connector {\)/\1\n\t${payment_gateway_camelcase},/" crates/api_models/src/connector_enums.rs
sed -i '' -e "/\/\/ Add Separate authentication support for connectors/{N;s/\(.*\)\n/\1\n\t\t\t| Self::${payment_gateway_camelcase}\n/;}" crates/api_models/src/connector_enums.rs
sed -i '' -e "s/\(match connector_name {\)/\1\n\t\tapi_enums::Connector::${payment_gateway_camelcase} => {${payment_gateway}::transformers::${payment_gateway_camelcase}AuthType::try_from(val)?;Ok(())}/" $src/core/admin.rs
@@ -182,7 +182,7 @@ sed -i'' -e "/pub ${previous_connector}: ConnectorParams,/a\\
# Remove temporary files created in above step
-rm $conn.rs-e $src/types/api/connector_mapping.rs-e $src/configs/settings.rs-e config/development.toml-e config/docker_compose.toml-e config/config.example.toml-e loadtest/config/development.toml-e crates/api_models/src/connector_enums.rs-e crates/euclid/src/enums.rs-e crates/api_models/src/routing.rs-e $src/core/payments/flows.rs-e crates/common_enums/src/connector_enums.rs-e $src/types/connector_transformers.rs-e $src/core/admin.rs-e crates/hyperswitch_connectors/src/default_implementations.rs-e crates/hyperswitch_connectors/src/default_implementations_v2.rs-e crates/hyperswitch_interfaces/src/configs.rs-e $src/connector.rs-e config/deployments/integration_test.toml-e config/deployments/production.toml-e config/deployments/sandbox.toml-e temp crates/connector_configs/src/connector.rs-e crates/router/tests/connectors/main.rs-e crates/router/src/core/payments/connector_integration_v2_impls.rs-e crates/hyperswitch_domain_models/src/connector_endpoints.rs-e
+rm $conn.rs-e $src/types/api/connector_mapping.rs-e $src/configs/settings.rs-e config/development.toml-e config/docker_compose.toml-e config/config.example.toml-e crates/api_models/src/connector_enums.rs-e crates/euclid/src/enums.rs-e crates/api_models/src/routing.rs-e $src/core/payments/flows.rs-e crates/common_enums/src/connector_enums.rs-e $src/types/connector_transformers.rs-e $src/core/admin.rs-e crates/hyperswitch_connectors/src/default_implementations.rs-e crates/hyperswitch_connectors/src/default_implementations_v2.rs-e crates/hyperswitch_interfaces/src/configs.rs-e $src/connector.rs-e config/deployments/integration_test.toml-e config/deployments/production.toml-e config/deployments/sandbox.toml-e temp crates/connector_configs/src/connector.rs-e crates/router/tests/connectors/main.rs-e crates/router/src/core/payments/connector_integration_v2_impls.rs-e crates/hyperswitch_domain_models/src/connector_endpoints.rs-e
cd $conn/