# Self-Hosted Agents Source: https://docs.basecut.dev/advanced/agent-deployment Deploy Basecut agents in your infrastructure for production workloads **Self-hosted agents are the recommended approach for production use.** Your agents run in your infrastructure with your database credentials—Basecut never touches your data or credentials. Agents continuously poll for snapshot jobs, execute extractions, and upload results to your configured storage (S3/GCS). All processing happens in your environment. ## Why Self-Hosted? **Security & Compliance:** * Your database credentials never leave your environment * Data processing happens entirely in your VPC/cloud * Meet strict compliance requirements (SOC2, HIPAA, GDPR) * Zero-trust architecture **Performance & Control:** * Choose your own compute resources (CPU, memory) * Deploy in the same region as your database * Scale agents based on your workload * No network latency to external services **Cost Efficiency:** * Pay only for your infrastructure (EC2, GCS, etc.) * No per-job fees or processing charges * Predictable costs at scale ## When to Use Self-Hosted Agents * **Production workloads** - Recommended default for all production snapshots * **Private databases** - Behind VPN/VPC without public access * **Compliance requirements** - Data cannot leave your infrastructure * **High volume** - Processing dozens or hundreds of snapshots *** ## Railway (Fastest) Deploy a Basecut agent to Railway in one click: [![Deploy on Railway](https://railway.com/button.svg)](https://railway.com/deploy/basecut-agent) After deployment, set at least: * `BASECUT_API_KEY` * `BASECUT_DATABASE_URL` Use this option when you want managed agent hosting without setting up Docker, Kubernetes, or ECS manually. *** ## Docker Deployment ### Basic Docker Run Run a single agent container: ```bash theme={null} docker run -d \ --name basecut-agent \ --restart unless-stopped \ -e BASECUT_API_KEY=your_org_api_key \ -e BASECUT_DATABASE_URL=postgres://readonly@prod-db:5432/myapp \ -v ~/.aws:/root/.aws:ro \ ghcr.io/basecuthq/basecut-agent:latest ``` **Environment variables**: | Variable | Required | Description | | -------------------------------- | -------- | -------------------------------------------------------------------- | | `BASECUT_API_KEY` | Yes | Organization-scoped API key (`bc_live_*` or `bc_test_*`) | | `BASECUT_DATABASE_URL` | Yes | Database connection string for the agent | | `AWS_ACCESS_KEY_ID` | No | AWS credentials (or mount `~/.aws`) | | `AWS_SECRET_ACCESS_KEY` | No | AWS credentials | | `AWS_REGION` | No | AWS region fallback when `output.region` is not set in `basecut.yml` | | `GOOGLE_APPLICATION_CREDENTIALS` | No | Path to GCS service account key | Agent settings like poll interval and agent ID are configured via CLI flags: `--poll-interval`, `--heartbeat-interval`, `--agent-id`, `--run-once`. *** ## Docker Compose For production deployments with multiple agents and monitoring: ```yaml theme={null} # docker-compose.yml version: '3.8' services: agent: image: ghcr.io/basecuthq/basecut-agent:latest restart: unless-stopped environment: BASECUT_API_KEY: ${BASECUT_API_KEY} BASECUT_DATABASE_URL: ${BASECUT_DATABASE_URL} GOOGLE_APPLICATION_CREDENTIALS: /etc/basecut/gcs-key.json volumes: # AWS credentials - ~/.aws:/root/.aws:ro # GCS credentials (if using GCS) - ./gcs-key.json:/etc/basecut/gcs-key.json:ro deploy: resources: limits: cpus: '2.0' memory: 4G reservations: cpus: '1.0' memory: 2G logging: driver: json-file options: max-size: '10m' max-file: '3' # Optional: Run multiple agents for parallelism agent-worker-2: extends: service: agent container_name: basecut-agent-2 agent-worker-3: extends: service: agent container_name: basecut-agent-3 ``` Start the agent pool: ```bash theme={null} # Create .env file cat > .env < 1M rows | 4.0 | 8GB | Enterprise-scale | ### Autoscaling Scale agents based on job queue depth: * **Kubernetes HPA**: Scale on CPU/memory utilization * **ECS Service Autoscaling**: Scale on CloudWatch metric `JobQueueDepth` (custom metric) * **Target**: 1 agent per 5-10 jobs in queue ### Spot Instances Agents are fault-tolerant—jobs resume if an agent dies: * **ECS**: Use Fargate Spot for 70% cost savings * **Kubernetes**: Use spot node pools * **EC2**: Use Spot Instances with interruption handling *** ## Next Steps Understand agent vs local execution Debug common agent issues Use agents in GitHub Actions Complete agent configuration reference # Environment Variables Source: https://docs.basecut.dev/advanced/environment-variables Complete reference for Basecut CLI configuration The Basecut CLI reads configuration from environment variables. This is useful for CI/CD pipelines, containerized environments, and avoiding command-line repetition. ## Core Variables ### BASECUT\_API\_KEY **Type:** String (required for snapshot create and self-hosted agent) **Format:** `bc_live_*` or `bc_test_*` Your Basecut API key for authentication with Basecut services. ```bash theme={null} export BASECUT_API_KEY=bc_live_abc123_yoursecret ``` **Where to get it:** * User keys: `basecut login` then view in dashboard * Org keys: Dashboard → Organization Settings → API Keys *** ### BASECUT\_NO\_BROWSER **Type:** String (set to any value) Disable automatic browser opening during `basecut login` (useful for SSH or headless environments). ```bash theme={null} export BASECUT_NO_BROWSER=1 ``` *** ### BASECUT\_NO\_UPDATE\_NOTIFIER **Type:** String (set to any value) Disable the CLI update notification check in interactive terminals. ```bash theme={null} export BASECUT_NO_UPDATE_NOTIFIER=1 ``` *** ### BASECUT\_DATABASE\_URL **Type:** String (PostgreSQL connection) **Format:** `postgresql://user:password@host:port/database` Default database connection string. Used when `--source` or `--target` flags are omitted. ```bash theme={null} export BASECUT_DATABASE_URL="postgresql://localhost:5432/myapp_dev" ``` **Examples:** ```bash theme={null} # Local development export BASECUT_DATABASE_URL="postgresql://localhost:5432/myapp" # Production (read-only user) export BASECUT_DATABASE_URL="postgresql://readonly:pass@prod-db:5432/myapp" # With SSL export BASECUT_DATABASE_URL="postgresql://user:pass@host:5432/db?sslmode=require" # With connection pooling export BASECUT_DATABASE_URL="postgresql://user:pass@host:5432/db?pool_max_conns=10" ``` *** ## Cloud Storage Variables ### AWS S3 #### AWS\_ACCESS\_KEY\_ID AWS access key for S3 bucket access. ```bash theme={null} export AWS_ACCESS_KEY_ID=AKIAIOSFODNN7EXAMPLE ``` #### AWS\_SECRET\_ACCESS\_KEY AWS secret key for S3 bucket access. ```bash theme={null} export AWS_SECRET_ACCESS_KEY=wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY ``` #### AWS\_SESSION\_TOKEN AWS session token for temporary credentials (optional). ```bash theme={null} export AWS_SESSION_TOKEN=FwoGZXIvYXdzEBYaDH... ``` #### AWS\_REGION Default AWS region for S3 buckets. Used as a fallback when `output.region` is not set in `basecut.yml` (including self-hosted agent `--async` runs). ```bash theme={null} export AWS_REGION=us-east-1 ``` **Alternative:** Use AWS CLI profiles (`~/.aws/credentials`) *** ### Google Cloud Storage #### GOOGLE\_APPLICATION\_CREDENTIALS Path to GCS service account JSON key file. ```bash theme={null} export GOOGLE_APPLICATION_CREDENTIALS=/path/to/service-account-key.json ``` **Alternative:** Use `gcloud auth application-default login` *** ## Agent Configuration Agent settings are configured via CLI flags (not environment variables): * `--agent-id` (optional) * `--poll-interval` (default: `5s`) * `--heartbeat-interval` (default: `1m`) * `--run-once` (useful for testing) ## Configuration Precedence When a value can come from multiple sources, precedence is: 1. **CLI flags** (highest priority) 2. **Environment variables** 3. **Config file** (basecut.yml) 4. **Defaults** (lowest priority) **Example:** ```bash theme={null} # Environment variable export BASECUT_DATABASE_URL="postgresql://localhost:5432/dev" # This uses the env var basecut snapshot create --config basecut.yml # This overrides the env var basecut snapshot create --config basecut.yml --source "postgresql://prod-db:5432/myapp" ``` *** ## Security Best Practices * Never commit credentials (`.env`, API keys) to source control * Use a read-only database user for extraction — see [Agent Deployment](/advanced/agent-deployment#database-credentials) * Use your CI platform's secret management for `BASECUT_API_KEY` and cloud storage credentials * Use IAM roles or Workload Identity instead of static credentials when possible *** ## Troubleshooting ### "BASECUT\_API\_KEY not set" ``` Error: BASECUT_API_KEY environment variable not set ``` **Solution:** ```bash theme={null} # Login to get your key basecut login # Or set manually export BASECUT_API_KEY=bc_live_abc123_secret ``` *** ### "BASECUT\_DATABASE\_URL not set" ``` Error: database connection string required ``` **Solution:** ```bash theme={null} # Set environment variable export BASECUT_DATABASE_URL="postgresql://localhost:5432/myapp" # Or use --source flag basecut snapshot create --source "postgresql://..." --config basecut.yml ``` *** ### "Invalid AWS credentials" ``` Error: AccessDenied: Access Denied ``` **Solution:** ```bash theme={null} # Verify AWS CLI works aws s3 ls s3://your-bucket # Check credentials are set echo $AWS_ACCESS_KEY_ID echo $AWS_SECRET_ACCESS_KEY # Or use AWS CLI credentials aws configure ``` *** ## Next Steps Command-line flag documentation Using environment variables in pipelines Environment variables for production agents Debug configuration issues # Troubleshooting Source: https://docs.basecut.dev/advanced/troubleshooting Common issues and solutions for Basecut CLI and agents This guide covers common issues you may encounter when using Basecut, along with their solutions and debugging techniques. ## Database Connection Issues ### Connection Refused **Symptoms:** ``` ✗ Error: failed to connect to database dial tcp: connection refused ``` **Solutions:** 1. **Verify database is running:** ```bash theme={null} pg_isready -h localhost -p 5432 ``` 2. **Check connection string format:** ```bash theme={null} # Correct format postgresql://user:password@host:5432/database # Common mistakes postgresql://host:5432 # Missing database name postgresql://user@host # Missing port ``` 3. **Test connectivity:** ```bash theme={null} psql "$BASECUT_DATABASE_URL" -c "SELECT 1" ``` 4. **Check firewall rules:** * Ensure port 5432 is open * For self-hosted agents, verify network security groups allow outbound connections *** ### Host Not Found **Symptoms:** ``` ✗ Error: failed to connect to database dial tcp: lookup prod-db.internal: no such host ``` **Solutions:** 1. **Verify hostname resolves:** ```bash theme={null} nslookup prod-db.internal dig prod-db.internal ``` 2. **Use IP address instead:** ```bash theme={null} postgresql://user:pass@10.0.1.100:5432/myapp ``` 3. **For private databases without public access:** * Use local execution (default) instead of agent execution * Or deploy self-hosted agents in the same VPC *** ### Permission Denied **Symptoms:** ``` ✗ Error: permission denied for schema public ✗ Error: must be owner of table users ``` **Solutions:** 1. **Grant SELECT permissions:** ```sql theme={null} GRANT USAGE ON SCHEMA public TO basecut_user; GRANT SELECT ON ALL TABLES IN SCHEMA public TO basecut_user; -- For future tables ALTER DEFAULT PRIVILEGES IN SCHEMA public GRANT SELECT ON TABLES TO basecut_user; ``` 2. **Verify user permissions:** ```sql theme={null} -- Check what schemas user can access SELECT schema_name FROM information_schema.schemata WHERE schema_name NOT LIKE 'pg_%' AND schema_name != 'information_schema'; -- Check table permissions SELECT table_schema, table_name, privilege_type FROM information_schema.table_privileges WHERE grantee = 'basecut_user'; ``` *** ### SSL/TLS Connection Errors **Symptoms:** ``` ✗ Error: SSL is not enabled on the server ✗ Error: certificate verify failed ``` **Solutions:** 1. **For databases requiring SSL:** ```bash theme={null} postgresql://user:pass@host:5432/db?sslmode=require ``` 2. **For self-signed certificates:** ```bash theme={null} postgresql://user:pass@host:5432/db?sslmode=require&sslrootcert=/path/to/ca.crt ``` 3. **Disable SSL verification (dev only, not recommended for production):** ```bash theme={null} postgresql://user:pass@host:5432/db?sslmode=disable ``` *** ## Authentication Failures ### Invalid API Key **Symptoms:** ``` ✗ Error: Unauthorized: invalid API key ✗ Error: API key is invalid or expired ``` **Solutions:** 1. **Verify API key is set:** ```bash theme={null} echo $BASECUT_API_KEY ``` 2. **Re-authenticate:** ```bash theme={null} basecut login ``` 3. **Check API key format:** * Live keys: `bc_live_*` * Test keys: `bc_test_*` * Ensure no extra spaces or newlines 4. **For CI/CD, verify secret is correctly set:** ```bash theme={null} # GitHub Actions echo "${{ secrets.BASECUT_API_KEY }}" | wc -c # Should be > 50 # GitLab CI echo "$BASECUT_API_KEY" | wc -c ``` 5. **Check API key in dashboard:** * Login to [basecut.dev](https://basecut.dev) * Navigate to Settings → API Keys * Verify key hasn't been revoked *** ### whoami Command Fails **Symptoms:** ```bash theme={null} $ basecut whoami not authenticated ``` **Solutions:** 1. **Login again:** ```bash theme={null} basecut login ``` 2. **Check credentials file:** ```bash theme={null} cat ~/.basecut/credentials # Should contain API key ``` 3. **Use the profile you logged into:** ```bash theme={null} basecut whoami --profile staging ``` *** ## Snapshot Creation Issues ### Extraction Limits Reached **Symptoms:** ``` ⚠ Warning: per_table limit (1000) reached for table 'users' ⚠ Warning: total row limit (50000) reached ✓ Snapshot created with partial data ``` **Solutions:** 1. **Increase limits in basecut.yml:** ```yaml theme={null} limits: rows: per_table: 5000 # Increase per-table limit total: 200000 # Increase total budget ``` 2. **Add more specific WHERE clauses:** ```yaml theme={null} from: - table: users where: 'created_at > :since AND status = :status' params: since: '2024-01-01' status: 'active' # More specific filter ``` 3. **Use table-specific limits:** ```yaml theme={null} limits: rows: per_table: 1000 tables: public.audit_logs: 100 # Limit noisy tables public.sessions: 0 # Unlimited for this table (use `exclude` to skip) ``` *** ### Foreign Key Constraint Violations **Symptoms:** ``` ✗ Error: foreign key constraint violation Table 'orders' references missing row in 'users' ``` **Solutions:** 1. **This shouldn't happen!** Basecut automatically ensures referential integrity. If you see this: * File a bug report at [github.com/basecuthq/basecut/issues](https://github.com/basecuthq/basecut/issues) * Include your `basecut.yml` configuration * Include the error message and stack trace 2. **Workaround - increase upstream depth:** ```yaml theme={null} traverse: parents: 15 # Follow parent relationships further children: 10 ``` *** ### Timeout on Large Extractions **Symptoms:** ``` ✗ Error: context deadline exceeded ✗ Error: operation timed out after 300s ``` **Solutions:** 1. **Use self-hosted agents instead of local execution:** ```bash theme={null} # Instead of local execution (default) basecut snapshot create --config basecut.yml # Use agent execution for large datasets basecut snapshot create --config basecut.yml --async ``` 2. **Reduce snapshot scope:** ```yaml theme={null} limits: rows: per_table: 1000 # Start smaller ``` 3. **Use sampling:** ```yaml theme={null} sampling: mode: 'first' # Faster than 'random' ``` *** ## Snapshot Restore Issues ### Schema Validation Failures **Symptoms:** ``` ✗ Error: schema mismatch: table 'users' missing column 'email_verified' ✗ Error: snapshot schema version incompatible with target database ``` **Solutions:** 1. **Run migrations first:** ```bash theme={null} # Run migrations to match snapshot schema npm run migrate # Then restore basecut snapshot restore dev-seed:latest --target "$BASECUT_DATABASE_URL" ``` 2. **Force restore (skip validation):** ```bash theme={null} basecut snapshot restore dev-seed:latest --target "$BASECUT_DATABASE_URL" --force ``` Only use `--force` if you understand the schema differences. Missing columns or type changes can still fail during insert. 3. **Inspect the exact snapshot reference you're restoring:** ```bash theme={null} basecut snapshot inspect dev-seed:latest --json ``` *** ### Duplicate Key Violations **Symptoms:** ``` ✗ Error: duplicate key value violates unique constraint "users_pkey" Key (id)=(123) already exists ``` **Solutions:** 1. **Use --reset flag to truncate tables first:** ```bash theme={null} basecut snapshot restore dev-seed:latest \ --target "$BASECUT_DATABASE_URL" \ --reset ``` `--reset` is destructive. It truncates all tables included in the snapshot before restoring. 2. **Manually truncate conflicting tables:** ```sql theme={null} TRUNCATE TABLE users, orders, line_items CASCADE; ``` 3. **Restore to empty database:** ```bash theme={null} # Create fresh database createdb myapp_test # Restore snapshot basecut snapshot restore dev-seed:latest \ --target "postgresql://localhost:5432/myapp_test" ``` *** ### Foreign Key Cycle / Non-Deferrable Constraint Block **Symptoms:** ``` ✗ Error: Restore blocked: your database has foreign key constraints that cannot be satisfied during bulk insert. ``` This usually means your restore scope includes self-referential tables or FK cycles, and at least some of those constraints are `NOT DEFERRABLE`. **Solutions:** 1. **Run FK preflight analysis first (recommended):** ```bash theme={null} basecut snapshot restore dev-seed:latest \ --target "$BASECUT_DATABASE_URL" \ --analyze-fks ``` Use the output to identify blocking tables/constraints and whether nullable fallback is available. 2. **If nullable fallback is available, run restore normally:** Basecut will automatically use a two-phase strategy (`INSERT` with temporary `NULL`s, then backfill) for eligible nullable FK cycles. 3. **Make blocking FK constraints deferrable (recommended long-term):** ```sql theme={null} ALTER TABLE . ALTER CONSTRAINT DEFERRABLE INITIALLY DEFERRED; ``` 4. **Use unsafe bypass only as a last resort:** ```bash theme={null} basecut snapshot restore dev-seed:latest \ --target "$BASECUT_DATABASE_URL" \ --unsafe-disable-fk-checks ``` `--unsafe-disable-fk-checks` disables FK enforcement during restore. Use only in controlled environments and validate integrity after restore. *** ### Restore Too Slow **Symptoms:** * Restore takes several minutes for small snapshots * Progress bar stuck at 0% **Solutions:** 1. **Check database connectivity:** ```bash theme={null} ping -c 3 your-db-host ``` 2. **Use local database for faster restore:** ```bash theme={null} # Instead of remote database basecut snapshot restore dev-seed:latest --target "postgresql://remote:5432/db" # Use local database basecut snapshot restore dev-seed:latest --target "postgresql://localhost:5432/db" ``` 3. **Disable triggers during restore (advanced):** ```sql theme={null} ALTER TABLE users DISABLE TRIGGER ALL; -- Restore snapshot ALTER TABLE users ENABLE TRIGGER ALL; ``` *** ## Storage Issues ### S3 Access Denied **Symptoms:** ``` ✗ Error: failed to upload snapshot AccessDenied: User does not have PutObject permission ``` **Solutions:** 1. **Verify AWS credentials:** ```bash theme={null} aws s3 ls s3://your-bucket/ ``` 2. **Check IAM policy** grants `s3:PutObject`, `s3:GetObject`, and `s3:ListBucket` on your bucket. See [Storage Providers](/core-concepts/storage-providers#required-permissions) for the full policy. 3. **Use correct credentials:** ```bash theme={null} export AWS_ACCESS_KEY_ID=your_key_id export AWS_SECRET_ACCESS_KEY=your_secret_key # Or use AWS CLI profile aws configure ``` *** ### S3 Region/Endpoint Errors (Common with `--async`) **Symptoms:** ``` ✗ Error: failed to upload snapshot ... Invalid region ... ``` **Why this happens:** * Local runs can succeed using your local AWS profile region * `--async` runs execute on a self-hosted agent, which may not have the same region config **Solutions:** 1. **Set region in `basecut.yml` for S3 output:** ```yaml theme={null} output: provider: s3 bucket: your-bucket region: us-east-1 ``` 2. **For Cloudflare R2 / S3-compatible endpoints, set both endpoint and region:** ```yaml theme={null} output: provider: s3 bucket: your-r2-bucket region: auto endpoint: https://.r2.cloudflarestorage.com ``` 3. **If you cannot set `output.region`, ensure `AWS_REGION` is set on the agent environment.** *** ### GCS Permission Errors **Symptoms:** ``` ✗ Error: failed to upload to GCS 403: Forbidden ``` **Solutions:** 1. **Verify GCS credentials:** ```bash theme={null} gsutil ls gs://your-bucket/ ``` 2. **Check service account permissions:** ```bash theme={null} gcloud storage buckets add-iam-policy-binding gs://your-bucket \ --member=serviceAccount:basecut@project.iam.gserviceaccount.com \ --role=roles/storage.objectAdmin ``` 3. **Use correct credentials:** ```bash theme={null} export GOOGLE_APPLICATION_CREDENTIALS=/path/to/service-account-key.json # Or use gcloud auth gcloud auth application-default login ``` *** ### Snapshot Not Found **Symptoms:** ``` ✗ Error: snapshot not found: dev-seed:latest ✗ Error: no versions found for snapshot 'dev-seed' ``` **Solutions:** 1. **List available snapshots:** ```bash theme={null} basecut snapshot list --name dev-seed ``` 2. **Check snapshot name spelling:** ```bash theme={null} # Common mistake: wrong name basecut snapshot restore dev-seed:latest # Wrong basecut snapshot restore dev-data:latest # Correct ``` 3. **Verify storage provider configuration:** ```yaml theme={null} # In basecut.yml output: provider: s3 bucket: your-bucket # Ensure this matches where snapshot was created region: us-east-1 ``` *** ## Self-Hosted Agent Issues ### Agent Not Picking Up Jobs **Symptoms:** * Jobs submitted with `--async` never complete * Agent logs show no activity **Solutions:** 1. **Check agent logs:** ```bash theme={null} docker logs basecut-agent ``` 2. **Verify API key format and org access:** ```bash theme={null} echo "$BASECUT_API_KEY" | grep -E '^bc_(live|test)_' ``` 3. **Check network connectivity to Basecut API:** ```bash theme={null} docker exec basecut-agent curl https://api.basecut.dev/health ``` 4. **Verify agent registration:** * Check dashboard for registered agents * Ensure agent is in "Active" state *** ### Agent Database Connection Failures **Symptoms:** ``` Agent log: failed to connect to database Agent log: dial tcp: i/o timeout ``` **Solutions:** 1. **Test database access from agent:** ```bash theme={null} docker exec basecut-agent psql "$BASECUT_DATABASE_URL" -c "SELECT 1" ``` 2. **Check network security groups:** * Verify agent's security group allows outbound to database port * Verify database's security group allows inbound from agent 3. **Use private IP for database in same VPC:** ```bash theme={null} # Instead of public IP postgresql://user:pass@1.2.3.4:5432/db # Use private IP postgresql://user:pass@10.0.1.100:5432/db ``` *** ## Performance Issues ### Slow Extractions **Symptoms:** * Snapshot creation takes hours * "Extracting..." stuck at same table count **Solutions:** 1. **Check database indexes:** ```sql theme={null} -- Ensure foreign key columns are indexed CREATE INDEX CONCURRENTLY idx_orders_user_id ON orders(user_id); CREATE INDEX CONCURRENTLY idx_line_items_order_id ON line_items(order_id); ``` 2. **Use sampling instead of full extraction:** ```yaml theme={null} sampling: mode: 'first' # Much faster than 'random' ``` 3. **Reduce traversal depth:** ```yaml theme={null} traverse: parents: 3 # Reduce from 10 children: 5 # Reduce from 10 ``` 4. **Use agent execution for large datasets:** ```bash theme={null} basecut snapshot create --config basecut.yml --async ``` *** ## Debugging Techniques ### Check Configuration Parsing **Verify YAML syntax:** ```bash theme={null} # Use a YAML validator python -c "import yaml; yaml.safe_load(open('basecut.yml'))" ``` *** ### Test Individual Components **Test database connection:** ```bash theme={null} psql "$BASECUT_DATABASE_URL" -c "SELECT current_database(), current_user;" ``` **Test storage access:** ```bash theme={null} # S3 aws s3 cp test.txt s3://your-bucket/test.txt # GCS echo "test" | gsutil cp - gs://your-bucket/test.txt # Local touch /path/to/snapshots/test.txt ``` *** ## Getting Help If you've tried the solutions above and still have issues: 1. **Check the logs:** * Agent: `docker logs basecut-agent` 2. **File a GitHub issue:** * [github.com/basecuthq/basecut/issues](https://github.com/basecuthq/basecut/issues) * Include: error message, configuration file, command used, Basecut version 3. **Contact support:** * Email: [support@basecut.dev](mailto:support@basecut.dev) * Include: account email, snapshot name, timestamp of error *** ## Next Steps Complete configuration reference Self-hosted agent setup and debugging Complete command documentation # basecut agent Source: https://docs.basecut.dev/cli-reference/agent Start a Basecut self-hosted agent The Basecut agent is a long-running process that waits for and executes remote snapshot jobs. It is typically deployed as a Docker container or Kubernetes pod within your private network, allowing it to connect to your database while keeping credentials secure. The self-hosted agent requires a **TEAM** plan. ## Usage ```bash theme={null} basecut agent [flags] ``` *** ## Flags ### Optional | Flag | Default | Description | | ---------------------------- | ------------------ | -------------------------------------------------------- | | `--api-key ` | `$BASECUT_API_KEY` | Basecut API key used to authenticate with the platform. | | `--agent-id ` | Auto-generated | Unique identifier for this agent instance. | | `--poll-interval ` | `5s` | How often the agent checks for new jobs. | | `--heartbeat-interval ` | `1m` | How often the agent sends a status heartbeat to the API. | | `--run-once` | `false` | If true, the agent exits after processing a single job. | | `--profile ` | `default` | Credential profile to use. | *** ## Examples ### Basic Agent Operation Start an agent and let it poll for jobs indefinitely: ```bash theme={null} basecut agent --api-key "$BC_KEY" ``` **What happens:** 1. The agent registers itself with the Basecut API. 2. It starts polling for jobs every 5 seconds. 3. Every minute, it sends a "heartbeat" to let the platform know it's healthy. 4. When a job is received, it executes the extraction based on the provided configuration. *** ### Run-Once (CI/CD or Job-Based) In some environments, you might want to start an agent only when you know a job is waiting (e.g., in a transient CI container): ```bash theme={null} basecut agent --run-once ``` **Behavior:** * The agent will poll for a job. * Once a job is completed (or fails), the agent process terminates immediately. *** ### Custom Polling Interval For high-priority environments or to reduce API overhead, adjust the polling frequency: ```bash theme={null} basecut agent --poll-interval 1s --heartbeat-interval 30s ``` *** ## Required Environment Variables The agent requires access to the database it will be extracting data from: | Variable | Description | | ---------------------- | ----------------------------------------------------- | | `BASECUT_DATABASE_URL` | PostgreSQL connection string for the source database. | | `BASECUT_API_KEY` | API Key (if not provided via flag). | *** ## Output ### Normal Startup ```bash theme={null} ✓ Agent started (ID: agent_abc123) ✓ Registered with Basecut API ⣾ Polling for jobs... (interval: 5s) ``` ### Processing a Job ```bash theme={null} ✓ Job received: job_xyz789 ✓ Processing extraction... (2,847 rows) ✓ Uploading snapshot to s3://my-bucket/snapshots/ ✓ Job completed successfully ⣾ Polling for jobs... ``` *** ## Error Handling ### Authentication Failure ``` ✗ Error: failed to register agent Unauthorized: Invalid API key ``` **Solutions:** * Verify your `BASECUT_API_KEY` is correct and active. * Check that your plan supports self-hosted agents. ### Database Connection Loss ``` ✗ Error: job failed could not connect to database: connection refused ``` **Solutions:** * Ensure the agent has network access to the database. * Verify the `BASECUT_DATABASE_URL` is correct. *** ## Next Steps Deploy agents using Docker and Kubernetes Understand how agents process jobs # basecut init Source: https://docs.basecut.dev/cli-reference/init Generate a ready-to-run basecut.yml from your schema `basecut init` introspects your database and generates a runnable `basecut.yml`. It guides you through: * root table selection * lookup/junction table handling * optional PII rule generation * preflight validation against the live schema ## Usage ```bash theme={null} basecut init [flags] ``` ## Flags | Flag | Default | Description | | --------------------- | ----------------------- | ------------------------------------------- | | `--source , -s` | `$BASECUT_DATABASE_URL` | PostgreSQL connection string to introspect. | | `--output , -o` | `basecut.yml` | Output config path. | | `--force, -f` | `false` | Overwrite existing file without prompt. | ## Examples ### Basic Usage ```bash theme={null} basecut init --source "postgresql://readonly@prod-db:5432/myapp" ``` Generated config shape: ```yaml theme={null} version: '1' name: 'my-snapshot' from: - table: users where: 'id = :id' params: id: 42 include_all: - countries traverse: stop_at: - user_roles limits: rows: per_table: 1000 total: 100000 sampling: mode: random seed: 0 anonymize: mode: auto rules: users: email: fake_email output: ./snapshots ``` ## Next Step ```bash theme={null} basecut snapshot create --config basecut.yml --name dev-seed --source "$BASECUT_DATABASE_URL" ``` # basecut login Source: https://docs.basecut.dev/cli-reference/login Authenticate with your Basecut account Authenticate the CLI with your Basecut account using the OAuth2 device authorization flow. This will open a browser window for you to sign in. Once complete, your credentials are saved to a local profile. `basecut login` requires an interactive terminal to open the browser and poll for the authentication token. ## Usage ```bash theme={null} basecut login [flags] ``` ## Flags ### Optional | Flag | Default | Description | | ------------------ | --------- | -------------------------------------------------------- | | `--profile ` | `default` | The name of the local profile to save credentials under. | *** ## Examples ### Quick Start ```bash theme={null} # Standard interactive login basecut login # Login and save to a specific profile basecut login --profile production ``` *** ### Standard Interactive Login Most common usage to get started: ```bash theme={null} basecut login ``` **What happens:** 1. The CLI generates a unique device code. 2. It attempts to open your default web browser to the Basecut login page. 3. You sign in via the browser. 4. The CLI polls the API until the authorization is confirmed. 5. Success credentials are stored in `~/.basecut/credentials`. *** ### Machine-to-Machine / Headless Login For environments without a browser (like SSH sessions), Basecut will print a URL for you to copy-paste: ```bash theme={null} basecut login ``` If a browser can't be opened, you'll see: ```bash theme={null} Please visit: https://basecut.dev/auth/device And enter code: ABCD-1234 ``` *** ## Environment Variables | Variable | Description | | -------------------- | ------------------------------------------------------------------- | | `BASECUT_NO_BROWSER` | Set to `true` to skip attempting to open the browser automatically. | *** ## Success Output ```bash theme={null} ✓ Authenticating... ✓ Browser opened to https://basecut.dev/auth/device ✓ Authenticated as jake@example.com ✓ Credentials saved to profile: default ``` *** ## Next Steps Verify your current login status and plan Remove stored credentials # basecut logout Source: https://docs.basecut.dev/cli-reference/logout Log out of your Basecut account Remove stored authentication credentials from your local machine for the specified profile. This does not revoke the session on the server, but clears the local access token. ## Usage ```bash theme={null} basecut logout [flags] ``` *** ## Flags ### Optional | Flag | Default | Description | | ------------------ | --------- | --------------------------------------------------- | | `--profile ` | `default` | The name of the profile to log out from. | | `--all` | `false` | Remove ALL stored profiles (confirmation required). | *** ## Examples ### Logout Default Profile ```bash theme={null} basecut logout ``` ### Logout All Profiles ```bash theme={null} basecut logout --all ``` *** ## Success Output ```bash theme={null} ✓ Logged out from profile 'default' ``` *** ## Next Steps Authenticate again with your account Verify no credentials remain # basecut snapshot create Source: https://docs.basecut.dev/cli-reference/snapshot-create Create a sanitized snapshot from a source database Create a snapshot from your config and source database. Authentication is required. `basecut snapshot create` always needs an API key before extraction starts. Provide it with `--api-key`, `BASECUT_API_KEY`, or a saved profile from `basecut login`. ## Usage ```bash theme={null} basecut snapshot create --config [flags] ``` ## Flags | Flag | Required | Description | | ------------------------------ | -------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `--config , -c` | Yes | Path to `basecut.yml`. | | `--name , -n` | No | Snapshot name. Must be provided via `--name` or `name` in config. | | `--source , -s` | Local | Source connection string for local execution. Required whenever the command runs locally (the default). Optional only when using `--async` with a non-local output provider. | | `--connect-timeout ` | `10s` | Timeout for initial source DB connection in local mode (for example `5s`, `30s`). | | `--async` | No | Queue for agent execution (TEAM plan). Ignored when output provider is `local` (for example `output: ./snapshots`), and the command runs locally instead. | | `--tag , -t` | No | Version tag. | | `--git` | No | Attach git metadata. | | `--profile ` | No | Credential profile used to resolve API key. | | `--api-key ` | No | API key override (otherwise uses `BASECUT_API_KEY` or the selected profile). | ## Examples ### Basic Local Example ```bash theme={null} basecut snapshot create \ --config basecut.yml \ --source "$DATABASE_URL" \ --name "dev-seed" ``` ### Agent Example ```bash theme={null} basecut snapshot create \ --config basecut.yml \ --name "nightly-seed" \ --async ``` `--async` only queues an agent job when the config output provider is non-local. If your config uses local output (for example `output: ./snapshots`), `--async` is ignored and local execution still requires `--source` or `BASECUT_DATABASE_URL`. Track async job progress with: ```bash theme={null} basecut snapshot status ``` ## Config Example ```yaml theme={null} version: '1' name: 'dev-seed' from: - table: users where: 'id = :id' params: id: 1 traverse: parents: 10 children: 2 limits: rows: per_table: 1000 total: 100000 anonymize: auto output: ./snapshots ``` See [YAML Reference](/configuration/yaml-reference) for full config options. # basecut snapshot delete Source: https://docs.basecut.dev/cli-reference/snapshot-delete Delete a snapshot by reference Delete a snapshot by reference. ## Usage ```bash theme={null} basecut snapshot delete [flags] ``` ## Arguments | Argument | Description | | ---------------- | --------------------------------------------------------------------------------------- | | `` | Snapshot identifier. Supported forms: UUID, `name:tag`, or `name` (resolves to latest). | ## Flags | Flag | Default | Description | | ------------------ | ----------- | -------------------------------- | | `--yes, -y` | `false` | Skip confirmation prompt. | | `--profile ` | `default` | Credential profile for API auth. | | `--api-key ` | env/profile | API key override. | ## Examples ```bash theme={null} # Delete by UUID (with prompt) basecut snapshot delete 550e8400-e29b-41d4-a716-446655440000 # Delete by ref without prompt basecut snapshot delete dev-seed:latest --yes ``` ## Notes * Snapshot deletion is currently a **metadata soft-delete**. * Underlying storage objects are not automatically removed by this command. # basecut snapshot inspect Source: https://docs.basecut.dev/cli-reference/snapshot-inspect Inspect snapshot metadata by reference Inspect a snapshot by reference. ## Usage ```bash theme={null} basecut snapshot inspect [flags] ``` ## Arguments | Argument | Description | | ---------------- | --------------------------------------------------------------------------------------- | | `` | Snapshot identifier. Supported forms: UUID, `name:tag`, or `name` (resolves to latest). | ## Flags | Flag | Default | Description | | ------------------ | ----------- | -------------------------------- | | `--json` | `false` | Output raw JSON response. | | `--profile ` | `default` | Credential profile for API auth. | | `--api-key ` | env/profile | API key override. | ## Examples ```bash theme={null} # Inspect by UUID basecut snapshot inspect 550e8400-e29b-41d4-a716-446655440000 # Inspect latest version for a name basecut snapshot inspect dev-seed # Inspect specific version basecut snapshot inspect dev-seed:v1 # JSON output basecut snapshot inspect dev-seed --json ``` # basecut snapshot list Source: https://docs.basecut.dev/cli-reference/snapshot-list List snapshots with filtering and cursor pagination List snapshots for your user or organization. ## Usage ```bash theme={null} basecut snapshot list [flags] ``` ## Flags | Flag | Default | Description | | -------------------------- | ----------- | --------------------------------------------------- | | `--limit ` | `20` | Number of snapshots to return per page (1-100). | | `--cursor ` | none | Cursor from a previous result page. | | `--all` | `false` | Fetch all pages automatically. | | `--status ` | none | Filter by status: `READY`, `EXPIRED`, or `DELETED`. | | `--name ` | none | Filter by snapshot name. | | `--tag ` | none | Filter by snapshot tag. | | `--search ` | none | Search snapshot metadata. | | `--source-host ` | none | Filter by source host. | | `--source-database ` | none | Filter by source database. | | `--json` | `false` | Output JSON instead of table format. | | `--profile ` | `default` | Credential profile for API auth. | | `--api-key ` | env/profile | API key override. | ## Examples ```bash theme={null} # List latest snapshots basecut snapshot list # Filter by name and status basecut snapshot list --name dev-seed --status READY # Continue from a cursor basecut snapshot list --cursor "cursor_abc123" # Fetch all pages basecut snapshot list --all # JSON output basecut snapshot list --json ``` # basecut snapshot restore Source: https://docs.basecut.dev/cli-reference/snapshot-restore Apply a snapshot's data to a target database Restore downloads a snapshot and inserts its data into a target database. It validates schema compatibility and ensures referential integrity during the process. Run your migrations first. Restore validates the target schema and inserts data; it does not create or alter tables. ## Usage ```bash theme={null} basecut snapshot restore [flags] ``` *** ## Arguments | Argument | Description | | ---------------- | --------------------------------------------------------------------------------------- | | `` | Snapshot identifier. Supported forms: UUID, `name:tag`, or `name` (resolves to latest). | ## Flags | Flag | Default | Description | | ---------------------------- | ------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------- | | `--target , -t` | `$BASECUT_TARGET_DATABASE_URL` | PostgreSQL connection string for the destination database. Restore does not use `BASECUT_DATABASE_URL` so you do not accidentally restore over your source. | | `--reset` | `false` | Truncate snapshot-managed tables before applying (destructive). | | `--force` | `false` | Skip schema validation (may fail if schemas are incompatible). | | `--batch-size ` | `1000` | Rows per insert batch (auto-capped per table by database limits). | | `--on-conflict ` | `error` | Conflict behavior: `error` (fail fast) or `skip` (ignore conflicts). | | `--analyze-fks` | `false` | Run FK preflight analysis only (no data is applied). | | `--unsafe-disable-fk-checks` | `false` | Unsafe bypass: disables FK checks during restore (requires elevated DB privileges). | | `--yes, -y` | `false` | Skip confirmation prompts. | | `--profile ` | `default` | Credential profile to use for API authentication. | | `--api-key ` | `$BASECUT_API_KEY` | API key override (otherwise uses `BASECUT_API_KEY` or saved profile). | *** ## Examples ### Quick Examples ```bash theme={null} # Restore the latest version of a snapshot basecut snapshot restore my-snapshot:latest \ --target "postgresql://localhost:5432/myapp_test" # Restore a specific version with a reset basecut snapshot restore my-snapshot:brave-lion \ --target "$BASECUT_TARGET_DATABASE_URL" \ --reset # Restore while skipping duplicate key conflicts basecut snapshot restore my-snapshot:latest \ --target "$BASECUT_TARGET_DATABASE_URL" \ --on-conflict skip ``` *** ### Basic Restore Apply the latest version of a snapshot to your local database: ```bash theme={null} basecut snapshot restore "weekly-dev-data" \ --target "postgresql://localhost:5432/myapp_dev" ``` **What happens:** 1. CLI resolves the latest tag for "weekly-dev-data". 2. Downloads manifest and schema metadata. 3. Connects to the target database and validates schema compatibility. 4. Downloads data files and inserts rows in dependency order. 5. Verifies referential integrity across all restored tables. *** ### Clean Restore (Local Development) Wipe existing data in the target tables before restoring: ```bash theme={null} basecut snapshot restore "clean-seed" \ --target "postgresql://localhost:5432/myapp_dev" \ --reset \ --yes ``` **When to use `--reset`:** * You want to ensure the target tables only contain the snapshot data. * You are re-running a seed script and want to avoid duplicate key errors. * You want a clean slate for debugging a specific issue. `--reset` runs inside the same transaction as restore inserts. If restore fails, all reset and insert operations are rolled back together. *** ### CI/CD Integration Automate restoration for integration tests: ```bash theme={null} export BASECUT_API_KEY=bc_live_abc123_secret export BASECUT_TARGET_DATABASE_URL=postgresql://test_user:pass@localhost:5432/test_db basecut snapshot restore "ci-baseline:latest" --yes ``` *** ### Analyze Foreign Key Restore Safety Preview FK-related restore risk before applying any data: ```bash theme={null} basecut snapshot restore "production:latest" \ --target "$BASECUT_TARGET_DATABASE_URL" \ --analyze-fks ``` `--analyze-fks` reports: * Number of non-deferrable foreign key constraints. * Self-referential tables in the restore scope. * Whether an inter-table FK cycle exists. * Whether safe restore mode would be blocked. * Whether nullable fallback is available for blocking constraints. If `Nullable fallback available: true`, Basecut will **automatically** handle the restore using a two-phase approach — inserting rows with temporary `NULL`s for the blocking FK columns, then backfilling the real values — with no additional flags required. This requires that all blocking FK columns are nullable and the affected table has a primary key or unique key. Use this when preparing migrations or debugging FK restore blockers. *** ### Unsafe FK Bypass (Last Resort) If you need a one-off restore and cannot make constraints deferrable immediately: ```bash theme={null} basecut snapshot restore "production:latest" \ --target "$BASECUT_TARGET_DATABASE_URL" \ --unsafe-disable-fk-checks ``` `--unsafe-disable-fk-checks` disables FK enforcement during restore. Use only in controlled environments and validate integrity after restore. This mode may require elevated PostgreSQL privileges. *** ## Output ### Success ```bash theme={null} ✓ Loading snapshot: my-snapshot:brave-lion ✓ Validated schema for 23 tables ✓ Inserted 2,847 rows ✓ Verified referential integrity ✓ Restore complete in 3.2s ``` ### With Reset ```bash theme={null} ⚠ Truncating 23 tables... ✓ Loading snapshot: my-snapshot:latest ✓ Validated schema for 23 tables ✓ Inserted 2,847 rows ✓ Restore complete ``` *** ## Error Handling ### Schema Compatibility Error ``` ✗ Error: schema mismatch detected Table 'users' is missing column 'last_login_at' which is present in snapshot. ``` **Solutions:** * Run your database migrations to align the target schema with the snapshot. * Use `--force` to skip validation (not recommended if data types have changed). ### Foreign Key Constraint Error ``` ✗ Error: foreign key violation during restore on orders (orders_user_id_fkey) ``` **Common causes:** * Non-deferrable foreign keys combined with cyclic or self-referential dependencies. * Parent rows missing from target scope while child rows are restored. **Solutions:** * Run FK preflight first: ```bash theme={null} basecut snapshot restore "" --target "$BASECUT_TARGET_DATABASE_URL" --analyze-fks ``` * Make relevant foreign key constraints `DEFERRABLE` where appropriate. * If `--analyze-fks` reports nullable fallback available, re-run restore normally — Basecut handles it automatically. Note: nullable fallback is not compatible with `--on-conflict skip`; use the default conflict policy. * Ensure referenced parent tables/rows are included in the snapshot. * If you need a temporary bypass, use `--unsafe-disable-fk-checks` (unsafe). * Re-run after schema alignment or adjust restore scope. ### Conflict Error (`--on-conflict error`) ``` ✗ Error: duplicate key value violates unique constraint ... ``` **Solutions:** * Use `--reset` for a clean restore target, or * Use `--on-conflict skip` to continue and skip conflicting rows. ### Connection Failed ``` ✗ Error: failed to connect to target database dial tcp 127.0.0.1:5432: connect: connection refused ``` **Solutions:** * Verify the target database is running. * Check the connection string and credentials. * Ensure the database is accessible from your network. *** ## Next Steps Learn how to extract data from your source database Understand the anatomy and lifecycle of snapshots Learn how tags and versions work Common issues and how to solve them # basecut snapshot status Source: https://docs.basecut.dev/cli-reference/snapshot-status Inspect async snapshot job status by job ID Inspect an async snapshot job by job ID. ## Usage ```bash theme={null} basecut snapshot status [flags] ``` ## Arguments | Argument | Description | | ---------- | ---------------------------------------------------------------- | | `` | Snapshot job UUID returned by `basecut snapshot create --async`. | ## Flags | Flag | Default | Description | | ------------------ | ----------- | -------------------------------- | | `--json` | `false` | Output raw JSON response. | | `--profile ` | `default` | Credential profile for API auth. | | `--api-key ` | env/profile | API key override. | ## Examples ```bash theme={null} # Check status for an async job basecut snapshot status 550e8400-e29b-41d4-a716-446655440000 # JSON output basecut snapshot status 550e8400-e29b-41d4-a716-446655440000 --json ``` # basecut whoami Source: https://docs.basecut.dev/cli-reference/whoami Check your current authentication status Displays authentication details for the current active profile. This is useful for verifying which account and plan you are currently using, especially when switching between multiple profiles. ## Usage ```bash theme={null} basecut whoami [flags] ``` *** ## Flags ### Optional | Flag | Default | Description | | ------------------ | --------- | -------------------------------- | | `--profile ` | `default` | The profile to check status for. | *** ## Examples ```bash theme={null} # Check the active default profile basecut whoami # Check a specific profile basecut whoami --profile production ``` *** ## Success Output ```bash theme={null} Authenticated as: Name: Jake Doe Email: jake@example.com Plan: TEAM Credential source: profile 'default' in /Users/you/.basecut/credentials API endpoint: https://api.basecut.dev ``` *** ## Next Steps Switch to a different account Start using your team benefits # Anonymization Source: https://docs.basecut.dev/configuration/anonymization Configure PII masking during PostgreSQL snapshot creation — auto-detection, explicit rules, internal email exceptions, and org-wide policies. Basecut applies anonymization **during extraction**, before data is written to a snapshot. Restores to dev, CI, or staging receive already-masked rows, so masking cannot be skipped as a separate step. For the full `anonymize` block and all YAML fields, see [YAML Reference](/configuration/yaml-reference#anonymize). For organization-wide enforcement, see [Snapshot rules](/configuration/snapshot-rules). ## Quick start ```yaml theme={null} anonymize: auto ``` `auto` turns on built-in PII detection and still lets you add explicit `rules` for overrides. ## Modes | Mode | Behavior | | :------- | :------------------------------------------------ | | `auto` | Built-in PII detection plus any explicit `rules`. | | `manual` | Only explicit `rules` — no auto-detection. | | `off` | No anonymization. | ## Which mode should I use? * Use `auto` if you want the safest default for most development, CI, and staging workflows. It catches common PII automatically and still lets you add overrides. * Use `manual` if you need full control over exactly which fields are masked and how. This is common when your schema has unusual field names or domain specific rules. * Use `off` only when you are certain the source data contains no sensitive information or you are working with already-anonymized input. Shorthand: ```yaml theme={null} anonymize: auto # anonymize: off ``` Object form: ```yaml theme={null} anonymize: mode: auto excluded_domains: - yourcompany.com rules: users: email: fake_email phone: fake_phone '*.password_hash': redact ``` ## Rules Use **table-grouped** keys for `public` tables (unqualified names resolve to `public.
`) or **wildcard** keys for patterns such as `*.email`. ```yaml theme={null} anonymize: mode: manual rules: users: full_name: fake_name date_of_birth: strategy: date_shift params: days: 90 '*.email': fake_email ``` Complex strategies use `strategy` + optional `params` (for example `partial_mask` with `visible`, `numeric_noise` with `percent`). ## Internal and test emails Top-level `excluded_domains` skips anonymization for matching email domains (case-insensitive). Per-rule `params.excluded_domains` overrides that list for a single field. Details and examples are in [YAML Reference — `anonymize`](/configuration/yaml-reference#anonymize). ## Organization policies On Team and Enterprise plans, **Snapshot rules** in the app can require specific strategies (for example `*.email: fake_email`) and excluded tables across every snapshot. See [Snapshot rules](/configuration/snapshot-rules). ## Strategies | Strategy | Description | | :---------------------- | :------------------------------------------------- | | `none` | No transformation | | `redact` | Replace with `[REDACTED]` | | `null` | Replace with `null` | | `fixed` | Replace with `params.value` | | `hash` | Deterministic hash | | `fake_name` | Realistic full name | | `fake_first_name` | First name | | `fake_last_name` | Last name | | `fake_email` | Realistic email | | `email_preserve_domain` | Fake local part, original domain | | `fake_phone` | Phone number | | `fake_date_of_birth` | Date of birth | | `fake_username` | Username / handle | | `fake_credit_card` | Luhn-valid card number | | `fake_ssn` | SSN-like value | | `fake_passport` | Passport-like value | | `fake_iban` | IBAN-like value | | `fake_routing_number` | Routing number | | `fake_bank_account` | Bank account–like value | | `fake_company` | Company name | | `fake_job_title` | Job title | | `fake_address` | Street address | | `fake_city` | City | | `fake_state` | State or province | | `fake_zip` | Postal code | | `fake_country` | Country | | `fake_ip` | IP address | | `fake_mac` | MAC address | | `fake_uuid` | UUID | | `fake_url` | URL | | `fake_paragraph` | Paragraph of text | | `partial_mask` | Mask value; `params.visible` = trailing chars kept | | `date_shift` | Shift date; `params.days` | | `numeric_noise` | ±`params.percent` variance | ## See also * [How it works](/core-concepts/how-it-works) — extraction and traversal * [`snapshot create`](/cli-reference/snapshot-create) — CLI usage # Snapshot Rules Source: https://docs.basecut.dev/configuration/snapshot-rules Define organization-level snapshot guardrails and configure snapshot anonymization Snapshot rules let you enforce organization-level guardrails for every snapshot job, including required transformations and always excluded tables. ## Organization Snapshot Rules (Team & Enterprise) Use **Settings -> Snapshot Rules** in the app to define org-wide rules that are enforced on every snapshot. When rules are enabled, Basecut applies them at snapshot-job creation time: * Missing required transformations are added automatically. * Conflicting transformations fail fast before extraction starts. * Always excluded tables are merged into the job config. ### Snapshot Rule Shape (`rules`) Most users configure rules in **Settings -> Snapshot Rules**. For API/CLI integrations, the `rules` object supports this shape: ```json theme={null} { "required_strategies": { "*.email": "fake_email", "users.ssn": { "strategy": "fake_ssn" }, "users.created_at": { "strategy": "date_shift", "params": { "days": 30 } } }, "required_excludes": ["audit_logs", "payment_events"] } ``` ### API Payload Shape When writing rules through the API, send `enabled` and `rules`: ```json theme={null} { "enabled": true, "rules": { "required_strategies": { "*.email": "fake_email", "users.ssn": "fake_ssn" }, "required_excludes": ["audit_logs", "payment_events"] } } ``` ### Rule Behavior | Rule | Behavior | | :-------------------- | :---------------------------------------------------------------------------- | | `required_strategies` | Ensures a transformation is used for matching fields (for example `*.email`). | | `required_excludes` | Forces tables into `tables.exclude` for every snapshot. | For rule keys like `users.email`, unqualified tables are normalized to `public.users`. ### Conflict Example If your org snapshot rules require `*.email: fake_email` and a job config sets `users.email: none`, Basecut returns a validation error and does not create the job. ### Precedence and Conflict Behavior 1. Organization snapshot rules are evaluated first at snapshot-job creation. 2. Required transformations are merged into the job config. 3. Always excluded tables are merged into `tables.exclude`. ## Snapshot-Level Anonymization Configuration Use YAML anonymization rules for snapshot-specific behavior. Organization snapshot rules are the governance layer above these settings. ## Configuration Shape ```yaml theme={null} anonymize: auto # or anonymize: mode: manual # auto | manual | off rules: users: email: fake_email phone: fake_phone '*.password_hash': redact ``` ### Modes | Mode | Behavior | | :------- | :------------------------------------------------------ | | `auto` | Enable built-in PII detection and apply explicit rules. | | `manual` | Apply only explicit rules. | | `off` | Disable anonymization entirely. | ## Rules You can define rules in two forms: 1. **Table-grouped rules** ```yaml theme={null} anonymize: mode: manual rules: users: full_name: fake_name date_of_birth: strategy: date_shift params: days: 90 ``` 2. **Wildcard / flat rules** ```yaml theme={null} anonymize: mode: manual rules: '*.email': fake_email '*.credit_card': redact ``` Unqualified table keys (for example `users`) are resolved as `public.users`. ## Example: Balanced Auto + Overrides ```yaml theme={null} anonymize: mode: auto rules: users: email: fake_email phone: fake_phone ssn: fake_ssn payments: card_number: strategy: partial_mask params: visible: 4 '*.password_hash': redact ``` ## Strategies ### Basic | Strategy | Description | | :------- | :---------------------------------------- | | `none` | No transformation | | `redact` | Replace with `[REDACTED]` | | `null` | Replace with `null` | | `fixed` | Replace with fixed value (`params.value`) | | `hash` | Deterministic hash | ### Person Data | Strategy | Description | | :---------------------- | :--------------------------- | | `fake_name` | Realistic person name | | `fake_first_name` | First name | | `fake_last_name` | Last name | | `fake_email` | Realistic email | | `email_preserve_domain` | Fake local part, keep domain | | `fake_phone` | Phone number | | `fake_date_of_birth` | Realistic DOB | | `fake_username` | Username/handle | ### Financial & Identity | Strategy | Description | | :------------------ | :---------------------- | | `fake_credit_card` | Luhn-valid card number | | `fake_ssn` | SSN-like value | | `fake_passport` | Passport-like value | | `fake_iban` | IBAN-like value | | `fake_bank_account` | Bank account-like value | | `fake_company` | Company name | ### Location & Networking | Strategy | Description | | :------------- | :------------- | | `fake_address` | Street address | | `fake_city` | City | | `fake_state` | State | | `fake_zip` | Postal code | | `fake_country` | Country | | `fake_ip` | IP address | | `fake_mac` | MAC address | ### Utility | Strategy | Description | Params | | :--------------- | :---------------------------- | :-------- | | `partial_mask` | Keep N trailing chars visible | `visible` | | `date_shift` | Shift date ±N days | `days` | | `numeric_noise` | Add ±N% variance | `percent` | | `fake_uuid` | Generate UUID | - | | `fake_url` | Generate URL | - | | `fake_paragraph` | Generate text | - | # YAML Reference Source: https://docs.basecut.dev/configuration/yaml-reference Full reference for the basecut.yml configuration file The `basecut.yml` file defines what Basecut extracts, how traversal is bounded, how PII is anonymized, and where output is written. ## Complete Example ```yaml theme={null} version: '1' name: 'my-snapshot' from: - table: users where: 'id = :id' params: id: 42 - table: billing.invoices where: 'org_id = :org_id' params: org_id: 10 exclude: - audit_logs - internal_tokens include_all: - countries - currencies traverse: parents: 10 children: 2 stop_at: - user_roles - order_tags virtual_foreign_keys: - from: posts.author_id to: users.id - from: table: billing.invoice_items columns: [invoice_id, tenant_id] to: table: billing.invoices columns: [id, tenant_id] limits: rows: per_table: 1000 total: 100000 tables: events: 200 logs: 0 sampling: mode: random seed: 42 anonymize: mode: auto excluded_domains: - yourcompany.com rules: users: email: fake_email phone: fake_phone '*.password_hash': redact output: ./snapshots # Or object form: # output: # provider: s3 # bucket: my-team-snapshots # region: us-east-1 ``` ## Top-Level Fields | Field | Required | Type | Description | | :--------------------- | :------- | :------------ | :------------------------------------------------------------------------- | | `version` | Yes | string | Config version. Must be `'1'`. | | `name` | No | string | Snapshot name fallback used by CLI if `--name` is not provided. | | `from` | Yes | array | One or more root selectors to start extraction. | | `exclude` | No | array | Tables to exclude entirely from extraction. | | `include_all` | No | array | Lookup/reference tables extracted in full before traversal. | | `traverse` | No | object | Traversal controls (`parents`, `children`, `stop_at`). | | `virtual_foreign_keys` | No | array | User-defined FK edges for relationships not declared in DB constraints. | | `limits` | No | object | Row-count budgets and overrides. | | `sampling` | No | object | Row selection mode and random seed. | | `anonymize` | No | string/object | `off`, `auto`, or object with `mode` + `rules`. | | `output` | Yes | string/object | Output destination (`./path`, `s3://...`, `gs://...`, or provider object). | ## `from` `from` defines the starting rows. ```yaml theme={null} from: - table: users where: 'id = :id' params: id: 1 ``` * Use `table: users` for `public.users`. * Use `table: schema.table` for non-public schemas. * `where` supports named params (`:id`), values go in `params`. ## `traverse` ```yaml theme={null} traverse: parents: 10 children: 2 stop_at: - user_roles ``` | Field | Type | Default | Description | | :--------- | :---- | :------ | :------------------------------------------------------- | | `parents` | int | `10` | Max parent FK depth (`-1` = unlimited). | | `children` | int | `2` | Max child FK depth (`0` = disable downstream traversal). | | `stop_at` | array | - | Junction/link tables where FK expansion should stop. | ## `virtual_foreign_keys` Use `virtual_foreign_keys` when related tables are enforced in application code but not declared as database FK constraints. Single-column (compact) form: ```yaml theme={null} virtual_foreign_keys: - from: posts.author_id to: users.id - from: comments.post_id to: public.posts.id ``` Composite-column (structured) form: ```yaml theme={null} virtual_foreign_keys: - from: table: billing.invoice_items columns: [invoice_id, tenant_id] to: table: invoices columns: [id, tenant_id] ``` Notes: * Virtual FK edges are traversed the same way as real FKs during extraction. * Bare table names are normalized to `public.
`. * Compact endpoints must be `table.column` or `schema.table.column`. * `from.columns` and `to.columns` must have the same number of columns. * Duplicate virtual FK definitions are rejected. ## `limits.rows` ```yaml theme={null} limits: rows: per_table: 1000 total: 100000 tables: users: 200 audit_logs: 0 ``` | Field | Type | Default | Description | | :---------- | :-------------- | :------- | :---------------------------------------------------------------------------------------------------- | | `per_table` | int | `1000` | Default row-count cap per table. | | `total` | int | `100000` | Total row-count cap across the snapshot. | | `tables` | map\[string]int | - | Per-table row-count overrides (`0` means unlimited for that table; use `exclude` to skip extraction). | **Cycle handling:** When tables form circular foreign key relationships (cycles), Basecut automatically caps the combined row count for the cycle group based on the sum of effective table limits. For example, if three tables in a cycle each have `per_table: 1000`, the cycle budget is 3000 total rows. Adjust `per_table` or add individual `tables` entries to control cycle sizes. ## `anonymize` Shorthand: ```yaml theme={null} anonymize: auto ``` Object form: ```yaml theme={null} anonymize: mode: manual # auto | manual | off excluded_domains: # optional: global email domains to skip anonymization - company.com - test.example.com rules: users: email: fake_email partners: email: strategy: fake_email params: excluded_domains: [partner.org] # per-rule: replaces global list for this rule audit_logs: email: strategy: fake_email params: excluded_domains: [] # explicit empty: anonymize ALL emails, ignore global list '*.password_hash': redact ``` Notes: * `mode: auto` enables built-in PII auto-detection plus explicit `rules`. * `mode: manual` applies only explicit `rules`. * `mode: off` disables anonymization. * Table-grouped rule keys can be unqualified (`users`) for `public.users`. * `excluded_domains` (top-level) is an optional list of email domains that bypass anonymization. Emails matching these domains (case-insensitive, exact match) are left unchanged, whether the email strategy was set via explicit rules or auto-detection. Useful for preserving internal/test emails like `@yourcompany.com`. * Per-rule `params.excluded_domains` overrides the global list for that specific rule. If present (even as an empty list), the global `excluded_domains` are ignored for that rule. A rule without `params.excluded_domains` inherits the global list. ## `output` String shorthand: ```yaml theme={null} output: ./snapshots # output: s3://my-bucket/team-a # output: gs://my-bucket/team-a ``` Object form: ```yaml theme={null} output: provider: local # local | s3 | gcs path: ./snapshots ``` For cloud providers: ```yaml theme={null} output: provider: s3 bucket: my-bucket region: us-east-1 endpoint: https://.r2.cloudflarestorage.com # optional for S3-compatible backends prefix: team-a/snapshots ``` Notes: * For `provider: s3`, `bucket` is required. * For Cloudflare R2, use `provider: s3` + `endpoint` and set `region: auto`. ## Minimal Config ```yaml theme={null} version: '1' from: - table: users where: 'id = :id' params: id: 1 anonymize: auto output: ./snapshots ``` # Execution Modes Source: https://docs.basecut.dev/core-concepts/execution-modes Choose where snapshot extraction runs: self-hosted agent or local CLI Basecut can execute snapshot creation in two modes. Both produce identical snapshots—the difference is **where the processing happens**. **For production workloads, self-hosted agents are recommended.** They provide better security (your credentials stay in your environment), better performance (same region as your database), and predictable costs. *** ## Choose Your Execution Mode Use this decision tree to select the right mode for your use case: ### Quick Decision Guide **1. Do you have a self-hosted agent with network access to your source database?** * **No** → Use **Local Execution** (default) * **Yes** → Continue **2. Are you working in production or with production-sized data?** * **Yes** → Use **Self-Hosted Agents** (recommended for production) * **No** → Continue **3. Do you have self-hosted agents deployed?** * **No** → Use **Local Execution** (default, no setup required) * **Yes** → Use **Self-Hosted Agents** (better performance and security) ### Quick Reference | Scenario | Recommended Mode | Reason | | ----------------------------- | --------------------- | --------------------------------------------- | | Private DB + agent in VPC | **Self-Hosted Agent** | Agent can reach private network safely | | Private DB + no agent path | **Local** | No remote worker can reach the database | | Quick testing / development | **Local** | Faster setup, no infrastructure needed | | Production workloads | **Self-Hosted Agent** | Better security, performance, and reliability | | Large datasets (> 1M rows) | **Self-Hosted Agent** | Doesn't consume local resources | | CI/CD pipelines | **Self-Hosted Agent** | Consistent execution environment | | Small datasets (\< 100k rows) | **Local** | Quick and simple | | Team collaboration | **Self-Hosted Agent** | Centralized execution and job history | **Default behavior:** Local execution (no `--async` flag) *** ## Agent Execution (Recommended for Production) Deploy agents in your infrastructure to process extractions. Your CLI submits jobs to the Basecut API, self-hosted agents pick up the work, and results are stored in your configured S3/GCS bucket. ### When to Use * **Production databases** - Agent runs in cloud environment with stable network and resources * **Large extractions** - Process millions of rows without consuming local CPU/memory * **Team workflows** - Centralized execution with job history and shared snapshots * **CI/CD pipelines** - No local database access needed—agent connects directly to your DB ### How It Works ```bash theme={null} basecut snapshot create \ --config basecut.yml \ --name "prod-snapshot" \ --async ``` 1. CLI submits job to Basecut API with your configuration 2. Self-hosted agent picks up the job from the queue 3. Agent connects to your database (requires network access) 4. Extraction runs on agent infrastructure 5. Snapshot uploaded to configured cloud storage (S3/GCS) 6. CLI polls for job status and reports completion **Storage**: Always uses cloud storage (S3 or GCS) **Requirements**: * Agent needs network access to your database * Database credentials passed securely via config * Cloud storage bucket configured in `basecut.yml` ### Configuration ```yaml theme={null} # basecut.yml output: provider: s3 bucket: my-basecut-snapshots region: us-east-1 # prefix: snapshots/ # optional path prefix # Agent execution is enabled with `--async` ``` `--async` is ignored when `output.provider: local` (agents can't write to your local filesystem). In that case, Basecut runs locally and prints a warning. *** ## Local Execution The CLI runs extraction directly on your machine. Useful for development and databases without public access. ### When to Use * **No agent deployment yet** - Start immediately with no infrastructure * **DB reachable from your machine** - Local dev DB, tunnel, or VPN from laptop * **Development/testing** - Quick iteration without job queue latency * **Small datasets** - Extraction completes in seconds on your laptop * **Air-gapped environments** - No internet access required (with local storage) ### How It Works ```bash theme={null} basecut snapshot create \ --config basecut.yml \ --name "dev-snapshot" \ --source "postgresql://localhost:5432/myapp" ``` 1. CLI reads configuration 2. Connects directly to your database 3. Runs extraction algorithm locally 4. Stores snapshot in local filesystem or uploads to cloud storage 5. Reports completion immediately **Storage**: Can use local filesystem or cloud storage (your choice) **Requirements**: * Database accessible from your machine * Sufficient local CPU/memory for extraction * Disk space for snapshot files (if using local storage) ### Configuration For local filesystem storage: ```yaml theme={null} # basecut.yml output: provider: local path: /absolute/path/to/snapshots format: directory ``` For cloud storage (CLI uploads after extraction): ```yaml theme={null} # basecut.yml output: provider: s3 # or gcs bucket: my-basecut-snapshots region: us-east-1 ``` Local snapshots stored on filesystem are tied to the creating machine. Restoring on a different machine requires access to the same file path. *** ## Comparison | Feature | Self-Hosted Agent | Local Execution | | -------------------- | --------------------------------------------- | --------------------------------------------- | | **Database Access** | Agent connects from your infrastructure | CLI connects directly | | **Processing Power** | Your infrastructure (EC2, GKE, etc.) | Your local machine | | **Storage** | S3 or GCS (required) | Local filesystem or cloud | | **Authentication** | `basecut login` or `BASECUT_API_KEY` required | `basecut login` or `BASECUT_API_KEY` required | | **Job Queue** | Yes (track history, retry failures) | No (immediate execution) | | **Best For** | Production, large datasets, teams | Development, quick testing, small extractions | | **Cost** | Your infrastructure costs (EC2, storage) | Free (your local resources) | | **Security** | Credentials stay in your environment | Direct database access | *** ## Switching Between Modes Same configuration file works for both modes. Control via CLI flags: ```bash theme={null} # Agent execution basecut snapshot create --config basecut.yml --async # Local execution basecut snapshot create --config basecut.yml ``` `--async` queues agent execution; omitting it runs locally. *** ## Next Steps Configure S3, GCS, or local filesystem Deploy agents in your infrastructure (recommended for production) Use self-hosted agents in GitHub Actions Local execution workflow examples # How It Works Source: https://docs.basecut.dev/core-concepts/how-it-works Understanding the relationship-following algorithm Basecut doesn't just export tables—it extracts **connected subgraphs** of your data by following foreign key relationships. This ensures every snapshot is self-contained and referentially valid. ## The Core Algorithm ### 1. Start from Root Tables You define one or more **root tables** with optional `WHERE` clauses: ```yaml theme={null} version: '1' name: 'my-snapshot' from: - table: users where: 'created_at > :since' params: since: '2024-01-01' - table: orders where: 'status = :status' params: status: 'completed' ``` Basecut executes these queries to get your **seed rows**—the starting points for extraction. ### 2. Follow Relationships Recursively From each seed row, Basecut traverses foreign keys in both directions: **Upstream (Parents)**: Follow foreign keys to referenced tables * `orders.user_id → users.id` * `line_items.product_id → products.id` **Downstream (Children)**: Follow reverse foreign keys to dependent tables * `users.id ← orders.user_id` * `orders.id ← shipments.order_id` You control how far to traverse in each direction: ```yaml theme={null} traverse: parents: 5 # Follow parent FKs 5 levels deep children: 10 # Follow child FKs 10 levels deep ``` Basecut also supports **virtual foreign keys** — application-enforced relationships that aren't declared as database constraints. Define them in your config and they're traversed exactly like real FK edges. See [YAML Reference](/configuration/yaml-reference#virtual_foreign_keys). ### 3. Ensure Referential Integrity As Basecut discovers rows, it tracks dependencies: * Before including a row, ensure all its foreign key targets are included * If a parent row is missing, add it (even if it requires traversing beyond depth limits) * Result: **zero broken foreign key references** ### 4. Apply Limits and Filters Prevent runaway extraction with safeguards: ```yaml theme={null} limits: rows: per_table: 1000 # Max 1000 rows per table total: 50000 # Max 50,000 rows overall ``` If limits are hit, Basecut stops adding new rows but ensures already-included rows remain referentially valid. *** ## Example Walkthrough Given this schema: ```text theme={null} users +-- orders (users.id -> orders.user_id) | +-- line_items (orders.id -> line_items.order_id) | | `-- products (line_items.product_id -> products.id) | `-- shipments (orders.id -> shipments.order_id) ``` With configuration: ```yaml theme={null} version: '1' name: 'my-snapshot' from: - table: users where: 'email = :email' params: email: 'alice@example.com' traverse: parents: 3 children: 10 ``` **Extraction process:** 1. **Seed**: Find `users` row for `alice@example.com` → 1 row 2. **Downstream L1**: Find all `orders` where `user_id = alice.id` → 5 rows 3. **Downstream L2**: Find all `line_items` for those 5 orders → 23 rows 4. **Upstream L1** (from line\_items): Find all `products` referenced → 8 rows 5. **Downstream L3**: Find all `shipments` for those 5 orders → 5 rows **Result**: 42 rows across 5 tables, all referentially valid. If you insert them into an empty database, no foreign key constraints will be violated. *** ## Why This Approach Works **Referential Integrity**: You can restore snapshots to empty databases without constraint violations. No manual dependency sorting needed. **Reproducibility**: Same configuration + same source data yields the same snapshot shape. If you use random sampling, set `sampling.seed` for stable row selection. **Composability**: Combine multiple root tables to extract overlapping data graphs. Basecut deduplicates automatically. **Safety**: Limits prevent accidentally extracting your entire production database. Anonymization runs inline during extraction. *** ## Next Steps Choose where extraction runs: self-hosted agent or local CLI Configure S3, GCS, or local filesystem storage All configuration options explained Protect PII during extraction # Snapshot Versioning Source: https://docs.basecut.dev/core-concepts/snapshot-versioning How Basecut manages multiple versions of snapshots and naming conventions Basecut automatically versions every snapshot you create, allowing you to maintain multiple point-in-time captures of your database and reference specific versions when restoring. ## How Versioning Works Every time you run `basecut snapshot create` with the same `--name`, Basecut creates a **new version** rather than overwriting the previous one. ### Generated Tags Each version is automatically assigned a unique, human-readable tag using an `adjective-animal` format: ``` brave-lion swift-falcon gentle-bison ``` These tags are generated by the Basecut API when you create a snapshot without providing an explicit tag. ### Storage Structure Snapshot references are name/tag based (`dev-seed:brave-lion`), while cloud storage objects are keyed by internal job IDs (for example `/snapshots//...`). Use CLI/API metadata (`snapshot list` and `snapshot inspect`) to map a name/tag reference to its storage location. *** ## Referencing Snapshots ### Using `:latest` The most common pattern—reference the newest version: ```bash theme={null} basecut snapshot restore dev-seed:latest --target "$BASECUT_DATABASE_URL" ``` **What happens:** 1. Basecut scans all versions of `dev-seed` 2. Selects the most recently created version 3. Restores that version **Use case:** Development workflows where you always want the freshest data. *** ### Using Specific Tags Reference an exact version by its unique tag: ```bash theme={null} basecut snapshot restore dev-seed:brave-lion --target "$BASECUT_DATABASE_URL" ``` **What happens:** 1. Basecut resolves `dev-seed:brave-lion` to an exact snapshot record 2. Restores that specific version 3. Fails if that tag doesn't exist **Use cases:** * Reproducing a bug with the exact data state * Rolling back to a known-good snapshot * Compliance/audit requirements for specific dates *** ### Implicit `:latest` Omitting the version defaults to `:latest`: ```bash theme={null} # These are equivalent basecut snapshot restore dev-seed --target "$BASECUT_DATABASE_URL" basecut snapshot restore dev-seed:latest --target "$BASECUT_DATABASE_URL" ``` *** ## Custom Tags You can override the automatic tag generation by providing your own tag using the `--tag` or `-t` flag: ```bash theme={null} # Create a snapshot with a custom tag basecut snapshot create --config basecut.yml --name dev-seed --tag v1-0-0 ``` **Referencing by custom tag:** ```bash theme={null} basecut snapshot restore dev-seed:v1-0-0 --target "$BASECUT_DATABASE_URL" ``` Custom tags must be lowercase alphanumeric with hyphens, starting and ending with an alphanumeric character. The tag `latest` is reserved. *** ## Version Management ### Listing Versions List snapshots from the CLI: ```bash theme={null} # List all snapshots (paginated) basecut snapshot list # Filter to one snapshot name basecut snapshot list --name dev-seed ``` For deeper details on one version: ```bash theme={null} basecut snapshot inspect dev-seed:brave-lion ``` ### Deleting Old Versions Delete snapshot metadata from the CLI: ```bash theme={null} basecut snapshot delete dev-seed:v1 --yes ``` For object cleanup, use storage lifecycle policies (recommended) or your storage provider CLI (`aws s3 rm`, `gsutil rm`). *** ## Best Practices ### 1. Use Descriptive Snapshot Names Names should indicate purpose, not just content: **Good:** ```bash theme={null} --name "dev-seed" # Clear: for development seeding --name "debug-user-12345" # Clear: debugging specific user --name "pre-migration-test" # Clear: testing before migration --name "qa-stable" # Clear: stable data for QA ``` **Avoid:** ```bash theme={null} --name "backup" # Vague: backup for what? --name "test" # Vague: test what? --name "data" # Vague: what data? ``` *** ### 2. Establish Naming Conventions **Pattern:** `-[-]` Examples: * `dev-seed` - Daily development data * `staging-smoke` - Smoke test data for staging * `prod-debug-issue-456` - Production debugging snapshot * `qa-regression-v2.0` - QA regression testing for v2.0 *** ### 3. Automate Snapshot Rotation Schedule snapshot creation in CI (see [CI/CD Integration](/workflows/ci-cd)) and configure storage lifecycle policies to automatically delete old versions. *** ### 4. Document Version Purpose Add metadata to your snapshot manifest for traceability: ```bash theme={null} # Capture git metadata basecut snapshot create \ --config basecut.yml \ --name "dev-seed" \ --git ``` **Result in manifest.json:** ```json theme={null} { "name": "dev-seed", "created_at": "2024-01-29T10:30:00Z", "git": { "commit": "a1b2c3d", "branch": "main", "repo": "github.com/myorg/myapp" } } ``` *** ### 5. Use Separate Snapshots for Different Use Cases Don't overload a single snapshot name: **Antipattern:** ```bash theme={null} # Same snapshot for everything --name "snapshot" # Used for dev, testing, debugging, etc. ``` **Better approach:** ```bash theme={null} # Separate snapshots by purpose --name "dev-daily" # Daily development refresh --name "ci-test" # CI/CD test suite --name "debug-prod-issues" # Production debugging --name "qa-regression" # QA regression suite ``` **Why:** Prevents accidental overwrites and makes version management clearer. *** ## Troubleshooting ### "Version Not Found" **Symptom:** ``` ✗ Error: version not found: dev-seed:old-tag ``` **Solutions:** 1. **List available versions:** ```bash theme={null} basecut snapshot list --name dev-seed ``` 2. **Check for typos in tag:** ```bash theme={null} # Tags are exact dev-seed:brave-lion # Correct dev-seed:brave-lions # Wrong (plural) ``` 3. **Use `:latest` instead:** ```bash theme={null} basecut snapshot restore dev-seed:latest --target "$BASECUT_DATABASE_URL" ``` *** ### "Multiple Versions Found" This shouldn't happen—Basecut resolves versions using unique snapshot tags and IDs. If you see this error, file a bug report. *** ## Next Steps Understand snapshot anatomy and structure Configure S3, GCS, or local storage Patterns for versioning in practice Complete command documentation # Snapshots Source: https://docs.basecut.dev/core-concepts/snapshots Understanding Basecut database snapshots: anatomy, lifecycle, and guarantees A **snapshot** is a point-in-time capture of a subset of your database, packaged with everything needed to restore that exact data state to any compatible database. ## What Makes a Snapshot Basecut doesn't just export tables—it creates self-contained, referentially-valid snapshots by following foreign key relationships. This ensures every snapshot can be applied to an empty database without constraint violations. ### Key Characteristics 1. **Referentially Complete**: Every row includes all its foreign key dependencies 2. **Point-in-Time**: Captures database state at a specific moment 3. **Self-Contained**: Includes schema metadata for validation 4. **Portable**: Can be restored to any database with matching schema 5. **Versioned**: Multiple versions can coexist for the same snapshot name *** ## Snapshot Anatomy Every snapshot consists of three required components and one optional component: ### 1. Manifest (`manifest.json`) Contains metadata about the snapshot: ```json theme={null} { "version": "1.0", "created_at": "2024-01-29T10:30:00Z", "source": { "host": "prod-db.internal", "database": "myapp", "database_name": "myapp_production" }, "stats": { "total_rows": 2847, "table_count": 23, "warning_count": 0, "extraction_duration_ms": 45320, "uncompressed_size": 12543200, "compressed_size": 3145600 }, "config": { "root_table": "public.users", "max_upstream_depth": 5, "max_downstream_depth": 10, "sample_mode": "random" }, "schema_hash": "a1b2c3d4e5f6..." } ``` **Purpose:** * Identifies the snapshot uniquely * Records extraction context for debugging * Stores git metadata for reproducibility * Tracks performance metrics *** ### 2. Schema (`schema.json`) Schema metadata for all included tables at extraction time. **Purpose:** * Validate target database compatibility before restore * Detect schema drift between snapshot and target * Document database structure at extraction time *** ### 3. Data Files (`tables/*.csv.gz`) One compressed CSV file per table with extracted rows: ``` tables/ ├── public.users.csv.gz (234 KB, 847 rows) ├── public.organizations.csv.gz (12 KB, 45 rows) ├── public.orders.csv.gz (523 KB, 2,134 rows) ├── public.line_items.csv.gz (891 KB, 8,912 rows) ├── public.products.csv.gz (156 KB, 432 rows) └── public.payment_methods.csv.gz (34 KB, 178 rows) ``` **Format:** * Standard CSV with header row * Gzip compressed for efficiency * NULL values represented as empty fields * Special characters escaped per RFC 4180 *** ### 4. Warnings (`warnings.json`) - Optional Only present if extraction encountered warnings: ```json theme={null} { "warnings": [ { "code": "LIMIT_REACHED", "message": "per_table limit (1000) reached for table 'audit_logs'", "table": "public.audit_logs", "severity": "warning" } ] } ``` **Purpose:** * Document extraction issues without failing * Warn users about partial data * Aid in debugging configuration problems *** ## Snapshot Lifecycle ### 1. Creation **Local Execution (default):** ```bash theme={null} basecut snapshot create \ --config basecut.yml \ --name "dev-seed" \ --source "$BASECUT_DATABASE_URL" ``` **Process:** 1. CLI reads configuration from `basecut.yml` 2. Connects to source database 3. Executes root queries to get seed rows 4. Recursively follows foreign keys (upstream + downstream) 5. Applies anonymization rules to PII fields 6. Compresses data to CSV.gz files 7. Generates manifest and schema metadata 8. Uploads to configured storage (S3/GCS/local) *** ### 2. Storage Snapshots are stored in your configured provider: **S3 Example:** ``` s3://my-basecut-snapshots/ └── team-a/ # optional prefix └── snapshots/ └── 8f4f4b0e-fbc7-4f70.../ # job id ├── manifest.json ├── schema.json ├── warnings.json (optional) └── tables/ ├── public.users.csv.gz └── public.orders.csv.gz ``` Name/tag references (for example `dev-seed:brave-lion`) are resolved via API metadata, not by directly constructing storage paths. *** ### 3. Restoration **Basic restore:** ```bash theme={null} basecut snapshot restore dev-seed:latest --target "$BASECUT_DATABASE_URL" ``` **Process:** 1. CLI resolves snapshot version (`:latest` → `brave-lion`) 2. Downloads manifest and schema from storage 3. Validates target database schema compatibility 4. Determines insertion order (respecting foreign keys) 5. Inserts data in dependency order (or uses an automatic two-phase fallback for eligible nullable FK cycles) 6. Verifies referential integrity 7. Reports completion with row counts *** ## Guarantees ### Referential Integrity **Guarantee:** Every snapshot is self-contained and referentially valid. **What this means:** * Every foreign key constraint will be satisfied after restore * No "dangling references" or broken relationships * Can restore to an empty database without errors **How it works:** * Basecut tracks all foreign key relationships during extraction * Before including a row, ensures all referenced rows are included * If a parent is missing, adds it (even beyond depth limits) *** ### Schema Preservation **Guarantee:** Schema metadata is captured at extraction time. **What this means:** * Restore validates target schema matches snapshot schema * Detects missing tables, columns, or type changes * Prevents data corruption from schema drift *** ## Size Estimation Estimate snapshot size before creating: ``` Snapshot size ≈ (Raw data size × compression ratio) + overhead Where: - compression ratio ≈ 0.1 to 0.3 (gzip) - overhead ≈ 50-100KB (manifest + schema) ``` | Source Data | Estimated Snapshot Size | | ----------- | ----------------------- | | 10MB | 1-3MB | | 100MB | 10-30MB | | 1GB | 100-300MB | | 10GB | 1-3GB | *** ## Performance Characteristics ### Creation Time | Dataset Size | Extraction Time | | ------------- | ------------------- | | \< 10k rows | 5-30 seconds | | 10k-100k rows | 30s-5 minutes | | 100k-1M rows | 5-30 minutes | | > 1M rows | Use agents (30m-2h) | *** ## Snapshot vs Backup **Basecut is NOT a backup tool.** Do not use snapshots as your database backup strategy. | Feature | Snapshot | Backup | | ----------------- | --------------------------- | ------------------- | | **Purpose** | Testing with realistic data | Disaster recovery | | **Completeness** | Subset of data | Full database | | **Size** | Small (10MB-1GB typical) | Full database size | | **Anonymization** | Built-in PII protection | Raw production data | **Use snapshots for:** * Seeding development databases * Sharing realistic test data with team * Reproducing production bugs locally **Use backups for:** * Disaster recovery * Point-in-time recovery * Compliance archiving *** ## Next Steps Deep dive into the extraction algorithm Managing multiple versions of snapshots Configure S3, GCS, or local filesystem Complete command documentation # Storage Providers Source: https://docs.basecut.dev/core-concepts/storage-providers Configure where snapshots are stored: S3, GCS, or local filesystem Basecut snapshots consist of manifest metadata, schema definitions, warnings (optional), and compressed CSV data files. You can store these artifacts in cloud storage or on your local filesystem. ## AWS S3 (Recommended for Teams) Store snapshots in Amazon S3 for team sharing and self-hosted agent integration. ### Configuration ```yaml theme={null} # basecut.yml output: provider: s3 bucket: my-basecut-snapshots region: us-east-1 # Optional for S3-compatible storage (e.g., Cloudflare R2, MinIO) endpoint: https://.r2.cloudflarestorage.com prefix: team-a # optional: path prefix within bucket ``` ### Authentication **Option 1: AWS CLI credentials** (recommended for development) ```bash theme={null} aws configure # Enter your AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY ``` Basecut automatically uses your `~/.aws/credentials` profile. ### S3-Compatible Backends (Cloudflare R2, MinIO, LocalStack) Use `provider: s3` with a custom `endpoint`: ```yaml theme={null} output: provider: s3 bucket: my-r2-bucket region: auto # recommended for Cloudflare R2 endpoint: https://.r2.cloudflarestorage.com prefix: team-a ``` Set credentials using standard AWS environment variables: ```bash theme={null} export AWS_ACCESS_KEY_ID=... export AWS_SECRET_ACCESS_KEY=... ``` **Option 2: Environment variables** ```bash theme={null} export AWS_ACCESS_KEY_ID=your_key_id export AWS_SECRET_ACCESS_KEY=your_secret_key export AWS_SESSION_TOKEN=your_token # if using temporary credentials ``` **Option 3: IAM role** (recommended for CI/CD and agents) No credentials needed—EC2 instances, ECS tasks, or GitHub Actions with OIDC can use IAM roles. ### Required Permissions ```json theme={null} { "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Action": ["s3:PutObject", "s3:GetObject", "s3:ListBucket"], "Resource": [ "arn:aws:s3:::my-basecut-snapshots/*", "arn:aws:s3:::my-basecut-snapshots" ] } ] } ``` ### Bucket Organization Cloud object keys are stored under `snapshots/` (optionally prefixed): ``` s3://my-basecut-snapshots/ └── team-a/ # optional prefix └── snapshots/ ├── 8f4f4b0e-fbc7-4f70.../ │ ├── manifest.json │ ├── schema.json │ ├── warnings.json # optional │ └── tables/ │ ├── public.users.csv.gz │ └── public.orders.csv.gz └── 2d3c1a91-3f23-4d83.../ ``` Use `basecut snapshot list` and `basecut snapshot inspect` to work with snapshot names/tags; object keys are internal storage details. *** ## Google Cloud Storage (Recommended for Teams) Store snapshots in Google Cloud Storage buckets. ### Configuration ```yaml theme={null} # basecut.yml output: provider: gcs bucket: my-basecut-snapshots prefix: team-a # optional: path prefix within bucket ``` ### Authentication **Option 1: gcloud CLI** (recommended for development) ```bash theme={null} gcloud auth application-default login ``` Basecut uses Application Default Credentials from `~/.config/gcloud`. **Option 2: Service account key** ```bash theme={null} export GOOGLE_APPLICATION_CREDENTIALS=/path/to/service-account-key.json ``` **Option 3: Workload Identity** (recommended for GKE) No credentials needed—pods with Workload Identity automatically authenticate. ### Required Permissions Grant the service account `Storage Object Admin` on the bucket: ```bash theme={null} gcloud storage buckets add-iam-policy-binding gs://my-basecut-snapshots \ --member=serviceAccount:basecut@project.iam.gserviceaccount.com \ --role=roles/storage.objectAdmin ``` Or use a custom role with: * `storage.objects.create` * `storage.objects.get` * `storage.objects.list` *** ## Local Filesystem Store snapshots on your local machine. Useful for development and air-gapped environments. ### Configuration ```yaml theme={null} # basecut.yml output: provider: local path: /absolute/path/to/snapshots format: directory ``` Relative paths are allowed, but absolute paths are recommended for clarity. ### Directory Structure Local output writes the snapshot artifact directly to your configured `output.path`: ``` /absolute/path/to/snapshots/ ├── manifest.json ├── schema.json ├── warnings.json # optional └── tables/ ├── public.users.csv.gz └── public.orders.csv.gz ``` ### Machine Identification Local snapshots capture machine metadata for safety. When restoring on a different machine, Basecut warns you but allows the operation if you have access to the file path. ### Use Cases * **Development** - Quick iteration without cloud storage setup * **Air-gapped environments** - No internet access required * **Testing** - Snapshots stay on your machine, no cloud costs **Not recommended for teams**: Local snapshots can't be shared without manual file copying. Use S3/GCS for team collaboration. *** ## Choosing a Provider | Provider | Best For | Team Sharing | Agent Support | Cost | | --------- | --------------------------- | ------------ | --------------------------- | -------------------- | | **S3** | Teams, production workflows | ✅ Yes | ✅ Yes | S3 storage + egress | | **GCS** | GCP-native teams | ✅ Yes | ✅ Yes | GCS storage + egress | | **Local** | Development, testing | ❌ No | ❌ No (local execution only) | Free (disk space) | **Recommendation**: Start with local for initial testing, migrate to S3/GCS when collaborating with teams or using self-hosted agents. *** ## Snapshot Naming and Versioning Reference snapshots by name and optional version: ```bash theme={null} # Latest version of a snapshot basecut snapshot restore dev-seed:latest # Specific tag version basecut snapshot restore dev-seed:brave-lion # Implicit latest basecut snapshot restore dev-seed ``` Each `snapshot create` with the same `--name` creates a new tagged version. Previous versions remain accessible. *** ## Next Steps Understand how storage provider affects execution mode Use cloud storage in GitHub Actions Complete output configuration options Debug storage authentication issues # Authentication Source: https://docs.basecut.dev/getting-started/authentication How to authenticate with Basecut services Basecut supports multiple authentication methods for local development and CI/CD environments. ## Interactive Login The easiest way to authenticate locally is using the `login` command: ```bash theme={null} basecut login ``` This will: 1. Generate a device code 2. Open your browser for authorization 3. Save an API key locally to `~/.basecut/credentials` ## API Keys For CI/CD or non-interactive environments, use an API key via environment variables: ```bash theme={null} export BASECUT_API_KEY=bc_live_xxx ``` ## Profiles Manage multiple environments using profiles: ```bash theme={null} # Login to a specific profile basecut login --profile production # Use a specific profile basecut snapshot create --config basecut.yml --name prod-seed --source "$BASECUT_DATABASE_URL" --profile production ``` ## Credentials Location Credentials are stored in `~/.basecut/credentials`. # Installation Source: https://docs.basecut.dev/getting-started/installation Get Basecut installed and ready to use ## Installation Methods ### Recommended: Homebrew (macOS / Linux) ```bash theme={null} brew install basecuthq/cli/basecut ``` ### Install Script (macOS / Linux / Windows) Downloads the latest public release and verifies SHA256 checksums: ```bash theme={null} curl -fsSL https://basecut.dev/install.sh | sh ``` Optional: install to a specific directory (default `~/.local/bin`) or pin a version: ```bash theme={null} curl -fsSL https://basecut.dev/install.sh | sh -s -- /usr/local/bin curl -fsSL https://basecut.dev/install.sh | sh -s -- ~/.local/bin v1.0.0 ``` Optional: pin the installer script itself to a specific Git ref (tag or commit SHA): ```bash theme={null} curl -fsSL "https://basecut.dev/install.sh?ref=v1.0.0" | sh ``` ### GitHub Releases Download the binary for your platform from the public release repository: * [https://github.com/basecuthq/cli/releases](https://github.com/basecuthq/cli/releases) ## Verification To verify the installation, run: ```bash theme={null} basecut --version ``` # Quick Start Source: https://docs.basecut.dev/getting-started/quick-start First snapshot in under 5 minutes using local execution This guide walks you through creating your first production-realistic snapshot using **local execution**. Perfect for getting started quickly without deploying infrastructure. ## What You'll Accomplish By the end of this guide, you'll have: * ✅ A `basecut.yml` configuration file tailored to your database schema * ✅ A production-realistic snapshot with anonymized PII * ✅ A restored snapshot in your local development database * ✅ Understanding of the `init` → `snapshot create` → `snapshot restore` workflow **For production**: After completing this guide, see [Self-Hosted Agents](/advanced/agent-deployment) for the recommended production deployment. ## Prerequisites * PostgreSQL database (12+) with some data * Database accessible from your local machine (localhost or network-accessible) *** ## Step 1: Install CLI Install the Basecut CLI: ```bash theme={null} curl -fsSL https://basecut.dev/install.sh | sh basecut --version ``` **Success indicator**: `basecut version x.y.z` *** ## Step 2: Authenticate Create a Basecut account and authenticate: ```bash theme={null} basecut login ``` This opens your browser for authentication. Once complete, your credentials are stored locally. **Success indicator**: `✓ Authenticated as you@example.com` *** ## Step 3: Generate Configuration Point Basecut at your database to auto-detect schema and relationships: ```bash theme={null} basecut init --source "postgresql://user:pass@localhost:5432/myapp" ``` **What `init` does automatically:** The `init` command does the heavy lifting for you: * 🔍 **Schema detection**: Analyzes all tables, columns, and data types * 🔗 **FK analysis**: Maps foreign key relationships to build the dependency graph * 🎯 **Root table suggestions**: Identifies good starting points (tables with many incoming FKs) * 🔄 **Cycle detection**: Finds and handles circular relationships * 🛡️ **PII detection**: Auto-detects common PII patterns (emails, phones, names, etc.) * 📝 **Config generation**: Creates a ready-to-use `basecut.yml` with sensible defaults This creates `basecut.yml` in your current directory with: * Detected tables and foreign key relationships * Suggested root tables and FK connectivity details * Optional PII anonymization rules (email, phone, etc.) Want to tune masking behavior before your first restore? See [Anonymization](/configuration/anonymization) for `auto`, `manual`, and org-level policy options. **Success indicator**: `✓ Created basecut.yml with 42 tables detected` **Troubleshooting `init`**: If you see connection errors, verify your database is accessible and the connection string format is correct (`postgresql://user:pass@host:port/dbname`). For SSH tunnels or complex setups, ensure the database is reachable from your local machine. ```yaml theme={null} # Auto-generated by basecut init version: "1" name: "my-snapshot" from: - table: users where: 'created_at > :since' params: since: '2024-01-01' traverse: parents: 10 # Follow parent relationships children: 2 # Follow child relationships limits: rows: per_table: 1000 # Max rows per table total: 100000 # Max total rows anonymize: mode: auto output: ./snapshots ``` *** ## Step 4: Create a Snapshot (Local Execution) Run the extraction locally (default): ```bash theme={null} basecut snapshot create \ --config basecut.yml \ --name "my-first-snapshot" \ --source "postgresql://localhost:5432/myapp_dev" ``` **What's happening:** 1. CLI reads your `basecut.yml` configuration 2. Connects directly to your database from your machine 3. Follows foreign keys from root tables to extract related data 4. Applies anonymization rules to PII fields 5. Stores snapshot on your local filesystem **Success indicator**: ``` ⣾ Extracting... (0/42 tables) ✓ Extracted 2,847 rows across 23 tables ✓ Anonymized 312 PII fields ✓ Snapshot written to local output path: ./snapshots ``` **Local is the default.** Omit `--async` to run extraction on your machine without agent infrastructure. *** ## Step 5: Restore the Snapshot Apply the extracted data to a different database (or the same one for testing): ```bash theme={null} basecut snapshot restore my-first-snapshot:latest \ --target "postgresql://localhost:5432/myapp_test" ``` **What's happening:** 1. CLI reads snapshot from storage 2. Validates target schema compatibility 3. Inserts data in dependency order (respects foreign keys) 4. Reports completion Run migrations first. Restore does not create or alter tables. **Success indicator**: ``` ✓ Loading snapshot: my-first-snapshot:latest ✓ Validated schema for 23 tables ✓ Inserted 2,847 rows ✓ Verified referential integrity ✓ Restore complete in 3.2s ``` Your local database now has a production-realistic subset with all PII safely anonymized. *** ## Common Next Steps Now that you've created your first snapshot, here's what to explore next: Add domain-specific PII protection rules and fine-tune anonymization strategies Automate snapshot creation and restore in your CI pipeline for consistent test data Run snapshot extraction inside your VPC for production databases (TEAM plan) Learn patterns for debugging, testing migrations, and sharing data with partners *** ## Verify the Data Check what was restored: ```sql theme={null} -- See available tables \dt -- Count rows SELECT relname AS table_name, n_live_tup::bigint AS estimated_rows FROM pg_stat_user_tables ORDER BY estimated_rows DESC; -- Verify anonymization worked SELECT email, phone FROM users LIMIT 5; -- email | phone -- ------------------------ | ------------- -- jane.doe42@example.com | 555-0192 -- john.smith7@example.com | 555-0847 ``` *** ## Ready for Production? You just completed a **local execution** quick start. For production workloads, deploy self-hosted agents: One-click managed deployment for a production-ready Basecut agent **Next step for production**: Deploy agents in Docker/Kubernetes (recommended) Understand agent vs local execution and when to use each *** ## Customize Your Setup Add custom PII protection for your domain-specific fields Fine-tune extraction depth, limits, and filters Automate snapshot creation in GitHub Actions Patterns for testing, debugging, and data sharing # Basecut with Docker Compose Source: https://docs.basecut.dev/integrations/docker-compose Integrate Basecut into your Docker Compose workflow for local development Use Basecut with Docker Compose to automatically restore snapshots when starting your local development environment. This ensures every developer starts with the same realistic dataset. ## Overview This guide shows how to: * Add Basecut CLI to your Docker Compose setup * Restore snapshots as part of `docker compose up` * Use `BASECUT_DATABASE_URL` with Docker networks * Share snapshots across your team This guide focuses on **local execution** - Basecut CLI runs in a container and connects to your database container. For production workloads, see [Agent Deployment](/advanced/agent-deployment). ## Basic Setup ### 1. Add Basecut Service to docker-compose.yml Add a Basecut service that runs after your database is ready: ```yaml theme={null} # docker-compose.yml version: '3.8' services: postgres: image: postgres:15 environment: POSTGRES_USER: postgres POSTGRES_PASSWORD: postgres POSTGRES_DB: myapp_dev ports: - "5432:5432" healthcheck: test: ["CMD-SHELL", "pg_isready -U postgres"] interval: 5s timeout: 5s retries: 5 basecut-restore: image: myapp-basecut # Build from the Dockerfile in this guide depends_on: postgres: condition: service_healthy environment: BASECUT_API_KEY: ${BASECUT_API_KEY} BASECUT_DATABASE_URL: postgresql://postgres:postgres@postgres:5432/myapp_dev volumes: - ./basecut.yml:/app/basecut.yml - ./snapshots:/app/snapshots working_dir: /app command: > sh -c " basecut snapshot restore dev-seed:latest --target \"$$BASECUT_DATABASE_URL\" --yes " profiles: - restore # Only run when explicitly requested ``` ### 2. Restore Snapshot on Startup Run Basecut restore as part of your startup: ```bash theme={null} # Start services and restore snapshot docker compose --profile restore up -d # Or restore separately after services are up docker compose up -d postgres docker compose run --rm basecut-restore ``` ## Using Docker Networks When your database is in a Docker network, use the service name as the hostname: ```yaml theme={null} services: postgres: # ... postgres config ... networks: - app-network basecut-restore: # ... basecut config ... networks: - app-network environment: # Use service name 'postgres' as hostname BASECUT_DATABASE_URL: postgresql://postgres:postgres@postgres:5432/myapp_dev networks: app-network: driver: bridge ``` ## Custom Basecut Image Create a custom Docker image with Basecut pre-installed for faster startup: ```dockerfile theme={null} # Dockerfile.basecut FROM alpine:latest RUN apk add --no-cache curl bash # Install Basecut CLI RUN curl -fsSL https://basecut.dev/install.sh | sh ENV PATH="/root/.local/bin:${PATH}" WORKDIR /app ENTRYPOINT ["basecut"] ``` Build and use: ```bash theme={null} docker build -f Dockerfile.basecut -t myapp-basecut . ``` Then reference in docker-compose.yml: ```yaml theme={null} services: basecut-restore: image: myapp-basecut # ... rest of config ... ``` ## Environment Variables Store Basecut credentials securely: ### Option 1: .env File (Local Development) ```bash theme={null} # .env BASECUT_API_KEY=bc_test_xxx BASECUT_DATABASE_URL=postgresql://postgres:postgres@postgres:5432/myapp_dev ``` Docker Compose automatically loads `.env`: ```yaml theme={null} services: basecut-restore: environment: BASECUT_API_KEY: ${BASECUT_API_KEY} BASECUT_DATABASE_URL: ${BASECUT_DATABASE_URL} ``` ### Option 2: Docker Secrets (Production) For production, use Docker secrets and export the value before running Basecut: ```yaml theme={null} services: basecut-restore: secrets: - basecut_api_key command: > sh -c " export BASECUT_API_KEY=$$(cat /run/secrets/basecut_api_key) && basecut snapshot restore dev-seed:latest --target \"$$BASECUT_DATABASE_URL\" --yes " secrets: basecut_api_key: external: true ``` ## Complete Example Full docker-compose.yml with app, database, and Basecut: ```yaml theme={null} version: '3.8' services: postgres: image: postgres:15 environment: POSTGRES_USER: postgres POSTGRES_PASSWORD: postgres POSTGRES_DB: myapp_dev ports: - "5432:5432" volumes: - postgres_data:/var/lib/postgresql/data healthcheck: test: ["CMD-SHELL", "pg_isready -U postgres"] interval: 5s timeout: 5s retries: 5 app: build: . depends_on: postgres: condition: service_healthy environment: DATABASE_URL: postgresql://postgres:postgres@postgres:5432/myapp_dev ports: - "3000:3000" volumes: - .:/app - /app/node_modules basecut-restore: image: myapp-basecut depends_on: postgres: condition: service_healthy environment: BASECUT_API_KEY: ${BASECUT_API_KEY} BASECUT_DATABASE_URL: postgresql://postgres:postgres@postgres:5432/myapp_dev volumes: - ./basecut.yml:/app/basecut.yml working_dir: /app command: > sh -c " echo 'Restoring snapshot...' && basecut snapshot restore dev-seed:latest --target \"$$BASECUT_DATABASE_URL\" --yes && echo 'Snapshot restored successfully' " profiles: - restore volumes: postgres_data: ``` **Usage:** ```bash theme={null} # Start everything docker compose up -d # Restore snapshot (one-time or when needed) docker compose --profile restore up basecut-restore # View logs docker compose logs basecut-restore ``` ## Tips * **Use profiles**: The `profiles` directive lets you run Basecut restore only when needed, not on every `docker compose up` * **Health checks**: Ensure your database is healthy before restoring (prevents connection errors) * **Volume mounts**: Mount `basecut.yml` and snapshot directories if using local storage * **Idempotency**: Use `--yes` flag to skip confirmation prompts in CI/automated environments ## Next Steps * Learn about [execution modes](/core-concepts/execution-modes) (local vs agent) * Set up [CI/CD integration](/workflows/ci-cd) for automated snapshots * Explore [common workflows](/workflows/common-workflows) for different use cases # Basecut in GitHub Actions Source: https://docs.basecut.dev/integrations/github-actions Integrate Basecut into your GitHub Actions workflows for automated testing and snapshot management Use Basecut in GitHub Actions to automatically seed test databases, create snapshots on schedule, and validate schema migrations with production-like data. ## Overview This guide covers: * Restoring snapshots before running tests * Creating snapshots on a schedule * Testing schema migrations against production-like data * Caching Basecut CLI for faster runs * Best practices for GitHub Actions workflows For other CI/CD platforms, see the [CI/CD Integration](/workflows/ci-cd) guide. For local development with Docker, see [Docker Compose Integration](/integrations/docker-compose). ## Quick Start: Test with Production-Like Data Restore a snapshot before running your test suite: ```yaml theme={null} # .github/workflows/test.yml name: Test on: [push, pull_request] jobs: test: runs-on: ubuntu-latest services: postgres: image: postgres:15 env: POSTGRES_USER: postgres POSTGRES_PASSWORD: postgres POSTGRES_DB: test_db ports: - 5432:5432 options: >- --health-cmd pg_isready --health-interval 10s --health-timeout 5s --health-retries 5 steps: - uses: actions/checkout@v4 - name: Install Basecut CLI run: | curl -fsSL https://basecut.dev/install.sh | sh echo "$HOME/.basecut/bin" >> $GITHUB_PATH - name: Restore Test Snapshot env: BASECUT_API_KEY: ${{ secrets.BASECUT_API_KEY }} AWS_ACCESS_KEY_ID: ${{ secrets.AWS_ACCESS_KEY_ID }} AWS_SECRET_ACCESS_KEY: ${{ secrets.AWS_SECRET_ACCESS_KEY }} run: | basecut snapshot restore test-data:latest \ --target "postgresql://postgres:postgres@localhost:5432/test_db" - name: Run Tests run: npm test ``` **Required Secrets** (Settings → Secrets and variables → Actions): * `BASECUT_API_KEY`: Your Basecut API key * `AWS_ACCESS_KEY_ID`: AWS credentials (if snapshot stored in S3) * `AWS_SECRET_ACCESS_KEY`: AWS secret key *** ## Create Snapshots on Schedule Refresh your dev snapshot weekly with latest production data: ```yaml theme={null} # .github/workflows/snapshot.yml name: Create Weekly Dev Snapshot on: schedule: - cron: '0 2 * * 1' # Every Monday at 2am UTC workflow_dispatch: # Manual trigger jobs: create-snapshot: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - name: Install Basecut CLI run: | curl -fsSL https://basecut.dev/install.sh | sh echo "$HOME/.basecut/bin" >> $GITHUB_PATH - name: Create Snapshot env: BASECUT_API_KEY: ${{ secrets.BASECUT_API_KEY }} BASECUT_DATABASE_URL: ${{ secrets.PROD_DATABASE_URL }} AWS_ACCESS_KEY_ID: ${{ secrets.AWS_ACCESS_KEY_ID }} AWS_SECRET_ACCESS_KEY: ${{ secrets.AWS_SECRET_ACCESS_KEY }} run: | basecut snapshot create \ --config basecut.yml \ --name "dev-seed" \ --source "$BASECUT_DATABASE_URL" - name: Notify Team if: success() uses: slackapi/slack-github-action@v1 with: webhook-url: ${{ secrets.SLACK_WEBHOOK }} payload: | { "text": "✅ New dev-seed snapshot created. Run `basecut snapshot restore dev-seed:latest` to update your local DB." } ``` *** ## Test Schema Migrations Validate migrations against production-like data before deploying: ```yaml theme={null} # .github/workflows/migration-test.yml name: Test Migration on: pull_request: paths: - 'migrations/**' jobs: test-migration: runs-on: ubuntu-latest services: postgres: image: postgres:15 env: POSTGRES_PASSWORD: postgres ports: - 5432:5432 options: >- --health-cmd pg_isready --health-interval 10s --health-timeout 5s --health-retries 5 steps: - uses: actions/checkout@v4 - name: Install Basecut CLI run: | curl -fsSL https://basecut.dev/install.sh | sh echo "$HOME/.basecut/bin" >> $GITHUB_PATH - name: Restore Pre-Migration Snapshot env: BASECUT_API_KEY: ${{ secrets.BASECUT_API_KEY }} run: | # Restore production-like data with OLD schema basecut snapshot restore prod-schema:latest \ --target "postgresql://postgres:postgres@localhost:5432/postgres" - name: Run Migration run: | npm run migrate - name: Verify Migration Success run: | # Run tests against migrated schema npm run test:integration - name: Comment on PR if: success() uses: actions/github-script@v7 with: script: | github.rest.issues.createComment({ issue_number: context.issue.number, owner: context.repo.owner, repo: context.repo.repo, body: '✅ Migration tested successfully against production-like snapshot.' }) ``` *** ## Optimize Performance ### Cache Basecut CLI Installation Speed up workflows by caching the Basecut CLI binary: ```yaml theme={null} - name: Cache Basecut CLI uses: actions/cache@v4 with: path: ~/.basecut/bin key: basecut-cli-${{ runner.os }}-v1 restore-keys: | basecut-cli-${{ runner.os }}- - name: Install Basecut CLI run: | if [ ! -f ~/.basecut/bin/basecut ]; then curl -fsSL https://basecut.dev/install.sh | sh fi echo "$HOME/.basecut/bin" >> $GITHUB_PATH ``` ### Parallel Test Jobs Restore snapshot once, run tests in parallel: ```yaml theme={null} jobs: setup: runs-on: ubuntu-latest services: postgres: image: postgres:15 # ... postgres config ... steps: - uses: actions/checkout@v4 - name: Install Basecut CLI run: | curl -fsSL https://basecut.dev/install.sh | sh echo "$HOME/.basecut/bin" >> $GITHUB_PATH - name: Restore Snapshot env: BASECUT_API_KEY: ${{ secrets.BASECUT_API_KEY }} run: | basecut snapshot restore test-data:latest \ --target "postgresql://postgres:postgres@localhost:5432/test_db" - name: Dump Database run: | pg_dump "postgresql://postgres:postgres@localhost:5432/test_db" > test-db.sql - name: Upload DB Snapshot uses: actions/upload-artifact@v4 with: name: test-db path: test-db.sql retention-days: 1 test: needs: setup strategy: matrix: shard: [1, 2, 3, 4] runs-on: ubuntu-latest services: postgres: image: postgres:15 # ... postgres config ... steps: - uses: actions/checkout@v4 - name: Download DB Snapshot uses: actions/download-artifact@v4 with: name: test-db - name: Restore DB run: | psql "postgresql://postgres:postgres@localhost:5432/test_db" < test-db.sql - name: Run Tests run: npm test -- --shard=${{ matrix.shard }}/4 ``` *** ## Best Practices ### 1. Use Dedicated Test Snapshots Create separate snapshots for CI with: * **Stable sampling**: Use `sampling.seed` when `sampling.mode: random` * **Small size**: Faster restore (use `limits.rows.per_table`) * **Stable schema**: Update when schema changes, not on every run ```yaml theme={null} # ci-test-data.yml version: '1' name: 'ci-test-data' from: - table: users limits: rows: per_table: 500 # Keep CI fast sampling: mode: random seed: 12345 anonymize: auto output: s3://my-team-snapshots/ci-test-data ``` ### 2. Handle Restore Failures Gracefully ```yaml theme={null} - name: Restore Snapshot with Fallback run: | if ! basecut snapshot restore test-data:latest \ --target "postgresql://postgres:postgres@localhost:5432/test_db"; then echo "⚠️ Snapshot restore failed, using seed data instead" npm run seed:test-data fi ``` ### 3. Use Matrix Strategy for Multiple Environments Test against different snapshot versions: ```yaml theme={null} jobs: test: strategy: matrix: snapshot: [v1, v2, latest] steps: - name: Restore Snapshot run: | basecut snapshot restore test-data:${{ matrix.snapshot }} \ --target "$BASECUT_DATABASE_URL" ``` ### 4. Conditional Snapshot Creation Only create snapshots on main branch: ```yaml theme={null} - name: Create Snapshot if: github.ref == 'refs/heads/main' run: | basecut snapshot create --config basecut.yml --name "dev-seed" ``` *** ## Troubleshooting ### Snapshot Restore Too Slow * **Use smaller snapshot**: Reduce `limits.rows.per_table` in your config * **Cache restore**: Restore once, reuse DB dump (see parallel tests above) * **Local storage**: Use local filesystem for CI snapshots (faster than S3) ### Authentication Failures ```bash theme={null} # Verify API key works basecut whoami # Check cloud storage credentials aws s3 ls s3://your-bucket/ # S3 gsutil ls gs://your-bucket/ # GCS ``` ### Database Connection Refused * Ensure `services` container is healthy before restoring * Check that `depends_on` isn't needed (services start in parallel) * Increase `--health-interval` if database starts slowly *** ## Next Steps Complete guide for GitHub Actions, GitLab CI, CircleCI, and more Other patterns for development, debugging, and data sharing Use Basecut with Docker Compose for local development Debug common CI/CD issues # Welcome to Basecut Source: https://docs.basecut.dev/introduction Production-like database snapshots in minutes — without production risk Give every developer realistic data without risky exports or slow manual workflows. Basecut extracts production-like subsets of your database, following foreign key relationships to ensure referential integrity while keeping PII safe. Run locally for quick starts, or deploy agents inside your VPC for production workloads. If you are evaluating how masking works, start with the [Anonymization](/configuration/anonymization) guide. ## The Problem Testing with toy data misses real-world bugs. Edge cases that happen in production—deeply nested relationships, specific data combinations, scale-dependent behavior—never surface in development. Manually creating realistic test data is slow and breaks every time your schema evolves. Copying production data wholesale exposes PII, bloats local databases, and violates compliance requirements. ## The Solution Basecut intelligently extracts complete, referentially-valid subsets of your database: Start from specific rows and automatically pull all related data through foreign keys. No broken references, no manual joins. 30+ anonymization strategies detect and transform sensitive data. Team and Enterprise plans can enforce org-wide snapshot rules for every snapshot. Use the local CLI for quick starts or run agents inside your VPC. Process millions of rows without external access to your data. Apply snapshots to local dev, staging, or CI environments. Identical data across your entire team. ## Quick Example Extract a user's complete account history—orders, payments, support tickets—from a production database with 200 tables: ```yaml theme={null} # basecut.yml version: '1' name: 'user-analysis' from: - table: users where: 'email = :email' params: email: 'john@example.com' traverse: parents: 5 # Follow parent relationships (account → org) children: 10 # Follow child relationships (user → orders → items) anonymize: mode: auto rules: '*.credit_card': { strategy: fake_credit_card } ``` ```bash theme={null} basecut snapshot create --config basecut.yml --name "user-analysis" --source "$BASECUT_DATABASE_URL" # ✓ Extracted 847 rows across 23 tables # ✓ Anonymized 156 PII fields # ✓ Snapshot stored: s3://snapshots/user-analysis basecut snapshot restore user-analysis:latest --target "postgres://localhost/dev" # ✓ Applied to local database in 2.3s ``` ## Choose Your Path Get your first snapshot in under 5 minutes Learn about relationship-following and FK traversal Learn when to use auto, manual, or org-level anonymization rules Patterns for testing, debugging, and data sharing ## Use Cases **Local Development**: Pull production patterns into your dev environment. Test with real data shapes, not `User 1`, `User 2`. **Team Testing**: Share consistent, realistic datasets across developers. Everyone tests against the same complex scenarios. **CI/CD Pipelines**: Seed test databases with production-like data. Catch integration bugs before deployment. **Debugging Production Issues**: Extract the exact data state that triggered a bug. Reproduce locally without production access. **Partner Data Sharing**: Provide realistic sample data to integration partners, with all PII safely anonymized. ## Get Started First snapshot in under 5 minutes Understand the relationship-following algorithm Complete YAML reference with examples Protect PII with 30+ strategies and extraction-time masking # CI/CD Integration Source: https://docs.basecut.dev/workflows/ci-cd Automate snapshot creation and test database seeding in your pipeline Integrate Basecut into your CI/CD workflow to automatically seed test databases, refresh dev snapshots, or validate schema migrations with production-like data. ## GitHub Actions ### Test with Production-Like Data Restore a snapshot before running your test suite: ```yaml theme={null} # .github/workflows/test.yml name: Test on: [push, pull_request] jobs: test: runs-on: ubuntu-latest services: postgres: image: postgres:15 env: POSTGRES_USER: postgres POSTGRES_PASSWORD: postgres POSTGRES_DB: test_db ports: - 5432:5432 options: >- --health-cmd pg_isready --health-interval 10s --health-timeout 5s --health-retries 5 steps: - uses: actions/checkout@v4 - name: Install Basecut CLI run: | curl -fsSL https://basecut.dev/install.sh | sh echo "$HOME/.basecut/bin" >> $GITHUB_PATH - name: Restore Test Snapshot env: BASECUT_API_KEY: ${{ secrets.BASECUT_API_KEY }} AWS_ACCESS_KEY_ID: ${{ secrets.AWS_ACCESS_KEY_ID }} AWS_SECRET_ACCESS_KEY: ${{ secrets.AWS_SECRET_ACCESS_KEY }} run: | basecut snapshot restore test-data:latest \ --target "postgresql://postgres:postgres@localhost:5432/test_db" - name: Run Tests run: npm test ``` **Secrets to configure** (Settings → Secrets): * `BASECUT_API_KEY`: Your Basecut API key * `AWS_ACCESS_KEY_ID`: AWS credentials (if snapshot stored in S3) * `AWS_SECRET_ACCESS_KEY`: AWS secret key *** ### Create Snapshot on Schedule Refresh your dev snapshot weekly with latest production data: ```yaml theme={null} # .github/workflows/snapshot.yml name: Create Weekly Dev Snapshot on: schedule: - cron: '0 2 * * 1' # Every Monday at 2am UTC workflow_dispatch: # Manual trigger jobs: create-snapshot: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - name: Install Basecut CLI run: | curl -fsSL https://basecut.dev/install.sh | sh echo "$HOME/.basecut/bin" >> $GITHUB_PATH - name: Create Snapshot env: BASECUT_API_KEY: ${{ secrets.BASECUT_API_KEY }} BASECUT_DATABASE_URL: ${{ secrets.PROD_DATABASE_URL }} AWS_ACCESS_KEY_ID: ${{ secrets.AWS_ACCESS_KEY_ID }} AWS_SECRET_ACCESS_KEY: ${{ secrets.AWS_SECRET_ACCESS_KEY }} run: | basecut snapshot create \ --config basecut.yml \ --name "dev-seed" - name: Notify Team if: success() uses: slackapi/slack-github-action@v1 with: webhook-url: ${{ secrets.SLACK_WEBHOOK }} payload: | { "text": "✅ New dev-seed snapshot created. Run `basecut snapshot restore dev-seed:latest` to update your local DB." } ``` *** ### Test Schema Migrations Validate migrations against production-like data before deploying: ```yaml theme={null} # .github/workflows/migration-test.yml name: Test Migration on: pull_request: paths: - 'migrations/**' jobs: test-migration: runs-on: ubuntu-latest services: postgres: image: postgres:15 env: POSTGRES_PASSWORD: postgres ports: - 5432:5432 options: >- --health-cmd pg_isready --health-interval 10s --health-timeout 5s --health-retries 5 steps: - uses: actions/checkout@v4 - name: Install Basecut CLI run: | curl -fsSL https://basecut.dev/install.sh | sh echo "$HOME/.basecut/bin" >> $GITHUB_PATH - name: Restore Pre-Migration Snapshot env: BASECUT_API_KEY: ${{ secrets.BASECUT_API_KEY }} run: | # Restore production-like data with OLD schema basecut snapshot restore prod-schema:latest \ --target "postgresql://postgres:postgres@localhost:5432/postgres" - name: Run Migration run: | npm run migrate - name: Verify Migration Success run: | # Run tests against migrated schema npm run test:integration - name: Comment on PR if: success() uses: actions/github-script@v7 with: script: | github.rest.issues.createComment({ issue_number: context.issue.number, owner: context.repo.owner, repo: context.repo.repo, body: '✅ Migration tested successfully against production-like snapshot.' }) ``` *** ## GitLab CI ### Test Pipeline with Snapshot Restore ```yaml theme={null} # .gitlab-ci.yml stages: - test test: stage: test image: node:20 services: - postgres:15 variables: POSTGRES_DB: test_db POSTGRES_USER: postgres POSTGRES_PASSWORD: postgres BASECUT_DATABASE_URL: 'postgresql://postgres:postgres@postgres:5432/test_db' before_script: # Install Basecut CLI - curl -fsSL https://basecut.dev/install.sh | sh - export PATH="$HOME/.basecut/bin:$PATH" # Restore test snapshot - | basecut snapshot restore test-data:latest \ --target "$BASECUT_DATABASE_URL" script: - npm ci - npm test only: - merge_requests - main ``` **CI/CD Variables** (Settings → CI/CD → Variables): * `BASECUT_API_KEY`: Your Basecut API key (masked) * `AWS_ACCESS_KEY_ID`: AWS credentials (masked) * `AWS_SECRET_ACCESS_KEY`: AWS secret key (masked, protected) *** ### Scheduled Snapshot Creation ```yaml theme={null} # .gitlab-ci.yml create-snapshot: stage: snapshot image: node:20 only: - schedules # Run on pipeline schedules before_script: - curl -fsSL https://basecut.dev/install.sh | sh - export PATH="$HOME/.basecut/bin:$PATH" script: - | basecut snapshot create \ --config basecut.yml \ --name "dev-seed-$(date +%Y%m%d)" \ --source "$PROD_DATABASE_URL" after_script: # Notify team on success - | if [ "$CI_JOB_STATUS" == "success" ]; then curl -X POST $SLACK_WEBHOOK \ -H 'Content-Type: application/json' \ -d '{"text":"✅ New dev snapshot created"}' fi ``` **Setup**: Go to CI/CD → Schedules → Create new schedule (e.g., weekly on Mondays). *** ## CircleCI ### Test Job with Snapshot ```yaml theme={null} # .circleci/config.yml version: 2.1 executors: node-postgres: docker: - image: cimg/node:20.0 - image: cimg/postgres:15.0 environment: POSTGRES_USER: postgres POSTGRES_PASSWORD: postgres POSTGRES_DB: test_db jobs: test: executor: node-postgres steps: - checkout - run: name: Install Basecut CLI command: | curl -fsSL https://basecut.dev/install.sh | sh echo 'export PATH="$HOME/.basecut/bin:$PATH"' >> $BASH_ENV - run: name: Wait for PostgreSQL command: | dockerize -wait tcp://localhost:5432 -timeout 1m - run: name: Restore Test Snapshot command: | basecut snapshot restore test-data:latest \ --target "postgresql://postgres:postgres@localhost:5432/test_db" environment: BASECUT_API_KEY: $BASECUT_API_KEY - run: name: Run Tests command: npm test workflows: test: jobs: - test ``` **Environment Variables** (Project Settings → Environment Variables): * `BASECUT_API_KEY` * `AWS_ACCESS_KEY_ID` * `AWS_SECRET_ACCESS_KEY` *** ## Jenkins ### Declarative Pipeline ```groovy theme={null} // Jenkinsfile pipeline { agent any environment { BASECUT_API_KEY = credentials('basecut-api-key') BASECUT_DATABASE_URL = credentials('test-database-url') } stages { stage('Setup Database') { steps { sh ''' curl -fsSL https://basecut.dev/install.sh | sh export PATH="$HOME/.basecut/bin:$PATH" basecut snapshot restore test-data:latest \ --target "$BASECUT_DATABASE_URL" ''' } } stage('Test') { steps { sh 'npm test' } } } post { always { junit 'test-results/*.xml' } } } ``` **Credentials**: Add `basecut-api-key` in Jenkins → Manage Credentials. *** ## Docker Compose for CI For local CI testing or custom CI systems: ```yaml theme={null} # docker-compose.ci.yml version: '3.8' services: postgres: image: postgres:15 environment: POSTGRES_USER: postgres POSTGRES_PASSWORD: postgres POSTGRES_DB: test_db ports: - '5432:5432' healthcheck: test: ['CMD-SHELL', 'pg_isready -U postgres'] interval: 5s timeout: 5s retries: 5 test: image: node:20 depends_on: postgres: condition: service_healthy environment: BASECUT_DATABASE_URL: postgresql://postgres:postgres@postgres:5432/test_db BASECUT_API_KEY: ${BASECUT_API_KEY} volumes: - .:/app working_dir: /app command: | sh -c " curl -fsSL https://basecut.dev/install.sh | sh && export PATH=\"\$HOME/.basecut/bin:\$PATH\" && basecut snapshot restore test-data:latest && npm ci && npm test " ``` Run locally: ```bash theme={null} export BASECUT_API_KEY=your_key docker compose -f docker-compose.ci.yml up --abort-on-container-exit test ``` *** ## Best Practices ### 1. Use Dedicated Test Snapshots Create separate snapshots for CI with: * **Stable sampling**: Use `sampling.seed` when `sampling.mode: random` * **Small size**: Faster restore (use `limits.rows.per_table`) * **Stable schema**: Update when schema changes, not on every run ```yaml theme={null} # ci-test-data.yml version: '1' name: 'ci-test-data' from: - table: users limits: rows: per_table: 500 # Keep CI fast sampling: mode: random seed: 12345 anonymize: auto output: s3://my-team-snapshots/ci-test-data ``` ### 2. Cache Basecut CLI Installation **GitHub Actions**: ```yaml theme={null} - name: Cache Basecut CLI uses: actions/cache@v3 with: path: ~/.basecut/bin key: cli-${{ runner.os }} - name: Install Basecut CLI run: | if [ ! -f ~/.basecut/bin/basecut ]; then curl -fsSL https://basecut.dev/install.sh | sh fi echo "$HOME/.basecut/bin" >> $GITHUB_PATH ``` **GitLab CI**: ```yaml theme={null} cache: paths: - .basecut/ before_script: - | if [ ! -f .basecut/basecut ]; then curl -fsSL https://basecut.dev/install.sh | sh mv $HOME/.basecut/bin/basecut .basecut/ fi - export PATH="$PWD/.basecut:$PATH" ``` ### 3. Handle Restore Failures Gracefully ```yaml theme={null} - name: Restore Snapshot with Fallback run: | if ! basecut snapshot restore test-data:latest --target "$BASECUT_DATABASE_URL"; then echo "⚠️ Snapshot restore failed, using seed data instead" npm run seed:test-data fi ``` ### 4. Parallel Test Jobs Restore snapshot once, run tests in parallel: ```yaml theme={null} # .github/workflows/test.yml jobs: setup: runs-on: ubuntu-latest services: postgres: [...] steps: - name: Restore Snapshot run: basecut snapshot restore test-data:latest --target "$BASECUT_DATABASE_URL" - name: Dump Database run: pg_dump "$BASECUT_DATABASE_URL" > test-db.sql - name: Upload DB Snapshot uses: actions/upload-artifact@v3 with: name: test-db path: test-db.sql test: needs: setup strategy: matrix: shard: [1, 2, 3, 4] runs-on: ubuntu-latest services: postgres: [...] steps: - name: Download DB Snapshot uses: actions/download-artifact@v3 with: name: test-db - name: Restore DB run: psql "$BASECUT_DATABASE_URL" < test-db.sql - name: Run Tests run: npm test -- --shard=${{ matrix.shard }}/4 ``` ### 5. Use Read-Only Database Credentials Never commit credentials to source control. Use your CI platform's secret management to store `BASECUT_API_KEY` and database credentials. See [Agent Deployment](/advanced/agent-deployment#database-credentials) for the recommended read-only user setup. *** ## Troubleshooting ### Snapshot Restore Too Slow * **Use smaller snapshot**: Reduce `limits.rows.per_table` * **Cache restore**: Restore once, reuse DB dump (see parallel tests above) * **Local storage**: Use local filesystem for CI snapshots (faster than S3) ### Authentication Failures ```bash theme={null} # Verify API key works basecut whoami # Check cloud storage credentials aws s3 ls s3://your-bucket/ # S3 gsutil ls gs://your-bucket/ # GCS ``` ### Database Connection Refused * Ensure `services` container is healthy before restoring * Check `depends_on` with `condition: service_healthy` * Increase `--health-interval` if database starts slowly *** ## Next Steps Other patterns for development, debugging, and data sharing Run your own agents for private databases Complete CLI configuration reference Debug common CI/CD issues # Common Workflows Source: https://docs.basecut.dev/workflows/common-workflows Real-world patterns for using Basecut in development, testing, and debugging This guide covers the most common ways teams use Basecut in their day-to-day workflows. ## Development: Pull Production Data Locally **Problem**: Your local database has toy data (`User 1`, `Test Order`). You need realistic data to develop against production-like scenarios. **Solution**: Extract a subset of production data, anonymize PII, restore to your local database. ```yaml theme={null} # basecut.yml version: "1" name: "dev-seed" from: - table: users where: 'created_at > :since' params: since: '2024-01-01' # Recent users traverse: parents: 5 children: 10 limits: rows: per_table: 500 # Keep local DB manageable anonymize: mode: auto output: provider: s3 bucket: my-team-snapshots region: us-east-1 ``` **Workflow**: ```bash theme={null} # 1. Create snapshot (self-hosted agent extracts from production) basecut snapshot create \ --config basecut.yml \ --name "dev-seed" \ --async # 2. Restore to local database basecut snapshot restore dev-seed:latest \ --target "postgresql://localhost:5432/myapp_dev" # 3. Develop with realistic data npm run dev ``` **Tradeoffs**: * ✅ Real data shapes, edge cases, and patterns * ✅ Everyone on the team has identical test data * ❌ One-time snapshot—doesn't auto-update as production changes **Tip**: Schedule weekly snapshot creation in CI to keep dev data fresh. *** ## Testing: CI Pipeline Integration **Problem**: Your test suite runs against seeded fixtures that don't match production schema or data complexity. **Solution**: Restore a production-like snapshot before running tests in CI. ```yaml theme={null} # .github/workflows/test.yml name: Test on: [push, pull_request] jobs: test: runs-on: ubuntu-latest services: postgres: image: postgres:15 env: POSTGRES_PASSWORD: postgres options: >- --health-cmd pg_isready --health-interval 10s --health-timeout 5s --health-retries 5 steps: - uses: actions/checkout@v3 - name: Install Basecut CLI run: | curl -fsSL https://basecut.dev/install.sh | sh echo "$HOME/.basecut/bin" >> $GITHUB_PATH - name: Restore Test Snapshot env: BASECUT_API_KEY: ${{ secrets.BASECUT_API_KEY }} run: | basecut snapshot restore test-data:latest \ --target "postgresql://postgres:postgres@localhost:5432/test_db" - name: Run Tests run: npm test ``` **Tradeoffs**: * ✅ Tests run against production-realistic data * ✅ Catches schema mismatches early * ❌ Slower CI (restore adds \~30s for typical snapshot) * ❌ Tests may be less deterministic (use `seed` for consistency) **Tip**: Create a dedicated `test-data` snapshot with fixed seed for reproducibility. *** ## Debugging: Extract Data Around Specific Issue **Problem**: A bug occurred in production for user ID `12345`. You need their exact data state to reproduce locally. **Solution**: Extract just that user and their related data. ```yaml theme={null} # debug-user-12345.yml version: "1" name: "debug-user-12345" from: - table: users where: 'id = :user_id' params: user_id: 12345 traverse: parents: 10 # Grab all parent data children: 10 # Grab all child data # No limits—get everything related to this user limits: rows: per_table: 0 # unlimited anonymize: # Minimal anonymization for debugging mode: manual rules: '*.credit_card': fake_credit_card ``` **Workflow**: ```bash theme={null} # 1. Extract the specific user's data basecut snapshot create \ --config debug-user-12345.yml \ --name "debug-user-12345" \ --source "postgresql://readonly@prod-db:5432/myapp" # 2. Restore to local debug environment basecut snapshot restore debug-user-12345:latest \ --target "postgresql://localhost:5432/debug_db" # 3. Reproduce the bug locally node scripts/reproduce-bug.js --user-id 12345 ``` **Tradeoffs**: * ✅ Exact production state causing the bug * ✅ No production access needed for debugging * ❌ May expose PII (use full anonymization if sharing externally) **Tip**: Delete the snapshot after debugging to avoid accumulating one-off extractions. *** ## Data Sharing: Realistic Datasets for Partners **Problem**: Integration partner needs sample data that matches your production API schema and data patterns. **Solution**: Create a curated snapshot with heavy anonymization. ```yaml theme={null} # partner-sample.yml version: "1" name: "partner-sample" from: - table: accounts where: 'plan = :plan' params: plan: 'enterprise' # Show enterprise features traverse: parents: 5 children: 10 limits: rows: per_table: 100 # Manageable size for partners anonymize: mode: auto rules: accounts: company_name: fake_company api_key: hash api_logs: request_body: redact response_body: redact output: provider: s3 bucket: partner-shared-data region: us-east-1 ``` **Workflow**: ```bash theme={null} # 1. Create partner-safe snapshot basecut snapshot create \ --config partner-sample.yml \ --name "partner-sample-v1" # 2. Share access to the snapshot # Option A: Generate pre-signed S3 URL (time-limited) # (Resolve storage key with `basecut snapshot inspect` first) aws s3 presign s3://partner-shared-data//manifest.json \ --expires-in 604800 # 7 days # Option B: Partner uses their own Basecut account to restore # (Give them the snapshot name and bucket access) ``` **Tradeoffs**: * ✅ Partners get realistic API response shapes * ✅ All PII anonymized for compliance * ❌ Static snapshot—may drift from current API * ❌ Requires partner to have Basecut CLI (or extract manually) *** ## Team Onboarding: Consistent Dev Environment **Problem**: New developers spend hours seeding local databases with realistic data. **Solution**: Document the snapshot restore process in your README. ```markdown theme={null} # README.md ## Local Development Setup ### 1. Install Dependencies \`\`\`bash npm install \`\`\` ### 2. Start Local Database \`\`\`bash docker compose up -d postgres \`\`\` ### 3. Restore Production-Like Data \`\`\`bash # Install Basecut CLI curl -fsSL https://basecut.dev/install.sh | sh # Login (or set BASECUT_API_KEY from 1Password) basecut login # Restore the latest dev snapshot basecut snapshot restore dev-seed:latest \ --target "postgresql://localhost:5432/myapp_dev" \`\`\` ### 4. Run the App \`\`\`bash npm run dev \`\`\` You now have 10k realistic users, orders, and activity logs in your local database! ``` **Tradeoffs**: * ✅ Onboarding takes minutes instead of hours * ✅ Everyone has identical data (easier to help debug) * ❌ Requires Basecut account for each developer *** ## Schema Migration Testing **Problem**: You're changing your database schema. Will the migration work on production data shapes? **Solution**: Test migrations against a production-like snapshot. ```bash theme={null} # 1. Create snapshot of current production schema basecut snapshot create \ --config basecut.yml \ --name "pre-migration-test" \ --source "postgresql://readonly@prod-db:5432/myapp" # 2. Restore to staging database basecut snapshot restore pre-migration-test:latest \ --target "postgresql://staging-db:5432/myapp" # 3. Run migration on staging npm run migrate # 4. Verify migration succeeded npm run test:integration # 5. If successful, run migration on production npm run migrate:production ``` **Tradeoffs**: * ✅ Catch migration issues before production deployment * ✅ Test with real data volumes and edge cases * ❌ Doesn't catch schema drift between snapshot and current prod **Tip**: Snapshot production immediately before running the migration test. *** *** ## Next Steps Detailed GitHub Actions, GitLab CI, and CircleCI examples Complete guide to PII protection strategies Choose between self-hosted agent and local execution Debug common workflow issues