{"messages": [{"role": "user", "content": "Analyze funnel drop after adding RAG citations to answers."}, {"role": "assistant", "content": "Segment funnel by query type, device, and user cohort to locate drop source. Compare task completion, dwell time, and citation click rates between variants. Check if latency added by retrieval hurts conversion versus trust gained. Survey users for verbosity complaints and inspect long answers with excessive citations. Run multivariate test on citation density and placement. Ensure logging captures render errors for citation UI. For AI UX, balance transparency with readability through collapsible sources. Recommend iterative tuning rather than rollback if trust metrics improve despite slight conversion dip. Document tradeoffs for stakeholders. This analysis distinguishes cosmetic friction from value loss, guiding citation design that preserves engagement while meeting groundedness and compliance requirements for high stakes domains."}], "metadata": {"domain": "backend", "task_type": "experiment_analysis", "difficulty": "advanced"}} {"messages": [{"role": "user", "content": "Design idempotency for POST payment API handling retries safely with keys."}, {"role": "assistant", "content": "Require Idempotency-Key header UUID, store key plus request hash plus response for 24h. On repeat with same hash return stored response 200; different hash return 422. Process with DB unique constraint on key to handle races. Expire keys with TTL and background cleanup. Support client retry with same key across timeouts. Test double submit concurrent expecting single charge via stubbed gateway. Monitor duplicate rate and key collisions. Document key generation, retention, error cases, and reconciliation. Ensure keys scoped per user to prevent cross-account reuse. Finally validate changes with automated tests peer review and staging verification to ensure correctness maintainability performance and alignment with project standards requirements and long term operational needs for production."}], "metadata": {"domain": "backend", "task_type": "architecture", "difficulty": "advanced"}} {"messages": [{"role": "user", "content": "Intermittent 502 and 504 from FastAPI behind Nginx with streaming responses and 60s upstream timeout. Direct to uvicorn works. Provide triage checklist with Nginx, keepalive, and header buffering fixes."}, {"role": "assistant", "content": "502 means upstream closed, 504 upstream slow, often Nginx buffering vs streaming mismatch. Checklist: increase proxy_read_timeout 120s for long streams, set proxy_http_version 1.1 and Connection empty for keepalive to uvicorn keepalive, disable proxy_buffering off for SSE, raise client_max_body_size, check uvicorn workers timeout and backlog. Verify upstream keepalive with upstream block keepalive 32. Capture Nginx error.log upstream prematurely closed. Test bypass Nginx to isolate. Add FastAPI timeout middleware returning 503 with Retry-After. Monitor upstream response time histogram. Fix is typically proxy_buffering off plus timeout alignment and worker count matching CPU. Validate with curl --no-buffer and load test. Additional notes: add logging with context, write unit tests for edge cases, validate inputs at API boundary, monitor metrics in production, and document assumptions for future maintainers to prevent regressions."}], "metadata": {"domain": "backend", "task_type": "api_debugging", "difficulty": "expert"}} {"messages": [{"role": "user", "content": "Write evaluation harness test for prompt regression detecting BLEU drop and refusal changes."}, {"role": "assistant", "content": "Create harness running golden prompt suite on baseline and candidate models, asserting BLEU and ROUGE deltas within tolerance and refusal rate stability. Include edge where minor wording improves fluency but breaks JSON schema compliance. Verify statistical significance with paired bootstrap. Store outputs with version tags for diff review. Test harness itself with synthetic degraded outputs ensuring sensitivity. Log per-prompt failures with input hash. Enforce schema validation alongside lexical metrics. Gate deployment on harness pass. Track cost and latency deltas. Additional validation includes shadow deployment, gradual rollout, and automated rollback on metric regression ensuring reliability. Add dashboard tracking precision, recall, latency, and cost with alerts on regression plus documented rollback procedure ensuring operational readiness."}], "metadata": {"domain": "backend", "task_type": "testing", "difficulty": "advanced"}} {"messages": [{"role": "user", "content": "Architect multi-region active-active API with Postgres, handling split brain and 5s replication lag for global checkout. Expert tradeoffs?"}, {"role": "assistant", "content": "Adopt region pinned writes with CRDT for carts and saga for checkout, avoiding synchronous cross region commits. Use CockroachDB or Aurora Global with write forwarding, conflict resolution via last writer with vector clocks. Route users to nearest region with latency DNS, pin session to home region for checkout. Accept eventual consistency for catalog, strong for payments via single primary. Test partition with Jepsen asserting no double spend via fencing tokens. Monitor replication lag and failover RPO. This balances availability and correctness, acknowledging CAP by isolating strong consistency to critical money path while keeping reads fast globally. Add structured logging with request IDs, metrics for latency and error rate, and runbooks for oncall so issues are diagnosable. Include integration tests with real dependencies in containers to catch contract drift before production deployment causes outage."}], "metadata": {"domain": "backend", "task_type": "experiment_analysis", "difficulty": "expert"}} {"messages": [{"role": "user", "content": "Design gRPC service for inventory with protobuf versioning and error details."}, {"role": "assistant", "content": "Define proto package inventory v1 with messages using reserved fields for deleted attributes to preserve backward compatibility. Use unary RPC for stock check and server streaming for bulk updates to optimize throughput. Return rich errors with google rpc Status details including ErrorInfo and RetryInfo for programmatic handling. Enforce deadlines via context timeout and propagate cancellation to database queries. Generate clients with buf lint and breaking change detection in CI. Version by package path not by reusing same service name with breaking changes. Add interceptors for auth and logging and metrics uniformly. Test with in process bufconn server covering success and not found and deadline exceeded. Document migration path for field renames using deprecated option. Well versioned gRPC design enables efficient strongly typed internal communication while allowing safe evolution of inventory schema across services."}], "metadata": {"domain": "backend", "task_type": "architecture", "difficulty": "intermediate"}} {"messages": [{"role": "user", "content": "How do I implement event-driven architecture with Kafka including partitioning and consumer groups?"}, {"role": "assistant", "content": "Kafka decouples services through durable partitioned logs with replay. Model topics per domain event, key by entity for ordering, choose partition counts for throughput and future growth. Produce idempotently with acks all and retries. Consume in groups for parallel processing, committing offsets after handling, handling rebalances gracefully. Enforce schemas with registry and compatibility rules. Retain logs for replay and audit. Handle poison messages via dead letters, backoff, and alerting. Monitor lag, throughput, and consumer health. Test broker failures, duplicate delivery, and schema evolution. Secure with TLS, ACLs, and quotas. Well designed event flows enable scalable integrations, temporal decoupling, and analytics, letting backend systems evolve independently while preserving ordering guarantees, durability, and observable processing semantics across organizational boundaries."}], "metadata": {"domain": "backend", "task_type": "instruction", "difficulty": "advanced"}} {"messages": [{"role": "user", "content": "Explain eventual consistency vs strong consistency for distributed order service."}, {"role": "assistant", "content": "Strong consistency guarantees all replicas see same data immediately, simplifying reasoning but increasing latency and reducing availability during partitions. Eventual consistency allows temporary divergence, converging later, enabling high availability and low latency. For orders, use strong consistency for inventory decrement to prevent oversell via transactional DB, and eventual for search index and analytics via outbox and Kafka. Explain CAP theorem tradeoffs and patterns like saga, idempotency, and read-your-writes. Provide example: order created synchronously, email sent asynchronously. Choose based on business invariants: money requires strong, notifications tolerate delay. This distinction guides database selection, API SLAs, and retry design while setting stakeholder expectations for visibility delays."}], "metadata": {"domain": "backend", "task_type": "instruction", "difficulty": "advanced"}} {"messages": [{"role": "user", "content": "Debug CORS error when frontend localhost:3000 calls backend localhost:8000 blocked."}, {"role": "assistant", "content": "Browser blocks cross-origin read without Access-Control-Allow-Origin header from backend. Fix in FastAPI with CORSMiddleware allow_origins=['http://localhost:3000'] allow_methods=['*'] allow_headers=['*'] allow_credentials=True. Do not use wildcard with credentials. Verify preflight OPTIONS returns 200 with headers. Test via curl -H Origin:http://localhost:3000 -v showing response header. In Express use cors({origin:'http://localhost:3000'}). Ensure frontend fetch includes credentials if cookies needed. For production, replace localhost with exact domain list from env. Check proxy alternative via Next.js rewrites to same origin avoiding CORS. Log origin mismatches server-side. Understanding same-origin policy versus CORS prevents insecure * in production, fixes local dev friction, and clarifies that Postman bypasses CORS so browser-only failures point directly to header misconfiguration not backend logic."}], "metadata": {"domain": "backend", "task_type": "debugging", "difficulty": "beginner"}} {"messages": [{"role": "user", "content": "Review Dockerfile FROM latest ubuntu apt update COPY all npm install root EXPOSE CMD. What production issues and hardened multi stage version"}, {"role": "assistant", "content": "Using latest tag is non reproducible, apt update without install creates stale layer, copying entire context includes secrets and node modules, running as root violates least privilege, no multi stage bloats image and slows deploys. Fix with pinned node slim base, multi stage dependencies build runner, dockerignore, USER node, npm ci omit dev, HEALTHCHECK, exec form CMD. Separate build-time dev dependencies from runtime. Scan with Trivy and sign images. Test rebuild determinism, size reduction, startup. Pin apt packages with no install recommends and cleanup lists. This improves supply chain security, reduces attack surface and startup time, ensures repeatable builds across CI production, and establishes minimal maintainable image practices with layer caching efficiency."}], "metadata": {"domain": "backend", "task_type": "code_review", "difficulty": "advanced"}} {"messages": [{"role": "user", "content": "Debug OAuth token refresh race causing duplicate sessions."}, {"role": "assistant", "content": "Concurrent requests with expired token trigger parallel refreshes creating multiple sessions. Serialize refresh with distributed lock keyed by user id or use atomic token rotation with reuse detection. Store refresh family id and invalidate old tokens on use. Retry failed requests with single refreshed token via request queue. Add logging with correlation ids to prove race. Test with parallel expired requests asserting one refresh call. Set clock skew tolerance and short retry window. For AI apps, avoid storing tokens in localStorage vulnerable to XSS. Fixing race prevents session proliferation and audit confusion. It ensures seamless UX under parallel API fan out common in agent workflows that issue many simultaneous tool calls after token expiry."}], "metadata": {"domain": "backend", "task_type": "api_debugging", "difficulty": "advanced"}} {"messages": [{"role": "user", "content": "Design multi tenant isolation for LLM inference platform."}, {"role": "assistant", "content": "Isolate tenants via namespaces with separate rate limits, quotas, and API keys. Enforce row level security in Postgres and prefix cache keys by tenant. Schedule GPU pools with fair sharing and priority preemption. Audit all prompts metadata without storing PII. Encrypt tenant data with per tenant keys and rotate regularly. Test noisy neighbor scenarios with load injection. Provide usage dashboards and budget alerts. For compliance, support data residency pinning and deletion workflows. Use admission control to reject over quota requests with clear errors. This architecture prevents cross tenant leakage, ensures fair performance, and simplifies billing. It scales by sharding stateful components while keeping control plane centralized for policy enforcement and observability across the fleet."}], "metadata": {"domain": "backend", "task_type": "architecture", "difficulty": "advanced"}} {"messages": [{"role": "user", "content": "How do I design background jobs with queues, retries, idempotency keys, and dead-letter handling?"}, {"role": "assistant", "content": "Reliable background work separates enqueue from execution with durable queues. Define small idempotent jobs with deterministic keys, versioned payloads, and explicit timeouts. Retry transient failures with exponential backoff and jitter, limiting attempts before routing to dead letter queues for inspection. Store progress and results durably, acknowledge only after success. Deduplicate with unique constraints to survive redelivery. Prioritize queues, isolate tenants, and scale workers independently. Monitor depth, age, failure rates, and processing latency. Test retries, duplicates, poison messages, and shutdown draining. Provide admin replay and alerting. Document operational runbooks. This design absorbs spikes, survives crashes, and guarantees eventual progress for emails, exports, webhooks, and integrations, keeping backend APIs fast while ensuring critical side effects complete correctly and observably."}], "metadata": {"domain": "backend", "task_type": "instruction", "difficulty": "intermediate"}} {"messages": [{"role": "user", "content": "Explain formal consistency proofs for distributed backend ledgers under network partitions."}, {"role": "assistant", "content": "Proving ledger consistency requires precise models of replicas, messages, and partitions. Specify safety as linearizability or serializability and liveness under fair delivery. Use TLA plus to model propose accept commit phases, then verify invariants with TLC for bounded cases. Extend to mechanized proofs in Coq or Isabelle for general guarantees. Test implementations with Jepsen nemesis injecting partitions, clocks, and crashes while checking histories with Elle. Monitor divergence metrics and proof assumptions in production. Document failure models and quorum requirements explicitly. Combine BFT assumptions where malicious nodes exist. Rigorous proofs expose edge cases like lost acknowledgments or split brain commits before deployment, guiding protocol fixes. This discipline yields trustworthy financial or supply ledgers that preserve correctness despite asynchrony, faults, and hostile networks at global backend scale."}], "metadata": {"domain": "backend", "task_type": "instruction", "difficulty": "expert"}} {"messages": [{"role": "user", "content": "Architect multi-tenant SaaS isolation choosing row-level security versus schema per tenant."}, {"role": "assistant", "content": "Evaluate row-level security with tenant_id column plus Postgres RLS policies enforcing current_setting app.tenant, offering low operational overhead and efficient pooling, ideal for thousands small tenants. Schema per tenant provides stronger isolation and per-tenant backup but multiplies migrations and connection overhead. Recommend RLS with composite indexes (tenant_id, id), mandatory tenant filter in ORM middleware, and separate encryption keys per tenant via envelope. Test isolation attempting cross-tenant read asserting empty. Monitor noisy neighbor via per-tenant quotas and statement_timeout. Provide migration path to dedicated DB for enterprise tier. Document onboarding provisioning transaction. Choice balances cost, compliance SOC2, scalability to 10k tenants, and developer velocity. Include audit logging tenant context. Architecture prevents data leakage, simplifies operations, supports tiered isolation without rewrite as business grows and requirements evolve."}], "metadata": {"domain": "backend", "task_type": "architecture", "difficulty": "expert"}} {"messages": [{"role": "user", "content": "Implement JWT auth and rate limiting for a FastAPI model serving endpoint with per-user quotas."}, {"role": "assistant", "content": "Use OAuth2 password bearer with RS256 JWT verification via JWKS caching. Validate issuer, audience, and expiry with clock skew tolerance. Store user tiers in Postgres and enforce quotas in Redis using token bucket with Lua scripts for atomicity. Return 429 with Retry-After when exceeded. Apply dependency injection for auth on predict routes while keeping health open. Log user ID hash, latency, and quota usage without storing tokens. Add refresh rotation and revocation list for logout. Test with pytest for expired, malformed, and insufficient scope tokens. Load test quota enforcement under concurrency to avoid race conditions. Document limits per tier. Use HTTPS, secure cookies if applicable, and rotate signing keys regularly."}], "metadata": {"domain": "backend", "task_type": "implementation", "difficulty": "intermediate"}} {"messages": [{"role": "user", "content": "Explain Kubernetes deployment strategies including rolling, blue-green, and canary with health probes."}, {"role": "assistant", "content": "Kubernetes deployment strategies balance speed and risk for backend releases. Rolling updates replace pods gradually with max surge unavailable bounds, using readiness liveness probes to gate traffic. Blue green runs parallel stacks switching service selector for instant rollback. Canary shifts small traffic percentages with metrics analysis via Argo Rollouts or Flagger. Define resource requests limits, PDBs, and termination grace for safe eviction. Test probes, migration compatibility, and rollback procedures. Monitor error rates, latency, and saturation during rollout. Automate promotion and abort on SLO burn. Document flags and database compatibility. Choosing strategy by blast radius and statefulness enables frequent reliable deploys, minimal downtime, and fast recovery, supporting backend teams delivering features safely to production at scale with confidence."}], "metadata": {"domain": "backend", "task_type": "instruction", "difficulty": "advanced"}} {"messages": [{"role": "user", "content": "Refactor background Celery tasks to be idempotent with transactional outbox."}, {"role": "assistant", "content": "Store task intent in outbox table within same DB transaction as business update to guarantee atomicity. Relay outbox rows to Celery via poller publishing with at least once delivery. Make task handler check processed id table with unique constraint to deduplicate retries safely. Use exponential retry with max three attempts then DLQ for manual inspection. Pass only IDs not full objects to avoid stale data and large payloads. Version task payloads to handle code deploys during backlog drain. Test crash between commit and publish and duplicate delivery asserting single effect. Monitor outbox lag and worker queue depth for alerting. Document exactly once effect achieved via idempotency versus true exactly once. Outbox refactor eliminates lost tasks after DB commit failures and prevents double side effects, crucial for billing and notification workflows requiring reliability."}], "metadata": {"domain": "backend", "task_type": "code_review", "difficulty": "advanced"}} {"messages": [{"role": "user", "content": "My Git push rejected with non fast forward after teammate pushed to same branch. I ran git pull and now have merge conflicts. What safe steps resolve"}, {"role": "assistant", "content": "Non fast forward means remote has commits you lack so push would overwrite history. Safe flow is git fetch origin, git status to confirm branch, then git pull rebase or git rebase origin main to replay your commits. Resolve conflicts by editing marked files, git add resolved paths, git rebase continue. Review with git log oneline graph and git diff origin main. Run tests before git push. If rebase messy use git rebase abort to reset. Avoid force push on shared branches use force with lease only for personal feature branches after communication. Enable git rerere to reuse resolutions. This preserves linear history, avoids merge bubbles, and prevents accidental loss of teammate work while unblocking collaboration in shared repos."}], "metadata": {"domain": "backend", "task_type": "debugging", "difficulty": "beginner"}} {"messages": [{"role": "user", "content": "How do database migrations work and how should I handle rollback, seeding, and zero-downtime changes?"}, {"role": "assistant", "content": "Migrations version schema changes as incremental scripts applied transactionally in order. Use tools like Alembic, record history, and review generated diffs manually. Make backward compatible expand migrate contract steps for zero downtime: add nullable columns, backfill, then enforce constraints. Avoid locking rewrites on huge tables via batched updates and concurrent indexes. Provide down migrations for emergencies but test restores from backups primarily. Seed reference data idempotently separate from schema. Run migrations in CI against clones, check performance, and gate deploys on success. Monitor lock waits and replication lag. Document breaking changes and coordination steps. Disciplined migration practice prevents outages, data loss, and drift, enabling safe continuous delivery of evolving backend data models across staging and production environments with confidence."}], "metadata": {"domain": "backend", "task_type": "instruction", "difficulty": "intermediate"}} {"messages": [{"role": "user", "content": "Review backend PR that introduces synchronous HTTP calls in request path. Explain risks."}, {"role": "assistant", "content": "Flag added latency and cascading failure risk. Require async client with timeout, retry budget, circuit breaker. Suggest caching or moving to background job if not needed synchronously. Check thread pool exhaustion under load. Ask for timeout values justification and fallback behavior. Demand tests for downstream slow, error, timeout. Verify observability with spans and metrics. Provide alternative pattern using events or parallel fan-out. Rate severity high if user-facing. Outline acceptance criteria: p95 impact measured, failure injection passing, docs updated. Encourage dependency dashboard for downstream SLO. Finally validate changes with automated tests peer review and staging verification to ensure correctness maintainability performance and alignment with project standards requirements and long term operational needs for production."}], "metadata": {"domain": "backend", "task_type": "code_review", "difficulty": "advanced"}} {"messages": [{"role": "user", "content": "Traceback TypeError unhashable dict in Python cache decorator. Diagnose mutable argument caching bug."}, {"role": "assistant", "content": "Unhashable error occurs when lru cache receives dict or list arguments that cannot hash. Cache key construction requires immutable types. Inspect call sites passing raw JSON dicts directly to cached function. Fix by serializing arguments to canonical JSON string with sorted keys or converting to frozenset tuples before caching. Implement custom key function handling nested structures. Add test passing nested dict and list variants. Avoid caching functions with side effects or large unbounded cache without maxsize. Log cache hit rates validating effectiveness. Document immutable contract in function signature using Mapping versus dict where appropriate plus type checking. Add regression coverage measuring latency, error budgets, and data drift with dashboards alerting on SLO breaches plus versioned runbook documentation for oncall response."}], "metadata": {"domain": "backend", "task_type": "traceback", "difficulty": "intermediate"}} {"messages": [{"role": "user", "content": "FastAPI endpoint returns 422 posting JSON datetime 2026-13-01. Pydantic model uses datetime field. How to debug validation and improve error message for clients"}, {"role": "assistant", "content": "Month thirteen is invalid so Pydantic datetime parsing fails and FastAPI returns 422 Unprocessable Entity with details array showing location message type. Inspect response JSON to identify exact field and correct client payload to valid ISO8601 like December first. Customize validation error handler to return user friendly message with expected format example. Consider using date versus datetime, timezone aware types, or BeforeValidator for flexible formats with strict fallback. Add tests for valid date, invalid month, missing field, extra field, and timezone variants. Log validation errors with request identifier without echoing sensitive data. Document expected format in OpenAPI examples and client SDK. This turns cryptic errors into actionable feedback, prevents bad temporal data entering system, and aligns contracts."}], "metadata": {"domain": "backend", "task_type": "debugging", "difficulty": "intermediate"}} {"messages": [{"role": "user", "content": "Intermittent 502 from Nginx to Gunicorn with upstream prematurely closed. Logs show worker timeout 30s on report endpoint. How to debug?"}, {"role": "assistant", "content": "Worker blocks on long report exceeding timeout, Nginx retries then 502. Move report to Celery background job returning 202 with poll endpoint or websocket. Increase timeout temporarily but fix root with streaming and pagination. Trace with request ID across Nginx to Gunicorn to worker. Profile report query for N+1. Set graceful timeout and worker restart max requests. Test slow endpoint with timeout assertion. Async streaming with chunked response prevents worker starvation. This decouples slow work from request thread, restoring 502 free operation while giving users progress feedback instead of hanging connections. Add structured logging with request IDs, metrics for latency and error rate, and runbooks for oncall so issues are diagnosable. Include integration tests with real dependencies in containers to catch contract drift before production deployment causes outage."}], "metadata": {"domain": "backend", "task_type": "traceback", "difficulty": "intermediate"}} {"messages": [{"role": "user", "content": "Document a REST endpoint for order creation with OpenAPI including errors."}, {"role": "assistant", "content": "Define path slash orders post with summary, operationId createOrder, tags Orders. Document requestBody JSON schema with required customerId, items array, idempotency key header. Detail 201 response with order object, 400 validation, 401 auth, 409 duplicate, 422 business rule. Include examples for success and errors. Specify auth securityScheme bearer. Add rate limit headers and retry guidance. Generate via code annotations or hand-written YAML validated in CI with spectral lint. Publish to Swagger UI and version alongside code. Document idempotency handling, webhook follow-ups, and support contact. Ensure examples are tested against implementation to prevent drift. Finally validate changes with automated tests peer review and staging verification to ensure correctness maintainability performance and alignment with project standards requirements and long term operational needs for production."}], "metadata": {"domain": "backend", "task_type": "instruction", "difficulty": "intermediate"}} {"messages": [{"role": "user", "content": "Kubernetes pod CrashLoopBackOff exit 137 OOMKilled after adding in memory cache dict. Limit 256Mi image processes large CSV. How to fix memory pattern"}, {"role": "assistant", "content": "Exit 137 indicates container exceeded memory limit and kernel OOM killer terminated process. Loading full CSV plus unbounded dictionary cache spikes beyond 256Mi, especially with object overhead. Diagnose via kubectl describe lastState, metrics server graphs, and local memory profiler. Fix by streaming CSV with chunksize iterator, using LRU cache with maxsize and TTL, releasing references promptly. Replace process local dict with Redis or disk cache for shared reuse. Increase limit only after profiling, set requests near p95, add readiness probe to prevent traffic during load. Implement generator pipeline processing batches with tracemalloc monitoring. Test with representative large file. This bounds memory, prevents eviction cascades, and makes usage predictable for autoscaling."}], "metadata": {"domain": "backend", "task_type": "debugging", "difficulty": "intermediate"}} {"messages": [{"role": "user", "content": "Describe database indexing, query planning with EXPLAIN, and N+1 query prevention with ORM eager loading."}, {"role": "assistant", "content": "Indexes accelerate lookups by ordering keys, but add write cost and storage. Create B-tree for equality and ranges, composite with correct column order, and partial for subsets. Analyze with EXPLAIN to inspect scans, join order, and row estimates; fix sequential scans on large tables. Avoid SELECT star, ensure statistics updated, and parameterize consistently. ORMs cause N plus one by lazy loading relations in loops; solve with joinedload, selectinload, or explicit joins fetching needed graphs. Batch endpoints, paginate, and project only required columns. Test with production like volumes and assert query counts. Monitor slow logs and bloat. Document index rationale. Thoughtful indexing plus eager strategy design cuts latency dramatically, reduces database load, and keeps backend APIs responsive, predictable, and cost efficient as data and traffic scale over time."}], "metadata": {"domain": "backend", "task_type": "instruction", "difficulty": "intermediate"}} {"messages": [{"role": "user", "content": "Review this FastAPI endpoint: @app.get('/users/{id}') def get(id: int): return db.query(User).filter(User.id==id).first(). It sometimes 500s and leaks DB details. What is wrong and what is the hardened version?"}, {"role": "assistant", "content": "It returns None as 200 with null body instead of 404, may raise 500 on DB error, and lacks response model. Harden with 404 and error mapping. Improved:\nfrom fastapi import Depends, HTTPException\nfrom pydantic import BaseModel\nclass UserOut(BaseModel):\n id: int\n name: str\n model_config = {'from_attributes': True}\n@app.get('/users/{uid}', response_model=UserOut)\ndef get(uid: int, db=Depends(get_db)):\n try:\n obj = db.get(User, uid)\n except Exception:\n raise HTTPException(500, 'database error')\n if not obj:\n raise HTTPException(404, 'user not found')\n return obj\nKey decisions: use path name uid to avoid shadowing builtin id. Return 404 for missing, hide internal details in 500. Add response_model to prevent leaking password hash. Validate uid ge 1. Log DB failures server side with traceback."}], "metadata": {"domain": "backend", "task_type": "code_review", "difficulty": "intermediate"}} {"messages": [{"role": "user", "content": "Show how to harden backend APIs against OWASP risks with validation, headers, and throttling."}, {"role": "assistant", "content": "Harden APIs by validating all inputs, encoding outputs, and layering defenses. Use strict schemas, allowlists, size limits, and parameterized queries to block injection. Enforce auth, least privilege scopes, and object level checks against IDOR. Set security headers CSP, HSTS, X Content Type, frame options, and referrer policy. Require HTTPS, secure cookies, and CORS allowlists. Throttle logins and sensitive routes, lock suspicious actors. Log security events without secrets and alert on anomalies. Scan dependencies, run SAST DAST, and test abuse cases. Review file uploads, SSRF vectors, and deserialization. Document threat model and incident response. Continuous hardening reduces breach likelihood and impact, ensuring backend APIs meet OWASP expectations, protect user data, and sustain trust under active adversarial pressure and compliance scrutiny."}], "metadata": {"domain": "backend", "task_type": "instruction", "difficulty": "advanced"}} {"messages": [{"role": "user", "content": "Write test for checkpoint resume preserving optimizer and scheduler after preemption."}, {"role": "assistant", "content": "Build test training two steps, saving state dictionary including model, optimizer, scheduler, scaler, epoch, and RNG states, then resuming in fresh process asserting loss trajectory equality. Include edge where scheduler stepped per batch versus per epoch catching off by one. Verify manual seed, numpy, and cuda RNG restoration. Mock preemption deleting in memory objects before load. Assert learning rate continuity and gradient norm parity. Test strict versus partial load for architecture changes. Log checkpoint hash detecting corruption. Ensure atomic write via temporary file rename plus recovery validation. Add regression coverage measuring latency, error budgets, and data drift with dashboards alerting on SLO breaches plus versioned runbook documentation for oncall response."}], "metadata": {"domain": "backend", "task_type": "testing", "difficulty": "advanced"}} {"messages": [{"role": "user", "content": "Implement feature flag service with LaunchDarkly-style targeting and audit log."}, {"role": "assistant", "content": "Store flags with rules JSON: percentage, attribute equals, segment. Evaluate in order with deterministic hash user_id%100. Cache flags 10s in Redis, poll DB changes via LISTEN. Audit every toggle with actor and diff. Serve /evaluate batch endpoint p95 10ms. Test gradual rollout 1% to 100%. Support kill switch default false. Document rule precedence. Monitor evaluation errors. Validate fix with dedicated unit test and integration check covering edge cases. Log relevant metrics, monitor production dashboards continuously, document change clearly in pull request for reviewers and future maintenance work. Include reproducible script, versioned config, seeded runs, ablation results, error analysis table, and follow-up monitoring plan to ensure durable improvement."}], "metadata": {"domain": "backend", "task_type": "implementation", "difficulty": "advanced"}} {"messages": [{"role": "user", "content": "Traceback Redis max clients reached no pooling per-request client. Debug?"}, {"role": "assistant", "content": "Root cause is new client per request leaking sockets exhausting maxclients under concurrency. Use shared ConnectionPool sized to workers with socket_timeout health checks. Init singleton at startup closed on shutdown. Ensure release via context manager even on exception. Set redis maxclients appropriately and TCP keepalive. Monitor INFO clients metric. Implement backoff retry for transient drops. Validate load test showing stable connections. Add circuit breaker failing fast when down. Refactor to pipeline batching reducing roundtrips. Log pool stats. Test burst 500 concurrent asserting no growth. Document pool sizing runbook to sustain reliable caching without cascading backend timeouts in production environments handling high throughput workloads."}], "metadata": {"domain": "backend", "task_type": "traceback", "difficulty": "advanced"}} {"messages": [{"role": "user", "content": "My pytest fails with AssertionError showing 422 != 200 on FastAPI POST with nested Pydantic model. Response body says missing field address.zip. My test sends address as string not object. How to fix test and model error messages?"}, {"role": "assistant", "content": "The test payload shape does not match nested model, so validation correctly returns 422. Fix payload to send object and assert error details. Example:\nfrom fastapi import FastAPI\nfrom pydantic import BaseModel\napp = FastAPI()\nclass Addr(BaseModel):\n zip: str\nclass U(BaseModel):\n name: str\n address: Addr\n@app.post('/u')\ndef create(u: U):\n return u\n# correct test:\n# client.post('/u', json={'name':'a','address':{'zip':'12345'}})\nKey decisions: print response.json on failure to see missing fields. Use response_model for output consistency. For better errors add Field description. In tests parametrize valid and invalid payloads. Ensure json not data param so content-type is correct. This avoids false 422 from form encoding. Additional notes: add logging with context, write unit tests for edge cases, validate inputs at API boundary, monitor metrics in production, and document assumptions for future maintainers to prevent regressions."}], "metadata": {"domain": "backend", "task_type": "traceback", "difficulty": "intermediate"}} {"messages": [{"role": "user", "content": "Review async LRU cache PR using dict without locks. Identify race and eviction issues."}, {"role": "assistant", "content": "Unsynchronized dict access under asyncio can interleave between await points, causing lost updates and inconsistent LRU ordering. Eviction logic scanning full dict is order n and blocks event loop on large caches. Review should demand asyncio lock around mutate paths or use OrderedDict with move to end atomically, plus maxsize enforcement test under concurrency. Check for key mutation after insertion breaking hash stability. Suggest metrics for hit rate and eviction count. Verify cancellation safety so evicted entries do not leak resources. Avoid time based expiry without monotonic clock. Require stress test with concurrent getters and setters plus profiling. Add regression coverage measuring latency, error budgets, and data drift with dashboards alerting on SLO breaches plus versioned runbook documentation for oncall response."}], "metadata": {"domain": "backend", "task_type": "code_review", "difficulty": "advanced"}} {"messages": [{"role": "user", "content": "Document webhook integration including signature verification, retries, and idempotency."}, {"role": "assistant", "content": "Describe endpoint URL and supported event types with example payloads for each version. Explain HMAC SHA256 signature header construction and verification steps with code snippet using constant time compare to prevent timing attacks. Specify retry policy with exponential backoff over 24 hours and expected 2xx response within five seconds. Require idempotency handling via event id deduplication table with 7 day retention. List IP allowlist ranges and TLS requirements. Provide test console and sample delivery logs for debugging. Document failure modes like 410 to stop retries for deactivated endpoints. Include changelog for payload evolution and deprecation timeline. Validate docs with contract tests replaying examples against implementation. Clear webhook docs reduce integration errors and support tickets by guiding consumers on security and reliability requirements for event driven workflows."}], "metadata": {"domain": "backend", "task_type": "instruction", "difficulty": "intermediate"}} {"messages": [{"role": "user", "content": "Write integration tests for a webhook receiver with signature verification."}, {"role": "assistant", "content": "Spin up test server with TestClient and generate valid HMAC signatures using test secret. Cover valid delivery, invalid signature 401, replayed nonce, and malformed JSON. Mock downstream processing to assert side effects without external calls. Test idempotency via duplicate delivery with same event id. Verify timestamp tolerance rejects stale requests. Check logs redact signature values. Run tests in parallel with isolated DB transactions. For AI pipelines, include large payload and timeout cases. Assert metrics increment for each outcome. Keep secrets in test fixtures, never production keys. These tests ensure webhook security and reliability, catching verification bypasses and duplicate processing bugs before they cause data corruption or unauthorized actions in production environments."}], "metadata": {"domain": "backend", "task_type": "testing", "difficulty": "intermediate"}} {"messages": [{"role": "user", "content": "Architect zero-downtime pgvector migration from IVFFlat to HNSW on fifty million vectors."}, {"role": "assistant", "content": "Build shadow HNSW index concurrently while serving old index backfilling with batched reindex and throttled resources. Dual-write new vectors to both indexes during cutover. Validate recall parity with sampled queries before switching planner. Use blue-green deployment flipping query flag atomically. Test rollback preserving old index. Monitor build progress, bloat, and query latency. Implement checksum verification per batch. Avoid exclusive locks blocking writes. Schedule vacuum and analyze post migration. Document rollback plan. Additional validation includes shadow deployment, gradual rollout, and automated rollback on metric regression ensuring reliability. Add dashboard tracking precision, recall, latency, and cost with alerts on regression plus documented rollback procedure ensuring operational readiness."}], "metadata": {"domain": "backend", "task_type": "architecture", "difficulty": "expert"}} {"messages": [{"role": "user", "content": "Implement Postgres row-level security for multi-tenant SaaS with FastAPI tenant context."}, {"role": "assistant", "content": "Enable RLS on tables with POLICY tenant_isolation USING (tenant_id = current_setting('app.tenant')::uuid). Set local per transaction via SET LOCAL from JWT claim in middleware. Force RLS for table owners. Test cross-tenant read blocked. Index tenant_id. Bypass for migrations with superuser. Audit with pgaudit. Document tenant extraction. Measure overhead under 5%. Validate fix with dedicated unit test and integration check covering edge cases. Log relevant metrics, monitor production dashboards continuously, document change clearly in pull request for reviewers and future maintenance work. Include reproducible script, versioned config, seeded runs, ablation results, error analysis table, and follow-up monitoring plan to ensure durable improvement."}], "metadata": {"domain": "backend", "task_type": "implementation", "difficulty": "advanced"}} {"messages": [{"role": "user", "content": "Backend Postgres pgvector vs Pinecone shows recall difference 0.05. How to analyze index versus infra cause?"}, {"role": "assistant", "content": "Difference often from index params where Pinecone HNSW tuned versus pgvector ivfflat lists undertrained. Compare exact brute force baseline to isolate approximate loss from data issues. Analyze lists probes and ef settings impact on recall latency curve. Measure recall at k 10 on 1000 queries with ground truth labels. Tune pgvector lists to sqrt rows and probes 20 for better accuracy. Evaluate latency cost of higher probes. Consider HNSW extension in Postgres for parity with managed service. Monitor recall after tuning to decide self host versus managed tradeoff. Document configuration and dataset characteristics. This rigorous comparison clarifies whether gap is tunable or architectural, guiding build versus buy decision for vector infrastructure at scale."}], "metadata": {"domain": "backend", "task_type": "retrieval_analysis", "difficulty": "intermediate"}} {"messages": [{"role": "user", "content": "Traceback AttributeError NoneType object has no attribute strip in Django view at line user.email.strip. Diagnose and fix."}, {"role": "assistant", "content": "This traceback means user is None because get user returned no row for the given id, likely deleted account or invalid session, then code dereferenced email without guard. Reproduce with missing user id and confirm request user handling. Fix by fetching with get_object_or_404 or explicit None check returning 404 or 401 with structured error. Add defensive normalization helper that handles None plus whitespace and lowercases safely. Validate input serializer to require authenticated user and add logging with user_id and path for triage. Write regression test for deleted user session and anonymous request covering both branches. Add type hints Optional User and enable mypy strict to catch similar dereferences early. This prevents 500s and improves auth edge handling in production Django backends reliably today. Code:\n# before:\n# email = user.email.strip()\n# after:\ndef clean_email(user):\n return '' if user is None or not user.email else user.email.strip().lower()\nfrom django.shortcuts import get_object_or_404\nuser = get_object_or_404(User, pk=uid)"}], "metadata": {"domain": "backend", "task_type": "traceback", "difficulty": "beginner"}} {"messages": [{"role": "user", "content": "Express no rate limit Mongo $where injection verbose errors. Harden checklist?"}, {"role": "assistant", "content": "Issues enable DoS brute force, NoSQL operator injection, and info leakage. Add express-rate-limit 100 per 15m and helmet headers. Sanitize inputs with mongo-sanitize blocking $ operators, validate via Joi allowlist. Disable $where mapReduce server side JS. Return generic 500 with error ID. Enforce authz on all routes. Validate ObjectId format before query. Log attacks with IP. Scan with npm audit snyk in CI. Test injection payload $gt asserting blocked. Monitor 429 500 rates. Require TLS HSTS. Store secrets in vault. Document secure coding checklist. Result hardens Node Mongo API against injection and abuse while preserving functionality with clear validation errors for legitimate production clients."}], "metadata": {"domain": "backend", "task_type": "security", "difficulty": "advanced"}} {"messages": [{"role": "user", "content": "My FastAPI POST returns 422 with detail missing body field name. I send form-data but endpoint expects JSON Pydantic model. How to debug content-type mismatch and fix client or server?"}, {"role": "assistant", "content": "422 means validation failed, often due to form vs JSON mismatch. Check content-type header and use json param in client. Server expects JSON:\nfrom fastapi import FastAPI\nfrom pydantic import BaseModel\napp = FastAPI()\nclass Item(BaseModel):\n name: str\n@app.post('/items')\ndef create(item: Item):\n return item\n# client correct:\n# requests.post(url, json={'name':'x'})\n# wrong: data={'name':'x'} sends form\nKey decisions: inspect request headers and body in docs try-it. If need form support use Form annotation. Log validation errors server side. For file plus JSON use multipart with separate fields. Test with curl -H Content-Type: application/json. This resolves most 422 from encoding mismatch. Additional notes: add logging with context, write unit tests for edge cases, validate inputs at API boundary, monitor metrics in production, and document assumptions for future maintainers to prevent regressions."}], "metadata": {"domain": "backend", "task_type": "api_debugging", "difficulty": "intermediate"}} {"messages": [{"role": "user", "content": "Test message queue consumer for at-least-once delivery, retries, and poison messages."}, {"role": "assistant", "content": "Verify consumer acknowledges only after successful processing to ensure redelivery on crash for at least once semantics. Test retry with exponential backoff and max attempts then route to dead letter queue preserving headers and failure reason. Simulate poison message causing repeated crash and assert DLQ routing without blocking healthy messages. Check idempotent handler using deduplication key in database to handle duplicate deliveries safely. Validate ordering guarantees per partition key where required. Use testcontainers RabbitMQ to run integration tests with real broker rather than mocks. Assert metrics for processed and retried and DLQ counts. Test graceful shutdown draining in flight messages before closing channel. Document visibility timeout tuning to balance redelivery speed versus processing time. Robust consumer tests prevent data loss and cascading blockages from single malformed message in production streams."}], "metadata": {"domain": "backend", "task_type": "testing", "difficulty": "intermediate"}} {"messages": [{"role": "user", "content": "My FastAPI endpoint serializes 10k rows slowly with nested Pydantic models. Response takes 2s. How to optimize serialization and DB fetching? Show faster pattern."}, {"role": "assistant", "content": "N+1 queries plus heavy validation dominate time. Use selectin loading, limit fields, and response_model with from_attributes. Example:\n# instead of lazy loop, eager load:\n# stmt = select(User).options(selectinload(User.orders))\n# return minimal DTO:\nfrom pydantic import BaseModel\nclass Row(BaseModel):\n id: int\n name: str\n model_config = {'from_attributes': True}\n@app.get('/rows', response_model=list[Row])\ndef rows(db=Depends(get_db)):\n return db.query(User.id, User.name).limit(500).all()\nKey decisions: paginate, default 20 not 10k, add cursor. Use orjson response class for faster JSON. Profile with timing middleware. For huge exports stream CSV instead of JSON. Add index on sort column. This cuts 2s to milliseconds by reducing payload and queries. Additional notes: add logging with context, write unit tests for edge cases, validate inputs at API boundary, monitor metrics in production, and document assumptions for future maintainers to prevent regressions."}], "metadata": {"domain": "backend", "task_type": "optimization", "difficulty": "intermediate"}} {"messages": [{"role": "user", "content": "Review SQL schema for storing chat histories at scale."}, {"role": "assistant", "content": "Normalize conversations, messages, and participants with UUID primary keys and timestamptz. Partition messages by created date for retention and query pruning. Index conversation id plus sequence for ordered retrieval. Use JSONB for metadata with GIN indexes only on queried paths. Enforce foreign keys and check constraints for role values. Avoid unbounded text without TOAST tuning and consider compression. Plan archival to object storage for old partitions. Test pagination performance with large histories. For AI audit needs, add immutable append only policy and redaction flags. Document retention and PII handling. This schema supports fast recent history loads, efficient range scans, and compliant deletion. It prevents hot partitions and keeps write amplification low as chat volume grows across tenants."}], "metadata": {"domain": "backend", "task_type": "code_review", "difficulty": "intermediate"}} {"messages": [{"role": "user", "content": "Postgres deadlock updating same rows concurrently long transactions. Debug isolation?"}, {"role": "assistant", "content": "Root cause is inconsistent lock order and wide transactions holding row locks across network calls. Acquire locks in sorted ID order and keep transactions short, moving IO outside. Use SELECT FOR UPDATE SKIP LOCKED for queue pattern. Set isolation READ COMMITTED default, retry on deadlock with exponential backoff. Inspect pg_stat_activity and deadlock logs. Add index to reduce lock escalation. Validate with concurrent pgbench reproducing then fixing order. Implement idempotent retry wrapper. Monitor deadlock count metric. Refactor to batch updates single statement. Document lock ordering rule in code review checklist. Test with 50 concurrent workers asserting success to ensure throughput without serialization failures in production OLTP workloads."}], "metadata": {"domain": "backend", "task_type": "debugging", "difficulty": "advanced"}} {"messages": [{"role": "user", "content": "Implement health checks and graceful shutdown for backend inference workers."}, {"role": "assistant", "content": "Expose liveness endpoint checking process alive and readiness checking model loaded plus downstream dependencies reachable. Use separate ports for health versus traffic to avoid pollution. Handle SIGTERM by stopping acceptance, draining in-flight requests with timeout, then exiting cleanly. Set Kubernetes readiness failure to remove pod from service before termination. Test shutdown with load ensuring zero dropped tracked jobs. Log shutdown phases with request counts. For AI workers, unload GPU models gracefully and flush metrics. Add startup probes with generous period for large model loads. Document expected timings. Robust health and shutdown logic prevents rolling deploy errors, reduces 502s, and ensures inference capacity scales safely without interrupting long running generation streams."}], "metadata": {"domain": "backend", "task_type": "testing", "difficulty": "intermediate"}} {"messages": [{"role": "user", "content": "How to optimize FastAPI with connection pooling and async timeouts for downstream calls? I have cascading timeouts causing thread exhaustion. Show pooling config."}, {"role": "assistant", "content": "Reuse httpx client via lifespan with limits and timeouts to avoid per-request connect overhead. Example:\nfrom contextlib import asynccontextmanager\nimport httpx\nfrom fastapi import FastAPI\n@asynccontextmanager\nasync def life(app: FastAPI):\n limits = httpx.Limits(max_connections=100, max_keepalive_connections=20)\n async with httpx.AsyncClient(timeout=3.0, limits=limits) as c:\n app.state.http = c\n yield\napp = FastAPI(lifespan=life)\n@app.get('/proxy')\nasync def proxy():\n r = await app.state.http.get('https://api.example.com/x')\n return r.json()\nKey decisions: shared client enables keepalive, limits prevent overload. Set timeout 3s to fail fast. Add retry with backoff for idempotent GET. Monitor pool exhaustion logs. For sync use requests.Session similarly. This prevents socket churn and cascading waits. Additional notes: add logging with context, write unit tests for edge cases, validate inputs at API boundary, monitor metrics in production, and document assumptions for future maintainers to prevent regressions."}], "metadata": {"domain": "backend", "task_type": "optimization", "difficulty": "intermediate"}} {"messages": [{"role": "user", "content": "Implement stratified K-fold cross validation with sklearn Pipeline including imputation and scaling for ROC-AUC."}, {"role": "assistant", "content": "Encapsulate all preprocessing steps and the final estimator inside a single sklearn Pipeline object so that imputation medians and scaling parameters are learned exclusively from training folds, thereby preventing optimistic leakage into validation folds. Combine SimpleImputer with median strategy, StandardScaler for zero mean unit variance, and LogisticRegression with balanced class weights and increased max iterations for convergence. Evaluate using StratifiedKFold with five splits, shuffling enabled, fixed random state, and cross_val_score with roc_auc scoring and parallel jobs. Report mean score, standard deviation, and individual per-fold scores to assess stability and variance across data partitions. Additionally compute average precision for imbalanced settings, plot fold ROC curves, inspect calibration, verify absence of target leakage, and finally refit the pipeline on complete data for deployment."}], "metadata": {"domain": "classical_ml", "task_type": "implementation", "difficulty": "beginner"}} {"messages": [{"role": "user", "content": "Train XGBoost with stratified CV class weights and calibrated probabilities for tabular data."}, {"role": "assistant", "content": "Boosting excels on tabular data but needs careful imbalance handling. Use scale pos weight and subsample plus isotonic calibration on held out folds for reliable probabilities and decisions. Code:\n```python\nfrom xgboost import XGBClassifier\nfrom sklearn.calibration import CalibratedClassifierCV\nfrom sklearn.model_selection import StratifiedKFold\nratio = (y_train == 0).sum() / max(1, (y_train == 1).sum())\nbase = XGBClassifier(n_estimators=400, max_depth=5, learning_rate=0.05, subsample=0.8, colsample_bytree=0.8, scale_pos_weight=ratio, eval_metric='logloss', n_jobs=-1, random_state=42)\ncal = CalibratedClassifierCV(base, method='isotonic', cv=StratifiedKFold(3))\ncal.fit(X_train, y_train)\nprint(cal.score(X_test, y_test))\n```\nTune with early stopping on validation set. Monitor logloss versus AUC and inspect gain based importances plus SHAP values for stakeholder trust and debugging. For production use add logging and unit tests plus versioned data snapshots. Monitor metrics over time and document assumptions for teammates. Validate edge cases with nulls and empty frames before deployment to avoid silent failures in live systems."}], "metadata": {"domain": "classical_ml", "task_type": "implementation", "difficulty": "intermediate"}} {"messages": [{"role": "user", "content": "Implement stratified KFold ROC AUC evaluation for imbalanced churn model."}, {"role": "assistant", "content": "Stratified folds preserve minority rate and ROC AUC measures ranking independent of threshold.\nfrom sklearn.datasets import make_classification\nfrom sklearn.model_selection import StratifiedKFold, cross_val_score\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.pipeline import make_pipeline\nfrom sklearn.preprocessing import StandardScaler\nX,y = make_classification(weights=[0.9], random_state=42)\npipe = make_pipeline(StandardScaler(), LogisticRegression(max_iter=1000))\ncv = StratifiedKFold(5, shuffle=True, random_state=42)\nprint(cross_val_score(pipe,X,y,cv=cv,scoring='roc_auc'))\nEdge cases: extreme imbalance needs more folds care. AUC ignores calibration, check separately. Data leakage across folds from duplicates inflates. Shuffle needed for ordered data. Small folds lack positives, reduce splits. Production hardening: validate feature schemas and check for empty inputs. Log class balance and prediction distributions. Pin sklearn versions. Set random_state 42 for reproducibility. Add tests for unseen categories, missing values and single-class edge cases. Monitor drift and calibration over time and document assumptions for reviewers to reproduce results reliably."}], "metadata": {"domain": "classical_ml", "task_type": "implementation", "difficulty": "intermediate"}} {"messages": [{"role": "user", "content": "Visualize high dimensional embeddings with PCA versus UMAP and cluster validation scores."}, {"role": "assistant", "content": "PCA preserves global variance linearly while UMAP preserves local neighborhoods nonlinearly. Compare both with silhouette scores to choose representation for segmentation and exploration. Code:\n```python\nimport matplotlib.pyplot as plt\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.decomposition import PCA\nfrom sklearn.metrics import silhouette_score\nfrom sklearn.cluster import KMeans\nimport umap\nXs = StandardScaler().fit_transform(X)\nZ_pca = PCA(n_components=2, random_state=42).fit_transform(Xs)\nZ_umap = umap.UMAP(n_components=2, random_state=42).fit_transform(Xs)\nfor name, Z in [('pca', Z_pca), ('umap', Z_umap)]:\n lab = KMeans(n_clusters=4, n_init=10, random_state=42).fit_predict(Z)\n print(name, round(float(silhouette_score(Z, lab)), 3))\n plt.scatter(Z[:, 0], Z[:, 1], c=lab, s=8, alpha=0.6)\n plt.title(name)\n plt.show()\n```\nTune UMAP neighbors and min distance. Validate clusters with domain metrics, not only internal scores, before operational decisions and launches."}], "metadata": {"domain": "classical_ml", "task_type": "experiment_analysis", "difficulty": "advanced"}} {"messages": [{"role": "user", "content": "How to test for data leakage between train and eval in LLM fine-tuning?"}, {"role": "assistant", "content": "Hash normalized prompts with SHA256 and check exact overlap, plus MinHash Jaccard over 5-grams flagging above 0.8 similarity to catch paraphrases. Verify temporal splits where eval dates postdate train cutoff, exclude same document ids, and run canary GUID strings inserted in eval to detect memorization via extraction tests. Measure perplexity gap; train much lower than eval suggests contamination, confirm with n-gram overlap analysis and embedding nearest neighbors. Automate checks in CI blocking training if overlap exceeds 1 percent, log dataset versions, and quarantine leaked samples. Maintain independent eval collection pipeline with different annotators and time windows, audit quarterly. This rigorous process prevents inflated 10 point gains and ensures reported improvements generalize to truly unseen production queries and evolving user distributions."}], "metadata": {"domain": "classical_ml", "task_type": "experiment_analysis", "difficulty": "intermediate"}} {"messages": [{"role": "user", "content": "Recommender traceback ZeroDivisionError precision at k user no relevant items. How to handle metric edge case and aggregation correctly"}, {"role": "assistant", "content": "Precision at k and recall divide by retrieved or relevant counts; users with zero relevant items cause division by zero and crash evaluation. Fix by defining explicit behavior: skip such users in mean, return zero with flag, or use nanmean to exclude. Implement check if relevant empty return nan and track coverage separately. Test empty relevant, k larger than retrieved, perfect retrieval, no predictions. Use zero division parameter pattern like sklearn. Document metric choice to avoid inflating scores by excluding hard cold users. Report coverage alongside mean metric. Validate aggregation distinguishes model failure from data sparsity. This prevents crash, yields interpretable offline metrics, supports fair comparison, and handles sparse feedback scenarios common in recommender assessment with robust edge handling."}], "metadata": {"domain": "classical_ml", "task_type": "traceback", "difficulty": "intermediate"}} {"messages": [{"role": "user", "content": "Detect outliers in sensor data with Isolation Forest and validate results."}, {"role": "assistant", "content": "Engineer windowed mean, std, and gradient features to capture context beyond raw values. Fit IsolationForest with contamination set from domain estimate, tuning n_estimators and max_samples. Evaluate on labeled events with precision recall at top K. Visualize anomaly scores over time with thresholds. Compare to One Class SVM and autoencoder reconstruction error. Analyze false positives during maintenance windows and sensor recalibration. Scale features robustly to limit outlier influence. Use chronological split to avoid leakage. Tune decision threshold by cost of missed faults versus inspections. Document feature windows, hyperparameters, and review process. Deploy with streaming scoring and alert cooldown. Monitor score drift after equipment changes."}], "metadata": {"domain": "classical_ml", "task_type": "experiment_analysis", "difficulty": "intermediate"}} {"messages": [{"role": "user", "content": "Debug pipeline error from StandardScaler on sparse one-hot output with with_mean True."}, {"role": "assistant", "content": "Centering sparse matrix densifies and blows memory. Set with_mean False or densify deliberately.\nfrom sklearn.compose import ColumnTransformer\nfrom sklearn.preprocessing import OneHotEncoder, StandardScaler\npre = ColumnTransformer([('cat', OneHotEncoder(handle_unknown='ignore'), ['c']), ('num', StandardScaler(), ['n'])])\n# for sparse: StandardScaler(with_mean=False)\nEdge cases: sparse_output True default in new sklearn. Tree models skip scaling entirely. Logistic saga handles sparse efficiently. Memory blowup appears as slowdown before OOM. Test pipeline on sparse slice to verify. Production hardening: validate feature schemas and check for empty inputs. Log class balance and prediction distributions. Pin sklearn versions. Set random_state 42 for reproducibility. Add tests for unseen categories, missing values and single-class edge cases. Monitor drift and calibration over time and document assumptions for reviewers to reproduce results reliably."}], "metadata": {"domain": "classical_ml", "task_type": "debugging", "difficulty": "advanced"}} {"messages": [{"role": "user", "content": "Evaluate a binary classifier beyond accuracy on imbalanced data with proper metrics."}, {"role": "assistant", "content": "Avoid accuracy on imbalance and report precision recall F1 ROC AUC and PR AUC together. Compute confusion_matrix, classification_report, RocCurveDisplay, and PrecisionRecallDisplay. Use StratifiedKFold five splits with cross_validate scoring including roc_auc average_precision f1. Select threshold by maximizing F1 or Youden J on validation precision_recall_curve, not default 0.5. Plot calibration_curve to check probability reliability and apply CalibratedClassifierCV isotonic if miscalibrated. Report Brier score for probabilistic quality. Stratify train_test_split and set random_state 42. Test decision impact with cost sensitive analysis for false negatives versus false positives. Save metrics to JSON for tracking. This reveals true minority performance, guides threshold choice, ensures calibrated risks, and prevents misleading high accuracy from majority class dominance in real imbalanced business problems today reliably."}], "metadata": {"domain": "classical_ml", "task_type": "experiment_analysis", "difficulty": "intermediate"}} {"messages": [{"role": "user", "content": "Explain precision-recall tradeoff and implement threshold tuning for imbalanced data with PR curve."}, {"role": "assistant", "content": "Lowering threshold raises recall but drops precision, so choose operating point by business cost not default 0.5. Plot precision-recall curve and compute average precision plus F1 across thresholds. Use stratified folds for stable estimates.\n```python\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.metrics import precision_recall_curve, average_precision_score, f1_score\nimport numpy as np\nclf = LogisticRegression(max_iter=1000, class_weight='balanced', random_state=42)\nclf.fit(X_train, y_train)\nscores = clf.predict_proba(X_test)[:, 1]\nprec, rec, ths = precision_recall_curve(y_test, scores)\nprint(average_precision_score(y_test, scores))\nbest, bt = 0, 0.5\nfor t in np.linspace(0.1, 0.9, 17):\n f1 = f1_score(y_test, scores >= t)\n if f1 > best:\n best, bt = f1, t\nprint(bt, best)\n```\nReport confusion matrix at chosen threshold, calibrate probabilities if needed, and document cost rationale for stakeholders."}], "metadata": {"domain": "classical_ml", "task_type": "instruction", "difficulty": "beginner"}} {"messages": [{"role": "user", "content": "Write runbook documentation for recovering a failed distributed training job on Slurm with checkpoint resume."}, {"role": "assistant", "content": "Document prerequisites including checkpoint directory structure, Weights and Biases run ID, and Slurm partition quotas. Provide steps to inspect sbatch logs, identify NCCL timeouts versus OOM, and locate latest valid checkpoint via validator script. Include commands for squeue, scancel, and sbatch resume script with updated node list and environment variables. Explain how to verify optimizer and scheduler state restoration and adjust learning rate for remaining steps. Add checklist for data loader worker counts and shared filesystem health. Include troubleshooting table for common errors like CUDA misaligned address and stale locks. Define roles, escalation paths, and post incident capture of metrics and failed node IDs for reliability tracking."}], "metadata": {"domain": "classical_ml", "task_type": "instruction", "difficulty": "intermediate"}} {"messages": [{"role": "user", "content": "Visualize clustering uncertainty and stability for single cell RNA embeddings."}, {"role": "assistant", "content": "Project PCA fifty components to UMAP and color by Leiden clusters with marker gene dot plots for biological interpretation. Show soft assignment entropy per cell highlighting transitional states at boundaries. Plot silhouette distributions and bootstrapped adjusted Rand across resamples to quantify stability. Compare UMAP versus t-SNE layouts to distinguish robust structure from method artifacts. Visualize batch mixing with kBET scores to rule out technical confounds. Add violin plots of quality metrics per cluster including mitochondrial rate. Document normalization highly variable gene selection and random seeds. Avoid clustering directly on UMAP coordinates and explain distortion risks. Export interactive cellxgene sessions with metadata for collaborative review and reproducible discovery."}], "metadata": {"domain": "classical_ml", "task_type": "experiment_analysis", "difficulty": "intermediate"}} {"messages": [{"role": "user", "content": "My RandomForest gives 99% train but 62% test accuracy. Debug overfitting and show fixes with max_depth, min_samples_leaf and validation curve."}, {"role": "assistant", "content": "Large gap between train and test indicates high variance from overly deep trees memorizing noise. Constrain complexity with max_depth, min_samples_split, min_samples_leaf, and increase n_estimators for stability. Validate with learning curves and out-of-bag score.\n```python\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.model_selection import validation_curve\nimport numpy as np\nclf = RandomForestClassifier(n_estimators=300, max_depth=8, min_samples_split=10, min_samples_leaf=5, max_features='sqrt', oob_score=True, random_state=42, n_jobs=-1)\nclf.fit(X_train, y_train)\nprint(clf.oob_score_)\nprint(clf.score(X_test, y_test))\nimport matplotlib.pyplot as plt\ndepths = [3, 5, 8, 12, None]\nfor d in depths:\n m = RandomForestClassifier(n_estimators=200, max_depth=d, random_state=42, n_jobs=-1)\n m.fit(X_train, y_train)\n print(d, m.score(X_train, y_train), m.score(X_test, y_test))\n```\nExpect train and test to converge around depth 6 to 10. Add more data, prune features via importance, and tune with cross-validation."}], "metadata": {"domain": "classical_ml", "task_type": "debugging", "difficulty": "beginner"}} {"messages": [{"role": "user", "content": "Explain precision recall F1 and when to use them instead of accuracy for fraud detection."}, {"role": "assistant", "content": "Precision measures false alarms, recall catches fraud coverage, F1 balances them on skewed data.\nfrom sklearn.metrics import precision_score, recall_score, f1_score\ny_true = [0]*95+[1]*5\ny_pred = [0]*97+[1]*3\nprint(precision_score(y_true,y_pred), recall_score(y_true,y_pred), f1_score(y_true,y_pred))\nEdge cases: threshold tunes tradeoff, default 0.5 rarely optimal. F1 ignores true negatives. Imbalanced support needs average macro versus weighted. Small positive count makes scores unstable. Cost asymmetry may favor recall over F1. Production hardening: validate feature schemas and check for empty inputs. Log class balance and prediction distributions. Pin sklearn versions. Set random_state 42 for reproducibility. Add tests for unseen categories, missing values and single-class edge cases. Monitor drift and calibration over time and document assumptions for reviewers to reproduce results reliably."}], "metadata": {"domain": "classical_ml", "task_type": "instruction", "difficulty": "intermediate"}} {"messages": [{"role": "user", "content": "My pipeline fails on unseen category at predict time. Debug and fix encoder."}, {"role": "assistant", "content": "OneHotEncoder defaults to error on unknowns. Set handle_unknown ignore to produce zeros for new levels.\nimport pandas as pd\nfrom sklearn.preprocessing import OneHotEncoder\ntr = pd.DataFrame({'c':['a','b']})\nte = pd.DataFrame({'c':['a','c']})\nenc = OneHotEncoder(handle_unknown='ignore', sparse_output=False)\nenc.fit(tr)\nprint(enc.transform(te))\nprint(enc.get_feature_names_out())\nEdge cases: ignore silently drops signal, monitor novel rate. High cardinality explodes width, consider target encoding with CV. Missing as NaN needs impute. Train-serve skew from new categories indicates drift, alert. Production hardening: validate feature schemas and check for empty inputs. Log class balance and prediction distributions. Pin sklearn versions. Set random_state 42 for reproducibility. Add tests for unseen categories, missing values and single-class edge cases. Monitor drift and calibration over time and document assumptions for reviewers to reproduce results reliably."}], "metadata": {"domain": "classical_ml", "task_type": "debugging", "difficulty": "intermediate"}} {"messages": [{"role": "user", "content": "RandomForest 95 percent train but 68 percent validation. How to diagnose overfitting and tune with cross validation?"}, {"role": "assistant", "content": "Gap indicates high variance. Plot validation curve versus max_depth and min_samples_leaf. Constrain depth 8 to 12, increase min_samples_leaf 5, add max_features sqrt. Use StratifiedKFold 5 with GridSearchCV scoring F1. Check leakage and label noise. Add more data or prune features via importance. Early stop with out of bag score. Test holdout after tuning expecting 75 to 80. Regularization trades train fit for generalization. Document best params and CV std. This systematic tuning reduces overfit while quantifying uncertainty instead of single split luck. Track experiments with MLflow logging params metrics and data version, compare cross validated scores with confidence intervals, and review learning curves to distinguish bias from variance before choosing final model for deployment."}], "metadata": {"domain": "classical_ml", "task_type": "experiment_analysis", "difficulty": "intermediate"}} {"messages": [{"role": "user", "content": "Scale GraphSAGE training to large graphs with neighbor sampling."}, {"role": "assistant", "content": "Use PyG NeighborLoader with fanout 10 10 and batch size 1024 to bound memory. Sample two hops balancing receptive field and cost. Train with Adam learning rate 0.001 and dropout 0.5. Evaluate accuracy and throughput epochs per minute. Compare full batch versus sampled accuracy gap. Tune num workers and pin memory for DataLoader speed. Use mixed precision and gradient accumulation. Partition with METIS for multi GPU. Log GPU memory and sampling time separately. Validate on inductive test nodes unseen during training. Document sampler config and seeds. Handle class imbalance with weighted loss. Monitor neighbor explosion on dense hubs and adjust fanout adaptively."}], "metadata": {"domain": "classical_ml", "task_type": "optimization", "difficulty": "intermediate"}} {"messages": [{"role": "user", "content": "Explain precision recall F1 and when to prefer each metric in imbalanced classification projects."}, {"role": "assistant", "content": "Precision measures correctness among predicted positives. Recall measures coverage of actual positives. F1 harmonically balances both metrics into one score. Use precision for fraud alerts where false alarms are costly and recall for screening where misses are fatal. Code:\n```python\nfrom sklearn.metrics import precision_score, recall_score, f1_score, classification_report\nprec = precision_score(y_test, y_pred, zero_division=0)\nrec = recall_score(y_test, y_pred, zero_division=0)\nf1 = f1_score(y_test, y_pred, zero_division=0)\nprint(prec, rec, f1)\nprint(classification_report(y_test, y_pred))\n```\nFor threshold tuning use precision recall curve. For highly imbalanced data prefer PR AUC over ROC AUC because it focuses on minority class performance without optimistic bias. For production use add logging and unit tests plus versioned data snapshots. Monitor metrics over time and document assumptions for teammates. Validate edge cases with nulls and empty frames before deployment to avoid silent failures in live systems."}], "metadata": {"domain": "classical_ml", "task_type": "instruction", "difficulty": "beginner"}} {"messages": [{"role": "user", "content": "Evaluating long-context 128k RAG: passkey tests pass but real QA fails. Better eval?"}, {"role": "assistant", "content": "Replace synthetic passkey with multi-hop HotpotQA-style tasks requiring 5 dispersed facts, conflicting info resolution, and citation precision measured via entailment. Build 800 real queries from support tickets with human graded completeness, faithfulness, and position bias testing facts at 0, 50, and 90 percent depth revealing lost-in-middle drops 20 points. Measure nDCG at 30, answer F1, and time-to-first-token versus context length, testing 8k to 128k sweeps. Use RULER and Needle-in-haystack variants with distractors, run 3 seeds, and blind judge with GPT-4 plus human audit 10 percent. Version retriever and prompt separately to attribute failures, dashboard per-depth accuracy, and require 0.75 F1 before launch. This realistic suite exposes chunking and reranking flaws hidden by trivial retrieval benchmarks and guides targeted fixes. Add dashboards, alerts, runbooks, versioning, rollback tests, audits, and cost tracking to sustain production reliability."}], "metadata": {"domain": "classical_ml", "task_type": "experiment_analysis", "difficulty": "advanced"}} {"messages": [{"role": "user", "content": "Optimize SVM RBF hyperparameters C and gamma with RandomizedSearchCV and scaling, handling class imbalance."}, {"role": "assistant", "content": "SVM needs scaling and careful C gamma search. Example: from sklearn.svm import SVC; from sklearn.pipeline import Pipeline; from sklearn.preprocessing import StandardScaler; from sklearn.model_selection import RandomizedSearchCV, StratifiedKFold; from scipy.stats import loguniform; pipe=Pipeline([('sc',StandardScaler()),('svc',SVC(class_weight='balanced',probability=True,random_state=42))]); dist={'svc__C':loguniform(1e-2,1e3),'svc__gamma':loguniform(1e-4,1e-1)}; rs=RandomizedSearchCV(pipe,dist,n_iter=30,cv=StratifiedKFold(5,shuffle=True,random_state=42),scoring='roc_auc',n_jobs=-1,random_state=42); rs.fit(X_train,y_train); print(rs.best_params_). Scale is mandatory for RBF. Use probability True only if needed due to cost. For large N subsample or use LinearSVC SGDClassifier. Plot validation heatmap of C versus gamma to diagnose under overfitting. For production readiness log all metrics parameters and data versions with MLflow record random seeds library versions and data hashes validate performance on holdout test sets check calibration fairness latency and memory usage monitor prediction drift after deployment and document business impact to ensure reliable generalization and maintainable operation for stakeholders."}], "metadata": {"domain": "classical_ml", "task_type": "optimization", "difficulty": "intermediate"}} {"messages": [{"role": "user", "content": "How to benchmark TTS latency versus quality for real-time voice agent?"}, {"role": "assistant", "content": "Measure first-chunk latency under 300ms, RTF below 0.5, and MOS via UTMOS plus human 100 samples across streaming XTTS versus CosyVoice. Test on L4 with TensorRT, batch 1, chunk 20 tokens, and cache speaker embeddings. Sweep temperature and top-p for naturalness, evaluate WER on 500 utterances and speaker similarity cosine over 0.85. Profile GPU versus CPU vocoder bottleneck, enable streaming with 200ms audio chunks, and monitor P95 end-to-end 800ms budget. Require MOS over 4.0 and latency SLO before promotion, A/B test 5 percent live measuring interruption rate. Version voices, log synthesis params, and fallback to cached prompts on overload. This balanced benchmark selects 400ms 4.2 MOS operating point enabling natural turn-taking without expensive A100 overprovisioning for 100 concurrent calls. Add dashboards, alerts, runbooks, versioning, rollback tests, audits, and cost tracking to sustain production reliability."}], "metadata": {"domain": "classical_ml", "task_type": "optimization", "difficulty": "advanced"}} {"messages": [{"role": "user", "content": "How to avoid membership inference from model API returning probabilities?"}, {"role": "assistant", "content": "Return only labels or rounded scores with rate limits to reduce leakage of training membership.\nfrom sklearn.linear_model import LogisticRegression\n# serve: proba.round(2) or label only, throttle per key\n# monitor confidence concentration on train members\nEdge cases: high confidence reveals members. Explainability outputs leak more. Overfitted models leak most, regularize. Logging queries enables abuse detection. Differentially private training bounds risk. Production hardening: validate feature schemas and check for empty inputs. Log class balance and prediction distributions. Pin sklearn versions. Set random_state 42 for reproducibility. Add tests for unseen categories, missing values and single-class edge cases. Monitor drift and calibration over time and document assumptions for reviewers to reproduce results reliably."}], "metadata": {"domain": "classical_ml", "task_type": "security", "difficulty": "intermediate"}} {"messages": [{"role": "user", "content": "Review time-series split using random KFold causing lookahead bias in sales forecasting."}, {"role": "assistant", "content": "Random KFold shuffles future into training, creating lookahead bias and optimistic error. Switch to TimeSeriesSplit n_splits 5 with gap 7 days. Engineer lag and rolling mean features strictly causal. Validate with expanding window backtest. Check stationarity via ADF and difference if needed. Evaluate MAPE and directional accuracy. Log forecast horizon stability. Add test asserting max train date < min val date. Document temporal split. Validate fix with dedicated unit test and integration check covering edge cases. Log relevant metrics, monitor production dashboards continuously, document change clearly in pull request for reviewers and future maintenance work. Include reproducible script, versioned config, seeded runs, ablation results, error analysis table, and follow-up monitoring plan to ensure durable improvement."}], "metadata": {"domain": "classical_ml", "task_type": "code_review", "difficulty": "intermediate"}} {"messages": [{"role": "user", "content": "Debug: OneHotEncoder fails on unseen categories in test set despite working on train. Show robust fix."}, {"role": "assistant", "content": "Default OneHotEncoder errors on unknown categories because test contains new levels. Set handle_unknown to ignore to produce all-zero rows for unseen values. Combine with SimpleImputer for missing strings and verify in Pipeline.\n```python\nimport pandas as pd\nfrom sklearn.preprocessing import OneHotEncoder\nfrom sklearn.compose import ColumnTransformer\nfrom sklearn.pipeline import Pipeline\nfrom sklearn.impute import SimpleImputer\nfrom sklearn.linear_model import Ridge\ncat = ['city', 'plan']\nnum = ['age']\npre = ColumnTransformer([('num', SimpleImputer(strategy='median'), num), ('cat', Pipeline([('imp', SimpleImputer(strategy='most_frequent')), ('oh', OneHotEncoder(handle_unknown='ignore', sparse_output=False))]), cat)])\npipe = Pipeline([('pre', pre), ('m', Ridge())])\npipe.fit(X_train, y_train)\n# simulate unseen\nX_test_unseen = X_test.copy()\nX_test_unseen.loc[X_test_unseen.index[0], 'city'] = 'new_city_xyz'\nprint(pipe.predict(X_test_unseen[:5]))\n```\nTest explicitly with synthetic unseen level, check output width stable, and consider rare category grouping for high cardinality."}], "metadata": {"domain": "classical_ml", "task_type": "debugging", "difficulty": "beginner"}} {"messages": [{"role": "user", "content": "SHAP values take hours on 100k rows with XGBoost. How to speed up explanations for production monitoring?"}, {"role": "assistant", "content": "Use TreeExplainer with approximate algorithm, sample 5k background, and shap values on aggregated daily sample not all rows. Cache explainer, use GPU, and parallelize with joblib. For global importance use gain plus permutation on sample. Monitor drift via PSI on top 10 features not full SHAP. Test runtime under 5m. Precompute for segments. This cuts hours to minutes while retaining actionable insights. Document sampling seed for reproducibility. Efficient monitoring balances fidelity with cost for large scale inference explanation. Track experiments with MLflow logging params metrics and data version, compare cross validated scores with confidence intervals, and review learning curves to distinguish bias from variance before choosing final model for deployment."}], "metadata": {"domain": "classical_ml", "task_type": "optimization", "difficulty": "advanced"}} {"messages": [{"role": "user", "content": "Review RandomForest 10 trees depth None no OOB class_weight imbalance. Improve?"}, {"role": "assistant", "content": "Issues are high variance underfitting and majority bias. Increase n_estimators 300 max_depth 12 min_samples_leaf 5 max_features sqrt. Set class_weight balanced_subsample oob_score True n_jobs minus 1 random_state 42. Validate OOB 0.82 and PR-AUC lift. Tune via RandomizedSearch 30 iter Stratified CV. Monitor feature importances stability. Test calibration via reliability curve. Log OOB vs CV gap. Document compute tradeoff. Prune with ccp_alpha. Ensure stratified split. Result improves generalization recall on minority while controlling overfit and training time for robust production random forest deployment handling imbalanced tabular data. Validate incrementally with minimal reproduction, logging metrics before and after change, adding regression tests and monitoring dashboards for lasting stability and confidence in production."}], "metadata": {"domain": "classical_ml", "task_type": "code_review", "difficulty": "advanced"}} {"messages": [{"role": "user", "content": "Analyze learning curves to decide if we need more data or bigger model."}, {"role": "assistant", "content": "Plot train versus validation versus size. Converged low scores need model capacity, gap needs data or regularization.\nfrom sklearn.datasets import make_classification\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.model_selection import learning_curve\nimport numpy as np\nX,y = make_classification(random_state=42)\ntr,va = learning_curve(LogisticRegression(max_iter=1000),X,y,cv=3,train_sizes=np.linspace(0.2,1.0,4),scoring='f1')\nprint(tr.mean(1), va.mean(1))\nEdge cases: single split noisy, use CV. Imbalanced needs stratify. Leakage shows optimistic both curves. High variance needs repeated splits. Scaling inside pipeline for valid curve. Production hardening: validate feature schemas and check for empty inputs. Log class balance and prediction distributions. Pin sklearn versions. Set random_state 42 for reproducibility. Add tests for unseen categories, missing values and single-class edge cases. Monitor drift and calibration over time and document assumptions for reviewers to reproduce results reliably."}], "metadata": {"domain": "classical_ml", "task_type": "experiment_analysis", "difficulty": "intermediate"}} {"messages": [{"role": "user", "content": "Reduce inference cost for GPT style endpoint by 40 percent via caching, batching, and model routing."}, {"role": "assistant", "content": "Analyze traffic to identify 30 percent repeated system prompts and implement semantic cache with embedding similarity over 0.97 and exact match for templates. Route simple queries to 8B model via intent classifier achieving 80 percent accuracy, reserving 70B for complex reasoning. Enable dynamic batching with max delay 50ms to increase tokens per forward pass. Compress prompts by stripping verbosity and using concise instructions saving 20 percent tokens. Use spot instances for batch workloads and reserved capacity for baseline. Track cost per 1k tokens, cache hit rate, and routing accuracy. A B test routing thresholds to balance quality drop under 2 percent while meeting savings target and document fallback logic."}], "metadata": {"domain": "classical_ml", "task_type": "optimization", "difficulty": "intermediate"}} {"messages": [{"role": "user", "content": "Review PCA applied after split incorrectly reusing fit on test with data leakage in visualization."}, {"role": "assistant", "content": "Fitting PCA on full data leaks test variance into components. Fit PCA only on train, transform test via same object. Choose n_components via 95% variance threshold, plot scree. Standardize before PCA. Validate reconstruction error on test. Use Pipeline scaler+PCA+classifier for CV honesty. Log explained variance ratio. Test transform reproducibility. Avoid interpreting leaked components for feature selection. Validate fix with dedicated unit test and integration check covering edge cases. Log relevant metrics, monitor production dashboards continuously, document change clearly in pull request for reviewers and future maintenance work. Include reproducible script, versioned config, seeded runs, ablation results, error analysis table, and follow-up monitoring plan to ensure durable improvement."}], "metadata": {"domain": "classical_ml", "task_type": "code_review", "difficulty": "intermediate"}} {"messages": [{"role": "user", "content": "Detect fraud rings with heterogeneous graph neural networks."}, {"role": "assistant", "content": "Model accounts devices transactions as heterogeneous graph with metapaths account device account. Use HGT or RGCN with relation specific weights. Label sparse fraud via expert rules and chargebacks with time split. Evaluate PR AUC and Recall at fixed FPR one percent. Compare to XGBoost on flat features to show relational lift. Explain with GNNExplainer subgraphs for investigators. Handle imbalance with focal loss and neighbor sampling. Visualize suspicious clusters. Tune metapath length and hidden dim. Document graph schema and labeling. Deploy batch scoring with case queue. Monitor adversarial adaptation and feedback delay. Validate inductive generalization to unseen nodes and test robustness to edge dropout simulating noisy relations. Record sampler settings seeds and hardware for full reproducibility."}], "metadata": {"domain": "classical_ml", "task_type": "implementation", "difficulty": "advanced"}} {"messages": [{"role": "user", "content": "Amortized inference with normalizing flows for astrophysics posteriors."}, {"role": "assistant", "content": "Train neural spline flow conditioned on telescope spectra to approximate posteriors. Use simulation based inference with 100k simulations. Evaluate calibration via rank histograms and coverage. Compare to MCMC on few examples for accuracy versus 1000x speedup. Visualize corner plots. Handle model misspecification with robustness checks. Tune flow depth and hidden units. Document simulator assumptions. Deploy for real time survey inference. Monitor shift in instrument noise. Update with new physics. Run posterior predictive checks and sensitivity analyses on prior choices to validate uncertainty estimates. Report convergence diagnostics including R-hat and effective sample sizes transparently. Log metrics artifacts and data hashes to enable auditing and consistent comparison across runs."}], "metadata": {"domain": "classical_ml", "task_type": "optimization", "difficulty": "advanced"}} {"messages": [{"role": "user", "content": "Forecast daily store sales for next week using historical sales and weekday features."}, {"role": "assistant", "content": "Create lag features for 7, 14, and 28 days plus rolling means and weekday holiday indicators to capture seasonality. Split chronologically, using last four weeks as validation to respect temporal order. Train gradient boosting or Ridge baseline and compare MAE and RMSE. Handle missing dates by reindexing calendar and forward filling closures appropriately. Scale features inside pipeline and encode store IDs with target encoding using only past data. Plot forecasts versus actuals and residual autocorrelation to diagnose bias. Tune depth and learning rate via time series cross validation. Retrain on full history before forecasting next seven days. Document horizon, metrics, and retraining cadence. Monitor live error and drift in promotions or holidays."}], "metadata": {"domain": "classical_ml", "task_type": "implementation", "difficulty": "beginner"}} {"messages": [{"role": "user", "content": "Fix sklearn API misuse: predict on sparse TF-IDF with StandardScaler(with_mean=True) crashes. Provide correct pipeline."}, {"role": "assistant", "content": "StandardScaler with mean centering densifies sparse matrices causing memory blowup or errors. Use MaxAbsScaler or StandardScaler with with_mean False for sparse TF-IDF, or place scaling only on dense branches. Keep pipeline sparse compatible end to end.\n```python\nfrom sklearn.feature_extraction.text import TfidfVectorizer\nfrom sklearn.preprocessing import MaxAbsScaler\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.pipeline import Pipeline\npipe = Pipeline([('tfidf', TfidfVectorizer(max_features=10000, ngram_range=(1, 2), stop_words='english')), ('scale', MaxAbsScaler()), ('clf', LogisticRegression(max_iter=1000, solver='saga', n_jobs=-1))])\npipe.fit(text_train, y_train)\nprint(pipe.score(text_test, y_test))\n# alternative without scaler\npipe2 = Pipeline([('tfidf', TfidfVectorizer()), ('clf', LogisticRegression(max_iter=1000))])\npipe2.fit(text_train, y_train)\n```\nValidate with sparse input checks, avoid with_mean True on sparse, and test predict on single string wrapped as list. Validate with stratified folds, compare ROC-AUC and PR-AUC, inspect calibration and permutation importance, and persist the full pipeline with versioned splits for reproducible deployment and drift monitoring."}], "metadata": {"domain": "classical_ml", "task_type": "api_debugging", "difficulty": "beginner"}} {"messages": [{"role": "user", "content": "Implement uplift modeling with two-learner XGB and propensity clipping for marketing targeting evaluation."}, {"role": "assistant", "content": "Estimate heterogeneous treatment effects by training separate outcome models for treated and control populations, clipping extreme propensity scores for stability, and ranking customers by predicted incremental benefit. Split randomized experiment data into treatment and control cohorts, fit calibrated XGB regressors per group with cross validated hyperparameters, estimate propensities with logistic model, clip weights to fifth and ninety fifth percentiles, compute uplift as treated prediction minus control prediction, and evaluate with Qini curves and uplift at top deciles. Validate unconfoundedness assumptions, check covariate balance, compare against single S-learner baseline, analyze segment level gains, monitor targeting fairness across demographics, test sensitivity to clipping thresholds, document business impact in incremental revenue, and ensure reproducible pipelines for campaign optimization decisions."}], "metadata": {"domain": "classical_ml", "task_type": "optimization", "difficulty": "intermediate"}} {"messages": [{"role": "user", "content": "Explain PCA versus LDA for dimensionality reduction in simple terms with usage guidance."}, {"role": "assistant", "content": "PCA is unsupervised and finds directions of maximum variance without using labels, ideal for compression, denoising, and visualization. It centers data, computes covariance eigendecomposition, and projects onto top components ranked by explained_variance_ratio_. LDA is supervised and finds directions maximizing class separation, ideal for classification preprocessing when labels exist. LDA assumes Gaussian classes with shared covariance and fails if n_features exceeds samples without shrinkage. Use PCA before clustering or when labels are unavailable, and standardize first because both are scale sensitive. Use LDA with solver lsqr and shrinkage auto for small samples. Evaluate PCA with cumulative variance plot and LDA with cross-validated accuracy. Set random_state 42 for SVD solver randomized. Choose component count by 95 percent variance for PCA and classes minus one for LDA to ensure meaningful low dimensional representations today."}], "metadata": {"domain": "classical_ml", "task_type": "instruction", "difficulty": "beginner"}} {"messages": [{"role": "user", "content": "Secure a RAG system handling confidential HR docs with access control and audit trails."}, {"role": "assistant", "content": "Enforce authentication via SSO and map groups to document ACLs indexed as metadata filters. Apply filters at retrieval time and post filter with policy engine to prevent cross tenant leakage. Encrypt vectors and source docs at rest with KMS and TLS in transit. Redact PII in logs and store only hashes for analytics. Implement query audit table with user, timestamp, and accessed doc IDs retained per compliance. Test with adversarial users attempting to access unauthorized namespaces measuring zero leakage. Add DLP scanner blocking bulk exfiltration and rate limiting. Regularly review permissions, rotate keys, and conduct penetration tests covering prompt injection aimed at privilege escalation."}], "metadata": {"domain": "classical_ml", "task_type": "security", "difficulty": "intermediate"}} {"messages": [{"role": "user", "content": "My accuracy is 95% but model predicts only majority class. Debug this imbalance trap."}, {"role": "assistant", "content": "Accuracy misleads on skewed data. Check confusion matrix, recall and balanced metrics instead.\nfrom sklearn.dummy import DummyClassifier\nfrom sklearn.metrics import confusion_matrix, classification_report\nfrom sklearn.datasets import make_classification\nX,y = make_classification(weights=[0.95], random_state=42)\nclf = DummyClassifier(strategy='most_frequent')\nclf.fit(X,y)\nprint(confusion_matrix(y, clf.predict(X)))\nprint(classification_report(y, clf.predict(X)))\nEdge cases: stratify split to preserve minority. Resampling only on train to avoid leakage. Precision recall tradeoff needs threshold tuning. Small minority causes high variance, use repeated CV. Production hardening: validate feature schemas and check for empty inputs. Log class balance and prediction distributions. Pin sklearn versions. Set random_state 42 for reproducibility. Add tests for unseen categories, missing values and single-class edge cases. Monitor drift and calibration over time and document assumptions for reviewers to reproduce results reliably."}], "metadata": {"domain": "classical_ml", "task_type": "debugging", "difficulty": "beginner"}} {"messages": [{"role": "user", "content": "Propose model registry and rollback architecture for logistic regression service."}, {"role": "assistant", "content": "Version data, code and params with champion challenger routing and automated rollback on metric drop.\nimport joblib\nfrom sklearn.linear_model import LogisticRegression\nmodel = LogisticRegression(max_iter=1000)\n# model.fit(Xtr,ytr); joblib.dump(model, 'model_v2.pkl')\n# registry promotes after shadow test\nEdge cases: incompatible sklearn version breaks load, pin. Feature pipeline must version together. Rollback needs instant traffic switch. Shadow scoring doubles cost, sample. Audit logs for compliance. Production hardening: validate feature schemas and check for empty inputs. Log class balance and prediction distributions. Pin sklearn versions. Set random_state 42 for reproducibility. Add tests for unseen categories, missing values and single-class edge cases. Monitor drift and calibration over time and document assumptions for reviewers to reproduce results reliably."}], "metadata": {"domain": "classical_ml", "task_type": "architecture", "difficulty": "intermediate"}} {"messages": [{"role": "user", "content": "Engineer recursive prompting for autonomous software refactoring across 100k line codebase."}, {"role": "assistant", "content": "Decompose codebase into module dependency graph, prioritize leaf modules for bottom up refactoring. Prompt architect to propose interfaces, then worker to rewrite files with tests, then critic to verify behavior preservation via test execution and diff review. Iterate up to three rounds per module with context window managed via summaries and vector retrieval of related files. Enforce style guides and API compatibility checks in prompt constraints. Track progress in task DB with checksums and rollback points. Evaluate with test pass rate, cyclomatic complexity reduction, and performance benchmarks. Implement human approval for core API changes. Log token cost per module and optimize via caching and smaller models for routine transforms."}], "metadata": {"domain": "classical_ml", "task_type": "instruction", "difficulty": "expert"}} {"messages": [{"role": "user", "content": "Engineer target-encoded categoricals for click prediction without leakage."}, {"role": "assistant", "content": "Use K-fold out of fold target encoding for high cardinality IDs like publisher and device. Apply smoothing with min_samples_leaf 100 to shrink noisy rare categories toward global mean. Add count features as complementary signals. Validate with time split optimizing log loss and calibration. Compare to one-hot and hashing baselines on memory and performance. Handle unseen categories by fallback to global mean at inference. Check for leakage by ensuring encodings use only training folds. Visualize encoding stability across folds. Combine with gradient boosting handling missing natively. Document mapping persistence and update cadence. Monitor category drift and PSI. Test impact of smoothing parameter via ablation to balance bias variance."}], "metadata": {"domain": "classical_ml", "task_type": "implementation", "difficulty": "intermediate"}} {"messages": [{"role": "user", "content": "Automate compliance deployment gates for EU AI Act high risk systems with evidence collection."}, {"role": "assistant", "content": "Encode requirements for risk assessment, data governance, and human oversight as OPA rules in CI. Collect evidence including eval reports, bias tests, and data cards automatically on each release. Block deployment if accuracy disparity exceeds threshold or documentation missing. Store signed attestations in immutable ledger with model hash. Generate technical documentation PDF and conformity declaration. Integrate with Jira for risk review approvals and notify legal on changes. Schedule post market monitoring jobs tracking incidents and performance. Provide auditor dashboard with traceability from requirement to test result. Version policies as law evolves and support rollback to last compliant release within minutes."}], "metadata": {"domain": "classical_ml", "task_type": "implementation", "difficulty": "expert"}} {"messages": [{"role": "user", "content": "Why does my random forest overfit with 500 deep trees? How to regularize?"}, {"role": "assistant", "content": "Deep unpruned trees memorize noise even bagged. Limit depth, leaves and require samples per split.\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.model_selection import cross_val_score\nfrom sklearn.datasets import make_classification\nX,y = make_classification(random_state=42)\nfor d in [None,8,5]:\n m = RandomForestClassifier(n_estimators=200, max_depth=d, min_samples_leaf=5, random_state=42, n_jobs=-1)\n print(d, cross_val_score(m,X,y,cv=3).mean())\nEdge cases: too shallow underfits. Imbalanced needs class_weight. Many noisy features need max_features tuning. OOB score validates without extra split. Large n_estimators rarely overfits, depth does. Production hardening: validate feature schemas and check for empty inputs. Log class balance and prediction distributions. Pin sklearn versions. Set random_state 42 for reproducibility. Add tests for unseen categories, missing values and single-class edge cases. Monitor drift and calibration over time and document assumptions for reviewers to reproduce results reliably."}], "metadata": {"domain": "classical_ml", "task_type": "debugging", "difficulty": "intermediate"}} {"messages": [{"role": "user", "content": "Write pytest for SMOTE oversampler ensuring shape balance and determinism invariants hold."}, {"role": "assistant", "content": "Custom samplers must preserve feature dimensions and increase minority count plus remain deterministic under seed. Test fit resample contracts and idempotence for pipeline safety in production. Code:\n```python\nimport numpy as np\nfrom imblearn.over_sampling import SMOTE\ndef test_smote_invariants():\n rng = np.random.RandomState(0)\n X = rng.randn(100, 5)\n y = np.array([0]*90 + [1]*10)\n Xs, ys = SMOTE(random_state=42, k_neighbors=3).fit_resample(X, y)\n assert Xs.shape[1] == 5\n assert (ys == 1).sum() == (ys == 0).sum()\n assert len(ys) > len(y)\n Xs2, ys2 = SMOTE(random_state=42, k_neighbors=3).fit_resample(X, y)\n assert np.allclose(Xs, Xs2)\n```\nAlso assert no NaNs introduced and original majority rows retained. Test inside imbalanced Pipeline with StandardScaler preceding sampler for correct order."}], "metadata": {"domain": "classical_ml", "task_type": "testing", "difficulty": "intermediate"}} {"messages": [{"role": "user", "content": "Design fraud system with 0.1 percent positives, 10ms inference, concept drift, adversarial attacks. What expert architecture wins?"}, {"role": "assistant", "content": "Deploy layered ensemble with real time LightGBM on engineered velocity features plus graph embeddings, calibrated threshold maximizing recall at 1 percent FPR, fallback rules for cold start. Serve via ONNX with 5ms p99, Kafka streaming, Feast online store. Monitor PSI, label delay feedback with active learning, adversarial validation detecting shift. Use cost sensitive learning 100 to 1, monotonic constraints, challenger champion A/B. Audit with counterfactuals. Test with backtesting and red team evasion. This expert design meets latency, handles imbalance and drift, and resists gaming via behavior features and rapid retraining pipeline. Track experiments with MLflow logging params metrics and data version, compare cross validated scores with confidence intervals, and review learning curves to distinguish bias from variance before choosing final model for deployment."}], "metadata": {"domain": "classical_ml", "task_type": "architecture", "difficulty": "expert"}} {"messages": [{"role": "user", "content": "How do I version prompts and indexes for LlamaIndex production deploys?"}, {"role": "assistant", "content": "Store prompt templates in git with semantic versioning, hash ServiceContext config and embedding model IDs into index manifest, persist indexes to versioned S3 prefix like indexes v42, deploy query service referencing manifest, implement blue green switch after eval passes, handle rollback by pointing to previous manifest, log prompt version per request, test compatibility between prompts and index versions, automate build pipeline with DVC, document release notes, monitor metrics per version, enforce migration tests, secure artifact storage, implement retention for old versions, validate reproducibility by rebuilding from commit, train team on release process and audit changes for compliance and debugging efficiency. Ongoing governance requires versioned configs, automated regression tests, monitored latency dashboards, and quarterly security reviews for durability and compliance."}], "metadata": {"domain": "llamaindex", "task_type": "implementation", "difficulty": "intermediate"}} {"messages": [{"role": "user", "content": "My OpenAIAgent fails with tool calling loop repeating the same call. How to fix?"}, {"role": "assistant", "content": "Repeated tool calls indicate the agent does not recognize tool output as sufficient, often due to poor tool return formatting or unclear instructions. Return concise structured strings, not huge raw JSON, and include a completion hint like final inventory count is 5. Add a system prompt stating when to stop and synthesize. Check that function schema uses simple types; nested objects confuse function calling. Reduce max_function_calls and add verbose logging to see observations. Another cause is temperature too high causing inconsistent reasoning. Set temperature zero for tool selection. If loop persists, add a guard tool that summarizes progress. Evaluate by running the failing task five times and checking for termination. Clear tool descriptions plus explicit stop criteria usually break the loop quickly."}], "metadata": {"domain": "llamaindex", "task_type": "debugging", "difficulty": "intermediate"}} {"messages": [{"role": "user", "content": "Implement secure multi-tenant router with tenant-aware metadata enforcement and audit."}, {"role": "assistant", "content": "Build router where each QueryEngineTool is wrapped with tenant filter injection, not trusting user input. Middleware adds MetadataFilters with tenant_id equals authenticated user tenant before retrieval. Router selector sees only allowed tools per tenant. Add audit logging of selector choice, filters, and accessed doc IDs. Prevent prompt injection from cross-tenant docs by namespacing indexes per tenant plus filter defense in depth. Test with forged tenant_id in query metadata to ensure override blocked. Review code for shared caches leaking across tenants. Use Pydantic validation for tenant context. Expert challenge is balancing latency with per-tenant retrievers; use connection pooling and lazy engine init. Security plus correctness testing is mandatory before launch."}], "metadata": {"domain": "llamaindex", "task_type": "security", "difficulty": "expert"}} {"messages": [{"role": "user", "content": "How do I debug empty retrieval in LlamaIndex when index has data?"}, {"role": "assistant", "content": "Verify document count via docstore and vector count. Check embedding model mismatch between ingest and query causing zero similarity. Inspect filters: overly strict metadata excludes all. Test with top_k 10 and similarity cutoff disabled. Print query embedding norm and sample node embeddings. Ensure storage context persisted and reloaded correctly, not empty in-memory. Check tokenizer truncation of long queries. Disable reranker temporarily to isolate. Log retrieval scores; all very low suggests model or chunking issue. Reproduce with minimal two docs. Fix by aligning embed models, relaxing filters, and rebuilding index. Add health check asserting retrieval non-empty on canary query in CI. Systematic checks resolve most empty results quickly."}], "metadata": {"domain": "llamaindex", "task_type": "debugging", "difficulty": "intermediate"}} {"messages": [{"role": "user", "content": "Implement LlamaIndex fine-tuned retriever with generated QA pairs and embedding adapter training."}, {"role": "assistant", "content": "Generate 2000 synthetic QA pairs from corpus using LLM with diverse question types. Split 80 10 10 for train validation test. Train embedding adapter with contrastive loss using hard negatives from BM25 misses. Integrate fine-tuned model via custom embedding class in LlamaIndex Settings. Evaluate recall at 3 improving from 0.68 to target 0.82. Handle overfitting with early stopping and cross validation. Version datasets and model checkpoints in MLflow. Automate retraining on monthly doc updates. Document compute cost and data generation prompts. Compare to base BGE performance with statistical significance. Deploy behind feature flag with shadow scoring. Provide rollback to base embeddings if production faithfulness regresses during A B test on live traffic samples."}], "metadata": {"domain": "llamaindex", "task_type": "implementation", "difficulty": "advanced"}} {"messages": [{"role": "user", "content": "How do I create a query engine with similarity_top_k tuning?"}, {"role": "assistant", "content": "Build index from documents, call as_query_engine with similarity_top_k 5, response_mode refine, streaming False for initial tests, issue representative queries covering factual and inferential cases, measure context precision and answer faithfulness manually, increase top_k to 10 if recall is low and observe latency impact, decrease to 3 if context is noisy, add NodePostprocessor for score threshold filtering, log retrieved node scores for analysis, cache frequent queries in memory, validate temperature settings for consistency, handle no-results with fallback message, secure keys, document optimal top_k per dataset, automate sweep with simple Python loop recording metrics, persist best configuration to config file for deployment consistency and future regression testing across releases. Ongoing governance requires versioned configs, automated regression tests, monitored latency dashboards, and quarterly security reviews for durability and compliance."}], "metadata": {"domain": "llamaindex", "task_type": "optimization", "difficulty": "beginner"}} {"messages": [{"role": "user", "content": "How do I integrate Qdrant vector store with LlamaIndex with metadata filtering and hybrid search?"}, {"role": "assistant", "content": "Install llama-index-vector-stores-qdrant and create QdrantClient with url and api_key. Instantiate QdrantVectorStore collection_name docs, with hybrid True if using sparse vectors. Build StorageContext.from_defaults vector_store store, then VectorStoreIndex nodes with embed_model. For hybrid, configure FastEmbed sparse model and set query_mode hybrid in retriever. Pass MetadataFilters for tenant isolation; Qdrant translates them to payload filters efficiently. Tune similarity_top_k 10 and sparse_top_k 10, then fuse with alpha 0.5. Persist collection on managed Qdrant Cloud for production, use in-memory for tests. Monitor latency and recall with retrieval evaluation. Handle dimension changes by recreating collection. This setup gives strong keyword plus semantic recall for technical docs with codes and product names."}], "metadata": {"domain": "llamaindex", "task_type": "implementation", "difficulty": "intermediate"}} {"messages": [{"role": "user", "content": "Design evaluator ensemble for regulated QA requiring citations, faithfulness, and correctness."}, {"role": "assistant", "content": "Combine FaithfulnessEvaluator, CorrectnessEvaluator, and custom citation precision check in ensemble. Run BatchEvalRunner with all three, then aggregate with weighted rule: fail if any critical check fails, not average. Citation check uses regex to verify every factual sentence has source ID present in retrieved nodes. Correctness compares to gold answer with rubric. Faithfulness verifies grounding. Require human review on borderline scores. Version evaluator prompts and models for audit. Common pitfall is averaging scores hiding citation failures. Instead enforce gating. Test ensemble on adversarial cases with correct answer but missing cites. Log full traces for compliance. This rigorous design suits finance or healthcare where unsupported answers carry significant risk beyond simple relevance."}], "metadata": {"domain": "llamaindex", "task_type": "testing", "difficulty": "expert"}} {"messages": [{"role": "user", "content": "What is the ReAct agent pattern in LlamaIndex and when should I avoid it?"}, {"role": "assistant", "content": "ReAct interleaves reasoning traces with tool actions, letting the LLM think, act, and observe in loops. In LlamaIndex, ReActAgent selects tools like query engines or APIs, executes them, and reasons over outputs until answering. It suits open-ended tasks requiring multi-step retrieval, calculations, or branching logic. Avoid it for simple single-hop QA where a query engine is faster and cheaper, since ReAct adds latency and token overhead. It also struggles with strict schemas, high compliance needs, or deterministic workflows; use function-calling agents or Workflows instead. Mitigate loops with max_iterations, clear tool descriptions, and structured outputs. Evaluate task success rate, tool precision, and cost per task. For production, add guardrails, human approval for side effects, and fallback to direct retrieval when confidence is high."}], "metadata": {"domain": "llamaindex", "task_type": "instruction", "difficulty": "intermediate"}} {"messages": [{"role": "user", "content": "How do I evaluate RAG faithfulness in LlamaIndex using FaithfulnessEvaluator?"}, {"role": "assistant", "content": "Use FaithfulnessEvaluator to check if generated answers are grounded in retrieved context. After running a query_engine.query, pass query string, response object, and contexts from response.source_nodes into evaluator.evaluate. It uses an LLM to decompose the answer into claims and verify each against context, returning passing boolean plus feedback. Wrap in batch with asyncio for multiple queries, set llm to gpt-4o for reliable judgments even if generation uses a cheaper model. Store results with query, contexts, score, and feedback for regression tracking. Combine with RelevancyEvaluator to catch fluent but off-topic answers. A common pattern is to run evaluation nightly on a golden set of 30 queries and alert if pass rate drops below threshold after index or prompt changes."}], "metadata": {"domain": "llamaindex", "task_type": "testing", "difficulty": "beginner"}} {"messages": [{"role": "user", "content": "Implement LlamaIndex response synthesizer with citation requirements"}, {"role": "assistant", "content": "Use compact refine or tree summarize with explicit QA template demanding citations. This grounds answers and eases verification. Example:\n\nfrom llama_index.core import get_response_synthesizer\nfrom llama_index.core.prompts import PromptTemplate\nQA_TMPL='Context list here. Answer using only context. Cite as filename page. If unknown say unknown. Query here.'\nsynth=get_response_synthesizer(response_mode='compact', text_qa_template=PromptTemplate(QA_TMPL), use_async=True)\nengine=index.as_query_engine(response_synthesizer=synth, similarity_top_k=5)\nprint(engine.query('refund window'))\nValidate citations post hoc checking cited node IDs exist in source nodes. Strip unmatched citations to catch hallucinations. Log citation precision metric. For long contexts use refine with streaming to stay within limits. Test refusal when context empty to ensure no invented sources. Validate on staging and monitor dashboards before production."}], "metadata": {"domain": "llamaindex", "task_type": "implementation", "difficulty": "intermediate"}} {"messages": [{"role": "user", "content": "Build LlamaIndex RAG with Chroma vector store, persistent client, and hybrid metadata filtering for product docs."}, {"role": "assistant", "content": "Initialize Chroma persistent client at ./chroma_db with collection product_docs and cosine space. Configure OpenAI embeddings text-embedding-3-small and SentenceSplitter 512 tokens with 50 overlap. Create ChromaVectorStore and StorageContext, then build VectorStoreIndex from product markdown files. Define metadata fields version, locale, and category for filtering. Build retriever with similarity_top_k 6 and query engine with MetadataFilters for version equals 2. Enable response synthesizer compact mode with citations. Add ingestion pipeline with duplicate detection via document hashes. Test filtered versus unfiltered recall. Persist index and validate reload. Instrument query latency and token usage. Handle collection reset safely with backup before deletion in development environments."}], "metadata": {"domain": "llamaindex", "task_type": "implementation", "difficulty": "intermediate"}} {"messages": [{"role": "user", "content": "How do I write a basic test for a LlamaIndex query engine to check it returns source nodes?"}, {"role": "assistant", "content": "Write a test that builds a tiny in-memory index from 3 to 5 synthetic documents, queries it, and asserts response source nodes exist. Use VectorStoreIndex.from_documents with a mock or cheap embedding, then query_engine equals index.as_query_engine with similarity_top_k 2. Assert response is not None, response.response is non-empty, and len response.source_nodes is greater than zero. Also assert query string appears related to expected content. Avoid hitting real OpenAI in unit tests by injecting a MockLLM and MockEmbedding from LlamaIndex test utilities. Add a second test for empty index behavior. Keep tests fast and deterministic with fixed documents. This guards against regressions in retriever config, synthesizer changes, and Settings overrides across refactors."}], "metadata": {"domain": "llamaindex", "task_type": "testing", "difficulty": "beginner"}} {"messages": [{"role": "user", "content": "Deploy a minimal LlamaIndex query API with FastAPI for internal use."}, {"role": "assistant", "content": "Build a FastAPI service that loads a persisted LlamaIndex StorageContext at startup and exposes a POST query endpoint accepting question and top_k parameters. Initialize VectorStoreIndex and query engine once as singletons to avoid reloading embeddings per request. Add request validation with Pydantic, basic API key authentication, and CORS restricted to internal domains. Implement async handling with run_in_threadpool for blocking retrieval calls and set timeouts to prevent hanging. Add health and readiness endpoints checking index load status and vector store connectivity. Containerize with Docker, pin dependencies, and configure environment variables for model keys and index paths. Include structured logging of queries, latency, and errors plus Prometheus metrics for request counts to support initial monitoring."}], "metadata": {"domain": "llamaindex", "task_type": "implementation", "difficulty": "beginner"}} {"messages": [{"role": "user", "content": "Implement LlamaIndex sub-question query engine for complex research questions."}, {"role": "assistant", "content": "Configure SubQuestionQueryEngine with QueryEngineTools for each corpus, providing detailed descriptions to guide decomposition. Set LLM to GPT-4 class for planning and a cheaper model for synthesis to control cost. Limit subquestions to four per query to avoid explosion. Implement async execution of subqueries with timeout handling and partial result synthesis on failures. Add citations per sub-answer aggregating into final response. Cache subquestion results keyed by normalized text. Evaluate decomposition quality by human rating on 30 complex queries. Log full decomposition traces for transparency. Provide UI showing intermediate steps so users trust multi-hop answers. Tune prompts to avoid redundant subquestions and ensure coverage of all query aspects efficiently."}], "metadata": {"domain": "llamaindex", "task_type": "implementation", "difficulty": "intermediate"}} {"messages": [{"role": "user", "content": "Build expert-level multi-step query engine that retries with broader retrieval on low confidence."}, {"role": "assistant", "content": "Design custom MultiStepQueryEngine with confidence check after initial synthesis. First query with top_k 4 and evaluate response via RelevancyEvaluator or self-check prompt. If score below threshold, retry with top_k 10 plus query rewriting and hybrid fusion. Implement as wrapper around RetrieverQueryEngine with loop and max_retries 2. Cache first attempt to avoid duplicate embedding cost. Log retry rate to tune threshold; too sensitive causes cost blowup. Add fallback message when both attempts low. Test on hard queries where initial retrieval misses due to paraphrase. This adaptive pattern improves robustness over static top_k. Ensure observability distinguishes initial versus retry paths for experiment analysis and latency monitoring in production."}], "metadata": {"domain": "llamaindex", "task_type": "architecture", "difficulty": "expert"}} {"messages": [{"role": "user", "content": "Implement custom response synthesizer that enforces citations per sentence in LlamaIndex."}, {"role": "assistant", "content": "Subclass BaseSynthesizer or wrap Refine with custom text_qa_template requiring citation after each sentence like [source 1]. Provide node IDs in prompt context and instruct model to cite only provided IDs. Add postprocessor that validates citation regex and retries without citation if missing. Ensure nodes carry doc_id and page metadata for meaningful cites. Test on multi-source questions where synthesis must combine facts. Pitfall is overly strict citation causing verbose or refused answers; allow uncited transitional sentences. Evaluate with FaithfulnessEvaluator plus manual citation precision check. Log prompts to verify IDs are injected correctly. Custom synthesizer gives auditability for regulated domains but increases token use, so cache templates and limit top_k to 5 for balance."}], "metadata": {"domain": "llamaindex", "task_type": "implementation", "difficulty": "advanced"}} {"messages": [{"role": "user", "content": "How do I get started with LlamaIndex for Q and A over my PDFs?"}, {"role": "assistant", "content": "Install llamaindex, choose an embedding model and LLM, then load PDFs with SimpleDirectoryReader. Configure chunking with SentenceSplitter at 512 tokens and 50 overlap to preserve context. Build a VectorStoreIndex from documents and persist the storage context to disk. Create a query engine with similarity top_k five and response mode compact. Start with basic queries, inspect retrieved nodes with source text to verify relevance. Add metadata like filename and page to enable citations. Evaluate on ten representative questions before tuning. For improvement, adjust chunk size, add a reranker, or switch embeddings. Keep API keys in env vars, cache indexes to avoid re-embedding, and log latency plus retrieved IDs for debugging. This minimal loop gives a working baseline you can iterate on."}], "metadata": {"domain": "llamaindex", "task_type": "instruction", "difficulty": "beginner"}} {"messages": [{"role": "user", "content": "LlamaIndex query slow at 4s with top_k 30. How to speed up?"}, {"role": "assistant", "content": "Lower top_k to 8 and add reranker over 20 instead of 30 to cut LLM context. Switch to compact response mode and stream tokens. Use smaller embedding batch and HNSW index with ef_search 64 for speed. Enable async query and cache embeddings in Redis. Pre-filter by metadata to shrink search space. Move to persistent vector store with proper indexes, not in-memory. Profile retrieval versus synthesis: often synthesis dominates, so truncate context to 3000 tokens. Use faster LLM for draft plus larger for final only if needed. Measure p50 p95 after each change on 50 queries. These tweaks typically drop latency from 4s to under 1s while preserving answer quality within eval tolerance."}], "metadata": {"domain": "llamaindex", "task_type": "optimization", "difficulty": "intermediate"}} {"messages": [{"role": "user", "content": "How do I set up SubQuestionQueryEngine in LlamaIndex to break a complex question into sub-questions across two query engines?"}, {"role": "assistant", "content": "Use SubQuestionQueryEngine to decompose complex questions and route sub-questions to different query engine tools. First build two indexes, for example a vector index for product docs and another for pricing docs, then wrap each in a QueryEngineTool with a clear description. Pass the tools to SubQuestionQueryEngine.from_defaults with an LLM for decomposition. The common mistake is vague tool descriptions, which causes misrouting, so describe scope, content type, and when to use each tool explicitly. Set verbose True during development to inspect generated sub-questions and answers. For synthesis, the engine combines partial answers, so instruct the LLM to cite sources. Test with a multi-hop question and verify both engines were called by checking the source nodes in the response metadata."}], "metadata": {"domain": "llamaindex", "task_type": "instruction", "difficulty": "beginner"}} {"messages": [{"role": "user", "content": "Traceback: TypeError: QueryEngineTool missing required metadata in LlamaIndex Workflows migration."}, {"role": "assistant", "content": "Newer LlamaIndex requires ToolMetadata with name and description explicitly. Old code passing query_engine directly without metadata now fails validation. Fix by wrapping as QueryEngineTool query_engine engine, metadata ToolMetadata name finance_qa description use for revenue questions. Update imports from llama_index.core.tools. Check workflow step signatures expecting BaseTool. Run migration script to add metadata to all tools. Pin versions and read changelog for breaking changes. Test tool resolution with agent.from_tools. Ensure names are unique and lowercase with underscores. Add Pydantic validation in CI to catch missing fields early. Clear pip cache if old package shadows new. This strictness improves routing accuracy by forcing clear tool descriptions."}], "metadata": {"domain": "llamaindex", "task_type": "traceback", "difficulty": "advanced"}} {"messages": [{"role": "user", "content": "Design a basic LlamaIndex RAG pipeline for PDF manuals that answers employee questions with citations."}, {"role": "assistant", "content": "Build a RAG pipeline using LlamaIndex VectorStoreIndex with SimpleDirectoryReader for PDFs and SentenceSplitter with chunk size 512 and overlap 50 to preserve context. Use HuggingFace or OpenAI embeddings with batch size 32 and store vectors in a persistent Chroma or Qdrant collection. Configure a retriever with similarity top_k 4 and a response synthesizer in compact mode that requires citation of source filename and page. Add a system prompt instructing concise answers and explicit fallback when context is insufficient. Enable CallbackManager to log retrieval scores and latency. Evaluate on 30 representative questions checking faithfulness and citation accuracy. Persist the storage context to disk so restarts avoid reindexing and document the ingestion script for maintainability."}], "metadata": {"domain": "llamaindex", "task_type": "architecture", "difficulty": "beginner"}} {"messages": [{"role": "user", "content": "LlamaIndex chatbot persists chat history without encryption, risking PII leak on disk. How to secure storage with low overhead?"}, {"role": "assistant", "content": "Plaintext chat files expose conversations if disk or backup leaks to unauthorized parties. Encrypt at rest using Fernet with KMS managed key and per user data key wrapped by master for isolation. Store only last 20 turns, redacting PII before persistence to minimize sensitivity. Set file permissions 0600 and separate directory per tenant. Enable Postgres pgcrypto or encrypted volume for database backend. Implement retention auto delete after 30 days and user export delete API for GDPR compliance. Test decryption failure handling returning safe empty history. Audit access logs for history reads. Measure latency overhead under 10ms to confirm negligible impact. Rotate keys annually with reencryption job. This protects history while maintaining personalization and meeting regulatory requirements for conversational AI systems."}], "metadata": {"domain": "llamaindex", "task_type": "security", "difficulty": "expert"}} {"messages": [{"role": "user", "content": "Implement LlamaIndex agent with memory, streaming, and tool timeouts for customer support automation."}, {"role": "assistant", "content": "Build ReActAgent from_tools with QueryEngineTool for knowledge base and FunctionTool for ticket creation. Configure ChatMemoryBuffer token limit 4000 with summarization for long threads. Enable streaming via agent.stream_chat for token UX. Set tool timeout 15 seconds with retry once and fallback message. Add system prompt enforcing grounding and escalation on low confidence. Instrument tool latency and success rate. Handle concurrent sessions with per user memory isolation. Test multi-turn scenarios with context carryover. Add guardrail blocking PII in tool inputs. Deploy with async FastAPI and queue for burst traffic. Document cost per resolution and human handoff triggers when agent loops exceed five iterations without answer."}], "metadata": {"domain": "llamaindex", "task_type": "architecture", "difficulty": "advanced"}} {"messages": [{"role": "user", "content": "Explain blue-green deployment for LlamaIndex index updates with zero downtime."}, {"role": "assistant", "content": "Maintain two Qdrant collections labeled blue and green, with router pointing queries to active one. Build new index offline in inactive collection from updated documents, running evaluation to verify quality before switch. Use versioned storage contexts and atomic alias update to flip traffic instantly. Keep old collection for quick rollback for 24 hours. Warm caches and embedding services before cutover. Monitor error rates and latency during switch with automated rollback on SLO breach. Script the process with checks for document counts and sample query diffs. Document runbook with commands for promotion and rollback. Schedule updates during low traffic and notify stakeholders of version changes to ensure safe continuous delivery."}], "metadata": {"domain": "llamaindex", "task_type": "implementation", "difficulty": "intermediate"}} {"messages": [{"role": "user", "content": "Build LlamaIndex document agent for hierarchical retrieval over manuals"}, {"role": "assistant", "content": "For thousand page manuals use DocumentAgent with per doc summaries plus chunk retrievers avoiding scanning everything. Example imports DocumentAgent OpenAI building agent verbose true querying calibration question. Build top summary index routing then delegate chapter agents. Cache summaries aggressively. Evaluate eighty section queries measuring time versus flat retrieval where hierarchical cuts latency thirty percent large docs. Log agent steps debugging misrouting. Limit depth two bounding cost. Validate on staging with realistic traffic, monitor dashboards for regressions, document version changes, and require human review before promoting agent changes to production for safety and quality. This pattern handles massive technical documentation effectively."}], "metadata": {"domain": "llamaindex", "task_type": "implementation", "difficulty": "advanced"}} {"messages": [{"role": "user", "content": "Optimize LlamaIndex query latency from 4 seconds to under 1 second for interactive chatbot."}, {"role": "assistant", "content": "Profile latency splitting embedding, retrieval, rerank, and synthesis stages using callbacks and OpenTelemetry spans. Cache query embeddings for repeated questions with Redis TTL 1 hour. Reduce similarity_top_k from 10 to 4 and switch response synthesizer to compact with gpt-4o-mini. Move to smaller embedding model and precompute document embeddings offline. Use async query engine with asyncio gather for parallel reranking. Enable streaming to improve perceived latency. Add vector index HNSW parameters ef_search 64 for speed recall tradeoff. Deploy index on SSD persistent volume and warm up on startup. Load test with 50 concurrent users measuring p50 p95. Document configuration changes and rollback plan if quality drops below faithfulness threshold in production traffic."}], "metadata": {"domain": "llamaindex", "task_type": "optimization", "difficulty": "intermediate"}} {"messages": [{"role": "user", "content": "Evaluate LlamaIndex RAG robustness to adversarial queries, jailbreaks, and poisoned documents."}, {"role": "assistant", "content": "Create red team set with prompt injections in documents, conflicting instructions, and disallowed requests. Test query engine with system prompt enforcing ignore embedded instructions and cite sources. Measure attack success rate, faithfulness drop, and refusal correctness. Implement input sanitization stripping markdown links with suspicious URLs. Add output filter checking for PII and policy violations. Test metadata provenance to identify poisoned source. Evaluate reranker resilience to keyword stuffing. Log all flagged interactions for review. Recommend allowlist for tool actions and human review for high risk answers. Document residual risks and incident response for data poisoning including index rollback, source quarantine, and rebuild verification before re-enabling public access."}], "metadata": {"domain": "llamaindex", "task_type": "experiment_analysis", "difficulty": "advanced"}} {"messages": [{"role": "user", "content": "Debug LlamaIndex import error for OpenAIEmbedding and no module named llama_index.embeddings issue."}, {"role": "assistant", "content": "This error usually comes from version mismatch between llama-index core and integration packages. Check installed versions with pip show llama-index and ensure llama-index-embeddings-openai matches core version. Uninstall legacy llama_index package if both old and new namespaces exist. Use from llama_index.embeddings.openai import OpenAIEmbedding for recent versions, not llama_index.embeddings. Verify Python 3.10 plus and virtual environment isolation. Clear pip cache and reinstall with pip install llama-index-core llama-index-embeddings-openai. Set OPENAI_API_KEY before import test. Run minimal reproduction script loading one document. Check for conflicting openai library versions. Document pinned versions in requirements to prevent recurrence across developer machines and continuous integration pipelines. Ensure pinned versions are committed and CI validates imports on clean images."}], "metadata": {"domain": "llamaindex", "task_type": "debugging", "difficulty": "beginner"}} {"messages": [{"role": "user", "content": "Why does metadata filter with operator IN fail on array metadata in LlamaIndex?"}, {"role": "assistant", "content": "IN operator semantics vary by vector store; some expect scalar field while array needs contains logic. Check store docs: for array tags, use contains or overlap operator, not IN. Also ensure ingestion stores tags as list, not comma string. Inspect node metadata type directly. Test filter in isolation with simple retriever query. Workaround is to normalize tags to separate boolean fields or use text search retriever for tags. Log filter translation to store query to see mismatch. This is a frequent framework integration mistake when switching stores, as each maps operators differently. Pin behavior with unit tests per store backend. Consistent metadata schema plus store-specific operator mapping resolves most IN failures."}], "metadata": {"domain": "llamaindex", "task_type": "debugging", "difficulty": "advanced"}} {"messages": [{"role": "user", "content": "Refactor large LlamaIndex ingestion script into modular pipeline components."}, {"role": "assistant", "content": "Split monolithic script into readers, transforms, index_builder, and query_service modules with clear interfaces. Extract configuration into YAML defining chunk_size, embedding model, and vector store parameters. Replace inline parsing with composable IngestionPipeline using transformations SentenceSplitter, TitleExtractor, and Embeddings. Implement idempotent upserts using doc_id hashing to prevent duplicates. Add CLI with argparse for ingest, query, and evaluate commands. Introduce dependency injection for ServiceContext to enable testing with mocks. Add type hints and pydantic models for metadata validation. Remove hardcoded paths favoring environment variables. Add logging with structlog. This improves maintainability, enables parallel ingestion, and simplifies onboarding for new engineers extending readers or stores. Additional implementation detail includes configuring service context retries, batching embedding calls, validating node metadata schemas, persisting storage context versions, and measuring retrieval recall on golden queries before promoting changes to production deployment."}], "metadata": {"domain": "llamaindex", "task_type": "code_review", "difficulty": "intermediate"}} {"messages": [{"role": "user", "content": "My router selects correctly in eval but fails in production with paraphrased queries. How to improve robustness?"}, {"role": "assistant", "content": "Eval queries are often clean while production paraphrases diverge. Augment router test set with paraphrases and typos to measure true accuracy. Improve QueryEngineTool descriptions with 3 to 5 example queries each covering phrasing variants. Consider adding embedding-based pre-router that narrows candidates before LLM selection. Set temperature zero and use PydanticSingleSelector for stability. Log production queries with low confidence and review weekly. Another fix is multi-route fallback: if confidence low, query top two engines and synthesize. Evaluate selection accuracy and end-to-end answer quality separately. Retrain descriptions iteratively from failure logs. Router robustness comes from diverse examples and fallback logic, not larger selector model alone. Always validate on a held-out golden set, log node IDs with scores and prompts, compare recall plus faithfulness before promoting changes, and monitor latency plus cost in production to avoid regressions."}], "metadata": {"domain": "llamaindex", "task_type": "retrieval_analysis", "difficulty": "advanced"}} {"messages": [{"role": "user", "content": "Implement property graph RAG in LlamaIndex for entity reasoning."}, {"role": "assistant", "content": "Use PropertyGraphIndex with LLM-driven extractors to identify entities and relations from documents. Configure kg_extractors with SchemaLLMPathExtractor constrained to your ontology like Person, Org, Product. Store graph in Neo4jPropertyGraphStore for traversals. Query via property graph retriever combining vector search for entry points with Cypher path expansion depth 2. Synthesize answers that explain multi-hop relationships with entity citations. Evaluate on questions requiring joins across documents that vector search alone misses. Handle extraction cost by batching and caching. Property graph RAG excels at relationship queries, organizational hierarchies, and fraud patterns, complementing vector retrieval with structured reasoning, explicit provenance, and interpretable traversal paths for complex analytical workloads."}], "metadata": {"domain": "llamaindex", "task_type": "implementation", "difficulty": "advanced"}} {"messages": [{"role": "user", "content": "Refactor legacy LlamaIndex GPTSimpleVectorIndex code to current VectorStoreIndex API."}, {"role": "assistant", "content": "Map old GPTSimpleVectorIndex calls to VectorStoreIndex with ServiceContext and StorageContext equivalents. Replace manual index.json handling with persist and load from storage directory. Update embedding configuration to new Settings API with explicit model names. Migrate custom prompts to updated PromptTemplate imports. Run side-by-side comparison on sample queries to verify parity in retrieved nodes and answers. Update tests to new import paths and async methods where applicable. Remove deprecated dependencies and pin current llamaindex version. Add migration script for converting old index files to new format. Document breaking changes, new defaults for chunking, and performance differences. Validate in staging before production rollout to avoid downtime."}], "metadata": {"domain": "llamaindex", "task_type": "code_review", "difficulty": "intermediate"}} {"messages": [{"role": "user", "content": "Fix this traceback: ValueError expected embedding dimension 1536 but got 3072 in Pinecone"}, {"role": "assistant", "content": "Mismatch means index was created with one embedding model but queried with another, for example ada 1536 versus large 3072. Pinecone dims are fixed at creation and cannot change. Fix by checking Settings embed model in ingestion and query paths, inspecting stored config, then either recreating index with correct dims or pinning model back. Example:\n\nfrom llama_index.embeddings.openai import OpenAIEmbedding\nfrom llama_index.core import Settings\nSettings.embed_model=OpenAIEmbedding(model='text-embedding-3-small', dimensions=1536)\nprint('dims pinned')\nTo migrate safely create new index with new dims, backfill in batches, dual read during cutover, then delete old index. Pin embedding version in config and add startup assertion comparing model dims to index dims to fail fast. Validate on staging, monitor dashboards, and require review before production promotion."}], "metadata": {"domain": "llamaindex", "task_type": "traceback", "difficulty": "intermediate"}} {"messages": [{"role": "user", "content": "How do I add reranking with CohereRerank to LlamaIndex retriever pipeline?"}, {"role": "assistant", "content": "Add CohereRerank as NodePostprocessor after initial retrieval to boost precision. Configure retriever with similarity_top_k 20 for high recall, then CohereRerank model rerank-english-v3.0 top_n 5 api_key from env. Chain via RetrieverQueryEngine retriever plus node_postprocessors list. This two-stage pattern retrieves broadly then re-scores with cross-encoder quality. Measure latency impact, typically extra 400ms, and cost per query. Cache rerank results for repeated queries. Handle Cohere rate limits with retry and fallback to original ordering on failure. Evaluate with MRR and hit-rate on golden set before and after. For air-gapped use cases replace with local FlagEmbeddingReranker. Keep top_n small to bound prompt tokens for synthesis. Reranking is highest ROI improvement for noisy chunking."}], "metadata": {"domain": "llamaindex", "task_type": "optimization", "difficulty": "intermediate"}} {"messages": [{"role": "user", "content": "How do I configure chunking with SentenceSplitter for better RAG recall in LlamaIndex?"}, {"role": "assistant", "content": "Tune chunk_size and chunk_overlap to balance context and precision. Start with chunk_size 512 tokens and overlap 50 for general docs, 1024 for legal or technical manuals needing broader context. Use SentenceSplitter to respect sentence boundaries instead of naive character splits. Apply via Settings.text_splitter or IngestionPipeline transformations list. Test recall on five representative queries with similarity_top_k 5. Smaller chunks improve precision for fact lookup, larger chunks improve synthesis for how and why questions. Add MetadataReplacementPostProcessor to swap in surrounding window for display while retrieving small chunks. Persist nodes and inspect average node length. Avoid overlap above 20 percent as it inflates index size without recall gains. Re-evaluate after any change with RelevancyEvaluator."}], "metadata": {"domain": "llamaindex", "task_type": "optimization", "difficulty": "beginner"}} {"messages": [{"role": "user", "content": "Refactor LlamaIndex retrieval code to support hybrid dense plus BM25 search."}, {"role": "assistant", "content": "Introduce a hybrid retriever combining VectorIndexRetriever and BM25Retriever via QueryFusionRetriever with reciprocal rank fusion. Encapsulate embedding and tokenization setup behind a factory to simplify configuration. Update ingestion to build both vector and keyword indexes from the same node set, ensuring IDs align. Add configuration for weights balancing semantic versus lexical relevance, defaulting to 0.7 dense. Refactor query code to use the fused retriever interface without changing callers. Add benchmarks comparing hybrid versus dense only on acronym and exact-match queries. Handle fallback when BM25 index is missing. Write unit tests for fusion scoring and integration tests for end-to-end queries. Document tuning guide for adjusting fusion weights per domain."}], "metadata": {"domain": "llamaindex", "task_type": "code_review", "difficulty": "intermediate"}} {"messages": [{"role": "user", "content": "How do I optimize LlamaIndex embedding costs with batching and caching?"}, {"role": "assistant", "content": "Cache embeddings in Redis or SQLite IngestionCache keyed by content hash to skip re-embedding on reindex. Use embed_batch_size 100 and num_workers 4 to maximize throughput. Choose text-embedding-3-small over large unless quality demands it; test recall delta first. Deduplicate docs with hash filter before embedding. For updates embed only changed chunks via docstore diff. Monitor token counts with TokenCountingHandler and attribute per tenant. Precompute embeddings offline in bulk jobs rather than on request. Consider Matryoshka truncation to 512 dimensions to halve storage and cost with minimal recall loss. Evaluate cheaper open models like bge-small for internal corpora. These steps often cut embedding spend by 60 percent while preserving hit-rate above threshold."}], "metadata": {"domain": "llamaindex", "task_type": "optimization", "difficulty": "intermediate"}} {"messages": [{"role": "user", "content": "Explain how a transformer decoder generates text step by step for a beginner. I know basic neural nets but get confused by self-attention and why generation is autoregressive."}, {"role": "assistant", "content": "A decoder-only transformer generates one token at a time and feeds it back in. First your prompt is tokenized into IDs and embedded into vectors plus positional information. Those vectors flow through stacked blocks. In each block, masked self-attention lets every position attend only to previous positions, computing queries, keys, and values, taking softmax over scaled dot products, then a weighted sum. This builds context-aware representations. A feedforward network then transforms each position independently, with residual connections and layer norm stabilizing training. The final hidden state for the last position is projected to vocabulary logits and sampled into the next token via greedy decoding, temperature, or top-p. That token is appended and the process repeats. KV caching avoids recomputing keys and values for prior tokens, making inference linear in sequence length per step rather than quadratic. Stop when EOS appears or max tokens is reached."}], "metadata": {"domain": "llm_engineering", "task_type": "instruction", "difficulty": "beginner"}} {"messages": [{"role": "user", "content": "Design a multi-LoRA serving system where 100 tenants each have their own adapter on a shared 70B base. How to keep cost sane?"}, {"role": "assistant", "content": "Serve one base model with dynamic adapter loading, not 100 full models. Use vLLM with multi-LoRA support or S-LoRA with unified paging, allowing hundreds of adapters in one process. Store adapters in CPU or NVMe and prefetch top-k by traffic; keep hot 10 in GPU. Batch requests across tenants sharing base weights, only adapter matmuls differ, achieving high utilization. Isolate tenants via request metadata and per-tenant rate limits to prevent noisy neighbor. Version adapters with model hash plus adapter hash and run canary for new versions. Memory plan: 70B fp16 is 140GB, needs 2x H100 with tensor parallel, plus few GB for adapters since rank 16 adapters are tens of MB each. Add router to pin long-tail tenants to CPU-offloaded replica. Monitor per-tenant latency and error rates. Fall back to merged model for highest QPS tenant to reduce overhead."}], "metadata": {"domain": "llm_engineering", "task_type": "architecture", "difficulty": "advanced"}} {"messages": [{"role": "user", "content": "Training and inference tokenizers mismatch: model inserts weird spaces before punctuation. How do I find and fix it?"}, {"role": "assistant", "content": "Weird spaces indicate different pre-tokenizers or added tokens. Compare tokenizer_config.json and special tokens: training used e.g. Llama tokenizer with legacy False, inference uses True, changing handling of leading spaces. Dump token IDs for same string with both tokenizers and diff. Check chat template: training template adds bos and newline handling differently than inference serving template in vLLM. Ensure same version of transformers and sentencepiece. Fix by pinning tokenizer files from training checkpoint and using its chat_template verbatim in serving. Test roundtrip: decode encode should preserve punctuation spacing. Add unit test with 50 edge strings containing code, emojis, and punctuation. If you added new tokens during fine-tune, ensure embedding resize and tokenizer save both pushed. Mismatch can drop 5 points on code evals, so validate with generation samples before release."}], "metadata": {"domain": "llm_engineering", "task_type": "debugging", "difficulty": "advanced"}} {"messages": [{"role": "user", "content": "Design scalable LLM gateway supporting high RPS with routing and fallbacks."}, {"role": "assistant", "content": "Build stateless FastAPI gateway with Redis rate limiting, API key auth, and request validation. Implement intelligent routing by task complexity using a distilled classifier to send simple queries to 8B models and hard ones to 70B models. Add semantic caching with 0.97 similarity threshold and exact cache for repeats. Support retries with jitter, timeout budgets per provider, and fallback chains across providers and self-hosted vLLM. Emit OpenTelemetry metrics for latency, cost, and error rates per route. Use Kafka for async logging to ClickHouse. Autoscale on GPU utilization and chaos test outages to verify fallback correctness and track savings per route."}], "metadata": {"domain": "llm_engineering", "task_type": "architecture", "difficulty": "advanced"}} {"messages": [{"role": "user", "content": "Optimize LLM inference with KV-cache reuse across multi-turn chats. Explain implementation and expected gains."}, {"role": "assistant", "content": "Enable prefix caching by structuring prompts with stable system instructions followed by append-only conversation history to maximize cache hits. Use an inference server like vLLM with automatic prefix caching or prompt_cache directives, ensuring identical token prefixes via deterministic templating and disabling random prompt mutations. Measure time to first token and inter-token latency with and without caching across 3-turn dialogues, expecting 30 to 60 percent latency reduction for long contexts. Manage cache eviction with LRU and TTL, track hit rates in metrics, and invalidate on system prompt version changes to avoid stale behavior. Validate correctness by comparing outputs with caching enabled versus disabled on a regression set. Document memory cost of cached KV blocks versus latency savings, and combine with streaming to improve perceived responsiveness in production chat."}], "metadata": {"domain": "llm_engineering", "task_type": "optimization", "difficulty": "intermediate"}} {"messages": [{"role": "user", "content": "Analyze temperature sweep 0 to 1 for JSON extraction accuracy and diversity requirements"}, {"role": "assistant", "content": "Sweep 5 temperatures on 1000 extractions shows accuracy 98 percent at 0 dropping to 85 percent at 1.0 due to invalid syntax and value drift. Diversity minimal benefit for extraction. Variance across seeds triples at high temp. Latency similar, but retries double cost at temp 1.0. Plot accuracy versus temp curve steep after 0.4. Recommend temp 0 to 0.2 for production extraction, sampling only for creative variants. Check edge entities like nested objects degrade fastest. Validate with constrained decoding which flattens curve, implement CI gate requiring 97 percent validity, and document that higher temps only suit brainstorming where exact schema less critical than varied ideas."}], "metadata": {"domain": "llm_engineering", "task_type": "experiment_analysis", "difficulty": "intermediate"}} {"messages": [{"role": "user", "content": "LLM streaming via SSE drops mid-response with network error after 2 minutes on serverless. How to debug whether it is function timeout or client disconnect?"}, {"role": "assistant", "content": "Serverless max duration and proxy buffering typically cut long SSE streams prematurely. Check function logs for timeout exceeded versus client closed connection events and correlate timestamps. Fix by moving to edge streaming with ReadableStream, flushing headers immediately, sending heartbeat comments every 15s to keep connection alive, and chunking tokens as data events with retry field. Set max duration config appropriately and use async iterator from provider stream. On client implement EventSource with auto reconnect using last event id and resume logic. Test with curl verbose to see stall location. Add metrics for stream duration, tokens per second, and disconnect reason. For very long generations switch to background job with webhook polling instead of holding SSE open for minutes to improve reliability."}], "metadata": {"domain": "llm_engineering", "task_type": "api_debugging", "difficulty": "intermediate"}} {"messages": [{"role": "user", "content": "How do I implement function calling with validation for a booking assistant?"}, {"role": "assistant", "content": "Define JSON schemas for functions like search_flights and book_hotel with required fields, enums, and descriptions. Use provider function calling API with temperature zero. Validate arguments with Pydantic before execution, rejecting missing or out-of-range values with user friendly clarification. Implement server-side authorization and idempotency keys for bookings. Handle model errors: if arguments invalid, return error to model for self-correction, max two loops. Log function name, args, latency, and outcome. Test with happy path, missing slot, invalid date, and refusal cases. Add confirmation step for side effects, showing summary before commit. Version schemas and keep backward compatibility. Monitor function selection accuracy and fallback to text response on low confidence. Strict schemas plus validation make tool use reliable and auditable."}], "metadata": {"domain": "llm_engineering", "task_type": "implementation", "difficulty": "intermediate"}} {"messages": [{"role": "user", "content": "What is best practice for versioning prompts and few-shot examples in production?"}, {"role": "assistant", "content": "Store prompts as Jinja templates in git with semantic versioning, frontmatter for model, temperature, and eval scores, reviewed via PRs like code. Manage few-shot examples as versioned JSONL datasets in DVC with hashes, selecting via embedding diversity to avoid redundancy. Deploy via config service with instant rollback, shadow test new versions on 5 percent traffic measuring task success and toxicity, and require 2 percent lift for promotion. Log prompt version with every request for debugging, dashboard performance by version, and alert on regressions. Include unit tests asserting output schema and forbidden content, run nightly evals on 200 cases. Document owners, changelog, and deprecation policy retaining last 5 versions. This discipline prevents silent prompt drift, enables reproducible debugging, and accelerates safe iteration across teams sharing LLM infrastructure."}], "metadata": {"domain": "llm_engineering", "task_type": "implementation", "difficulty": "intermediate"}} {"messages": [{"role": "user", "content": "Dense vs BM25 retrieval for technical docs: which to choose for a starter RAG?"}, {"role": "assistant", "content": "Start with hybrid retrieval because technical docs contain exact identifiers like error codes, API names, and version numbers where BM25 excels, plus conceptual explanations where dense embeddings excel. Use BM25 for keyword matching and a general-purpose embedding model like E5 or BGE for semantics. Fuse results with reciprocal rank fusion and deduplicate by document ID. This setup requires no training and performs robustly across queries. Evaluate on 50 real questions measuring whether correct pages appear in top 5. If queries are mostly exact matches, weight BM25 higher; if paraphrased, weight dense higher. Add a lightweight reranker later only if precision remains insufficient for answer generation."}], "metadata": {"domain": "llm_engineering", "task_type": "retrieval_analysis", "difficulty": "beginner"}} {"messages": [{"role": "user", "content": "Intermediate llm_engineering refactoring task: extract monolithic agent loop into testable planner and executor?"}, {"role": "assistant", "content": "Split loop into planner producing structured plan with steps, tools, and success criteria, and executor running tools with retries and state updates. Define typed interfaces and immutable state to enable isolated unit tests. Replace global variables with context object carrying history, observations, and budget. Add orchestrator enforcing max steps, cost limits, and approval gates. Log plans, tool calls, and outcomes with correlation ids. Test planner with golden goals and executor with mocked tools including failures. Measure clarity, reuse, and defect rate improvement. Version prompts separately. Document migration, maintain backward compatible wrapper, and enforce linting. Monitor production plan quality and execution success. This separation improves debuggability, allows independent iteration on reasoning versus tool handling, and supports safer deployment of complex agents."}], "metadata": {"domain": "llm_engineering", "task_type": "code_review", "difficulty": "intermediate"}} {"messages": [{"role": "user", "content": "Write Python code to call an LLM with retry, timeout, and JSON output validation."}, {"role": "assistant", "content": "Use Python httpx with ten second timeout, three retries with exponential backoff, and pydantic validation for JSON outputs. Define response schema with required fields and types, set response_format to json_object when supported, and include explicit schema in system prompt. On timeout or 429 or 500, wait 1, 2, then 4 seconds with jitter before retrying. After each call, parse JSON, validate with model_validate, and on failure send one repair call with validation error included. Log latency, tokens, model version, and error type for observability. Wrap calls in async semaphore to limit concurrency to ten. Store raw responses for debugging. This pattern prevents crashes, reduces malformed outputs, and makes LLM integration testable, observable, and safe for production workflows requiring structured data."}], "metadata": {"domain": "llm_engineering", "task_type": "implementation", "difficulty": "beginner"}} {"messages": [{"role": "user", "content": "Our RAG misses relevant docs despite them existing. How to debug retrieval misses systematically?"}, {"role": "assistant", "content": "Start by reproducing misses with a labeled set of query to expected chunk IDs and computing recall at 5 and MRR. Inspect chunking to see if answers are split across boundaries, check tokenizer mismatch between indexing and querying, and verify metadata filters are not over-constraining. Analyze embedding similarity distributions for hits versus misses to set thresholds, and test query rewriting with HyDE or decomposition for vocabulary mismatch. Compare dense-only versus BM25 to identify lexical gaps, and review stopwords, stemming, and multilingual handling. Log retrieved IDs, scores, and filters for each failure, cluster failures by cause, and fix iteratively: adjust chunk size, add overlap, enrich metadata, or add synonyms. Validate fixes on held-out queries and monitor live feedback signals to prevent regression and guide reranker adoption."}], "metadata": {"domain": "llm_engineering", "task_type": "retrieval_analysis", "difficulty": "intermediate"}} {"messages": [{"role": "user", "content": "Optimize TTFT and TPOT separately for real-time voice assistant."}, {"role": "assistant", "content": "Voice requires TTFT under 300ms and TPOT under 40ms for natural turn-taking. Optimize TTFT via short 200 token prompts, prefix caching, small 7B model, and speculative decoding with draft length two. Optimize TPOT via 4-bit quantization, KV cache pinned on GPU, and max batch tokens tuned to avoid queuing. Stream partial sentences to TTS after 12 tokens to mask remaining decode. Measure first audio chunk latency end-to-end. Use dedicated GPU pool with no batch mixing of long jobs. Fallback to text-only on overload. Profile separately because TTFT bottleneck is prefill compute while TPOT is memory bandwidth. Tune accordingly rather than generic latency. Load test with 50 concurrent voice sessions. This split optimization achieves human-like responsiveness, reduces interruption rate, and controls cost by reserving aggressive acceleration only for latency-critical voice path versus asynchronous summarization tasks."}], "metadata": {"domain": "llm_engineering", "task_type": "optimization", "difficulty": "advanced"}} {"messages": [{"role": "user", "content": "Document best practices for versioning LLM prompts in git with rollback and A/B testing support."}, {"role": "assistant", "content": "Store prompts as versioned YAML or Jinja files with frontmatter for model, temperature, and owner metadata. Use semantic versioning for breaking changes in variables or output format. Require pull requests with diff previews, evaluation results, and reviewer approval before merging. Tag releases and maintain a changelog describing behavior changes. Implement a prompt registry service that serves prompts by version and supports aliasing stable versus experimental. Enable runtime routing for A/B tests with traffic splitting and metric collection on task success. Automate rollback by switching aliases when error rates spike. Archive evaluation datasets alongside prompts for reproducibility. Add linting for required variables and forbidden phrases. This workflow brings software engineering rigor to prompts, prevents silent regressions, and enables data-driven iteration with safe deployment and rapid recovery."}], "metadata": {"domain": "llm_engineering", "task_type": "instruction", "difficulty": "intermediate"}} {"messages": [{"role": "user", "content": "Implement streaming RAG with incremental retrieval as LLM generates partial answers."}, {"role": "assistant", "content": "Start with initial retrieval for query, generate outline, then trigger follow up retrievals when model emits citation needed token. Use async retriever with 150ms budget overlapping generation. Maintain working memory of passages with deduplication and relevance scoring. Implement controller deciding when to retrieve versus continue based on uncertainty. Stream partial tokens via SSE while background retrieval updates context for next sentences. Evaluate faithfulness improvement on multi hop HotpotQA and latency overhead. Handle race conditions with versioned context and rollback if retrieved evidence contradicts drafted sentence. Log retrieval triggers for tuning thresholds and cost control. Additionally track metrics in versioned experiments and document tradeoffs to guide rollout decisions and future tuning priorities effectively. Additionally track metrics in versioned experiments and document tradeoffs to guide rollout decisions and future tuning priorities effectively. Additionally track metrics in versioned experiments and document tradeoffs to guide rollout decisions and future tuning priorities effectively."}], "metadata": {"domain": "llm_engineering", "task_type": "implementation", "difficulty": "advanced"}} {"messages": [{"role": "user", "content": "Intermediate llm_engineering coding task: implement streaming chat API with function calls using OpenAI SDK?"}, {"role": "assistant", "content": "Implement async generator consuming chat completion chunks, accumulating content deltas and tool call deltas by index until finish reason indicates stop or tool_calls. Define tools with JSON Schema, use strict mode, and validate arguments with pydantic before execution. Handle partial JSON by buffering until complete, then dispatch to functions with timeouts and retries. Stream partial text to client via SSE while holding tool execution until fully parsed. Log request id, chunk counts, time to first token, and tool latency. Add cancellation handling, backpressure, and error mapping to user friendly messages. Unit test mocked streams with split JSON, multiple tools, and interruptions. Measure reliability and latency. Version prompts and tool schemas, document client integration, and enforce guardrails before side effects in production."}], "metadata": {"domain": "llm_engineering", "task_type": "implementation", "difficulty": "intermediate"}} {"messages": [{"role": "user", "content": "Track guardrail effectiveness with real-time metrics."}, {"role": "assistant", "content": "Log every guardrail decision with rule, score, action, latency, and session context. Dashboard block rate, false positive appeals, bypass attempts, and per-rule precision. Alert on sudden drop suggesting misconfiguration or attack. Sample blocked and passed traffic for human review weekly. Correlate guardrail triggers with downstream user satisfaction. Version rules and measure impact of changes via A-B. Optimize latency by ordering cheap regex before heavy classifiers. Report monthly with top patterns and tuning actions. Retain logs for incident forensics with PII minimization. Add load testing with realistic traces, capacity headroom analysis, autoscaling thresholds, and incident playbook so performance remains stable under peak demand. Maintain documentation for onboarding, troubleshooting guides, data retention policy, and compliance checks to ensure long term operability and governance."}], "metadata": {"domain": "llm_engineering", "task_type": "implementation", "difficulty": "intermediate"}} {"messages": [{"role": "user", "content": "Build property-based tests for LLM summarization to check length, faithfulness, and language constraints."}, {"role": "assistant", "content": "Use Hypothesis to generate random documents varying length, domain, and complexity with strategies for news, tickets, and legal text. Define properties asserting summary length is under twenty percent of source, language matches input, and no URLs are invented. Implement entailment checks with an NLI model to flag unsupported claims automatically. Test idempotence by summarizing summaries and checking further compression. Include edge cases for empty inputs, single sentences, and highly repetitive text. Run one hundred examples per CI build and store failing seeds for reproduction. Measure property violation rates across model versions to detect regressions. Combine with golden example tests for qualitative review. Property-based testing uncovers edge failures missed by fixed datasets, ensures invariants hold across diverse inputs, and builds confidence for deploying summarization in user-facing products."}], "metadata": {"domain": "llm_engineering", "task_type": "testing", "difficulty": "advanced"}} {"messages": [{"role": "user", "content": "Implement structured output enforcement with Pydantic, JSON schema validation, and retry repair loops for LLMs."}, {"role": "assistant", "content": "Enforce structured outputs by defining Pydantic BaseModel schemas for each task with field types, descriptions, and validators for ranges or regex patterns. Generate JSON schema from models to include in system prompts with explicit instruction to output only valid JSON without markdown fences. Call LLMs with response_format json_object or guided_json via Outlines for constrained decoding, then parse and validate responses, catching ValidationError details. On failure, construct repair prompt including original output plus validation errors, retry up to three times with temperature zero, falling back to default safe object after exhaustion. Implement utility functions validate_and_repair with logging of retry counts and error types, unit tests for malformed JSON, missing fields, and type coercion, benchmark format validity improvement from eighty to ninety nine percent, track added latency and token cost, and document schema evolution practices to maintain backward compatibility across prompt versions."}], "metadata": {"domain": "llm_engineering", "task_type": "implementation", "difficulty": "intermediate"}} {"messages": [{"role": "user", "content": "Implement dynamic batch scheduling with priority queues, preemption handling, and SLO aware timeouts for chat serving."}, {"role": "assistant", "content": "Implement dynamic scheduling with a priority queue separating interactive chat from background batch jobs to meet SLOs under burst load. Use vLLM continuous batching with max batched tokens eight thousand, preempt low priority requests when KV cache exceeds eighty percent, resume via recompute with saved prefix. Enforce per request timeouts at ten seconds, retry once on preemption, log queue wait versus prefill versus decode breakdown. Add Python scheduler with heap queues, async dispatch, unit tests for preemption correctness and starvation freedom, load tests at forty RPS measuring p99 improvement, Prometheus metrics for preemptions and wait time, configuration for weights and thresholds, documentation for operators tuning fairness versus latency in multi tenant serving environments with strict responsiveness guarantees."}], "metadata": {"domain": "llm_engineering", "task_type": "implementation", "difficulty": "intermediate"}} {"messages": [{"role": "user", "content": "Analyze safety filter bypass where encoded jailbreak instructions hidden in retrieved PDF escaped detection."}, {"role": "assistant", "content": "Incident review reveals attacker embedded Base64 encoded instructions in PDF appendix ingested by RAG, decoded by LLM despite guardrail scanning only raw text. Classifier trained on plain English missed obfuscated payload, allowing exfiltration of system prompt via tool output. Retrieval returned poisoned chunk ranked third with high similarity to benign query about policy exceptions. Timeline shows lack of payload decoding before scanning, no output validation for secrets, and overly permissive tool scope. Mitigations include decoding common encodings before classification, treating retrieved content as untrusted data with delimiter isolation, adding output regex for system leakage, restricting tools to read only for untrusted sessions. Retest with two hundred encoded variants shows block rate improving from forty to ninety seven percent. Document attack pattern, share indicators across teams, require red team sign off, and schedule continuous monitoring for new obfuscation techniques in document ingestion pipelines."}], "metadata": {"domain": "llm_engineering", "task_type": "experiment_analysis", "difficulty": "advanced"}} {"messages": [{"role": "user", "content": "Explain KV caching for faster LLM inference for beginners and why it reduces latency for long generations."}, {"role": "assistant", "content": "KV caching stores key and value tensors from processed prompt tokens so each new generated token only computes attention over cached states plus one new token. Without caching, every decoding step would recompute attention over the full sequence, causing quadratic cost and high latency for long outputs. The cache grows linearly with sequence length and batch size, trading GPU memory for substantial speed gains, often three to ten times faster. For beginners, use Hugging Face generate with use_cache enabled, monitor memory with long contexts, combine with bfloat16 precision and paged attention in vLLM for larger batches. Cache invalidation matters when prompts change, so reuse prefix caches for shared system prompts across requests. Measure time to first token versus tokens per second separately, profile max sequence length before out of memory, and consider quantization or sliding window attention when serving extended conversations."}], "metadata": {"domain": "llm_engineering", "task_type": "instruction", "difficulty": "beginner"}} {"messages": [{"role": "user", "content": "Design constitutional critique-revise loop with red-teaming and harmlessness gates before release."}, {"role": "assistant", "content": "Align language models to safety principles by generating draft responses, critiquing violations automatically, revising outputs, and adversarially testing across jailbreak suites before any production promotion. Implement pipeline sampling base model, critic model flagging bias and disallowed content with rationales, reviser rewriting to comply with constitution, DPO training on revised versus original pairs, and evaluation on BBQ plus ToxiGen plus five hundred red-team prompts. Require harmlessness above ninety eight percent, helpfulness drop under two percent, and human audit of one thousand samples. Monitor refusal calibration and over-refusal rates by demographic slice, version constitutions explicitly, log critiques for transparency, gate releases in CI on thresholds, test multilingual safety, refresh red teams quarterly, and enable rollback to prior safe checkpoint within hours of bypass discovery."}], "metadata": {"domain": "llm_engineering", "task_type": "architecture", "difficulty": "advanced"}} {"messages": [{"role": "user", "content": "Intermediate llm_engineering explanation task: explain evaluation of hallucinations with NLI and LLM judges?"}, {"role": "assistant", "content": "Explain decomposing responses into atomic claims then verifying each against source using natural language inference for entailment versus contradiction. Detail LLM judge prompting with evidence quotes, labels, and calibrated thresholds. Compare NLI speed and determinism versus judge nuanced reasoning. Cover metrics like faithfulness rate, claim recall, and citation F1. Show examples of subtle numeric and temporal hallucinations. Discuss handling long contexts via chunked checks and aggregation. Address judge bias, leniency, and cost controls with sampling. Recommend combining both with human spot checks. Log claims, verdicts, and evidence for audit. Provide implementation checklist, versioning, and CI integration. This approach quantifies grounding reliably, prioritizing fixes for retrieval versus generation based on evidence rather than intuition."}], "metadata": {"domain": "llm_engineering", "task_type": "instruction", "difficulty": "intermediate"}} {"messages": [{"role": "user", "content": "Fine tune Llama 3 8B with QLoRA for finance QA on 50k examples while preserving general\u80fd\u529b without catastrophic forgetting."}, {"role": "assistant", "content": "Use 4 bit NF4 quantization with double quantization and paged AdamW to fit on single 48GB GPU. Configure LoRA rank 32 alpha 64 targeting query key value and MLP projections, dropout 0.05. Mix finance data with 10 percent general instruction data like OpenAssistant to retain capabilities. Train with cosine schedule 2e-4 learning rate, 3 percent warmup, effective batch 128 via accumulation, sequence length 4096 with packing. Apply Neftune noise alpha 5 for regularization and early stop on blended validation of finance accuracy and MMLU subset. Evaluate forgetting via baseline comparisons and general benchmarks. Merge adapters selectively and run safety checks for disallowed financial advice, adding disclaimer template in system prompt."}], "metadata": {"domain": "llm_engineering", "task_type": "implementation", "difficulty": "intermediate"}} {"messages": [{"role": "user", "content": "Review LLM evaluation harness handling prompt versioning, caching, and cost tracking."}, {"role": "assistant", "content": "Verify prompts stored with git hash and parameters, not inline strings. Check cache key includes prompt hash, model ID, and temperature to avoid collisions. Ensure cost tracking logs tokens per eval and aggregates budget alerts. Look for missing retries on rate limits causing flaky CI. Confirm dataset splits prevent contamination and eval sampling stratified. Flag non-deterministic ordering without seeds. Assess judge bias testing with human calibration. Verify PII redaction before external API calls. Recommend dashboards for score trends and regression detection. Suggest bounded concurrency with semaphore and checkpoint resume. Ensure secrets not logged. Propose interface for adding new metrics without code duplication."}], "metadata": {"domain": "llm_engineering", "task_type": "code_review", "difficulty": "intermediate"}} {"messages": [{"role": "user", "content": "How to debug OpenAI API 400 invalid function schema with nested objects?"}, {"role": "assistant", "content": "400 errors indicate schema violates function spec, often nested objects without strict properties or unsupported types. Simplify to flat parameters with primitives, avoid recursive schemas. Validate JSON schema with linter. Check enum types and required arrays. Log payload before send. Test with minimal schema then add fields incrementally. Use Pydantic to generate compliant schema. Once valid, reintroduce nesting carefully. Strict simple schemas improve reliability and model compliance. Always validate on a held-out golden set, log node IDs with scores and prompts, compare recall plus faithfulness before promoting changes, and monitor latency plus cost in production to avoid regressions. Record config versions, rerun nightly evals, and review failure samples manually to ensure gains persist across data shifts and model updates."}], "metadata": {"domain": "llm_engineering", "task_type": "api_debugging", "difficulty": "advanced"}} {"messages": [{"role": "user", "content": "Conduct threat modeling for agent with browser tool covering SSRF prompt injection and credential leakage"}, {"role": "assistant", "content": "Map threats with STRIDE: spoofed tool outputs, tampered webpages with injections, repudiation gaps without logs, info disclosure via URLs with tokens, DoS via large pages, elevation via admin endpoints. Mitigate with URL allowlist plus SSRF block on private IPs, fetch size limits 1MB and timeout 10s, content sanitization stripping scripts, require user confirmation before submitting forms or accessing authenticated sites. Isolate browser in sandbox without credentials, redact cookies from transcripts, log all navigations. Test with malicious pages attempting metadata exfiltration, internal service probing, file downloads. Review quarterly, pentest chaining browser plus code tools, measure task success versus blocks, and document residual risks with monitoring alerts for anomalous browsing patterns."}], "metadata": {"domain": "llm_engineering", "task_type": "security", "difficulty": "advanced"}} {"messages": [{"role": "user", "content": "Review LangChain to LlamaIndex migration where callbacks and memory were dropped."}, {"role": "assistant", "content": "Migration often loses observability and state. Review for missing callback_manager, token counting, and memory persistence. Map LangChain memory to LlamaIndex Memory, callbacks to handlers. Ensure tracing still logs. Test multi-turn continuity and cost tracking. Common integration mistake is assuming defaults match; explicitly configure. Add tests for memory retention and callback invocation. Verify streaming still works. Careful mapping preserves features while gaining LlamaIndex retrieval strengths. Always validate on a held-out golden set, log node IDs with scores and prompts, compare recall plus faithfulness before promoting changes, and monitor latency plus cost in production to avoid regressions. Record config versions, rerun nightly evals, and review failure samples manually to ensure gains persist across data shifts and model updates."}], "metadata": {"domain": "llm_engineering", "task_type": "code_review", "difficulty": "advanced"}} {"messages": [{"role": "user", "content": "Build retrieval augmented generation with hybrid search and reranking."}, {"role": "assistant", "content": "Chunk documents 512 tokens with 50 overlap, embed with bge-large, and index in FAISS plus BM25 for hybrid. Retrieve top 50 then rerank with cross encoder to top five. Generate with grounded prompts citing sources and no answer fallback. Evaluate Faithfulness, Answer Relevance, and Context Precision with RAGAS. Tune chunk size and top K via ablation. Handle versioning and access control filtering pre retrieval. Log retrieved IDs for audit. Compare dense only versus hybrid on recall. Document embedding model and prompts. Monitor hallucination rate and latency. Update index incrementally. Red team for prompt injection via retrieved docs. Audit tokenizer coverage and out of vocabulary rates across languages and domains to guide vocabulary updates. Add regression tests for edge cases including emojis negations and code switching."}], "metadata": {"domain": "llm_engineering", "task_type": "optimization", "difficulty": "advanced"}} {"messages": [{"role": "user", "content": "Document a fine-tuning run including dataset, hyperparameters, and reproducibility steps for audit."}, {"role": "assistant", "content": "Record dataset version hash, sample counts, train validation split, and preprocessing steps including filtering and deduplication. List base model checkpoint, tokenizer version, and hardware configuration. Document hyperparameters for learning rate, scheduler, batch size, epochs, LoRA rank, alpha, dropout, and random seeds. Include training curves for loss and validation metrics plus final evaluation on held-out benchmarks. Provide exact commands, environment lock files, and Docker image digests to reproduce. Note data licenses and PII handling measures. Archive model adapters, tokenizer files, and evaluation reports in versioned storage. Include failure modes and known limitations. Thorough documentation enables auditors to verify compliance, teammates to reproduce results, and future iterations to build on validated baselines without repeating expensive experiments or introducing untracked variations."}], "metadata": {"domain": "llm_engineering", "task_type": "instruction", "difficulty": "intermediate"}} {"messages": [{"role": "user", "content": "Optimize prompts for a table QA agent that writes Pandas code to answer questions over CSVs."}, {"role": "assistant", "content": "Structure prompt with schema preview showing dtypes, sample rows, and allowed libraries only. Require model to plan steps, generate single fenced python block, and avoid destructive ops. Provide few shots covering filtering, groupby, and join with error handling for missing columns. Include self debugging instruction to read traceback and retry once with fix. Enforce output contract returning answer plus code and explanation separately for verification. Test on 200 WikiTableQuestions style tasks measuring execution accuracy and runtime. Add guardrails sandboxing execution in Docker with timeout and memory limits. Iterate on common failures like hallucinated columns by adding schema linking step, and version prompts with performance dashboard."}], "metadata": {"domain": "llm_engineering", "task_type": "instruction", "difficulty": "intermediate"}} {"messages": [{"role": "user", "content": "How to compact long chat history for LLM without losing key facts?"}, {"role": "assistant", "content": "Use rolling summary: keep last 4 turns verbatim, summarize older into 200-token brief with entities preserved. Update summary incrementally. Include summary plus recent in prompt. Test on 10-turn tasks requiring early facts. Avoid naive truncation dropping names. Validate by checking task success versus full history. Log summary quality. For critical facts, extract to structured memory like user preferences. Compaction cuts cost while retaining continuity. Tune summary length per domain. Evaluate hallucination rate of summaries regularly. Always validate on a held-out golden set, log node IDs with scores and prompts, compare recall plus faithfulness before promoting changes, and monitor latency plus cost in production to avoid regressions."}], "metadata": {"domain": "llm_engineering", "task_type": "architecture", "difficulty": "intermediate"}} {"messages": [{"role": "user", "content": "Experiment to decide fine-tune versus RAG for domain QA. How to compare cost, quality, and maintainability?"}, {"role": "assistant", "content": "Run a head-to-head study on 300 domain questions with ground truth, testing base model, RAG with curated corpus, fine-tuned model, and combined approach. Control prompts and decoding parameters, and measure exact match, faithfulness, citation accuracy, and hallucination rate via human review plus LLM judge. Track total cost including data labeling, GPU training, indexing, and per-query inference tokens and latency. Assess maintainability by simulating corpus updates: measure time to reflect new facts via reindex versus retraining, and test catastrophic forgetting on general tasks. Analyze results by question type, finding RAG excels for rapidly changing facts while fine-tuning helps style and reasoning. Recommend RAG as default for factual freshness, fine-tuning only for persistent behavior shifts, and hybrid when both matter. Report confidence intervals and decision thresholds for stakeholders."}], "metadata": {"domain": "llm_engineering", "task_type": "experiment_analysis", "difficulty": "advanced"}} {"messages": [{"role": "user", "content": "Fine-tune Llama 3 8B with LoRA for support ticket classification."}, {"role": "assistant", "content": "Prepare 5k to 20k labeled tickets with balanced classes, deduplicated and split by time to avoid leakage. Tokenize with chat template and mask labels correctly. Configure LoRA rank 16, alpha 32, dropout 0.05 targeting q_proj, k_proj, v_proj, o_proj, and MLP. Train with 8-bit AdamW, cosine schedule, warmup 5 percent, and early stopping on validation F1. Use gradient accumulation to reach effective batch 64. Evaluate on held-out recent tickets and report per-class metrics. Compare against prompt-only baseline to justify tuning. Merge adapter for deployment or serve via PEFT with multi-adapter support. Log hyperparameters, data hash, and seed. Test robustness to typos and new product names. Document inference template to match training format exactly."}], "metadata": {"domain": "llm_engineering", "task_type": "debugging", "difficulty": "intermediate"}} {"messages": [{"role": "user", "content": "Refactor a LangChain prototype into production-ready modular LLM services."}, {"role": "assistant", "content": "Decouple prompts, tools, models, and orchestration into separate packages with explicit interfaces. Replace magic chains with typed functions accepting pydantic inputs and returning validated outputs. Externalize model names, temperatures, and timeouts into versioned config with feature flags. Introduce a ModelGateway abstraction supporting OpenAI, Anthropic, and local endpoints for easy switching. Add retries with exponential backoff, circuit breakers, and timeout handling per dependency. Implement OpenTelemetry tracing for prompts, tokens, and tool latency. Remove magic memory in favor of explicit Postgres conversation store with TTL. Add contract tests and golden evaluations for prompts before deployment. Track metrics continuously and document learnings for future iterations across teams and releases."}], "metadata": {"domain": "llm_engineering", "task_type": "code_review", "difficulty": "intermediate"}} {"messages": [{"role": "user", "content": "Design a secure architecture for enterprise code assistant with repo access."}, {"role": "assistant", "content": "Architecture isolates repo indexer in VPC with read-only GitHub App, chunks code with AST awareness, stores embeddings in tenant-isolated vector DB with encryption. Gateway authenticates via SSO, enforces repo ACLs per query, and redacts secrets using detect-secrets before LLM call. Model runs in private VPC or zero-retention SaaS with audit logging. Responses include file citations and diff suggestions requiring human approve before apply. Add DLP scan on outputs blocking keys and PII. Monitor prompt injection via classifier on retrieved code comments. Provide admin dashboard for access reviews and retention policies. Test with red-team attempting cross-repo access. This balances productivity with IP protection, satisfies SOC2, and prevents leakage across teams. Version access policies as code. Regular permission sync ensures departed employees lose access immediately while maintaining fast sub-second retrieval over million-line monorepos."}], "metadata": {"domain": "llm_engineering", "task_type": "architecture", "difficulty": "advanced"}} {"messages": [{"role": "user", "content": "Define evaluation metrics BLEU ROUGE BERTScore and LLM-as-judge and their limits for production LLM monitoring"}, {"role": "assistant", "content": "BLEU measures n-gram precision for translation, ROUGE measures recall for summarization, both cheap but correlate poorly with factuality and user preference. BERTScore uses embedding similarity to capture paraphrase, better for semantic overlap but still ignores grounding. LLM-as-judge prompts a strong model to score relevance, coherence, and correctness, aligning better with humans but introducing bias, cost, and variance. For production, combine lexical checks for format, embedding metrics for drift, LLM judges with calibrated rubrics and multiple seeds, plus human audits on samples. Track distributions, segment by task type, require high inter-rater agreement, version prompts and judges, and alert on regressions rather than absolute scores alone."}], "metadata": {"domain": "llm_engineering", "task_type": "instruction", "difficulty": "beginner"}} {"messages": [{"role": "user", "content": "Design a multi-model router with quality-cost tradeoff and fallback."}, {"role": "assistant", "content": "Classify requests by complexity using lightweight model plus heuristics like length, domain keywords, and history. Route simple FAQs to 7B distilled model, coding to specialized code model, and complex reasoning to 70B. Implement cascade: try small first, escalate if confidence low or judge flags inadequacy. Cache frequent answers to cut cost further. Measure cost per successful task, not per token, via task success and judge scores. Add timeouts and fallback to primary large model on downstream failure. Expose routing decisions in traces for debugging. Tune thresholds on 1000 production samples to hit 95 percent quality at 40 percent cost reduction. Monitor escalation rate and router bias across languages. In production add versioned configs, staged rollout, dashboard alerts on latency and error rate, and weekly review of failure clusters to sustain reliability."}], "metadata": {"domain": "llm_engineering", "task_type": "architecture", "difficulty": "intermediate"}} {"messages": [{"role": "user", "content": "Implement token streaming with the OpenAI API in FastAPI so the UI shows partial output. Include cancellation and error handling."}, {"role": "assistant", "content": "Use Server-Sent Events with async generator. In FastAPI, define endpoint returning StreamingResponse with media_type text-event-stream. Inside, call AsyncOpenAI chat.completions.create with stream True, temperature 0.7. Iterate async for chunk in stream, extract delta.content, yield f'data: json.dumps chunk\\n\\n' escaped properly. Handle client disconnect via asyncio.CancelledError and abort upstream stream to save cost. Add timeouts and retry on rate limit with backoff, sending error event to UI. Buffer tokens to avoid excessive flushes: flush every 20ms or 5 tokens. Log TTFT and total tokens for observability. On frontend, use EventSource or fetch reader to append. Test with slow network and mid-stream cancel to ensure GPU resources release. For self-hosted vLLM, same pattern works with its OpenAI-compatible endpoint, enabling consistent UI code."}], "metadata": {"domain": "llm_engineering", "task_type": "implementation", "difficulty": "intermediate"}} {"messages": [{"role": "user", "content": "How to implement automatic prompt optimization using DSPy for RAG pipelines?"}, {"role": "assistant", "content": "Define your RAG program in DSPy with signatures for query rewriting, reranking, and answer synthesis including citation requirements. Provide trainset of 150 query-context-answer triples with faithfulness labels. Use MIPROv2 optimizer to search instructions and few-shot examples maximizing combined faithfulness and answer relevance. Compile separate programs for factual versus multi-hop intents. Evaluate compiled prompts on held-out sets with LLM judges plus deterministic citation checks. Version compiled JSON prompts and pin with retriever configs. Monitor token cost changes since optimized prompts may be longer. Iterate by adding failure cases back to trainset. Deploy behind feature flags with A-B testing to confirm optimizer gains transfer to live traffic distributions."}], "metadata": {"domain": "llm_engineering", "task_type": "instruction", "difficulty": "advanced"}} {"messages": [{"role": "user", "content": "Propose formal verification for agent safety policies using model checking of tool call sequences and information flow constraints."}, {"role": "assistant", "content": "Propose modeling agent policies as finite state machines where states represent data sensitivity levels and transitions correspond to tool calls with preconditions. Specify safety invariants in temporal logic, such as never sending PII to external search and requiring human approval before financial transactions. Use model checker PRISM to exhaustively verify all paths up to depth twelve, generating counterexamples for violations. Complement with information flow tracking tagging untrusted retrieval content, enforcing no flow from untrusted to privileged actions without sanitization. Implement runtime monitor enforcing verified policy, blocking disallowed sequences with explanations. Evaluate on two hundred attack traces showing prevention of ninety eight percent violations with under five percent false blocks. Provide proofs of soundness, code generation from verified models, integration with CI to reverify on tool changes, and documentation of assumptions. This Rigorous approach moves beyond empirical red teaming toward guaranteed safety properties."}], "metadata": {"domain": "llm_engineering", "task_type": "retrieval_analysis", "difficulty": "expert"}} {"messages": [{"role": "user", "content": "Traceback: pydantic ValidationError for structured output with extra fields. How to handle?"}, {"role": "assistant", "content": "ValidationError on extra fields means model adds unrequested keys. Set Pydantic model_config extra forbid or ignore based on need, and instruct model to output only defined fields. In parser, strip unknown keys as tolerant fallback while logging. Retry with error message listing allowed fields. Test with varied queries. Prefer function calling strict mode to enforce schema. Balanced strict prompt plus tolerant parser reduces failures without hiding issues. Always validate on a held-out golden set, log node IDs with scores and prompts, compare recall plus faithfulness before promoting changes, and monitor latency plus cost in production to avoid regressions. Record config versions, rerun nightly evals, and review failure samples manually to ensure gains persist across data shifts and model updates."}], "metadata": {"domain": "llm_engineering", "task_type": "traceback", "difficulty": "advanced"}} {"messages": [{"role": "user", "content": "How to evaluate retriever recall when ground truth passages are incomplete?"}, {"role": "assistant", "content": "Use pooling: combine top results from multiple retrievers and have annotators judge relevance to expand ground truth. Report recall at K alongside precision and NDCG to account for missing labels. Apply LLM-as-judge for scalable relevance labeling, validated against human agreement rates. Use counterfactual testing by injecting known relevant passages and checking retrieval. Measure downstream answer faithfulness as proxy when labels are noisy. Perform error analysis on queries with zero hits to discover unlabeled positives. Iterate labels for high-impact queries rather than entire corpus. Use rank-biased overlap to compare systems without complete judgments. Document labeling guidelines and version judgments with corpus snapshots to ensure fair comparisons across index changes."}], "metadata": {"domain": "llm_engineering", "task_type": "retrieval_analysis", "difficulty": "intermediate"}} {"messages": [{"role": "user", "content": "How to test LLM fallback behavior under simulated API outages?"}, {"role": "assistant", "content": "Mock primary to raise timeout and 500 errors, assert fallback triggers and response quality acceptable. Test circuit breaker opens after threshold and recovers. Include chaos test with 30 percent failure rate. Verify logs and metrics. Ensure no duplicate side effects on retry for write tools via idempotency keys. Automate in CI with mocked transport. Robust fallback testing prevents outage surprises. Measure degraded quality versus full outage. Always validate on a held-out golden set, log node IDs with scores and prompts, compare recall plus faithfulness before promoting changes, and monitor latency plus cost in production to avoid regressions. Record config versions, rerun nightly evals, and review failure samples manually to ensure gains persist across data shifts and model updates."}], "metadata": {"domain": "llm_engineering", "task_type": "testing", "difficulty": "advanced"}} {"messages": [{"role": "user", "content": "Intermediate llm_engineering design task: design memory module for long conversations with summarization?"}, {"role": "assistant", "content": "Design layered memory with short term message buffer, summarized long term store, and vector recall for salient facts. Define write policy extracting entities, preferences, and decisions via LLM with schema validation. Implement token budgeted compaction summarizing oldest turns while preserving citations and action history. Support retrieval by recency, importance, and embedding similarity. Handle conflicts with timestamps and user correction priority. Log memory writes, reads, and token savings. Evaluate coherence, factual consistency, and task success over long dialogues. Add privacy controls for redaction and expiry. Provide APIs for inspect, edit, and reset. Test edge cases like contradiction and overflow. Document schema, tuning knobs, and monitoring. Ensure deterministic fallback when summarizer fails to avoid data loss and maintain seamless user experience."}], "metadata": {"domain": "llm_engineering", "task_type": "architecture", "difficulty": "intermediate"}} {"messages": [{"role": "user", "content": "Explain theoretical limits of in-context learning for compositional generalization."}, {"role": "assistant", "content": "In-context learning approximates Bayesian inference over pretraining concepts but struggles with novel compositional rules unseen in training due to limited induction heads capacity and positional biases. Theory shows transformers can implement gradient descent steps in forward pass, yet depth and width bound complexity of learnable functions. Empirically, accuracy drops exponentially with composition depth beyond three operations. Explain via mechanistic view of copying versus rule extraction, citing failures on SCAN and synthetic arithmetic. Mitigate with chain-of-thought decomposition, tool use, and fine-tuning on compositional data. Evaluate on held-out compositions varying length and structure. Understanding limits prevents overreliance on few-shot for systematic generalization tasks requiring true reasoning. Design systems that offload composition to code execution rather than expecting emergent magic, reserving in-context examples for style and format guidance where theory predicts reliable performance within distribution."}], "metadata": {"domain": "llm_engineering", "task_type": "instruction", "difficulty": "expert"}} {"messages": [{"role": "user", "content": "Explain speculative decoding for faster LLM inference with tradeoffs."}, {"role": "assistant", "content": "Speculative decoding uses a small draft model to propose multiple tokens quickly, then a large target model verifies them in parallel. Accepted tokens save sequential forward passes, yielding 2 to 3x speedups. Implement with draft length 4 to 8 tuning acceptance rate above 70 percent. Choose draft model from same family for aligned distributions. Measure speedup across tasks as creative text accepts fewer tokens than code. Handle sampling consistency with speculative sampling algorithms preserving target distribution. Evaluate added memory for draft model versus latency gains. Test with vLLM assisted generation APIs. Monitor rejection rates to detect mismatch and document fallback to standard decoding."}], "metadata": {"domain": "llm_engineering", "task_type": "instruction", "difficulty": "advanced"}} {"messages": [{"role": "user", "content": "Propose information theoretic framework for prompt compression preserving task relevant mutual information under token budgets."}, {"role": "assistant", "content": "Formulate compression as rate distortion optimization maximizing mutual information between compressed prompt and task output under token length constraint. Derive variational bound using LLM surprisal to score token importance, pruning low information tokens while retaining structural anchors like schemas and examples. Implement algorithm combining perplexity filtering, embedding clustering for redundancy removal, and learned summarizer for long contexts, achieving three times compression with under two percent accuracy loss on LongBench. Prove optimality under Markov assumptions, analyze failure modes on reasoning chains requiring exact numbers, compare to LLMLingua baselines, evaluate across models for transferability, measure latency savings versus compression cost, release code and benchmarks, discuss connections to KV cache theory, and outline adaptive compression policies conditioned on query complexity. This principled view guides efficient long context prompting beyond heuristic truncation for production cost control."}], "metadata": {"domain": "llm_engineering", "task_type": "retrieval_analysis", "difficulty": "expert"}} {"messages": [{"role": "user", "content": "Implement adversarial safety testing harness generating jailbreak variants, scoring refusals, and reporting attack success rates."}, {"role": "assistant", "content": "Develop harness loading HarmBench prompts and applying transformations like Base64 encoding, roleplay framing, multilingual translation, and multi turn escalation to create one thousand variants. Execute against target model with async concurrency ten and timeout thirty seconds, capturing responses with full traces. Score with Llama-Guard classifier plus regex for refusal phrases, marking success if disallowed content is provided without safe completion. Compute attack success rate overall and per technique with Wilson confidence intervals, flagging techniques above five percent for urgent mitigation. Generate HTML report with example failures, severity ratings, and remediation suggestions. Add pytest for scorer accuracy on labeled fixtures, track historical trends across model versions, integrate with CI to block releases on regression, support custom policy plugins, log costs, and ensure test data isolation from training to avoid contamination while enabling reproducible safety benchmarking."}], "metadata": {"domain": "llm_engineering", "task_type": "implementation", "difficulty": "intermediate"}} {"messages": [{"role": "user", "content": "Refactor research prototype agent into SOC2-compliant production service."}, {"role": "assistant", "content": "Refactor by adding authentication with OAuth, tenant isolation, encrypted storage, and audit logging of prompts, tool calls, and approvals. Replace hardcoded keys with Vault, sandbox code execution in Firecracker, and pin dependencies with SBOM. Implement rate limiting, input validation, and output DLP. Add health checks, graceful degradation, and runbooks. Conduct penetration test and vulnerability scan, remediate highs before launch. Create data retention policy with automated deletion and customer export. Document architecture, incident response, and access reviews for auditors. Test compliance controls via 100 control checks in CI. This transformation typically takes six weeks but unblocks enterprise sales. Maintain feature parity via golden replay tests. Prototype speed must yield to principled engineering for production trust. Version infrastructure as code and require dual approval for production deploys to meet change management requirements and ensure traceability."}], "metadata": {"domain": "llm_engineering", "task_type": "code_review", "difficulty": "expert"}} {"messages": [{"role": "user", "content": "Design multi-model routing with cost-aware selection and quality guarantees."}, {"role": "assistant", "content": "Route queries by predicted difficulty using lightweight classifier plus confidence. Easy to 7B local, medium to mid API, hard to frontier. Enforce quality via sampled audit and fallback on low confidence. Track cost per query and correctness. Calibrate thresholds on validation set. Add cache for repeats. Test misrouting impact. Expert design balances 50 percent savings with minimal quality drop. Monitor drift and retrain router quarterly. Include observability of routing reasons. Always validate on a held-out golden set, log node IDs with scores and prompts, compare recall plus faithfulness before promoting changes, and monitor latency plus cost in production to avoid regressions. Record config versions, rerun nightly evals, and review failure samples manually to ensure gains persist across data shifts and model updates."}], "metadata": {"domain": "llm_engineering", "task_type": "architecture", "difficulty": "expert"}} {"messages": [{"role": "user", "content": "Optimize inference with speculative decoding and continuous batching for coding assistant latency reduction"}, {"role": "assistant", "content": "Deploy draft model 1B proposing 4 tokens per step verified by 7B target, achieving 1.8x speedup on code with high acceptance rate. Tune speculation length by measuring acceptance versus overhead, fallback to standard decoding on low acceptance. Combine with continuous batching packing diverse request lengths, prioritize interactive queries over batch jobs. Profile TTFT TPOT under 50 concurrency, monitor draft-target agreement, GPU memory overhead, and output equivalence. Validate code pass rates unchanged, test with varied prompt lengths and temperatures, handle divergent outputs with rollback to target, dashboard speedup and cost per completion, and document when to disable speculation for creative tasks with low predictability."}], "metadata": {"domain": "llm_engineering", "task_type": "optimization", "difficulty": "intermediate"}} {"messages": [{"role": "user", "content": "Diffusion training loss plateaus with color shift artifacts on 8 GPUs. Fix distribution?"}, {"role": "assistant", "content": "Color shifts indicate EMA decay mismatch and mixed-precision overflow in VAE latents across ranks. Set EMA 0.9999 synced every 10 steps via broadcast, use FP32 for VAE and loss scaling 1024 for UNet bf16. Balance data shards by aesthetic score buckets to avoid rank bias, set num_workers 8 with WebDataset, and LR 1e-4 with 10k warmup plus SNR weighting gamma 5.0. Log per-rank loss and gradient histograms to detect diverging worker, validate with 1k image FID every 5k steps requiring steady decline. Checkpoint EMA separately, resume with exact RNG state, and test single-GPU overfit 10 images to isolate model versus distribution bug. Monitor DCGM clock throttling causing stragglers, replace slow nodes. These fixes restore convergence dropping FID 15 to 8 within 50k steps and eliminate tint artifacts."}], "metadata": {"domain": "llm_engineering", "task_type": "debugging", "difficulty": "advanced"}} {"messages": [{"role": "user", "content": "How can I reduce token cost for my LLM summarization feature for beginners?"}, {"role": "assistant", "content": "Start by measuring input and output tokens per request using tiktoken or provider usage fields. Trim system prompts to essential rules and remove redundant examples. Set max tokens to a tight budget like 200 for summaries and use stop sequences. Implement semantic caching with Redis for identical or near-duplicate documents using embedding similarity above 0.98. Switch from large models to smaller models like Haiku or GPT-4o-mini for simple summarization and route only complex inputs upward. Batch requests where possible and compress context by removing HTML and boilerplate. Enable streaming to improve perceived latency without extra cost. Track cost per thousand requests and set alerts for spikes."}], "metadata": {"domain": "llm_engineering", "task_type": "optimization", "difficulty": "beginner"}} {"messages": [{"role": "user", "content": "Optimize prompt caching to cut costs for repetitive legal document analysis."}, {"role": "assistant", "content": "Structure prompts with stable prefixes containing instructions and few-shot examples followed by variable document sections to maximize cache hits. Use provider prompt caching by ensuring prefix tokens exceed minimum thresholds. Measure cache hit rate, time to first token reduction, and cost savings over 1000 requests. Implement deterministic formatting with sorted keys and consistent whitespace to avoid cache fragmentation. Cache frequent system instructions and tool definitions separately. Set appropriate TTL and version cache keys by prompt hash. Combine with semantic caching for near-duplicate documents. Evaluate accuracy parity between cached and uncached paths. Automate prefix analysis in CI to flag changes that break caching."}], "metadata": {"domain": "llm_engineering", "task_type": "optimization", "difficulty": "intermediate"}} {"messages": [{"role": "user", "content": "Architect on device LLM system for offline medical triage on 8GB RAM smartphone."}, {"role": "assistant", "content": "Select 3B Phi model quantized to 4 bit GGUF fitting 2.5GB with 1GB KV budget for 4k context. Use llama.cpp with NEON acceleration and memory mapped weights. Implement triage flow with symptom checklist, red flag detection, and offline guideline DB in SQLite FTS. Ensure no network calls with airplane mode tests and encrypted local storage. Validate diagnostic safety with 1000 vignettes reviewed by clinicians achieving 95 percent appropriate referral. Provide fallback to call emergency when uncertainty high. Monitor battery and latency targeting under 2 sec per turn. Document FDA considerations, update mechanism via signed model packs, and usability for low literacy users."}], "metadata": {"domain": "llm_engineering", "task_type": "architecture", "difficulty": "expert"}} {"messages": [{"role": "user", "content": "Analyze prompt example retrieval bias where similar few shots caused overfitting to specific formatting styles."}, {"role": "assistant", "content": "Evaluation of dynamic example retrieval shows selecting top similar examples improves in distribution accuracy by eight percent but degrades out of distribution generalization by six percent due to style overfitting. Retrieved examples share formatting quirks like date styles that model copies even when inappropriate. Diversity analysis reveals retrieved sets have low entropy, repeating same template. Fixes include maximal marginal relevance with lambda zero point five balancing similarity and diversity, enforcing template variety constraints, and including one contrastive negative example. Test across domains shows MMR restores generalization while preserving most gains. Log example ids per request for audit, measure formatting error rates, A-B test static versus diverse retrieval, and document selection policies. Recommend hybrid approach using fixed diverse base examples plus one dynamically retrieved relevant case, validated to achieve best tradeoff on cross domain benchmarks with stable performance and reduced brittleness to retrieval quirks."}], "metadata": {"domain": "llm_engineering", "task_type": "retrieval_analysis", "difficulty": "advanced"}} {"messages": [{"role": "user", "content": "Detect prompt drift and model degradation in production."}, {"role": "assistant", "content": "Track embedding distribution of inputs and outputs, judge scores, task success, and user corrections over time. Establish baseline during first two weeks post-deploy. Alert on statistically significant shifts using PSI or KS test. Correlate drift with upstream data changes, prompt edits, or model version updates. Maintain golden query set rerun hourly to detect silent regressions. Dashboard segment by feature, locale, and tenant. Trigger investigation playbook when helpfulness drops 5 percent or refusal spikes. Retrain routers or update prompts based on clustered failure examples. Log all versions to attribute drift cause. Review weekly with product and adjust thresholds to balance noise. Add load testing with realistic traces, capacity headroom analysis, autoscaling thresholds, and incident playbook so performance remains stable under peak demand."}], "metadata": {"domain": "llm_engineering", "task_type": "implementation", "difficulty": "intermediate"}} {"messages": [{"role": "user", "content": "How to measure faithfulness versus helpfulness tradeoff in RAG answers?"}, {"role": "assistant", "content": "Score faithfulness with NLI entailment against retrieved passages and helpfulness with human preference on 200 samples. Plot Pareto where strict grounding reduces completeness 15%. Vary decoding constraints from free generation to extractive quotes to map curve. Segment by query type where factual lookup needs high faithfulness but brainstorming tolerates creativity. Use RAGAS metrics reporting faithfulness, answer relevancy, and context recall separately. Run A/B where variant prompts emphasize cite every claim. Decide threshold based on domain risk; medical requires 0.95 faithfulness even at helpfulness cost. Monitor user follow-ups asking for more detail as helpfulness proxy. Version prompts with hashes and run regression suites in CI. Track token cost, latency, and judge scores per release for safe rollout. Record metrics in dashboards segmented by relevant cohorts. Require explicit approval when quality, cost, or latency regress beyond agreed thresholds."}], "metadata": {"domain": "llm_engineering", "task_type": "experiment_analysis", "difficulty": "advanced"}} {"messages": [{"role": "user", "content": "Implement QLoRA for Llama-3-8B on a 16GB GPU for medical Q&A. What settings keep it stable and avoid catastrophic forgetting?"}, {"role": "assistant", "content": "Load in 4-bit NF4 with double quantization to fit 8B in 16GB: BitsAndBytesConfig load_in_4bit, bnb_4bit_quant_type nf4, use_double_quant True, compute dtype bf16. Set LoRA r 32, alpha 64 for knowledge-heavy task, dropout 0.1, targets all linear layers to retain reasoning. Use small lr 1e-4 with cosine and 5 percent warmup, batch 4 with accumulation 8 for effective 32. Limit to 2 epochs on curated 8k medical pairs mixed with 10 percent general instruction data to preserve fluency. Enable neftune_noise_alpha 5 for robustness and gradient checkpointing. Monitor MMLU general plus medical accuracy; if general drops over 2 points, increase replay mix or lower lr. Evaluate faithfulness with clinician checklist, not just BLEU. Save adapters separately and test merged versus adapter inference for deployment. Never train on PHI without de-identification and access controls."}], "metadata": {"domain": "llm_engineering", "task_type": "implementation", "difficulty": "intermediate"}} {"messages": [{"role": "user", "content": "Secure LLM plugin system against tool hijacking, SSRF, and excessive permissions."}, {"role": "assistant", "content": "Define minimal tool schemas with allowlisted domains and URL validation blocking private IPs to prevent SSRF. Require explicit user consent for state-changing tools with preview of arguments. Isolate tool execution in sandboxed workers with egress filtering and timeouts. Validate tool outputs for injection before feeding to model. Implement OAuth scoped per tool with short-lived tokens. Log all tool invocations with arguments for audit. Test with malicious tool descriptions attempting to override instructions. Enforce rate limits per tool and user. Conduct threat modeling for each new plugin. Monitor anomalous tool sequences indicating hijack. Document permission model and review plugins quarterly for least privilege."}], "metadata": {"domain": "llm_engineering", "task_type": "security", "difficulty": "advanced"}} {"messages": [{"role": "user", "content": "Refactor single-agent workflow into multi-agent planner-executor-critic system."}, {"role": "assistant", "content": "Refactor by splitting responsibilities: planner decomposes goal into DAG of subtasks with success criteria, executors invoke tools per subtask with limited scope, critic validates outputs against criteria and triggers retries. Use shared blackboard for state with versioned entries to avoid context duplication. Define message schemas between agents and enforce via pydantic. Limit planner to five subtasks and executor to six tool calls each. Add orchestrator handling timeouts and budget caps. Test on twenty complex tasks comparing success rate, cost, and latency versus monolith. Multi-agent improves success twelve points on compositional tasks but doubles cost; gate its use to high-value queries via router. Log inter-agent messages for debugging. This modularity isolates failures, enables independent prompt tuning, and scales better than stuffing all reasoning into single overloaded context window prone to distraction."}], "metadata": {"domain": "llm_engineering", "task_type": "code_review", "difficulty": "advanced"}} {"messages": [{"role": "user", "content": "Explain KV cache and continuous batching in LLM serving."}, {"role": "assistant", "content": "KV cache stores key and value tensors for prior tokens to avoid recomputing attention on each decode step, trading GPU memory for speed. Without it, latency grows quadratically; with it, decode is linear. Continuous batching, pioneered by vLLM, packs requests at token granularity rather than request level, inserting new prompts as soon as space frees in KV cache. This raises throughput three to five times versus static batching under variable lengths. PagedAttention fragments KV cache into blocks to reduce waste. Operators must balance max sequence length, GPU memory utilization, and batch tokens to avoid evictions. Monitor cache hit rate and preemptions. Understanding these mechanics helps tune max-model-len, choose quantization, and predict cost versus latency tradeoffs when scaling chat, summarization, or agent workloads with bursty traffic patterns."}], "metadata": {"domain": "llm_engineering", "task_type": "instruction", "difficulty": "intermediate"}} {"messages": [{"role": "user", "content": "Prevent data contamination in LLM benchmarking with canary and hashing."}, {"role": "assistant", "content": "Insert canary strings and hash test items, filtering pretraining data via Bloom filters. Audit overlap with 13-gram matching. Evaluate inflated scores by ablating contaminated docs. Compare private held out versus public benchmarks. Document data cutoff and filtering. Use trusted execution for evaluation. Monitor web leakage post release. Rotate test sets. Require contamination reports. Implement license checks. Plan dynamic benchmarks. Audit tokenizer coverage and out of vocabulary rates across languages and domains to guide vocabulary updates. Add regression tests for edge cases including emojis negations and code switching. Log metrics artifacts and data hashes to enable auditing and consistent comparison across runs. Log metrics artifacts and data hashes to enable auditing and consistent comparison across runs."}], "metadata": {"domain": "llm_engineering", "task_type": "debugging", "difficulty": "expert"}} {"messages": [{"role": "user", "content": "Implement vectorized rolling z-score anomaly detection in pandas for 5M-row sensor data without Python loops."}, {"role": "assistant", "content": "Use vectorized rolling statistics with shift to prevent lookahead bias while keeping all computation in optimized C loops for maximum throughput on large frames. Compute rolling mean and standard deviation exclusively on prior observations, then score each current value against that historical context to detect abrupt deviations reliably. For example shifted equals column shift one, mean equals shifted rolling sixty min_periods thirty mean, std equals shifted rolling sixty min_periods thirty std with ddof zero, replacement of zero by tiny epsilon, and fillna for startup stability. Cast features to float32 to halve memory footprint on five million rows and preserve cache efficiency. Validate approach by injecting synthetic spikes of known magnitude and measuring recall, precision, false positive rate, and detection delay across thresholds. This method runs O(n) in C versus O(n times w) in Python, typically one hundred times faster, supports incremental streaming updates with fixed buffers, and avoids fragmentation."}], "metadata": {"domain": "numpy_pandas", "task_type": "implementation", "difficulty": "beginner"}} {"messages": [{"role": "user", "content": "Refactor wide to long with melt for time-series modeling."}, {"role": "assistant", "content": "Replace manual column loops with pd_melt id_vars entity date_vars value_vars month columns var_name month value_name sales. Convert month to datetime with to_datetime format. Sort by entity date and validate row count equals wide rows times n months. Use pivot_table to invert if needed. Handle mixed dtypes with value_vars selection. Test roundtrip melt plus pivot equals original within tolerance. Use categorical month for memory. Benchmark versus stack. Document for modeling requiring tidy series. This creates ML ready long format, removes brittle loops, preserves metadata, and enables groupby rolling features for forecasting pipelines today reliably with extended validation and reproducible checks for production readiness always ensuring stability and generalization performance today."}], "metadata": {"domain": "numpy_pandas", "task_type": "code_review", "difficulty": "intermediate"}} {"messages": [{"role": "user", "content": "Visualize missingness bars and correlation heatmap for EDA reporting to stakeholders."}, {"role": "assistant", "content": "Stakeholders grasp gaps faster from visuals than tables. Plot missingness bars plus correlation heatmap to prioritize cleaning and feature selection for modeling. Code:\n```python\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nmiss = df.isna().mean().sort_values(ascending=False)\nmiss[miss > 0].plot(kind='barh')\nplt.xlabel('missing rate')\nplt.show()\ncorr = df.select_dtypes('number').corr(numeric_only=True)\nplt.imshow(corr, vmin=-1, vmax=1)\nplt.xticks(range(len(corr)), corr.columns, rotation=90)\nplt.yticks(range(len(corr)), corr.columns)\nplt.colorbar()\nplt.show()\nprint(corr.abs().max().sort_values(ascending=False).head())\n```\nHighlight highly correlated pairs above threshold for removal. Export figures for data quality documentation and review meetings with engineering teams. For production use add logging and unit tests plus versioned data snapshots. Monitor metrics over time and document assumptions for teammates. Validate edge cases with nulls and empty frames before deployment to avoid silent failures in live systems."}], "metadata": {"domain": "numpy_pandas", "task_type": "experiment_analysis", "difficulty": "advanced"}} {"messages": [{"role": "user", "content": "Architect a validation layer with pandera for critical financial ETL."}, {"role": "assistant", "content": "Declare schema with range checks and regex to fail fast before downstream corruption.\nimport pandas as pd\nimport pandera.pandas as pa\nschema = pa.DataFrameSchema({'id': pa.Column('string', unique=True), 'amt': pa.Column(float, pa.Check.between(0, 1e6)), 'ts': pa.Column('datetime64[ns]')})\ndef validate(df):\n return schema.validate(df)\nEdge cases: nullable versus required changes validation outcome. Coerce True hides dirty data, prefer strict plus explicit cleaning. Timezone aware needs tz-aware dtype. Large frames validation cost high, sample plus full key checks. Version schema with code to track drift. Production hardening: validate input schemas and check for empty frames. Log missing rates and memory usage. Pin pandas and numpy versions. Set random_state 42 for reproducibility. Add unit tests for empty, all-NaN and single-group inputs. Monitor downstream distribution drift and document assumptions for reviewers to reproduce results reliably in production."}], "metadata": {"domain": "numpy_pandas", "task_type": "architecture", "difficulty": "advanced"}} {"messages": [{"role": "user", "content": "Optimize memory of DataFrame with object columns and int64 that OOMs at 20M rows."}, {"role": "assistant", "content": "Downcast numerics and convert low-cardinality objects to category, load only needed columns.\nimport pandas as pd\ndef shrink(df):\n for c in df.select_dtypes('integer').columns:\n df[c] = pd.to_numeric(df[c], downcast='integer')\n for c in df.select_dtypes('object').columns:\n if df[c].nunique()/len(df) < 0.05:\n df[c] = df[c].astype('category')\n return df\nEdge cases: category breaks if new labels appear, handle with union. Downcast int may overflow, check min max first. Float downcast to float32 loses precision for money. Date objects stay heavy, convert to datetime64. Measure with memory_usage deep True before and after. Production hardening: validate input schemas and check for empty frames. Log missing rates and memory usage. Pin pandas and numpy versions. Set random_state 42 for reproducibility. Add unit tests for empty, all-NaN and single-group inputs. Monitor downstream distribution drift and document assumptions for reviewers to reproduce results reliably in production."}], "metadata": {"domain": "numpy_pandas", "task_type": "optimization", "difficulty": "intermediate"}} {"messages": [{"role": "user", "content": "Implement zero-copy sliding windows with numpy stride_tricks for 10M length signal safely."}, {"role": "assistant", "content": "Sliding_window_view creates strided view without copy, but must ensure contiguous input and bound memory.\nimport numpy as np\nfrom numpy.lib.stride_tricks import sliding_window_view\nx = np.ascontiguousarray(np.random.randn(10000000))\nw = sliding_window_view(x, 256)\nmeans = w.mean(axis=1)\nprint(w.shape, means[:3])\nEdge cases: non-contiguous slice gives wrong strides, call ascontiguousarray. View holds reference preventing GC, delete when done. Write to view mutates original, copy if needed. Huge windows explode shape, chunk processing. Overlapping windows break independence assumptions in CV, use grouped splits. Production hardening: validate input schemas and check for empty frames. Log missing rates and memory usage. Pin pandas and numpy versions. Set random_state 42 for reproducibility. Add unit tests for empty, all-NaN and single-group inputs. Monitor downstream distribution drift and document assumptions for reviewers to reproduce results reliably in production."}], "metadata": {"domain": "numpy_pandas", "task_type": "implementation", "difficulty": "expert"}} {"messages": [{"role": "user", "content": "Review groupby apply returning inconsistent shapes. Recommend transform or agg."}, {"role": "assistant", "content": "Apply with conditional return creates ragged frames and slow python loops. Use transform for broadcast, agg for reduction.\nimport pandas as pd\ndf = pd.DataFrame({'g': ['a','a','b'], 'v': [1,2,3]})\n# fragile: df.groupby('g').apply(lambda d: d if len(d)>1 else None)\ngood = df.assign(centered=df['v'] - df.groupby('g')['v'].transform('mean'))\nagg = df.groupby('g')['v'].agg(['mean','std'])\nprint(good, agg)\nEdge cases: apply on empty group returns empty, breaking concat. Transform preserves original index alignment. Agg with custom func must return scalar. For ranking use rank method not apply. Test with single-row groups which often break apply logic. Production hardening: validate input schemas and check for empty frames. Log missing rates and memory usage. Pin pandas and numpy versions. Set random_state 42 for reproducibility. Add unit tests for empty, all-NaN and single-group inputs. Monitor downstream distribution drift and document assumptions for reviewers to reproduce results reliably in production."}], "metadata": {"domain": "numpy_pandas", "task_type": "code_review", "difficulty": "intermediate"}} {"messages": [{"role": "user", "content": "Explain loc vs iloc with examples on a customer DataFrame. How to safely update a slice?"}, {"role": "assistant", "content": "Loc selects by label and iloc by position, both return views or copies unpredictably so assign only via loc or iloc directly.\nimport pandas as pd\ndf = pd.DataFrame({'name': ['ann','bob','cid'], 'age': [25,30,22]}, index=[10,20,30])\nprint(df.loc[10])\nprint(df.iloc[0])\ndf.loc[df['age']>24, 'age'] = 99\ndf.iloc[0:2, 1] = 50\nEdge cases: slicing loc includes stop label while iloc excludes stop position. Non-unique index with loc returns DataFrame not Series. Setting on filtered copy warns, use loc on original. Integer index confuses loc versus iloc, prefer explicit method. After sorting, positions change but labels persist, revalidate iloc ranges. Production hardening: validate input schemas and check for empty frames. Log missing rates and memory usage. Pin pandas and numpy versions. Set random_state 42 for reproducibility. Add unit tests for empty, all-NaN and single-group inputs. Monitor downstream distribution drift and document assumptions for reviewers to reproduce results reliably in production."}], "metadata": {"domain": "numpy_pandas", "task_type": "instruction", "difficulty": "intermediate"}} {"messages": [{"role": "user", "content": "Visualize multi-index sales with faceted heatmaps."}, {"role": "assistant", "content": "Set MultiIndex region category month then unstack month for matrix. Plot seaborn heatmap annot fmt .0f cmap YlGnBu with tight_layout. Facet by year with catplot or subplots sharey. Normalize by row for share view and annotate top cells. Handle missing with fill_value 0 and mask. Validate totals with groupby sum. Save 200 dpi. Add colorbar label. Test figure generation in CI with Agg backend. Explain seasonality to stakeholders. This reveals regional patterns, highlights outliers, communicates performance compactly, and supports inventory decisions with reproducible visual analytics today reliably with extended validation and reproducible checks for production readiness always ensuring stability and generalization today. Set random_state 42 for reproducibility and validate on stratified holdout with cross-validation to confirm generalization stability and deployment readiness for production workflows."}], "metadata": {"domain": "numpy_pandas", "task_type": "experiment_analysis", "difficulty": "advanced"}} {"messages": [{"role": "user", "content": "My pivot_table double counts revenue. Orders have duplicate order_ids. Debug it."}, {"role": "assistant", "content": "Duplicates inflate sums unless deduplicated or aggregated at correct grain before pivot. Validate uniqueness first.\nimport pandas as pd\ndf = pd.DataFrame({'oid': [1,1,2], 'cat': ['a','a','b'], 'rev': [10,10,20]})\nprint(df.duplicated('oid', keep=False))\ndedup = df.drop_duplicates('oid')\npt = dedup.pivot_table(index='cat', values='rev', aggfunc='sum')\nprint(pt)\nEdge cases: same id with differing values indicates data quality issue, audit before drop. Pivot with margins includes totals that confuse validation. NaN categories dropped by default, use dropna False. Multiple aggfuncs create MultiIndex columns needing flatten. Ensure numeric dtype, strings concatenate instead of summing. Production hardening: validate input schemas and check for empty frames. Log missing rates and memory usage. Pin pandas and numpy versions. Set random_state 42 for reproducibility. Add unit tests for empty, all-NaN and single-group inputs. Monitor downstream distribution drift and document assumptions for reviewers to reproduce results reliably in production."}], "metadata": {"domain": "numpy_pandas", "task_type": "debugging", "difficulty": "intermediate"}} {"messages": [{"role": "user", "content": "Tune chunked CSV processing for minimal memory and max throughput."}, {"role": "assistant", "content": "Read with pd_read_csv chunksize 200k usecols dtypes parse_dates engine pyarrow to bound memory. Process each chunk vectorized groupby agg then combine partials with concat plus groupby sum mean weighted. Use categorical dtype consistent across chunks via dtype dict. Benchmark chunk sizes 50k 200k 1M for throughput. Validate totals versus single pass on sample. Write output incrementally to Parquet dataset. Monitor RSS with psutil. Set low_memory False and on_bad_lines skip. Use multiprocessing for CPU bound transforms. This avoids OOM on 50GB logs, maintains correctness of global aggregates, maximizes IO overlap, and enables scalable ETL on modest machines for production analytics today reliably. Track metrics with versioned data splits and persist artifacts with joblib to ensure auditability and reliable promotion from staging to production."}], "metadata": {"domain": "numpy_pandas", "task_type": "experiment_analysis", "difficulty": "intermediate"}} {"messages": [{"role": "user", "content": "Explain how to handle missing timestamps and duplicate events in pandas time series."}, {"role": "assistant", "content": "Parse with pd.to_datetime utc True and sort by event time. Deduplicate on event_id keeping last with keep last after sorting by ingestion time. Reindex to complete range with asfreq and flag imputed rows. Use forward fill limited to 3 steps then mark gaps over 1 hour as NaN. Detect duplicates via groupby size over 1. Validate no future timestamps beyond now. Resample with closed left and label left for consistency. Plot gaps histogram to distinguish sensor outage from missing uploads. Document imputation policy for downstream models. Validate outputs against a small pandas baseline for correctness. Profile memory and runtime with representative data sizes before scaling. Record metrics in dashboards segmented by relevant cohorts. Require explicit approval when quality, cost, or latency regress beyond agreed thresholds."}], "metadata": {"domain": "numpy_pandas", "task_type": "instruction", "difficulty": "beginner"}} {"messages": [{"role": "user", "content": "Pandas API allows arbitrary column selection leading to data exfiltration of sensitive columns. How to secure while keeping analytics flexible?"}, {"role": "assistant", "content": "Dynamic column params without allowlist expose sensitive fields like salary to low privilege roles. Define explicit allowlisted columns per role, validate query params against schema, reject unknown fields with 400. Implement column level ACL mapping user role to permitted set enforced before DataFrame projection. Mask sensitive values with hashing for analysts needing distributions. Log selected columns and user id for audit. Test matrix of roles versus columns asserting denial for unauthorized access. Add integration test for injection like password column attempt. Monitor denied attempts spikes indicating probing. Cache permitted schemas to avoid per request overhead. Document allowed fields in OpenAPI. This prevents exfiltration while keeping flexible analytics for permitted fields and maintaining query performance with clear error messages."}], "metadata": {"domain": "numpy_pandas", "task_type": "security", "difficulty": "intermediate"}} {"messages": [{"role": "user", "content": "Test resampling logic: ensure hourly to daily OHLC preserves totals and handles gaps."}, {"role": "assistant", "content": "Resampling must define label and closed conventions plus missing handling. Test OHLC aggregation, sum totals match, and forward fill limits. Use fixed freq and timezone aware index.\n```python\nimport pandas as pd\nimport numpy as np\nidx = pd.date_range('2024-01-01', periods=48, freq='h', tz='UTC')\ndf = pd.DataFrame({'price': np.arange(48)+100, 'vol': 10}, index=idx)\ndaily = df.resample('D').agg({'price': 'ohlc', 'vol': 'sum'})\nprint(daily.head())\nassert daily[('vol','sum')].sum() == df['vol'].sum()\ndef test_gaps():\n d2 = df.drop(df.index[5:10])\n r = d2['price'].resample('D').mean()\n assert len(r) == 2\n print(r)\n```\nAssert monotonic index, no duplicate timestamps, and document gap policy for downstream models. Validate dtypes and row counts after each transform, profile memory with deep usage, assert no silent index misalignment, and persist partitioned parquet with schema checks for reproducible downstream analysis."}], "metadata": {"domain": "numpy_pandas", "task_type": "testing", "difficulty": "intermediate"}} {"messages": [{"role": "user", "content": "Implement efficient top-k per group retrieval in pandas for recommendation candidates."}, {"role": "assistant", "content": "Top-k per group needs sorting within groups without full sort overhead. Use groupby rank or nlargest per group, then filter. Pre-sort by score descending for speed and reset index cleanly.\n```python\nimport pandas as pd\n# method 1 rank\ndf['rank'] = df.groupby('user')['score'].rank(method='first', ascending=False)\ntop = df[df['rank'] <= 5].sort_values(['user','rank'])\nprint(top.head())\n# method 2 nlargest per group\n# top2 = df.groupby('user', group_keys=False).apply(lambda g: g.nlargest(5, 'score'))\n# faster sort + head\n# top3 = df.sort_values(['user','score'], ascending=[True, False]).groupby('user').head(5)\nprint(top.shape)\n```\nBenchmark on large frames, ensure deterministic tie break, and test k larger than group size. Validate dtypes and row counts after each transform, profile memory with deep usage, assert no silent index misalignment, and persist partitioned parquet with schema checks for reproducible downstream analysis."}], "metadata": {"domain": "numpy_pandas", "task_type": "implementation", "difficulty": "advanced"}} {"messages": [{"role": "user", "content": "Optimize join skew with adaptive salting driven by runtime histogram sampling for terabyte scales."}, {"role": "assistant", "content": "Handle unpredictable data skew by sampling key distributions at runtime, dynamically assigning salt factors proportional to observed frequencies, and executing two phase aggregation without manual tuning. Sample one percent partitions to estimate counts, classify hot keys exceeding three standard deviations, broadcast salt mapping to workers, apply salted groupby for hot subset while preserving\u76f4\u901a\u8f66 direct path for cold keys, then merge partial results deterministically. Measure partition max to median ratio dropping eight to one point five, runtime halving on terabyte joins, and sampling overhead under two percent. Validate exactness against baseline on controlled datasets, test evolving skew across micro-batches, monitor sampling accuracy, automate threshold adaptation, document operational visibility with skew dashboards, and enable reliable processing of highly imbalanced clickstream and transaction workloads at scale."}], "metadata": {"domain": "numpy_pandas", "task_type": "experiment_analysis", "difficulty": "expert"}} {"messages": [{"role": "user", "content": "Analyze Dask groupby skew where 1 percent keys hold 80 percent rows with salting fix."}, {"role": "assistant", "content": "Detect severe key imbalance through value counts and partition size diagnostics, then distribute hot keys with randomized salting and two stage aggregation to eliminate stragglers. Identify top ten hot identifiers, append salt zero to fifteen for hot rows versus zero otherwise, perform first stage groupby on identifier plus salt, then second stage groupby on identifier alone for exact totals. Profile partition sizes shrinking from eight gigabytes to five hundred megabytes, verify result equality against sampled single machine computation, monitor Dask dashboard for balanced runtimes, tune salt cardinality eight to thirty two based on hot key prevalence, persist intermediates to disk to reduce memory pressure, use deterministic seeds for reproducibility, cut runtime forty five to nine minutes, automate skew alerts when maximum partition exceeds twice median, and document hot key handling procedures."}], "metadata": {"domain": "numpy_pandas", "task_type": "experiment_analysis", "difficulty": "advanced"}} {"messages": [{"role": "user", "content": "Optimize Parquet reading for pandas training loop scanning 500GB."}, {"role": "assistant", "content": "Use pyarrow dataset with filters pushed down on date and category to read 10% data. Select columns projection to cut IO 70%. Set engine pyarrow with dtype_backend pyarrow for zero-copy. Partition files 256MB to balance parallelism. Pre-sort by label for faster sampling. Enable async IO with 16 threads. Cache metadata with _metadata file. Benchmark pandas versus polars scan showing 3x gain. Monitor S3 GET count and throttle. Convert to Feather for hot epochs after first scan. Validate outputs against a small pandas baseline for correctness. Profile memory and runtime with representative data sizes before scaling. Record metrics in dashboards segmented by relevant cohorts. Require explicit approval when quality, cost, or latency regress beyond agreed thresholds."}], "metadata": {"domain": "numpy_pandas", "task_type": "optimization", "difficulty": "intermediate"}} {"messages": [{"role": "user", "content": "Implement a function to clean currency strings like $1,200.50 into float column safely."}, {"role": "assistant", "content": "Strip symbols with regex then coerce to numeric to handle malformed entries as NaN for audit.\nimport pandas as pd\ndef clean_currency(s: pd.Series) -> pd.Series:\n cleaned = s.astype('string').str.strip().str.replace(r'[$,]', '', regex=True)\n cleaned = cleaned.replace({'': pd.NA, 'nan': pd.NA, 'None': pd.NA})\n return pd.to_numeric(cleaned, errors='coerce')\ns = pd.Series(['$1,200.50', ' 300 ', None])\nprint(clean_currency(s))\nEdge cases: parentheses accounting negatives need custom handling. European formats with dot thousand separator require locale logic. Empty strings become NaN not zero, decide business rule. Preserve original column for audit trail. Object dtype with mixed types needs astype string first to avoid attribute errors. Production hardening: validate input schemas and check for empty frames. Log missing rates and memory usage. Pin pandas and numpy versions. Set random_state 42 for reproducibility. Add unit tests for empty, all-NaN and single-group inputs. Monitor downstream distribution drift and document assumptions for reviewers to reproduce results reliably in production."}], "metadata": {"domain": "numpy_pandas", "task_type": "implementation", "difficulty": "intermediate"}} {"messages": [{"role": "user", "content": "Debug misaligned arithmetic between pandas Series with different indexes silently producing NaNs."}, {"role": "assistant", "content": "Pandas aligns on index, so adding Series with mismatched indexes yields NaNs instead of positional sums. Detect with missing spikes then reindex or use values for positional math. Code:\n```python\nimport pandas as pd\nimport numpy as np\na = pd.Series([10, 20, 30], index=[0, 1, 2])\nb = pd.Series([1, 2, 3], index=[1, 2, 3])\nprint(a + b)\nprint(a.add(b, fill_value=0))\nprint(pd.Series(a.values + b.values[:3], index=a.index))\nassert a.add(b, fill_value=0).notna().all()\n```\nReset indexes before numpy interop. Use to numpy method for positional math and validate lengths match to avoid silent errors in financial calculations and reporting. For production use add logging and unit tests plus versioned data snapshots. Monitor metrics over time and document assumptions for teammates. Validate edge cases with nulls and empty frames before deployment to avoid silent failures in live systems."}], "metadata": {"domain": "numpy_pandas", "task_type": "debugging", "difficulty": "advanced"}} {"messages": [{"role": "user", "content": "Optimize slow pandas apply with vectorized string and numeric operations for speed."}, {"role": "assistant", "content": "Row wise apply is Python loop slow. Replace with vectorized string accessors and numpy where to achieve large speedups while handling nulls safely and cleanly. Code:\n```python\nimport pandas as pd\nimport numpy as np\ndf['domain'] = df['email'].str.split('@').str[1].str.lower()\ndf['high_value'] = np.where(df['amount'].fillna(0) > 1000, 1, 0)\ndf['fee'] = df['amount'].fillna(0) * np.where(df['plan'] == 'premium', 0.01, 0.02)\nprint(df[['domain', 'high_value', 'fee']].head())\n```\nBenchmark with timeit to prove gains. Use numba only if vectorization impossible, and categoricals for repeated strings to cut memory usage and improve join performance substantially. For production use add logging and unit tests plus versioned data snapshots. Monitor metrics over time and document assumptions for teammates. Validate edge cases with nulls and empty frames before deployment to avoid silent failures in live systems."}], "metadata": {"domain": "numpy_pandas", "task_type": "optimization", "difficulty": "beginner"}} {"messages": [{"role": "user", "content": "Debug inconsistent embeddings from a multilingual E5 model where same sentence yields different vectors across batches."}, {"role": "assistant", "content": "Inconsistency usually comes from nondeterministic pooling, varying attention masks, or tokenizer padding side effects. First fix model to eval mode disabling dropout and verify deterministic algorithms. Compare tokenization outputs for single versus batched inputs, checking padding token handling and truncation. Ensure L2 normalization applied consistently after pooling and that mean pooling divides by true mask sum. Test with batch size one versus 32 using fixed seed and log max absolute difference. Inspect mixed precision casting and fused kernels that may introduce variance. Pin transformers and tokenizers versions and disable dynamic quantization during test. Once root cause found, add regression test asserting cosine similarity above 0.999 for identical inputs across batch sizes and document preprocessing contract."}], "metadata": {"domain": "numpy_pandas", "task_type": "debugging", "difficulty": "intermediate"}} {"messages": [{"role": "user", "content": "Fix pandas datetime parsing bug with mixed formats and timezones correctly."}, {"role": "assistant", "content": "Mixed formats and naive versus aware timestamps break sorting and resampling. Parse with coercion then localize and convert consistently across all sources. Code:\n```python\nimport pandas as pd\ndf['ts'] = pd.to_datetime(df['raw_ts'], errors='coerce', utc=True)\nprint(df['ts'].isna().sum())\nprint(df.loc[df['ts'].isna(), 'raw_ts'].unique()[:5])\ndf['ts'] = df['ts'].dt.tz_convert('America/New_York')\ndf = df.dropna(subset=['ts']).sort_values('ts')\nprint(df['ts'].dt.tz)\nprint(df['ts'].min(), df['ts'].max())\n```\nValidate no future timestamps and monotonicity after sort. Store as UTC parquet and convert only for display to avoid daylight saving bugs in global pipelines. For production use add logging and unit tests plus versioned data snapshots. Monitor metrics over time and document assumptions for teammates. Validate edge cases with nulls and empty frames before deployment to avoid silent failures in live systems."}], "metadata": {"domain": "numpy_pandas", "task_type": "debugging", "difficulty": "intermediate"}} {"messages": [{"role": "user", "content": "Implement vectorized z-score outlier clipping per group in pandas without iterrows."}, {"role": "assistant", "content": "Groupwise clipping requires group mean and std broadcast via transform, not row loops. Compute z-scores vectorized, clip beyond threshold, and preserve original index. Use robust median and MAD for skewed data.\n```python\nimport pandas as pd\nimport numpy as np\ndf['mean'] = df.groupby('store')['sales'].transform('mean')\ndf['std'] = df.groupby('store')['sales'].transform('std').fillna(0)\ndf['z'] = (df['sales'] - df['mean']) / df['std'].replace(0, np.nan)\ndf['sales_clipped'] = df['sales'].clip(df['mean'] - 3*df['std'], df['mean'] + 3*df['std'])\n# robust alternative\nmed = df.groupby('store')['sales'].transform('median')\nmad = (df['sales'] - med).abs().groupby(df['store']).transform('median')\ndf['robust_z'] = 0.6745*(df['sales']-med)/mad.replace(0, np.nan)\nprint(df[['store','sales','sales_clipped']].head())\nprint((df['z'].abs() > 3).mean())\n```\nValidate clip rate per group and plot before after distributions to avoid over-smoothing. Validate dtypes and row counts after each transform, profile memory with deep usage, assert no silent index misalignment, and persist partitioned parquet with schema checks for reproducible downstream analysis."}], "metadata": {"domain": "numpy_pandas", "task_type": "implementation", "difficulty": "intermediate"}} {"messages": [{"role": "user", "content": "Analyze why my A/B test CHI-square in pandas disagrees with statsmodels proportions_ztest."}, {"role": "assistant", "content": "Check whether you used Yates correction in chi2_contingency default True, which underestimates significance for large samples. Verify counts versus rates input; ztest expects successes and nobs separately. Inspect handling of zero cells and small expected frequencies under 5 violating chi-square assumptions. Compare two-sided versus one-sided alternatives. Recompute with scipy stats chi2 without correction to match ztest squared. Segment by day to detect Simpson paradox where pooled test hides heterogeneity. Plot confidence intervals with Wilson method for clarity. Document that chi-square and z-test are asymptotically equivalent but finite-sample corrections cause 0.01 p-value gaps. Validate outputs against a small pandas baseline for correctness. Profile memory and runtime with representative data sizes before scaling. Record metrics in dashboards segmented by relevant cohorts. Require explicit approval when quality, cost, or latency regress beyond agreed thresholds."}], "metadata": {"domain": "numpy_pandas", "task_type": "experiment_analysis", "difficulty": "intermediate"}} {"messages": [{"role": "user", "content": "My A/B revenue per user looks higher in variant but driven by one whale. How to analyze robustly in pandas?"}, {"role": "assistant", "content": "Report medians, trimmed means and rank tests alongside means to reveal outlier-driven lifts.\nimport pandas as pd\nimport numpy as np\ndf = pd.DataFrame({'grp': ['a']*100+['b']*100, 'rev': list(np.random.exponential(10,199))+[1000]})\nprint(df.groupby('grp')['rev'].agg(['mean','median','count']))\nprint(df.groupby('grp')['rev'].apply(lambda x: x.quantile(0.99)))\nEdge cases: single whale inflates mean and variance, winsorize sensitivity check. Zero-inflated revenue needs hurdle analysis. Unequal variances invalidate t-test, use Mann-Whitney. Attrition differences bias per-user metrics. Log transform helps but mishandles zeros, add one or use rank. Production hardening: validate input schemas and check for empty frames. Log missing rates and memory usage. Pin pandas and numpy versions. Set random_state 42 for reproducibility. Add unit tests for empty, all-NaN and single-group inputs. Monitor downstream distribution drift and document assumptions for reviewers to reproduce results reliably in production."}], "metadata": {"domain": "numpy_pandas", "task_type": "experiment_analysis", "difficulty": "intermediate"}} {"messages": [{"role": "user", "content": "Optimize memory of large string DataFrame by converting to categorical and pyarrow with measurements."}, {"role": "assistant", "content": "Measure then compress. Example: print(df.memory_usage(deep=True).sum()/1e6); for c in df.select_dtypes('object'): ratio=df[c].nunique()/len(df); if ratio<0.05: df[c]=df[c].astype('category'); df=df.convert_dtypes(dtype_backend='pyarrow'); print(df.memory_usage(deep=True).sum()/1e6); Use observed=True groupby, category codes for sklearn via .cat.codes. Pyarrow strings cut 60% versus object. Avoid object dtype for ints with NaN; use Int32. Drop unused categories remove_unused_categories. Save parquet dictionary encoding. Benchmark groupby speed before after. This optimization fits 5GB logs in RAM and accelerates merges, critical for feature engineering without cluster. For production readiness log all metrics parameters and data versions with MLflow record random seeds library versions and data hashes validate performance on holdout test sets check calibration fairness latency and memory usage monitor prediction drift after deployment and document business impact to ensure reliable generalization and maintainable operation for stakeholders."}], "metadata": {"domain": "numpy_pandas", "task_type": "optimization", "difficulty": "advanced"}} {"messages": [{"role": "user", "content": "Design a NumPy-based feature engineering pipeline for 10M time-series rows without pandas overhead."}, {"role": "assistant", "content": "Store data as structured arrays with float32 and int32 dtypes in contiguous C-order for cache efficiency. Compute rolling means with stride tricks and bottleneck move_mean 10x faster than pandas. Vectorize lag features via advanced indexing instead of shift loops. Use numba njit for custom rolling skewness handling NaNs. Chunk by entity ID sorting once with argsort to keep locality. Validate with equal checks against pandas on 10k sample. Memory-map large arrays from disk to avoid RAM blowup. Pipeline outputs memmapped features directly to training. Benchmark showing 4x throughput versus pandas apply. Validate outputs against a small pandas baseline for correctness. Profile memory and runtime with representative data sizes before scaling. Record metrics in dashboards segmented by relevant cohorts. Require explicit approval when quality, cost, or latency regress beyond agreed thresholds."}], "metadata": {"domain": "numpy_pandas", "task_type": "architecture", "difficulty": "advanced"}} {"messages": [{"role": "user", "content": "Propose streaming data quality framework for LLM ingestion with online sketches, adaptive thresholds, and exactly once semantics."}, {"role": "assistant", "content": "Propose Kafka Flink pipeline validating documents on arrival using Count-Min sketches for duplicate estimation, HyperLogLog for cardinality, and online toxicity classifiers with adaptive thresholds based on drift detection. Enforce exactly once semantics with transactional sinks and idempotent content hashing, quarantining violations to dead letter topics with lineage metadata. Implement windowing aggregations computing hourly quality dashboards, alerting on sudden PII spikes or language shifts. Evaluate on billion scale web crawl replay showing ninety nine percent precision at fifty millisecond p95 overhead. Provide fault tolerance via checkpointing, schema registry evolution, backpressure handling, cost modeling for state stores, formal guarantees of completeness, reproducible experiments with seed control, and operational runbooks. This enables continuous high quality LLM corpora without batch delays, supporting fresh retrieval indexes and safe finetuning on rapidly evolving internet and enterprise data streams."}], "metadata": {"domain": "numpy_pandas", "task_type": "retrieval_analysis", "difficulty": "expert"}} {"messages": [{"role": "user", "content": "Implement efficient rolling zscore anomaly detection in pandas without lookahead bias."}, {"role": "assistant", "content": "Global thresholds miss local shifts. Rolling mean and std adapt to regime changes and flag contextual anomalies without lookahead when properly shifted for streaming. Code:\n```python\nimport pandas as pd\nimport numpy as np\ns = pd.Series(np.random.default_rng(0).normal(0, 1, 1000).cumsum() + 50)\nwindow = 50\nroll_mean = s.shift(1).rolling(window, min_periods=window).mean()\nroll_std = s.shift(1).rolling(window, min_periods=window).std() + 1e-9\nz = (s - roll_mean) / roll_std\nflags = z.abs() > 3.5\nprint(flags.sum(), round(float(flags.mean()), 4))\nprint(s[flags].head())\n```\nTune window to seasonality. Exclude flagged points from rolling stats for robustness in streaming detectors with EWMA alternatives and adaptive thresholds for alerts. For production use add logging and unit tests plus versioned data snapshots. Monitor metrics over time and document assumptions for teammates. Validate edge cases with nulls and empty frames before deployment to avoid silent failures in live systems."}], "metadata": {"domain": "numpy_pandas", "task_type": "implementation", "difficulty": "advanced"}} {"messages": [{"role": "user", "content": "Property-test a numpy normalization function for idempotence, shape invariance, and NaN propagation."}, {"role": "assistant", "content": "Use hypothesis. Example: from hypothesis import given, strategies as st; import numpy as np; @given(st.lists(st.floats(-1e3,1e3,allow_nan=False),min_size=5)); def test_z(xs): a=np.array(xs); z=(a-a.mean())/(a.std()+1e-9); assert z.shape==a.shape; assert abs(z.mean())<1e-6; z2=(z-z.mean())/(z.std()+1e-9); assert np.allclose(z,z2,atol=1e-6); Test NaN: assert np.isnan(norm(np.array([np.nan]))).all(); Test empty raises ValueError. Check dtype float64 preserved, no mutation of input. Property tests reveal division-by-zero on constant arrays and overflow, guiding epsilon and masking. Run 200 examples in CI for robust numeric contract. For production readiness log all metrics parameters and data versions with MLflow record random seeds library versions and data hashes validate performance on holdout test sets check calibration fairness latency and memory usage monitor prediction drift after deployment and document business impact to ensure reliable generalization and maintainable operation for stakeholders."}], "metadata": {"domain": "numpy_pandas", "task_type": "testing", "difficulty": "expert"}} {"messages": [{"role": "user", "content": "Debug pandas SettingWithCopyWarning in chained assignment pipeline."}, {"role": "assistant", "content": "Warning arises from df[df.x>0].y=1 creating view versus copy ambiguity. Fix with .loc: df.loc[df.x>0, y]=1. Avoid chained indexing entirely. Use copy explicitly when slicing for independent transform. Enable mode chained_detection raise in tests to catch early. Refactor functions to take and return frames without inplace. Validate with assert after assignment. Check groupby apply returning views. Rewrite pipeline with assign and pipe for clarity. Add lint rule forbidding chained assignment. Consistent loc usage eliminates silent failures where updates do not persist, ensuring reproducible cleaning and feature engineering without hidden bugs.Add regression tests covering edge cases, log key metrics for observability, document versioned configs, and review failure modes in staging before promoting changes to production systems."}], "metadata": {"domain": "numpy_pandas", "task_type": "debugging", "difficulty": "advanced"}} {"messages": [{"role": "user", "content": "Pandas merge explodes row count from 10k to 2M. How do I diagnose?"}, {"role": "assistant", "content": "Check key uniqueness with duplicated and value_counts on both frames before merging. A many-to-many join on duplicated keys causes Cartesian blowup. Decide correct cardinality: use validate one_to_many or many_to_one to fail fast. Deduplicate keys with drop_duplicates or aggregate to one row per key via groupby. Inspect join type: inner versus left versus outer changes retention. Profile key dtypes and whitespace or case mismatches causing missed matches. Use indicator True to see merge source counts. After fixing, assert output rows within expected bounds and log input versus output shapes. For large merges, set keys as indexes, sort, and use pyarrow dtypes for memory. Reproduce on sample slice first. Explicit cardinality checks prevent silent explosion in ETL pipelines."}], "metadata": {"domain": "numpy_pandas", "task_type": "debugging", "difficulty": "intermediate"}} {"messages": [{"role": "user", "content": "Protect training data pipeline from poisoning via untrusted web sources and user uploads."}, {"role": "assistant", "content": "Establish allowlists for domains and validate uploads with ClamAV plus content type sniffing. Compute perceptual hashes to detect duplicate malicious payloads and run anomaly detection on embedding clusters for outlier injection. Require cryptographic signatures for partner feeds and quarantine new sources for manual review. Filter with toxicity and PII detectors and remove instructions attempting to influence model behavior. Maintain immutable raw bucket with versioning and audit logs. Test robustness by simulating poisoning attacks measuring impact on benchmarks. Implement data cards documenting provenance and risk scores. Schedule periodic rescans as detectors improve and define incident response for revoking tainted shards and retraining affected checkpoints."}], "metadata": {"domain": "numpy_pandas", "task_type": "security", "difficulty": "intermediate"}} {"messages": [{"role": "user", "content": "How do I monitor embedding drift signaling retrieval decay?"}, {"role": "assistant", "content": "Compute weekly embedding centroids for queries and docs with bge model, track cosine shift over 0.05 as drift alert. Visualize UMAP in Phoenix comparing prod versus eval distributions. Slice hit-rate by intent to find decayed segments like new product vocabulary. Trigger reindex or synonym expansion when drift detected. Store embeddings sample 10k in warehouse for analysis. Correlate drift with user feedback downvotes. Schedule job with Airflow running drift check nightly. Alert Slack with cluster examples. Validate fix by A/B recall lift. Proactive drift detection catches vocabulary shifts before major quality outage. Operational note: emit Prometheus metrics for latency and cost per tenant, add structured logs with trace ids, gate rollout behind feature flag with automatic rollback on error spike, and run load tests to validate SLOs before full promotion."}], "metadata": {"domain": "production_ai", "task_type": "retrieval_analysis", "difficulty": "intermediate"}} {"messages": [{"role": "user", "content": "Threat model for autonomous agent with code execution and browsing in production."}, {"role": "assistant", "content": "Map threats: prompt injection via web, tool abuse for data exfiltration, resource exhaustion. Mitigate with sandbox gVisor, no network except allowlist, read-only FS, CPU 2s timeout. Require approval for writes. Sanitize browsing output stripping scripts. Log all actions with trace. Isolate per tenant with separate containers. Scan generated code with Semgrep before exec. Rate limit tool calls 10 per task. Red-team quarterly with injection suite. Incident plan to kill agent and revoke keys. Document residual risk acceptance. This hardening enables useful agents without giving attackers shell in your VPC, balancing autonomy and safety for enterprise deployment. Operational note: emit Prometheus metrics for latency and cost per tenant, add structured logs with trace ids, gate rollout behind feature flag with automatic rollback on error spike, and run load tests to validate SLOs before full promotion."}], "metadata": {"domain": "production_ai", "task_type": "security", "difficulty": "expert"}} {"messages": [{"role": "user", "content": "Document incident response for data leakage via LLM memorization of training PII."}, {"role": "assistant", "content": "Outline detection via extraction tests and user reports, triage severity based on PII type and exploitability. Provide containment steps including disabling affected model version, purging caches, and rotating keys. Detail eradication through unlearning or retraining on scrubbed data with differential privacy. Include customer notification templates and regulatory timelines for GDPR 72 hours. Add postmortem template capturing root cause like inadequate redaction and corrective actions. Provide extraction test scripts and canary secrets to verify fix. Define roles for security, legal, and ML teams with on call rotations. Maintain evidence chain and update data handling policies to prevent recurrence. Additionally track metrics in versioned experiments and document tradeoffs to guide rollout decisions and future tuning priorities effectively. Additionally track metrics in versioned experiments and document tradeoffs to guide rollout decisions and future tuning priorities effectively. Additionally track metrics in versioned experiments and document tradeoffs to guide rollout decisions and future tuning priorities effectively."}], "metadata": {"domain": "production_ai", "task_type": "instruction", "difficulty": "advanced"}} {"messages": [{"role": "user", "content": "Triage sudden prediction drift in a pricing model. How to isolate data versus model versus upstream causes?"}, {"role": "assistant", "content": "Follow a structured triage tree starting with data validation before blaming the model. Check input schema, null rates, and distribution shifts with PSI per feature over the last 24 hours versus baseline, and correlate drift onset with deploys or upstream pipeline changes. Review feature pipeline logs for failed joins, stale tables, or timezone bugs, and verify label delay is not masquerading as decay. Compare shadow predictions from previous model version on current data to separate model staleness from input corruption. Inspect calibration plots and slice performance by segment to localize impact. If a single upstream column shifted, rollback or hotfix imputation and backfill; if concept drift, trigger retraining. Document timeline, evidence queries, and preventive monitors for schema and freshness to avoid recurrence."}], "metadata": {"domain": "production_ai", "task_type": "retrieval_analysis", "difficulty": "intermediate"}} {"messages": [{"role": "user", "content": "Harden multi-tenant RAG isolation against filter bypass and embedding inversion attacks."}, {"role": "assistant", "content": "Adopt strict namespace or collection separation for highly sensitive tenants rather than relying solely on shared-index filters, complemented by server-side mandatory filter validation and comprehensive bypass tests. Disable raw embedding exposure through public APIs to reduce inversion risks. Implement rate limiting, bulk extraction detection, and immutable audit logging of accessed chunks. Encrypt vectors at rest with per-tenant managed keys and enforce TLS throughout. Evaluate reconstruction feasibility using open inversion models to quantify risk. Apply calibrated noise only where recall impact remains acceptable. Conduct periodic penetration tests simulating malicious tenants attempting cross-boundary access. Document architectural decisions, key management procedures, threat models, and residual risks for security review, ensuring compliance and customer confidence in isolation guarantees."}], "metadata": {"domain": "production_ai", "task_type": "security", "difficulty": "advanced"}} {"messages": [{"role": "user", "content": "How do I detect and mitigate embedding drift in a production semantic search system?"}, {"role": "assistant", "content": "Track distribution of query and document embedding norms, cosine similarity scores, and nearest-neighbor distances over sliding windows. Compute PSI and maximum mean discrepancy between baseline and live embeddings to quantify shift. Monitor downstream metrics like CTR, zero-result rate, and reformulation rate as proxy labels. Version embeddings and maintain backward-compatible mapping with linear projection when upgrading models to avoid full reindexing. Trigger retraining or reindexing when drift exceeds threshold for three consecutive hours. Visualize with UMAP samples weekly to catch topic shift. Log out-of-distribution scores using Mahalanobis distance in embedding space. Implement canary index with new embeddings serving 5% traffic and compare recall at k on golden query set before full cutover."}], "metadata": {"domain": "production_ai", "task_type": "retrieval_analysis", "difficulty": "intermediate"}} {"messages": [{"role": "user", "content": "Design multi-model endpoints that serve 5 models on shared GPUs with isolation and cost efficiency."}, {"role": "assistant", "content": "Consolidate models behind a single gateway that routes by model ID with separate versioning and quotas. Use NVIDIA MPS or MIG slices to partition GPU compute, plus per-model memory quotas and concurrency limits to prevent noisy neighbors. Load models lazily with LRU eviction and warm the top two to meet latency SLOs, storing artifacts in shared volume cache. Implement per-tenant rate limiting, request batching per model, and independent autoscaling signals based on queue per model. Monitor per-model latency, error rates, GPU memory, and cost allocation withChargeback tags. Support canary per model without affecting others via header-based routing. Include fallback to CPU for low-traffic models and unified logging with model version tracing. This design cuts GPU count significantly while preserving isolation, observability, and safe independent releases."}], "metadata": {"domain": "production_ai", "task_type": "architecture", "difficulty": "advanced"}} {"messages": [{"role": "user", "content": "How do I add OpenTelemetry tracing to production LLM service with FastAPI?"}, {"role": "assistant", "content": "Instrument FastAPI with OpenTelemetryInstrumentator and httpx for downstream calls. Create spans for embed, retrieve, rerank, synthesize with attributes model, tokens, top_k. Export via OTLP to Tempo or Honeycomb with batch processor. Propagate W3C traceparent from gateway. Sample head 20 percent plus tail-based for errors. Add metrics for latency histogram and token counter using MeterProvider. Correlate logs via trace_id injection. Dashboard p95 by endpoint and model. Alert on error rate over 1 percent. Test locally with console exporter. Secure exporter with TLS and auth header. This setup pinpoints whether retriever or LLM dominates latency and enables per-customer cost analysis, essential for scaling from prototype to multi-tenant production with SLO compliance."}], "metadata": {"domain": "production_ai", "task_type": "implementation", "difficulty": "intermediate"}} {"messages": [{"role": "user", "content": "Design a production architecture for real-time fraud scoring with 50ms SLA, 5k RPS, and daily model retraining."}, {"role": "assistant", "content": "Place a lightweight gradient-boosted model or distilled neural net behind a low-latency service in Go or Rust with ONNX, achieving under 15ms inference. Use Kafka for transaction ingestion, Flink for streaming features from a Redis or DynamoDB online store, and batch features from Snowflake offline. Decouple scoring from retraining via feature store with point-in-time correctness. Daily retraining runs on Airflow with validation gates on AUC, PSI, and calibration before promotion. Deploy with blue-green and shadow scoring to compare challenger without affecting decisions. Add circuit breaker to rule-based fallback if model latency exceeds 40ms. Log features and scores to S3 for audit and drift detection with Evidently. Scale stateless scorers via Kubernetes HPA on p99 and RPS."}], "metadata": {"domain": "production_ai", "task_type": "architecture", "difficulty": "advanced"}} {"messages": [{"role": "user", "content": "How do I implement rate limiting and quota enforcement for production LLM gateway?"}, {"role": "assistant", "content": "Deploy token bucket rate limiter in Redis per API key and team with burst 100 and refill 50 per second, enforce daily quotas with counters and graceful 429 responses including Retry-After headers, prioritize interactive traffic over batch via separate queues, log throttled requests with tenant context, test limits with k6 ramp to 2k RPS, handle clock skew with centralized Redis time, monitor throttle rate alert over 5 percent, version limit configs in git, document quota increase process, secure bypass for internal health checks, implement fair queuing to avoid starvation, review usage weekly, automate quota alerts to Slack, ensure gateway remains stateless for horizontal scaling. Ongoing governance requires versioned configs, automated regression tests, monitored latency dashboards, and quarterly security reviews for durability and compliance."}], "metadata": {"domain": "production_ai", "task_type": "testing", "difficulty": "intermediate"}} {"messages": [{"role": "user", "content": "Refactor prompt construction code to use versioned templates."}, {"role": "assistant", "content": "Move inline f-strings into Jinja templates stored in prompts directory with semantic versioning. Create PromptLoader class validating required variables via pydantic. Replace ad-hoc concatenation with render function handling escaping and truncation. Add unit tests ensuring all variables supplied and output within token limits. Log template version with each LLM call for traceability. Support environment-specific overrides for staging versus production. Implement code review checklist for prompt changes. Add linter checking for injection-prone patterns. This reduces duplication, enables A/B testing, and simplifies rollback. Measure reduction in prompt-related bugs after migration. Document template naming conventions and ownership for team collaboration. Operationally enforce versioned prompts, canary analysis with automatic rollback, centralized logging with redacted PII, Prometheus metrics for latency and cost, and scheduled regression evaluation to prevent silent quality degradation in production."}], "metadata": {"domain": "production_ai", "task_type": "code_review", "difficulty": "intermediate"}} {"messages": [{"role": "user", "content": "P99 inference latency 3s for 34B model on 2xA100. Need 800ms at same cost. Plan?"}, {"role": "assistant", "content": "Disaggregate prefill on 1xA100 with chunked prefill 2048 tokens and decode on 1xA100 with paged attention and prefix caching to isolate tail effects. Quantize to FP8 e4m3 preserving 99 percent quality, enable speculative decoding with 1B draft achieving 1.8x speedup, and enforce max 1024 input plus 256 output with early truncation. Add two-level cache with Redis for exact matches and semantic cache threshold 0.95 covering 30 percent traffic. Autoscale decode replicas on TPOT over 40ms, use continuous batching size 128, and optimize kernels with torch.compile plus CUDA graphs. Measure TTFT under 200ms and TPOT under 25ms via detailed tracing, load test 80 RPS, and monitor KV fragmentation. This hybrid optimization meets 800ms P99 while keeping GPU count constant and cost per 1k tokens under 0.02 dollars."}], "metadata": {"domain": "production_ai", "task_type": "optimization", "difficulty": "advanced"}} {"messages": [{"role": "user", "content": "Tune dynamic batching for an embedding service to maximize GPUs without breaching 50ms p99. Show method."}, {"role": "assistant", "content": "Profile single-request latency then sweep max_batch_size 32 to 256 and timeout 5 to 20ms under realistic Poisson load. Implement server-side batching that accumulates requests up to timeout or size limit, padding efficiently and using CUDA graphs to reduce launch overhead. Measure throughput, p50 and p99 latency, GPU utilization, and queue drops, plotting latency versus throughput curves to find the saturation knee. Select settings that achieve 90 percent of max throughput while holding p99 under 50ms, typically batch 128 with 10ms timeout. Add priority bypass for single urgent requests and adaptive timeout that shrinks under high load. Validate with sustained soak tests and burst tests, monitoring memory fragmentation. Document per-GPU tuning, fallback to smaller batches on OOM, and autoscaling triggers based on queue depth."}], "metadata": {"domain": "production_ai", "task_type": "optimization", "difficulty": "advanced"}} {"messages": [{"role": "user", "content": "Write load tests for LLM chat API targeting 500 RPS with SLOs."}, {"role": "assistant", "content": "Script Locust with realistic conversation distributions, head versus long tail prompts, ramp to 500 RPS over 10 minutes, assert p50 under 800ms p95 under 2s error under 1 percent, monitor GPU queue, KV cache, autoscaler behavior, handle rate limiting with test API keys, isolate test environment to avoid prod impact, analyze bottlenecks via tracing, test autoscale from 5 to 20 replicas, validate graceful degradation under overload, log detailed histograms, version test scenarios, document capacity limits, automate nightly runs, alert on regression, secure test data, test websocket streaming separately, review results with capacity planning and ensure cost tracking for load test resources. Ongoing governance requires versioned configs, automated regression tests, monitored latency dashboards, and quarterly security reviews for durability and compliance."}], "metadata": {"domain": "production_ai", "task_type": "testing", "difficulty": "intermediate"}} {"messages": [{"role": "user", "content": "Design an observability stack for LLM apps covering traces, costs, and user feedback."}, {"role": "assistant", "content": "Unify traces, metrics, logs, and feedback around request IDs. Instrument with OpenTelemetry for spans covering gateway, retrieval, rerank, LLM calls, and tools, capturing tokens, latency, and model versions. Ship metrics to Prometheus for SLOs on availability, TTFB, error rates, and cost per request. Centralize structured logs with redacted prompts and hashed user IDs for debugging. Store feedback signals like thumbs, escalations, and corrections linked to traces. Build dashboards slicing by tenant, intent, model, and region. Add sampling for high-volume traffic and tail-based retention for errors. Alert on burn rates, cost spikes, and quality drops detected by sampled LLM judges. Enable trace replay for incident analysis and dataset creation to continuously improve prompts and retrieval."}], "metadata": {"domain": "production_ai", "task_type": "architecture", "difficulty": "intermediate"}} {"messages": [{"role": "user", "content": "Diagnose vector DB recall collapse after embedding upgrade."}, {"role": "assistant", "content": "Verify version mismatch old vectors versus new query embeddings via dimension check, inspect deployment logs for mixed model rollout, reproduce with sample queries comparing cosine distributions, rollback query embedding to previous version, rebuild index with new model in shadow collection, backfill with batch job checkpointed, validate recall recovers to baseline 92 percent, handle partial rebuild with versioned namespaces, add CI check enforcing model hash match, monitor embedding version metric, document incident, test upgrade procedure in staging, implement atomic switch, alert on recall drop, secure model artifacts, audit affected tenants and communicate timeline to prevent recurrence. Ongoing governance requires versioned configs, automated regression tests, monitored latency dashboards, and quarterly security reviews for durability and compliance."}], "metadata": {"domain": "production_ai", "task_type": "debugging", "difficulty": "advanced"}} {"messages": [{"role": "user", "content": "Craft chain of thought prompts for math word problems that improve accuracy without leaking final answer early."}, {"role": "assistant", "content": "Instruct model to restate problem, list knowns, plan solution steps, then execute calculations sequentially enclosed in scratch tags before final answer tag. Provide three exemplars showing algebraic setup and unit checks. Require verification step substituting answer back and checking plausibility. Use temperature 0 and max tokens 1024 to allow reasoning. Test on GSM8K subset measuring accuracy gain versus direct answering and analyze failure modes like arithmetic slips. Add tool use for calculator for large numbers to reduce errors. Constrain prompt to avoid revealing answer in reasoning prefix for evaluation fairness. Iterate wording to reduce verbosity while preserving stepwise structure and log token cost impact."}], "metadata": {"domain": "production_ai", "task_type": "instruction", "difficulty": "intermediate"}} {"messages": [{"role": "user", "content": "Implement distributed tracing sampling strategy for 1M LLM spans per day."}, {"role": "assistant", "content": "Apply head sampling 5 percent plus tail sampling 100 percent errors and high latency over 3s or high cost over 10 cents. Use OTel collector tail processor with 30s window. Store full traces in ClickHouse, metrics aggregated in Prometheus. Tag with tenant tier to ensure free tier sampled less. Implement dynamic sampling increasing during incidents. Estimate storage 50GB per day with compression. Dashboard sampling rate vs visibility. Test that critical failures always captured. Document tradeoff for compliance. This strategy retains diagnostic power while cutting observability cost 20x versus full capture at high volume, essential for sustainable production AI monitoring. Operational note: emit Prometheus metrics for latency and cost per tenant, add structured logs with trace ids, gate rollout behind feature flag with automatic rollback on error spike, and run load tests to validate SLOs before full promotion."}], "metadata": {"domain": "production_ai", "task_type": "implementation", "difficulty": "expert"}} {"messages": [{"role": "user", "content": "Design Redis semantic cache for RAG to handle paraphrased queries."}, {"role": "assistant", "content": "Store query embeddings alongside responses in Redis with RediSearch vector index. On new query embed with same model, perform vector search threshold cosine 0.92 for near-duplicate. If hit return cached answer with citations, else call LLM and store. Use TTL 7 days and LRU eviction maxmemory 2GB. Normalize embeddings to unit length for cosine. Log similarity distribution to tune threshold; too low causes wrong answers, too high misses savings. Namespace keys by index version to avoid stale hits after reindex. Measure hit_rate target 25 percent for support bots. Handle embedding failures with fallback to exact match. Invalidate on doc updates affecting cached queries via dependency tags. Semantic cache cuts LLM cost significantly while preserving quality for repetitive intents."}], "metadata": {"domain": "production_ai", "task_type": "architecture", "difficulty": "intermediate"}} {"messages": [{"role": "user", "content": "Test cross-encoder fallback when quantized reranker confidence is low on multilingual queries."}, {"role": "assistant", "content": "Design fallback routing quantized scores below calibrated threshold to full cross-encoder, balancing cost versus accuracy. Evaluate threshold sweep measuring NDCG lift and added latency on multilingual golden set. Cache cross-encoder results by query-document hash. Include edge where quantization degrades low-resource languages triggering fallback more often. Monitor fallback rate and tail latency. Test adversarial paraphrases. Log confidence histograms per language. Ensure deterministic batching for evaluation. Document threshold tuning procedure and rollback criteria. Additional validation includes shadow deployment, gradual rollout, and automated rollback on metric regression ensuring reliability. Add dashboard tracking precision, recall, latency, and cost with alerts on regression plus documented rollback procedure ensuring operational readiness."}], "metadata": {"domain": "production_ai", "task_type": "testing", "difficulty": "advanced"}} {"messages": [{"role": "user", "content": "Deploy blue-green releases for stateful vector index updates."}, {"role": "assistant", "content": "Build new index version in isolated green environment with updated embeddings or chunking. Run offline eval comparing green versus blue on golden queries for recall and faithfulness. Mirror shadow traffic to green and compare latency. Switch router to green after passing gates, keeping blue warm for instant rollback. Version collections explicitly like docs_v42 and update alias atomically. Monitor error rate and user feedback post-switch. Automate cleanup of old versions after retention period. Document migration steps. Blue-green deployment eliminates downtime during reindexing, enables safe testing on production data, provides immediate rollback, isolates resource contention during builds, and ensures reproducible index lineage for compliance and debugging."}], "metadata": {"domain": "production_ai", "task_type": "implementation", "difficulty": "advanced"}} {"messages": [{"role": "user", "content": "Expert architect global rate limiting with Redis Cluster for 10k QPS gateway"}, {"role": "assistant", "content": "Local limiters diverge at scale centralize Redis Cluster sliding windows sharded key hash. Use Lua atomic check increment avoiding races 10k QPS. Example Lua does rangebyscore card add expiry one roundtrip. Cache decisions locally 100ms reducing Redis load ten times jitter avoiding sync. Handle failover failing open local fallback alert. Shard tenant avoiding hot keys hashtag pinning. Benchmark single Redis 50k ops cluster linear. Monitor p99 limiter under 5ms. Chaos test node loss asserting error under 0.1 percent. Document quota tiers. Validate on staging with realistic traffic, monitor dashboards, document version changes, and require human review before promoting limiter changes to production for safety and reliability at scale."}], "metadata": {"domain": "production_ai", "task_type": "architecture", "difficulty": "expert"}} {"messages": [{"role": "user", "content": "Design evaluation for text to image model measuring compositionality, fairness, and photorealism."}, {"role": "assistant", "content": "Use T2I CompBench for attribute binding and spatial relations plus human ratings for photorealism on 2000 prompts. Measure demographic parity across gender and ethnicity with FairFace classifier and report skew. Assess image text alignment with CLIPScore and human preference. Include robustness to paraphrased prompts and adversarial spelling. Conduct blind pairwise comparisons with Bradley Terry ranking and report confidence intervals. Check for memorization via near duplicate detection against training set. Establish release gates for bias and safety violations including NSFW rate under 0.05 percent. Publish prompts, seeds, and scoring code for reproducibility. Additionally track metrics in versioned experiments and document tradeoffs to guide rollout decisions and future tuning priorities effectively. Additionally track metrics in versioned experiments and document tradeoffs to guide rollout decisions and future tuning priorities effectively. Additionally track metrics in versioned experiments and document tradeoffs to guide rollout decisions and future tuning priorities effectively."}], "metadata": {"domain": "production_ai", "task_type": "architecture", "difficulty": "advanced"}} {"messages": [{"role": "user", "content": "Optimize MoE routing load balancing to reduce token dropping in 8 expert model."}, {"role": "assistant", "content": "Analyze expert utilization histograms revealing 2 overloaded experts receiving 40 percent tokens. Introduce auxiliary load balancing loss coefficient 0.01 and capacity factor 1.25 with token dropping fallback to residual. Switch to expert choice routing for balanced assignment and add jitter noise during training. Profile all to all communication and overlap with computation using DeepSpeed MoE. Tune top k from 2 to 1 with larger experts to cut communication. Evaluate perplexity and downstream tasks confirming no quality loss. Monitor live expert skew and implement adaptive bias correction. Document tradeoff between load balance strength and specialization degradation observed in ablation studies. Additionally track metrics in versioned experiments and document tradeoffs to guide rollout decisions and future tuning priorities effectively. Additionally track metrics in versioned experiments and document tradeoffs to guide rollout decisions and future tuning priorities effectively. Additionally track metrics in versioned experiments and document tradeoffs to guide rollout decisions and future tuning priorities effectively."}], "metadata": {"domain": "production_ai", "task_type": "optimization", "difficulty": "advanced"}} {"messages": [{"role": "user", "content": "How do I implement PII redaction for LLM logs while preserving debugging utility?"}, {"role": "assistant", "content": "Redact at the edge while retaining hashed correlations. Deploy Presidio or regex plus NER to detect emails, phones, SSNs, and API keys before persistence. Replace with typed placeholders like [EMAIL_1] and store mapping separately with strict access. Hash user IDs and query text for join keys without revealing content. Keep full payloads only in short-lived encrypted buffers with explicit approval for debugging. Set retention policies: raw traces for days, redacted for months. Audit redaction recall on synthetic datasets covering edge formats. Monitor leakage with secondary scanners on stored logs. Provide safe replay tools that rehydrate placeholders only for authorized incidents. Document flows for SOC2, train engineers on handling, and block deploys if redaction tests fail."}], "metadata": {"domain": "production_ai", "task_type": "security", "difficulty": "intermediate"}} {"messages": [{"role": "user", "content": "Debug training serving skew where offline AUC 0.92 but online 0.78. Diagnose features and pipeline."}, {"role": "assistant", "content": "Skew comes from different feature code time windows or missing values handling between training and serving. Compare feature distributions with PSI and log live feature values sampled. Freeze shared transform code in single library used both paths and version it. Add feature parity tests asserting offline online vectors equal for same entity. Backfill with point in time correct joins to avoid leakage. Monitor live PSI plus prediction drift daily. Test with replay of prod requests through training pipeline. Document feature ownership. This closes gap and restores online quality for production models today. Code:\n# parity check\n# off = train_transform(raw)\n# on = serve_transform(raw)\n# assert off==on\nfrom scipy.stats import ks_2samp\nprint(ks_2samp(train['age'], serve['age']))\n# log live\n# logger.info('feat', extra={'f': feats})"}], "metadata": {"domain": "production_ai", "task_type": "debugging", "difficulty": "intermediate"}} {"messages": [{"role": "user", "content": "How do I test prompt version upgrade without quality regression?"}, {"role": "assistant", "content": "Freeze golden set 200 queries with reference answers and contexts. Run both old and new prompts via shadow calls logging faithfulness, correctness, latency, cost. Require new mean within 1 percent of old with paired t-test p over 0.05 plus no critical failures. Automate in CI with cached embeddings under 10 minutes. Human review 20 diffs for tone. Rollout canary 10 percent monitoring downvotes. Rollback automatically on 2 percent drop. Version prompts in git with scores. Use deterministic temperature 0 and averaged judge twice to reduce variance. Document decision in ADR. Operational note: emit Prometheus metrics for latency and cost per tenant, add structured logs with trace ids, gate rollout behind feature flag with automatic rollback on error spike, and run load tests to validate SLOs before full promotion."}], "metadata": {"domain": "production_ai", "task_type": "testing", "difficulty": "intermediate"}} {"messages": [{"role": "user", "content": "How to choose between GPT-4 and self-hosted Llama-3-70B for 10M tokens per day?"}, {"role": "assistant", "content": "Model cost at 10M tokens daily is 300 dollars per day for GPT-4 versus 40 dollars for two A100 80GB hosts running AWQ quantized Llama-3-70B at 30 tokens per second. Benchmark quality on 500 production prompts with human preference and task success; if gap is under 5 percent, route 80 percent simple queries to self-hosted and 20 percent complex to GPT-4 via classifier router. Implement LiteLLM gateway with fallbacks, caching, and budget alerts per team, track cost per request and P95 latency. Include engineering overhead of 0.5 FTE for hosting, plus eval maintenance. Run 2 week shadow test, compare hallucination rates, and decide threshold for escalation. This hybrid cuts spend 65 percent while preserving quality, allowing gradual migration as open models improve and usage scales further without vendor lock-in risks."}], "metadata": {"domain": "production_ai", "task_type": "optimization", "difficulty": "intermediate"}} {"messages": [{"role": "user", "content": "Debug training instability where loss spikes to NaN after 10 epochs in mixed precision Transformer."}, {"role": "assistant", "content": "NaNs in mixed precision often come from overflow in FP16 gradients or unstable loss scaling. Enable GradScaler with initial scale 65536 and check for inf gradients. Add gradient clipping at 1.0 and verify learning rate warmup over first 5 percent steps. Inspect data for NaNs or extreme values using anomaly detection. Use epsilon 1e-6 in LayerNorm and AdamW to avoid division issues. Switch to bfloat16 if hardware supports for better range. Log per-layer gradient norms to isolate exploding layer. Reduce batch size if loss spikes correlate with specific batches. Validate checkpoint resuming restores scaler state. Test with full precision on subset to confirm numerics versus data. Add NaN hooks to halt early with batch dump."}], "metadata": {"domain": "production_ai", "task_type": "debugging", "difficulty": "intermediate"}} {"messages": [{"role": "user", "content": "Build streaming chat API with FastAPI and OpenAI for production."}, {"role": "assistant", "content": "Implement POST chat completions endpoint accepting messages and stream flag. Call OpenAI async client with stream True and forward Server-Sent Events chunks to client. Handle client disconnect and cancellation tokens. Add authentication, rate limiting, and request validation. Log usage per stream with token counts from final chunk. Set timeouts and retry for transient errors. Deploy behind ingress supporting long-lived connections. Test with httpx async client asserting chunk order. Monitor time to first token. Provide SDK example handling SSE parsing. Ensure CORS and compression configured. Scale workers for concurrent streams without blocking event loop by offloading CPU work. Operationally enforce versioned prompts, canary analysis with automatic rollback, centralized logging with redacted PII, Prometheus metrics for latency and cost, and scheduled regression evaluation to prevent silent quality degradation in production."}], "metadata": {"domain": "production_ai", "task_type": "implementation", "difficulty": "intermediate"}} {"messages": [{"role": "user", "content": "Write integration tests for an OpenAI-compatible chat endpoint with retries."}, {"role": "assistant", "content": "Mock HTTP transport to simulate success, 429 rate limit, 500 error, and timeout sequences. Test retry logic with exponential backoff and jitter respects max attempts and surfaces final error. Verify request payload includes model, messages, temperature, and response_format. Assert token usage parsing and cost logging occur on success. Test streaming path aggregates chunks correctly and handles mid-stream disconnect. Include contract test against real staging endpoint nightly with recorded fixtures. Check PII redaction in logs. Measure test runtime to keep suite fast. Thorough integration tests validate resilience to provider flakiness, ensure correct API usage, prevent regressions in error handling, document expected failure modes, and give confidence to upgrade SDKs or switch providers without breaking production behavior."}], "metadata": {"domain": "production_ai", "task_type": "testing", "difficulty": "intermediate"}} {"messages": [{"role": "user", "content": "vLLM server OOMs on burst of long-context requests. Debug KV cache overcommit and scheduling failure."}, {"role": "assistant", "content": "Burst long prompts exhaust KV cache because scheduler admits too many sequences without reserving output tokens. Fragmentation worsens when paged attention blocks scatter. Inspect gpu memory utilization, max model length, and max number sequences settings against profiling. Fix by lowering max number sequences, enabling chunked prefill, setting reservation for max tokens, and implementing queue backpressure with 429 responses. Add load test with mixed context lengths measuring time to first token and eviction rate. Monitor cache hit and preemption metrics. Avoid unlimited concurrent requests without admission control. Consider tensor parallelism split for larger context windows plus autoscaling. Add regression coverage measuring latency, error budgets, and data drift with dashboards alerting on SLO breaches plus versioned runbook documentation for oncall response."}], "metadata": {"domain": "production_ai", "task_type": "debugging", "difficulty": "intermediate"}} {"messages": [{"role": "user", "content": "Create CI pipeline for ML with tests, linting, and model validation gates."}, {"role": "assistant", "content": "Configure GitHub Actions to install locked dependencies, run ruff and mypy, then pytest unit and integration tests. Add data validation with Great Expectations checking schema and ranges. Train on sample data and assert validation metric above baseline to block regressions. Store artifacts and test reports. Require code review and passing checks before merge. Version data and models via DVC and MLflow. Add precommit hooks for formatting. Cache dependencies for speed. Document pipeline stages and failure triage. Include security scanning for dependencies. Promote to staging on main merge with smoke inference tests. Monitor pipeline duration and flakiness. This ensures reliable, reproducible changes and catches data or performance regressions early."}], "metadata": {"domain": "production_ai", "task_type": "implementation", "difficulty": "intermediate"}} {"messages": [{"role": "user", "content": "How do I build fallback from OpenAI to local Ollama when quota exhausted?"}, {"role": "assistant", "content": "Wrap chat call with try except for RateLimitError then route to Ollama llama3.1 8B local endpoint with 60 second timeout. Normalize prompts to fit smaller 4096 context by truncating retrieved docs to top 3. Log provider_used and quality delta for analysis. Health check Ollama every 30 seconds updating routing table in memory. Test failover by mocking 429 verifying local response within 3 seconds. Cache frequent answers in Redis to reduce fallback load. Alert on fallback rate over 10 percent indicating quota need increase. Keep temperature 0 for consistency across providers. Document degraded quality expectations for stakeholders. Operational note: emit Prometheus metrics for latency and cost per tenant, add structured logs with trace ids, gate rollout behind feature flag with automatic rollback on error spike, and run load tests to validate SLOs before full promotion."}], "metadata": {"domain": "production_ai", "task_type": "architecture", "difficulty": "intermediate"}} {"messages": [{"role": "user", "content": "Debug tail latency spikes in a vLLM cluster serving mixed workloads."}, {"role": "assistant", "content": "Correlate p99 spikes with long-context requests hogging KV cache by analyzing request length histograms. Check GPU memory fragmentation and queueing delay metrics from vLLM stats. Isolate batch versus interactive traffic into separate deployments with different max_model_len. Enable prefix caching to reuse system prompt blocks. Tune max_num_seqs and max_num_batched_tokens to prevent head-of-line blocking. Profile NCCL communication and CPU scheduling delays. Add request timeouts and retry with smaller max_tokens for large prompts. Replay production trace in staging to validate fixes. Resolving tail latency requires distinguishing queueing, memory, and scheduling causes, then applying isolation, caching, and tuning. Result is predictable SLO compliance, better GPU utilization, fair scheduling, and improved user experience for interactive use cases."}], "metadata": {"domain": "production_ai", "task_type": "debugging", "difficulty": "advanced"}} {"messages": [{"role": "user", "content": "Intermittent 429 errors from OpenAI are failing user requests despite retries. What is the robust fix?"}, {"role": "assistant", "content": "Combine client retries with server-side queueing and prioritization. Implement exponential backoff with jitter, honoring Retry-After headers and capping retries at four. Add a Redis queue to smooth bursts, with separate lanes for interactive versus batch traffic. Enforce per-user and per-tenant token budgets to prevent noisy neighbors triggering limits. Cache frequent completions and embeddings to cut call volume. Configure fallback to another provider or smaller self-hosted model when 429 rate exceeds threshold. Scale API keys across projects and request quota increases proactively. Monitor 429 rate, retry success, queue wait time, and dropped requests with alerts. Load test burst scenarios and document degraded-mode UX that explains delays while preserving trust."}], "metadata": {"domain": "production_ai", "task_type": "api_debugging", "difficulty": "advanced"}} {"messages": [{"role": "user", "content": "Connect LLM service to feature store and real-time personalization."}, {"role": "assistant", "content": "Fetch user embeddings and recent actions from Feast online store p99 20ms, inject into prompt as structured context, handle missing features with defaults, cache features in Redis, log feature versions per request, monitor feature drift, test personalization lift via A B 8 percent CTR, secure PII with tokenization, version feature definitions, document feature list, handle store outages with fallback to generic prompts, validate latency budget, automate backfills, review fairness across cohorts, ensure compliance, implement feature flag to disable, track lineage, optimize serialization with protobuf, test under peak load and audit access for privacy reviews regularly. Ongoing governance requires versioned configs, automated regression tests, monitored latency dashboards, and quarterly security reviews for durability and compliance."}], "metadata": {"domain": "production_ai", "task_type": "implementation", "difficulty": "intermediate"}} {"messages": [{"role": "user", "content": "Optimize embedding pipeline throughput from 50 to 500 docs per second."}, {"role": "assistant", "content": "Parallelize with async batches 200, workers 10, connection pool 50. Deduplicate and cache to skip 30 percent repeats. Use smaller model text-embedding-3-small and truncated dimensions 512. Move to dedicated worker with GPU for local models or provisioned throughput for OpenAI. Stream from Kafka with backpressure. Checkpoint to S3 every 1000 docs for resume. Profile with cProfile to remove sync bottlenecks. Monitor queue depth and autoscale workers. Validate recall unchanged via evaluation. Add dead-letter for failures. Target p95 batch under 2s. This 10x gain typically comes from batching plus caching rather than hardware, enabling nightly reindex of millions of docs within SLA without cost explosion."}], "metadata": {"domain": "production_ai", "task_type": "optimization", "difficulty": "intermediate"}} {"messages": [{"role": "user", "content": "Implementehr scalable RLHF with PPO across 64 GPUs handling 1M preference pairs."}, {"role": "assistant", "content": "Shard policy, reference, reward, and value models with DeepSpeed ZeRO 3 and CPU offload. Stream preference data with dynamic packing to 4096 length. Train reward model with pairwise loss and calibration, then freeze for PPO rollout generating 256 responses per batch. Use GAE lambda 0.95, clip 0.2, KL target 0.05 with adaptive controller. Overlap generation and training via separate rollout workers. Checkpoint every 100 steps with eval on win rate and MT Bench. Handle OOM via gradient accumulation and activation checkpointing. Monitor reward hacking via length and perplexity guards. Document scaling efficiency and cost, achieving stable training without collapse. Additionally track metrics in versioned experiments and document tradeoffs to guide rollout decisions and future tuning priorities effectively. Additionally track metrics in versioned experiments and document tradeoffs to guide rollout decisions and future tuning priorities effectively. Additionally track metrics in versioned experiments and document tradeoffs to guide rollout decisions and future tuning priorities effectively."}], "metadata": {"domain": "production_ai", "task_type": "implementation", "difficulty": "expert"}} {"messages": [{"role": "user", "content": "Deploy quantized Llama 3 with vLLM on Kubernetes for low latency."}, {"role": "assistant", "content": "Build image with vLLM, AWQ quantized weights, and tokenizer. Define StatefulSet with GPU resources, shared memory, and model cache volume. Configure vLLM server with tensor parallelism, max batch tokens, and quantization flag. Expose OpenAI-compatible endpoint via service and ingress. Set readiness probe hitting health endpoint. Implement HPA on GPU utilization and queue length. Add PodDisruptionBudget for availability. Monitor TTFT and tokens per second. Optimize with prefix caching and chunked prefill. Secure with API key middleware. Document rollback to previous weights. Load test to validate SLOs before production cutover. Operationally enforce versioned prompts, canary analysis with automatic rollback, centralized logging with redacted PII, Prometheus metrics for latency and cost, and scheduled regression evaluation to prevent silent quality degradation in production. Document deployment procedures, thresholds, owners, and rollback steps in runbooks while tracking improvements through dashboards and postmortems for continuous reliability."}], "metadata": {"domain": "production_ai", "task_type": "implementation", "difficulty": "intermediate"}} {"messages": [{"role": "user", "content": "Implement semantic caching for LLM responses to handle near-duplicate queries at scale."}, {"role": "assistant", "content": "Cache by meaning, not just exact text, with safety guardrails. Embed incoming queries, lookup nearest neighbors in Redis or Qdrant above similarity threshold like 0.95, and return cached answers with citations. Include tenant, model version, and time window in cache keys to avoid cross-tenant leakage and staleness. Set TTLs by intent: short for pricing, longer for FAQs. Invalidate on index updates or policy changes via version tags. Measure hit rate, latency savings, and quality impact with human spot checks for false matches. Fall back to live generation on low similarity or high-risk queries. Monitor cache size, eviction rates, and cost savings. Start with exact cache, then enable semantic matching gradually with shadow validation to tune thresholds safely."}], "metadata": {"domain": "production_ai", "task_type": "implementation", "difficulty": "advanced"}} {"messages": [{"role": "user", "content": "My RAG retriever returns high embedding similarity but answers are wrong. How to analyze retrieval failure modes systematically?"}, {"role": "assistant", "content": "High similarity with wrong answers signals semantic mismatch, chunk fragmentation, or annotation error rather than ranking bug. Start by logging top 10 chunks with scores and manual relevance labels for 100 failing queries. Categorize failures into irrelevant retrieval, relevant but truncated, and relevant but LLM ignores. Compute recall at k and MRR to quantify ranking versus generation blame. Visualize embeddings with UMAP to spot cluster overlap from ambiguous queries. Test query rewriting and hypothetical expansion to bridge vocabulary gap. Add reranker and evaluate delta on failure slice. Implement failure dashboard tracking type distribution weekly to guide chunking versus prompting fixes systematically. This structured triage prevents random tuning and focuses effort where metrics show greatest leverage for quality improvement."}], "metadata": {"domain": "production_ai", "task_type": "retrieval_analysis", "difficulty": "intermediate"}} {"messages": [{"role": "user", "content": "Design a human evaluation protocol for comparing two summarization models on legal contracts."}, {"role": "assistant", "content": "Recruit three attorneys per sample and use blind pairwise comparison with randomized order to reduce bias. Define rubric covering factual fidelity, coverage of obligations, conciseness, and readability on 5 point scales. Sample 300 contracts stratified by length and clause complexity. Provide annotation UI showing source with highlighted claims and require span level justification for errors. Measure inter annotator agreement with Krippendorff alpha and adjudicate disagreements. Include attention checks and calibrate with training round. Analyze win rate with Bradley Terry model and report confidence intervals. Complement with automatic metrics like AlignScore for grounding. Document guidelines, pay rates, and ethics approval to ensure reproducibility and allow future model comparisons."}], "metadata": {"domain": "production_ai", "task_type": "architecture", "difficulty": "intermediate"}} {"messages": [{"role": "user", "content": "Analyze an A/B test where the new checkout recommender shows +2% conversion but -1.5% average order value. Should we ship?"}, {"role": "assistant", "content": "Compute total revenue per visitor as primary metric rather than viewing conversion and AOV in isolation, since 1.02 times 0.985 equals 0.5% revenue lift before significance. Check confidence intervals for revenue using bootstrap because ratio metrics violate t-test assumptions. Segment by cart size and price sensitivity to see if model pushes cheap items to price-sensitive users, which may be intended. Evaluate long-term effects like repeat purchase and return rate, not just immediate conversion. Run variance reduction with CUPED using pre-period spend to increase power. Verify sample ratio mismatch and novelty effects over first three days. If revenue lift is neutral, consider shipping only if latency and cost improve, otherwise iterate with multi-objective loss weighting conversion versus order value."}], "metadata": {"domain": "production_ai", "task_type": "experiment_analysis", "difficulty": "advanced"}} {"messages": [{"role": "user", "content": "Implement Dockerized batch inference reading Parquet from S3 scoring and writing predictions with logging."}, {"role": "assistant", "content": "Create a minimal production image based on python slim with pinned dependency versions, layer caching for faster rebuilds, non-root user for security, and explicit entrypoint script for batch execution. Implement inference script using boto3 with configured retries to list input prefixes, pyarrow dataset to stream Parquet partitions in bounded batches, model loading from versioned artifact path, vectorized prediction, addition of prediction plus model version plus timestamp columns, and writing output Parquet back to versioned S3 prefix. Emit structured JSON logs including processed row counts, batch duration, error counts, and S3 paths for CloudWatch querying. Validate output schema with pandera, detect empty inputs early, test locally with moto or LocalStack, deploy as ECS task or SageMaker transform, and alarm on failure rate, duration anomalies, and output freshness."}], "metadata": {"domain": "production_ai", "task_type": "implementation", "difficulty": "beginner"}} {"messages": [{"role": "user", "content": "Design prompt caching strategy to cut costs by 40 percent."}, {"role": "assistant", "content": "Identify stable prefixes like system instructions, few-shot examples, and retrieved doc templates across requests. Structure prompts with cacheable prefix first and variable user query last to maximize prefix hits. Enable provider prefix caching with minimum 1024 tokens and track cache hit rate. For self-hosted vLLM, enable automatic prefix caching and radix attention. Set TTL aligned with prompt version lifecycle and invalidate on template changes. Measure cost savings separating cached versus uncached tokens. Fall back to smaller model when cache miss would exceed budget. Document cache key construction for debugging. Effective caching exploits repetition in RAG and agent workflows, dramatically reduces input cost and latency, encourages disciplined prompt structure, provides measurable ROI, and scales savings with traffic volume."}], "metadata": {"domain": "production_ai", "task_type": "architecture", "difficulty": "advanced"}} {"messages": [{"role": "user", "content": "Optimize large embedding index sharding and quantization for 100M vectors."}, {"role": "assistant", "content": "Shard by hash into 8 partitions with IVF PQ compression 64 bytes per vector to fit memory, tuning nprobe 16 for recall latency. Replicate hot shards and route by tenant. Benchmark recall at 10 above 0.92 and P95 under 80ms. Test node failure with replica promotion. Monitor recall drift plus cache hit. Automate reindex on model change. This scales vector search to 100M cost effectively today with horizontal growth plus operational runbooks and capacity planning for peak query traffic reliably. Code:\nimport faiss\nivf=faiss.IndexIVFPQ(quant, 768, 4096, 16, 8)\nivf.train(train_vecs)\nivf.add(all_vecs)\nivf.nprobe=16\n# shard: idx_shard = hash(id)%8 Add experiment tracking with data plus code plus model hashes and offline online parity checks plus drift dashboards to keep training serving consistent and auditable in production environments daily. Include rollback aliases and shadow metrics review to ensure safe promotion under shifting data conditions today reliably."}], "metadata": {"domain": "production_ai", "task_type": "optimization", "difficulty": "advanced"}} {"messages": [{"role": "user", "content": "Implement shadow deployment for a new ranking model with live traffic mirroring and metric comparison."}, {"role": "assistant", "content": "Mirror production requests to shadow service asynchronously without affecting user responses. Log both baseline and challenger scores with request IDs. Deploy shadow as separate Kubernetes deployment with resource limits to avoid interference. Compare business metrics like CTR proxy, latency, and error rates offline. Use Kafka to replay traffic deterministically. Ensure PII handling compliant in shadow logs with same retention. Add feature parity checks to detect skew between training and serving. Run for one week covering weekly seasonality. Analyze slices by user segment. Promote only if statistically significant improvement with no latency regression. Automate comparison dashboards and alerts for divergence. Document rollback criteria."}], "metadata": {"domain": "production_ai", "task_type": "implementation", "difficulty": "intermediate"}} {"messages": [{"role": "user", "content": "Kubernetes CrashLoopBackOff after adding a 70B model sidecar without resource limits. How to recover?"}, {"role": "assistant", "content": "The pod exceeds node memory or GPU capacity, causing repeated OOM kills. Describe pods and check events for OOMKilled and insufficient nvidia.com/gpu warnings. Remove the sidecar or move inference to dedicated GPU node pools with taints. Set explicit requests and limits for memory, CPU, and GPUs, plus ephemeral storage. Use separate Deployments for API and model servers to scale independently. Add readiness probes that check model load completion, not just port open. Roll back the deployment, then load test the 70B model on appropriate nodes like 2xA100 with quantization. Monitor GPU memory, evictions, and scheduling failures. Document capacity per model size and enforce resource reviews in CI to prevent recurrence."}], "metadata": {"domain": "production_ai", "task_type": "traceback", "difficulty": "advanced"}} {"messages": [{"role": "user", "content": "Build CI pipeline testing LLM prompts, evaluation gates, and cost budgets on pull requests."}, {"role": "assistant", "content": "Create GitHub Actions workflow running pytest for prompt rendering, golden set evaluation, and toxicity checks. Fail PR if faithfulness below 0.85 or latency p95 above 2 seconds. Estimate token cost per 1k queries and block if increase above 10 percent. Cache models and datasets for speed. Upload evaluation report as artifact with diff versus main. Require manual approval for prompt changes affecting safety. Run nightly full regression with larger dataset. Integrate with MLflow tracking runs. Handle flaky LLM judge with three repeats and majority vote. Document how to update golden set and thresholds. Provide Slack notifications for failures. Ensure secrets masked and no live API calls in unit stage using mocks for fast feedback."}], "metadata": {"domain": "production_ai", "task_type": "testing", "difficulty": "intermediate"}} {"messages": [{"role": "user", "content": "Profile and optimize slow Python ETL from 2 hours to minutes using vectorization and caching."}, {"role": "assistant", "content": "Profile with cProfile and snakeviz to find hotspots, typically loops and repeated DB queries. Replace row apply with vectorized pandas and numpy, batch inserts with executemany, and cache lookups in dict instead of per-row queries. Use PyPy or numba for remaining loops. Parallelize independent partitions with ProcessPoolExecutor. Example: mapping via df['code'].map(lookup_dict) eliminates N queries. Add indexes on join keys. Measure after each change. Cache reference data in memory with TTL. Convert CSV to parquet for faster reads. Result cuts runtime by precomputing, reducing IO, and exploiting parallelism. Document bottleneck analysis, maintain tests for equivalence, and monitor new runtime. Systematic profiling ensures effort targets dominant cost rather than micro-optimizing irrelevant code paths."}], "metadata": {"domain": "python", "task_type": "optimization", "difficulty": "expert"}} {"messages": [{"role": "user", "content": "Python gRPC service wrapping embedding model throws DEADLINE EXCEEDED under 50 QPS. How to tune deadline and batching?"}, {"role": "assistant", "content": "Deadline exceeded indicates server batch inference slower than client 2s deadline at load. Trace server handler duration histogram versus deadline setting to confirm. Increase deadline to 10s for batch path, implement dynamic batching collecting requests for 20ms up to 32 items to amortize GPU cost. Use async handler with thread pool for tokenization to avoid blocking. Enable keepalive and connection pooling to avoid handshake overhead. Add server queue metrics and client retry with backoff only on unavailable, not deadline to avoid amplification. Load test ramp to find saturation point and set autoscaling on GPU utilization. Cache frequent embeddings by hash. Log batch size distribution to tune window. This restores p99 under deadline while raising throughput significantly without adding hardware immediately."}], "metadata": {"domain": "python", "task_type": "api_debugging", "difficulty": "advanced"}} {"messages": [{"role": "user", "content": "Write pytest tests for a Python retry decorator covering backoff, jitter, exceptions, and async support."}, {"role": "assistant", "content": "Test retry decorator using parametrized pytest cases, fake clock, and deterministic random for jitter. Cover success first try, retry then success, exhaustion raising RetryExhaustedError with cause chain, non retryable exception immediate propagation, max delay cap, and backoff growth validation. Use monkeypatch for sleep in sync path and async sleep mock with anyio or asyncio. Verify decorator preserves function name, annotations, and signature via inspect.signature. Test thread safety, cancellation propagation for asyncio.CancelledError never retried, logging of attempts with correlation ids, and metrics increments. Add property test for delay bounds, measure overhead, isolate flaky timing with tolerances, and document configuration of attempts, base delay, and jitter strategy clearly."}], "metadata": {"domain": "python", "task_type": "testing", "difficulty": "beginner"}} {"messages": [{"role": "user", "content": "Review Python packaging setup for reproducible builds, lockfiles, SBOM, and vulnerability scanning."}, {"role": "assistant", "content": "Check pyproject pins, uv lock or pip-tools compiled requirements with hashes, reproducible sdist wheel builds, and SBOM generation via cyclonedx. Flag unpinned transitive deps, missing requires-python, extras drift, and absent yank policy. Recommend trusted publishing, sigstore signing, private index auth via env tokens, and pip audit or osv scanner in CI. Verify clean venv install test, license compliance, entry point smoke tests. Monitor build times, artifact sizes, vulnerability counts. Document bump workflow, lock update cadence, rollback, and incident response for compromised deps. Ensure build isolation, no network at build, deterministic timestamps, and architecture test that application imports only declared dependencies to prevent shadow imports."}], "metadata": {"domain": "python", "task_type": "code_review", "difficulty": "intermediate"}} {"messages": [{"role": "user", "content": "Show how to optimize Python performance with profiling, cProfile, and targeted data structure choices."}, {"role": "assistant", "content": "Optimize by measuring first with cProfile, pstats, and timeit to find hot functions. Visualize with snakeviz or py-spy for production safe sampling. Focus on algorithmic complexity before micro tweaks, replacing O n squared loops with sets, dicts, or sorting. Use local variables, list comprehensions, generator pipelines, and builtins implemented in C. Cache repeated work with lru_cache and avoid redundant IO. Vectorize numeric code with numpy or offload with numba. Reduce allocations, reuse buffers, and batch operations. Benchmark with representative data and track regressions in CI. Document tradeoffs between speed, memory, and readability. Avoid premature optimization and keep fallbacks simple. Test correctness after changes with property tests. Disciplined profiling delivers substantial speedups, lower costs, and responsive Python applications without sacrificing maintainability or introducing fragile, overly clever optimizations."}], "metadata": {"domain": "python", "task_type": "instruction", "difficulty": "advanced"}} {"messages": [{"role": "user", "content": "How do I design async context managers, async iterators, and backpressure handling in asyncio?"}, {"role": "assistant", "content": "Async resources require async enter exit and async iteration protocols to avoid blocking loops. Implement dunder aenter aexit for connections and dunder aiters anext for streams. Use async with and async for to guarantee cleanup and pacing. Apply backpressure with bounded asyncio Queue, semaphores, and producer consumer coordination, awaiting put when full. Handle cancellation via CancelledError, timeouts with wait_for, and shutdown with sentinel values. Avoid unbounded buffers that exhaust memory. Test slow consumers, abrupt closes, and exception paths. Monitor queue size, latency, and dropped items. Compose pipelines with clear ownership and graceful drain. Proper async design sustains throughput under burst load, prevents overload cascades, and keeps Python streaming systems responsive, fair, and resilient across network, file, and inter task communication scenarios."}], "metadata": {"domain": "python", "task_type": "instruction", "difficulty": "advanced"}} {"messages": [{"role": "user", "content": "Design a Python plugin architecture allowing third-party extensions to register data transformers."}, {"role": "assistant", "content": "Define a Transformer Protocol with transform(df) method and metadata name and version. Use entry_points or a registry dict where plugins call register(name, cls). Implement PluginManager that discovers modules via importlib, validates subclass compliance, and instantiates lazily. Isolate plugin failures with try-except during load so one broken plugin does not crash startup. Support configuration via dataclass and dependency injection. Provide base class with helper methods and versioned API to maintain backward compatibility. Document contract and example plugin. Add tests loading dummy plugins from temp directory. Use importlib.metadata for distribution. This design enables extensibility, keeps core stable, allows independent plugin versioning, enforces interface contracts, and provides clear error messages for invalid plugins while supporting dynamic discovery."}], "metadata": {"domain": "python", "task_type": "architecture", "difficulty": "expert"}} {"messages": [{"role": "user", "content": "Optimize asyncio ETL with connection pooling backpressure and bulk inserts for 500k rows per minute."}, {"role": "assistant", "content": "Sustain high ingestion rates by reusing database connections, applying explicit backpressure queues to avoid memory blowup, and loading records with bulk copy protocols instead of row by row inserts. Create asyncpg pool with twenty connections, bound input queue to one thousand items, fetch upstream pages with semaphore limited concurrency, transform batches in memory, and flush with COPY command every ten thousand rows. Measure rows per minute, pool wait times, queue depth, error retry rates, and end-to-end latency under sustained load. Validate exactly once effect with idempotent keys, test database failover handling, tune pool size versus CPU contention, monitor connection leaks, handle schema mismatches with dead letter routing, and document operational runbooks for backfill versus streaming modes to ensure reliable pipeline performance."}], "metadata": {"domain": "python", "task_type": "optimization", "difficulty": "advanced"}} {"messages": [{"role": "user", "content": "Explain list vs tuple vs set vs dict tradeoffs in Python with use cases."}, {"role": "assistant", "content": "List is ordered mutable sequence ideal for stacks and ordered collections, O(1) append and O(n) search. Tuple is immutable ordered, hashable if elements hashable, perfect for keys and fixed records with lower memory. Set is unordered unique collection with O(1) membership, ideal for deduplication and intersections. Dict maps keys to values with O(1) lookup, ideal for indexes and counters. Choose tuple for integrity, list for mutation, set for uniqueness checks, dict for associations. Memory: tuple smallest, dict largest. Iteration order guaranteed for list, tuple, dict insertion order, but not set. Example: use set for visited nodes, dict for adjacency. Understanding mutability and hashing prevents TypeError with unhashable keys and guides efficient data structure selection for correctness and performance."}], "metadata": {"domain": "python", "task_type": "instruction", "difficulty": "intermediate"}} {"messages": [{"role": "user", "content": "Code review Python async function swallowing CancelledError and leaking connections."}, {"role": "assistant", "content": "Identify except Exception capturing CancelledError in Python 3.8+ where it inherits BaseException, preventing proper task cancellation. Require except asyncio.CancelledError: cleanup; raise plus separate except Exception for logging. Flag unclosed ClientSession created per call; recommend shared session passed as argument with async with lifespan. Suggest using try finally to release semaphore and close file handles even on cancellation. Check for bare except and missing await on cleanup coroutines. Propose structured concurrency with TaskGroup ensuring child tasks cancelled together. Add test simulating cancellation via task.cancel() asserting session.close called. Severity blocker because leak exhausts sockets under load. Provide corrected snippet with proper ordering: except CancelledError first, then Exception. This preserves cooperative cancellation, prevents resource exhaustion, and aligns with asyncio best practices for production services handling deploys and timeouts."}], "metadata": {"domain": "python", "task_type": "code_review", "difficulty": "advanced"}} {"messages": [{"role": "user", "content": "Optimize Python JSON parsing for 500k records using orjson and multiprocessing."}, {"role": "assistant", "content": "Replace stdlib json with orjson.loads for 3-5x faster parsing due to Rust implementation and zero-copy handling. Read file in batches, distribute batches to ProcessPoolExecutor to parallelize CPU-bound decoding. Use orjson options for datetime and numpy handling. Avoid per-record overhead by parsing lines with memoryview and reusing buffers. Example: with Pool(8) as p: results=p.map(parse_batch, chunks). Combine with ijson for streaming if file exceeds memory. Benchmark loads versus load, measure with timeit. Ensure correct handling of bytes versus str since orjson expects bytes. Validate schema after parsing to catch corrupt lines early. This combination reduces parse time from minutes to seconds, scales linearly with cores, lowers GC pressure, and maintains correctness while handling large JSONL datasets efficiently."}], "metadata": {"domain": "python", "task_type": "optimization", "difficulty": "advanced"}} {"messages": [{"role": "user", "content": "How to test async aiohttp handler that calls DB and external API with pytest? My test hangs on await."}, {"role": "assistant", "content": "Use pytest-asyncio with async test and anyio fixtures. Mock DB with async fake returning canned rows and patch aiohttp ClientSession.get with aioresponses. Await handler directly passing fake request. Set event loop scope function and timeout 5s to avoid hangs. Assert on JSON response and mocked call counts. Isolate with fresh loop per test. For integration use testcontainers Postgres. Ensure proper closing of sessions via async with. This yields deterministic async tests without real I/O. Document async fixture patterns. Hangs usually stem from unclosed session or missing await, fixed by strict async context management and explicit event loop control in test setup."}], "metadata": {"domain": "python", "task_type": "testing", "difficulty": "intermediate"}} {"messages": [{"role": "user", "content": "How do metaclasses and descriptors work in Python and when should they be used sparingly?"}, {"role": "assistant", "content": "Metaclasses customize class creation while descriptors customize attribute access via get set delete protocols. Type subclasses can validate fields, register plugins, or enforce patterns at definition time. Descriptors like property, classmethod, or custom validators intercept reads and writes for reuse. Use sparingly because implicit magic harms readability and debugging. Prefer decorators, mixins, or explicit factories first. When justified, keep logic minimal, document behavior, and provide escape hatches. Implement new, init, call carefully and preserve metadata. Test inheritance, pickling, and thread interactions. Profile overhead for hot attributes. Examples include ORM fields, typed configs, and API schemas. Isolate metaclass machinery behind clear helpers. Restrained use delivers declarative power, consistency, and DRY enforcement while avoiding obscure failures, surprising side effects, and maintenance burden in large Python frameworks and libraries."}], "metadata": {"domain": "python", "task_type": "instruction", "difficulty": "advanced"}} {"messages": [{"role": "user", "content": "Traceback ModuleNotFoundError in Docker slim but works locally. Debug packaging?"}, {"role": "assistant", "content": "Root cause is missing system libs and package not installed in slim image due to requirements drift or PYTHONPATH mismatch. Pin requirements txt with hashes and install with pip no-cache in Dockerfile. Set WORKDIR PYTHONPATH and copy package correctly. Use python -m pip list inside container to diff. Validate import with docker run python -c import. Avoid local editable install masking missing dependency. Add multi-stage build compiling wheels then runtime slim. Log sys.path and site packages. Test CI building fresh image no cache. Include gcc for compiled deps or use manylinux wheels. Document base image version pin. Enforce lock file sync via pip-compile check to prevent local versus prod divergence causing import failures at runtime."}], "metadata": {"domain": "python", "task_type": "traceback", "difficulty": "intermediate"}} {"messages": [{"role": "user", "content": "Implement Python async retry with exponential backoff, jitter, deadlines, and idempotency keys."}, {"role": "assistant", "content": "Implement async_retry decorator with Generic ParamSpec preserving types, config max_attempts, base delay, max delay, jitter ratio, and overall deadline via monotonic clock. Apply full jitter to avoid thundering herd, respect Retry-After headers for HTTP, generate idempotency keys per operation. Never retry cancellation or validation errors, only transient timeouts and 5xx. Use asyncio.sleep, handle deadline exceeded raising TimeoutError with attempts context. Log attempts with correlation ids, emit retry metrics. Test deterministic with mocked sleep and clock, cover success, exhaustion, non retryable, deadline, and concurrent usage. Benchmark sleep overhead, document backoff tuning, interaction with circuit breaker, and safe shutdown cancellation behavior for production pipelines."}], "metadata": {"domain": "python", "task_type": "implementation", "difficulty": "intermediate"}} {"messages": [{"role": "user", "content": "I see KeyError: 'email' when processing JSON records. Some records lack the key. Traceback at row['email'].lower(). How to make this robust while still catching truly invalid data?"}, {"role": "assistant", "content": "Direct indexing assumes key always present, but real data is dirty. Use .get with validation and collect errors instead of crashing. Example:\nrecords = [{'name':'a'}, {'email':'A@X.COM'}]\nclean = []\nbad = []\nfor i, r in enumerate(records):\n email = (r.get('email') or '').strip().lower()\n if not email or '@' not in email:\n bad.append((i, r))\n continue\n clean.append({**r, 'email': email})\nprint(clean, bad)\nKey decisions: distinguish missing vs malformed, log index for triage. If email required, raise ValueError with context after loop. For Pydantic use Optional with validator. Avoid try except KeyError around large blocks which hides bugs. Add schema check early with jsonschema if ingesting external feeds. Additional notes: add logging with context, write unit tests for edge cases, validate inputs at API boundary, monitor metrics in production, and document assumptions for future maintainers to prevent regressions."}], "metadata": {"domain": "python", "task_type": "traceback", "difficulty": "intermediate"}} {"messages": [{"role": "user", "content": "Describe unit testing with pytest including fixtures, parametrization, and temporary directories."}, {"role": "assistant", "content": "Pytest simplifies testing with plain asserts, auto discovery, and powerful fixtures. Organize tests in test files, use descriptive names, and arrange act assert structure. Parametrize with mark parametrize to cover multiple inputs without duplication. Fixtures supply reusable setup like configs, database connections, or tmp_path temporary directories, with function or module scope controlling lifetime. Use monkeypatch for environment and caplog for logs. Isolate external IO with fakes or mocks. Run selectively with k expressions, measure coverage, and enforce failures in CI. Test happy paths, boundaries, and errors, keeping tests fast and deterministic. Avoid shared mutable state and time dependence via freezing. Refactor helpers into conftest. Good pytest suites document behavior, catch regressions early, support refactoring confidence, and scale from small utilities to large Python applications and services."}], "metadata": {"domain": "python", "task_type": "instruction", "difficulty": "intermediate"}} {"messages": [{"role": "user", "content": "Explain asyncio event loop, tasks, executors, and cancellation semantics for robust Python services."}, {"role": "assistant", "content": "Event loop schedules coroutines as Tasks, runs IO callbacks efficiently, offloads blocking work to ThreadPool or ProcessPool executors. Create tasks via create_task with names, track for shutdown, use TaskGroup for structured concurrency and automatic cancellation propagation. Cancellation via CancelledError is cooperative, must be re raised after cleanup, shield critical sections. Avoid bare except swallowing cancellation, use timeouts with wait_for. Monitor slow callbacks, pending tasks, and executor queue depth. Test graceful shutdown, timeouts, exception aggregation, and context propagation. Profile loop lag, document backpressure, retry budgets, idempotency for cancelled operations, and clear ownership of task lifetimes across service layers for reliability daily. Add explicit runbooks and dashboards for sustained operational confidence today."}], "metadata": {"domain": "python", "task_type": "instruction", "difficulty": "intermediate"}} {"messages": [{"role": "user", "content": "My Python loop using iterrows is very slow on a 2M row dataframe. How do I vectorize it?"}, {"role": "assistant", "content": "Replace iterrows with vectorized pandas or numpy operations to eliminate Python level row overhead. For arithmetic, use direct column ops like df[total] = df[price] * df[qty] instead of looping. For conditional logic, use numpy.where or pandas mask, and for string ops use str accessor methods. When custom logic is needed, use apply with axis=1 only as fallback, or better numba vectorize for numeric kernels. Ensure dtypes are efficient, such as float32 and categoricals, to improve cache use. Benchmark with timeit on a sample and verify results with pandas.testing.assert_frame_equal. In feature engineering for ML, vectorization can reduce hours to seconds and lower memory churn. If data exceeds RAM, switch to chunked processing or polars for multithreaded execution while preserving the same vectorized logic."}], "metadata": {"domain": "python", "task_type": "debugging", "difficulty": "beginner"}} {"messages": [{"role": "user", "content": "Debug sklearn inference latency spike from large pickle model loading per request path."}, {"role": "assistant", "content": "Latency spikes because model pickle loads from disk each request instead of singleton cache adding IO overhead. Large trees exacerbate delay. Inspect profiling showing load dominating inference. Fix loading model at startup into memory, using memory mapping where supported, and warming up with dummy prediction. Implement versioned cache with background reload. Add test asserting p95 latency bound and single load count. Monitor memory and reload events. Avoid reloading on config change without need. Use lightweight format like ONNX for faster initialization. Document deployment procedure. Additional validation includes shadow deployment, gradual rollout, and automated rollback on metric regression ensuring reliability. Add dashboard tracking precision, recall, latency, and cost with alerts on regression plus documented rollback procedure ensuring operational readiness."}], "metadata": {"domain": "python", "task_type": "api_debugging", "difficulty": "advanced"}} {"messages": [{"role": "user", "content": "Implement self tuning batcher in Python using feedback control, latency SLOs, and adaptive sizing."}, {"role": "assistant", "content": "Implement batcher collecting items up to max size or max latency window, adjusting size via AIMD based on downstream p95 versus SLO. Use asyncio.Queue, timer task flushing partial batches, concurrency limit via semaphore. Record throughput error rate, increase on success decrease on timeout or overload signal. Provide fallback single item path on persistent failures. Test burst steady and spiky loads, slow downstream, config changes live. Benchmark tuning convergence, stability avoiding oscillation with damping. Log batch sizes decisions, emit metrics. Document SLO selection, initial parameters, manual override, interaction with retry and circuit breaker. Keep batching in adapter layer, domain unaware, ensuring testability with fake clock and deterministic load scripts."}], "metadata": {"domain": "python", "task_type": "implementation", "difficulty": "advanced"}} {"messages": [{"role": "user", "content": "Write pytest integration tests for file upload validation allowing only pdf under 5MB."}, {"role": "assistant", "content": "Create parametrized tests for valid pdf, oversized file, wrong extension, empty file, and missing content-type. Use tmp_path to generate dummy bytes: valid content b'%PDF-1.4 test' padded to 1KB, oversized to 6MB via seek or sparse write to avoid memory blowup. Call validate_upload(filename, content_bytes) asserting (True, '') versus (False, reason). Check magic bytes not just extension to prevent spoofing. Test boundary exactly 5*1024*1024 passes, 5*1024*1024+1 fails. Mock storage layer to isolate validation logic. Use fixtures for reusable file factory. Assert error messages user-friendly and stable. Run pytest -k upload for fast feedback. This suite documents policy, guards regression when limits change, and ensures security against malicious uploads while keeping feedback precise for frontend handling."}], "metadata": {"domain": "python", "task_type": "testing", "difficulty": "intermediate"}} {"messages": [{"role": "user", "content": "Code review asyncio rate limiter for correctness and fairness."}, {"role": "assistant", "content": "Verify token bucket refill uses monotonic time, not wall clock, to avoid skew. Check lock granularity allows concurrency without starving waiters. Ensure acquire respects cancellation and timeout to prevent hung tasks. Look for burst handling and max wait queue bounds. Test with high concurrency simulation asserting throughput near limit and no over admission. Check fairness via FIFO ordering or jitter to avoid thundering herd. Inspect metrics for rejected vs delayed requests. For LLM clients, confirm per key and global limits compose correctly. Suggest using asyncio.Semaphore plus refill task for simplicity. Document behavior under clock jumps and process restarts. A correct limiter protects budgets, respects provider quotas, and provides predictable backpressure instead of cascading 429 errors across the system."}], "metadata": {"domain": "python", "task_type": "code_review", "difficulty": "advanced"}} {"messages": [{"role": "user", "content": "Build zero copy data pipeline with memoryview and struct for binary sensor logs."}, {"role": "assistant", "content": "Map files with mmap to avoid copies, then wrap buffers in memoryview for sliced access. Use struct.unpack_from with precompiled format to parse headers in place. Avoid bytes slicing that copies, prefer memoryview casts to typed layouts. Batch process frames with numpy.frombuffer for vectorized decoding. Validate magic numbers and checksums before processing. Benchmark against naive read and parse to quantify gains. Handle endianness explicitly and document record layout. Test with corrupted frames and truncated files. For AI ingestion, zero copy reduces GC pressure and speeds preprocessing of large binary corpora. This low level approach is justified only after profiling shows IO parsing as bottleneck, as it trades readability for throughput and memory efficiency in hot paths."}], "metadata": {"domain": "python", "task_type": "implementation", "difficulty": "expert"}} {"messages": [{"role": "user", "content": "Implement distributed tracing context propagation in Python microservices for LLM calls."}, {"role": "assistant", "content": "Use OpenTelemetry SDK to create tracers per service and propagate W3C traceparent headers across HTTP and queue boundaries. Wrap LLM clients in spans capturing model, tokens, and latency without logging prompts containing PII. Ensure contextvars propagate through asyncio tasks correctly. Sample tail based traces for errors and high latency. Export to Jaeger or OTLP collector with resource attributes. Test propagation with integration tests asserting parent child links. Correlate traces with metrics and logs via trace ids. For AI systems, tracing reveals retrieval vs generation cost breakdown. Enforce redaction policies and retention limits. This observability foundation simplifies debugging cross service failures and supports SLO analysis for complex agent workflows spanning multiple tools and models."}], "metadata": {"domain": "python", "task_type": "implementation", "difficulty": "advanced"}} {"messages": [{"role": "user", "content": "Review Python concurrency code using threads, asyncio, and multiprocessing for safety and performance."}, {"role": "assistant", "content": "Verify IO bound uses asyncio with bounded semaphore, CPU bound uses ProcessPool with picklable inputs, thread usage limited to blocking legacy libs. Flag shared mutable state without locks, GIL assumptions, unbounded task creation, missing shutdown joins. Recommend message passing via queues, immutable snapshots, per task contextvars, structured logging. Check executor sizing based on cores and IO latency, timeouts everywhere, cancellation handling. Suggest benchmarks for throughput and latency, stress tests for races, architecture tests forbidding loop blocking calls. Document choice rationale, backpressure limits, fallback degradation, resource cleanup ordering, and observability with task counts, queue depths, and worker utilization metrics for production readiness."}], "metadata": {"domain": "python", "task_type": "code_review", "difficulty": "intermediate"}} {"messages": [{"role": "user", "content": "My generator yields 10M rows but memory still blows up when I do list(gen). How to keep pipeline lazy end to end?"}, {"role": "assistant", "content": "Avoid materializing with list, iterate streaming through pipeline stages using generator expressions and itertools chain islice. Process in chunks writing to file or DB incrementally. Use yield from for delegation. Profile memory with tracemalloc showing list spike. For pandas use chunksize iterator. Test with large input asserting constant memory via psutil delta. If need length, compute separately without storing. This preserves laziness, enabling 10M scale on modest RAM. Refactor consumers to accept iterables not lists. Document lazy contract in type hints using Iterator. Proper streaming turns OOM into steady low footprint with slightly more complex flow control worth the scalability gain."}], "metadata": {"domain": "python", "task_type": "optimization", "difficulty": "advanced"}} {"messages": [{"role": "user", "content": "Review prompt templating PR concatenating user input into system prompt. Identify injection flaws."}, {"role": "assistant", "content": "Direct concatenation enables prompt injection where user text overrides system instructions via delimiter confusion. Formatting with fstrings breaks on braces inside user content. Review must require structured chat messages with separate roles, input sanitization preserving intent, and delimiter tagging like XML sections. Check for token limit handling when user input is large. Suggest centralized template renderer with escaping and unit tests for injection payloads such as ignore previous instructions. Verify logging redacts sensitive user spans. Avoid building prompts via plus operator in business logic. Enforce allowlist for system instruction overrides plus security testing. Add regression coverage measuring latency, error budgets, and data drift with dashboards alerting on SLO breaches plus versioned runbook documentation for oncall response."}], "metadata": {"domain": "python", "task_type": "code_review", "difficulty": "advanced"}} {"messages": [{"role": "user", "content": "Explain formal verification of Python protocols with runtime contracts, property tests, and type checkers."}, {"role": "assistant", "content": "Combine static Protocol checking via mypy, runtime beartype or deal contracts for pre post invariants, and Hypothesis property tests for law verification. Define port contracts with precise types, value constraints, error guarantees. Encode invariants as decorators asserting inputs outputs, monitor violations in staging logging. Prove idempotency commutativity via stateful testing, model based checks. Integrate contract tests in CI failing on breach, measure overhead and disable hot path in prod behind flag with sampling. Document contract evolution, versioning, blameless breach triage. Show clean architecture where domain invariants enforced statically and at boundaries, adapters wrapped with contracts, enabling confident refactoring and plugin compatibility with machine checked guarantees beyond unit examples."}], "metadata": {"domain": "python", "task_type": "instruction", "difficulty": "expert"}} {"messages": [{"role": "user", "content": "Traceback RecursionError in custom __getattr__ delegating to self dict. Explain fix?"}, {"role": "assistant", "content": "Root cause is __getattr__ accessing self dot attr triggering itself infinitely when key missing, since __getattr__ only called on failure. Use object.__getattribute__ or self.__dict__ lookup without dot access inside method. Guard with if name starts with underscore raise AttributeError. Implement __getattr__ fetching from internal dict via object.__getattribute__(self, '_data')[name]. Validate with missing attribute raising correctly not recursing. Add test for copy deepcopy pickle. Avoid delegating special methods via getattr. Prefer __getattribute__ override carefully with parent call. Log recursion limit stack to confirm cycle. Refactor to composition exposing explicit properties instead of magic delegation for clarity. Document expected attributes to aid static typing and prevent silent infinite loops in production code."}], "metadata": {"domain": "python", "task_type": "traceback", "difficulty": "intermediate"}} {"messages": [{"role": "user", "content": "Write pytest tests with fixtures for a Python order calculator that applies discounts and tax."}, {"role": "assistant", "content": "Create fixtures for sample products, discount rules, and tax rates using @pytest.fixture to reuse setup across tests. Test calculate_total(items, discount, tax_rate) with parametrized cases covering empty cart, percentage discount, fixed discount, and tax-exempt items. Use assert with pytest.approx for floating point totals to avoid precision failures. Add edge tests for negative quantity, invalid discount code, and zero tax. Mock external price service with monkeypatch or unittest.mock to isolate logic. Organize tests into TestOrderCalculator class for clarity. Run with pytest -v and check coverage with pytest --cov. Fixtures ensure deterministic inputs, parametrization covers business rules compactly, and mocking prevents flaky network dependencies while verifying calculation correctness and error handling."}], "metadata": {"domain": "python", "task_type": "testing", "difficulty": "advanced"}} {"messages": [{"role": "user", "content": "Design Python monorepo with Bazel shared libs pinned deps and affected-target CI for ML services."}, {"role": "assistant", "content": "Scale development across twenty machine learning services by organizing shared feature and training libraries with hermetic Bazel builds, locked dependencies, and incremental continuous integration. Structure repository with libs common plus services fraud and churn each containing BUILD files, generate requirements locks with pip-compile, enforce mypy strict and ruff linting per package, define pytest targets with explicit dependencies, and execute only affected targets via Bazel query in pull requests. Cache remote execution artifacts aggressively, version libraries semantically with compatibility tests, govern ownership with CODEOWNERS, support local development with bazel run wrappers, reduce build times from twenty to four minutes, validate cross-service refactors safely, handle diamond dependencies with constraints, and document onboarding procedures enabling new engineers to build and test within one hour."}], "metadata": {"domain": "python", "task_type": "architecture", "difficulty": "advanced"}} {"messages": [{"role": "user", "content": "Traceback: RecursionError: maximum recursion depth exceeded in custom __getattr__ wrapper class."}, {"role": "assistant", "content": "Recursion in __getattr__ happens when you access self.attr inside itself, retriggering lookup infinitely. Use object.__getattribute__ or self.__dict__ lookup inside method. Guard with if name.startswith('_'): raise AttributeError. Store wrapped object in __dict__ via object.__setattr__ to avoid __setattr__ loop. Prefer __getattribute__ with try-except fallback for explicit control. Add depth counter for debugging. Test with copy.deepcopy and pickle which probe attributes. Refactor to composition without magic methods if possible. Set sys.getrecursionlimit higher only masks bug; fix logic. Validate fix with dedicated unit test and integration check covering edge cases. Log relevant metrics, monitor production dashboards continuously, document change clearly in pull request for reviewers and future maintenance work."}], "metadata": {"domain": "python", "task_type": "traceback", "difficulty": "intermediate"}} {"messages": [{"role": "user", "content": "Optimize GIL-bound preprocessing with Cython memoryviews and process sharding for 10x throughput."}, {"role": "assistant", "content": "Bypass Global Interpreter Lock limitations by moving numerical hot loops into Cython extensions with typed memoryviews and nogil execution, then distribute file shards across process pool for linear multicore scaling. Declare double typed one dimensional buffers, disable bounds checking and wraparound for speed, implement parallel reductions with prange, release GIL during compute intensive sections, compile with optimized flags and pinned numpy ABI, and invoke from eight worker Pool with balanced chunksize. Profile with py-spy to confirm lock contention before optimization, compare pure Python versus Cython microbenchmarks showing twentyfold gains, validate floating point equality within tolerance, package wheels for manylinux portability, provide pure Python fallback for unsupported platforms, document build requirements, and monitor worker memory duplication to prevent unexpected overhead growth."}], "metadata": {"domain": "python", "task_type": "optimization", "difficulty": "intermediate"}} {"messages": [{"role": "user", "content": "Design Python plugin API using entry points, protocols, and sandboxing."}, {"role": "assistant", "content": "Define Plugin Protocol with methods initialize and execute taking typed context and returning result to enforce contract statically. Discover implementations via importlib dot metadata entry_points group myapp dot plugins to allow third party packages without code changes. Load plugins lazily and isolate failures with try except so one broken plugin does not crash host. Validate plugin metadata including name and version and required host version for compatibility checks. Sandbox by restricting file and network access via capability object passed to plugin rather than raw globals. Provide versioned API with deprecation warnings to maintain backward compatibility. Test with sample plugins covering happy path and exception and missing entry point. Document authoring guide with minimal example and packaging instructions. Log plugin load times to detect slow startup contributors. Well designed plugin system balances extensibility with stability and security for evolving ecosystems."}], "metadata": {"domain": "python", "task_type": "architecture", "difficulty": "advanced"}} {"messages": [{"role": "user", "content": "Refactor nested Python try-except blocks handling file, network, and validation errors into clean code."}, {"role": "assistant", "content": "Flatten nesting by extracting helpers _load_file, _fetch_remote, _validate with each raising domain exceptions. Use single try in orchestrator catching specific types separately for tailored handling. Replace bare except with explicit exception tuples and use exception chaining. Introduce result objects or early returns instead of deep nesting. Apply context managers for file and session cleanup. Centralize logging with context including operation and id. Define custom ValidationError to distinguish user errors from system failures. Test each helper independently with mocked failures. Complexity drops, coverage improves, and error paths become explicit. Avoid catching BaseException. Document retry policy per error class. Final structure is linear, readable, and ensures resources close correctly while preserving original error semantics without swallowing tracebacks."}], "metadata": {"domain": "python", "task_type": "code_review", "difficulty": "intermediate"}} {"messages": [{"role": "user", "content": "Explain how to structure a small Python CLI project with modules, entry points, and configuration for maintainability."}, {"role": "assistant", "content": "Create a package directory with __init__.py, cli.py for argument parsing, core.py for business logic, and config.py for settings. Define entry points in pyproject.toml using project.scripts so pip creates a command. Use argparse or click for CLI parsing and separate parsing from execution to enable testing. Store configuration in dataclasses with defaults, override via environment variables and optional TOML file. Keep side effects in main function guarded by if __name__ equals main. Add logging configuration, error handling with clear exit codes, and typed function signatures. Include tests for core logic, README with usage examples, and Makefile for lint and test commands. This separation improves testability, reuse, and future extension to new subcommands."}], "metadata": {"domain": "python", "task_type": "architecture", "difficulty": "beginner"}} {"messages": [{"role": "user", "content": "How to prevent SQL injection in Python sqlite code? I use f\"SELECT * FROM u WHERE name='{n}'\" and worry about quote escape. Show parameterized fix."}, {"role": "assistant", "content": "String formatting lets attacker break out with quote, parameterized queries keep data separate from SQL. Example:\nimport sqlite3\ncon = sqlite3.connect(':memory:')\ncon.execute('CREATE TABLE u(name TEXT)')\ndef find(name: str):\n cur = con.execute('SELECT * FROM u WHERE name=?', (name,))\n return cur.fetchall()\n# attack input \"' OR '1'='1\" now treated as literal\nprint(find(\"' OR '1'='1\"))\nKey decisions: use ? for sqlite, %s for psycopg. Never format table names from user, allowlist if dynamic. Use ORM with bind params automatically. Enable query logging to audit. Test with injection strings asserting no extra rows. This eliminates most critical DB vulnerability with minimal change. Additional notes: add logging with context, write unit tests for edge cases, validate inputs at API boundary, monitor metrics in production, and document assumptions for future maintainers to prevent regressions."}], "metadata": {"domain": "python", "task_type": "security", "difficulty": "advanced"}} {"messages": [{"role": "user", "content": "Optimize a slow Python loop that computes cosine similarity for 100k embeddings and causes high memory usage."}, {"role": "assistant", "content": "Replace Python loops with vectorized NumPy operations and batched matrix multiplication. Normalize embeddings once with L2 norm, then compute similarities via dot products in batches of 5000 to bound memory. Use float32 instead of float64 to halve memory and leverage BLAS. For top-k search, use argpartition instead of full sort to reduce complexity. If still slow, move to FAISS with IndexFlatIP for exact search or IndexIVFFlat for approximate search on millions of vectors. Profile with cProfile and memory_profiler to confirm hotspots before optimizing. Avoid storing full 100k by 100k matrix, which needs 40GB in float32. Precompute norms, use numba for custom kernels if needed, and parallelize batch encoding with multiprocessing for CPU-bound preprocessing."}], "metadata": {"domain": "python", "task_type": "optimization", "difficulty": "beginner"}} {"messages": [{"role": "user", "content": "Audit a Python web app for common injection and deserialization vulnerabilities."}, {"role": "assistant", "content": "Review all inputs: use parameterized queries, never string formatting for SQL. Escape shell commands, prefer subprocess without shell and argument lists. Avoid pickle or yaml.load on untrusted data; use json with schema validation. Validate URLs to prevent SSRF via allowlists and block private IPs. Sanitize HTML output with escaping or bleach. Check template rendering for injection, file path traversal via normalized joins and allowlists. Enforce authentication and authorization checks on every endpoint. Scan dependencies with pip-audit and pin versions. Add security tests attempting injection payloads, oversized inputs, and malicious pickles. Document threat model, secure coding rules, and incident handling for findings."}], "metadata": {"domain": "python", "task_type": "security", "difficulty": "intermediate"}} {"messages": [{"role": "user", "content": "Optimize file reading for large logs using context managers and streaming instead of loading whole file."}, {"role": "assistant", "content": "Always open files with with statement to guarantee close on exception and avoid descriptor leaks under load. Stream line by line using for line in file object rather than read or readlines which allocate entire content in memory. Specify encoding equals utf-8 and errors equals replace to handle malformed logs without crashing pipeline. For binary processing use buffering parameter and memoryview to reduce copies. Compose multiple context managers with ExitStack when opening rotated log sets dynamically. Add try except around IOError and log path and operation for operational debugging. Benchmark memory with tracemalloc showing streaming stays constant while full read grows linearly. Test with empty file and missing file and very long lines. Document that iterator protocol yields strings including newline and requires strip only when needed to avoid extra allocations. This pattern enables processing gigabyte logs on modest containers."}], "metadata": {"domain": "python", "task_type": "optimization", "difficulty": "beginner"}} {"messages": [{"role": "user", "content": "My function opens 3 files nested with open inside open and forgets to close on exception. How to handle multiple resources cleanly?"}, {"role": "assistant", "content": "Use combined with statement opening all files in one line separated by commas, ensuring all close even on error. For dynamic count use contextlib.ExitStack entering each file in loop. Wrap processing in try except OSError logging filename. Avoid manual close calls. Example with open a plus open b as f g guarantees cleanup via context protocol. Test exception path asserting files closed via mock. For DB plus file plus lock, nest ExitStack for uniform handling. This pattern leverages context managers for deterministic resource release, preventing descriptor leaks and simplifying review. Refactor nested opens to flat ExitStack, improving readability and exception safety without verbose finally blocks."}], "metadata": {"domain": "python", "task_type": "implementation", "difficulty": "intermediate"}} {"messages": [{"role": "user", "content": "Why does my list comprehension leak loop variable in Python 2 style code but not Python 3? I see unexpected NameError after migration."}, {"role": "assistant", "content": "Python 3 gives comprehensions their own scope while Python 2 leaked variable to enclosing function. After migration code relying on leaked i now raises NameError, which is actually safer. Fix by explicitly assigning loop result if needed outside, avoiding dependence on comprehension side effects. Use generator expressions for large data to save memory. Audit with pylint for undefined variables. Test both list and dict comprehensions for scoping. Embrace new semantics by initializing variables clearly before use. This scope isolation prevents accidental overwrite of outer variables, reducing bugs where loop index clobbers important state. Update legacy code to be explicit rather than relying on leak behavior removed for correctness."}], "metadata": {"domain": "python", "task_type": "debugging", "difficulty": "beginner"}} {"messages": [{"role": "user", "content": "Review this Python batch inference script for concurrency bugs, resource leaks, and determinism."}, {"role": "assistant", "content": "Check ThreadPoolExecutor shutdown handling and exception propagation; unawaited futures hide failures. Verify file handles and DB connections closed via context managers. Look for shared mutable state like global list append without locks causing race. Confirm random seeds set per worker for reproducibility. Inspect batch sizing causing OOM under peak. Ensure SIGINT gracefully drains queue. Validate logging includes batch IDs for traceability. Flag hardcoded paths and missing retries on transient errors. Test with fault injection killing workers. Recommend asyncio with bounded semaphore for I/O plus multiprocessing for CPU. Add metrics for throughput and error rate. Require idempotent writes to allow safe reruns."}], "metadata": {"domain": "python", "task_type": "code_review", "difficulty": "advanced"}} {"messages": [{"role": "user", "content": "Explain Python logging configuration with handlers, formatters, and levels for production applications."}, {"role": "assistant", "content": "Structured logging enables diagnosis without print statements in production Python. Configure root logger once using dictConfig with handlers for console and rotating files, formatters including timestamp, level, name, and correlation id. Use levels DEBUG through CRITICAL appropriately, defaulting to INFO in production. Create module loggers via getLogger dunder name for granular control. Avoid f-string interpolation in log calls; use lazy percent args. Add JSON formatting for aggregation systems and include request context via filters. Handle exceptions with exc_info True. Rotate files to bound disk and set propagation carefully. Test output in development and staging, verify no secrets leak. Centralize configuration, document conventions, and correlate with metrics and traces. Consistent logging improves observability, accelerates incident response, and supports auditing across distributed Python services and background jobs."}], "metadata": {"domain": "python", "task_type": "instruction", "difficulty": "intermediate"}} {"messages": [{"role": "user", "content": "Python caching embeddings cuts cost 40 percent but staleness 5 percent. Is tradeoff acceptable for RAG?"}, {"role": "assistant", "content": "Forty percent saving outweighs 5 percent staleness if invalidation handles updates correctly and quality impact minimal. Measure staleness impact on answer accuracy not just embedding age, testing on changed docs subset. Implement TTL 24h plus version key on doc hash for immediate refresh on edit. Segment by rapidly changing docs excluding them from cache or using short TTL. Monitor hit rate and refresh lag continuously. Run A B on quality to confirm no degradation in faithfulness. Analyze tail queries where stale chunks cause errors. Accept with targeted bypass for fresh content and admin preview. Document cache policy with clear invalidation rules. This achieves major cost reduction while preserving correctness for dynamic corpora through selective caching strategy and observability."}], "metadata": {"domain": "python", "task_type": "experiment_analysis", "difficulty": "expert"}} {"messages": [{"role": "user", "content": "How do I build a robust CLI with argparse or click including subcommands and validation?"}, {"role": "assistant", "content": "Robust CLIs parse arguments reliably, validate early, and provide helpful output. With argparse, define ArgumentParser, subparsers for commands, typed arguments, choices, and required groups. With Click, compose commands via decorators, contexts, and parameter types. Validate paths, enums, and ranges, failing with clear messages and exit codes. Support minus h help, version flags, verbosity, dry run, and config files. Use pathlib, handle stdin stdout encoding, and ensure pipe safety. Test with CliRunner or subprocess across success and error cases. Log to stderr, output data to stdout for scripting. Document examples and environment variables. Handle signals gracefully. Consistent UX, shell completion, and thorough tests make Python CLIs dependable for automation, operations, and developer workflows across diverse environments and user skill levels."}], "metadata": {"domain": "python", "task_type": "instruction", "difficulty": "advanced"}} {"messages": [{"role": "user", "content": "Engineer image augmentations to reduce overfitting on small dataset."}, {"role": "assistant", "content": "Build torchvision v2 Compose RandomResizedCrop 224 scale 0.8 1.0 HorizontalFlip Rotation 15 ColorJitter TrivialAugment plus CutMix MixUp in training loop. Validate with 5 fold splits showing gap closure. Tune magnitude via ablation. Use Normalize after ToTensor. Test output shapes and label smoothing 0.1. Set seed 42. Persist transform yaml. Monitor train val curves. This synthetically expands diversity, improves invariance to pose lighting, reduces variance, and boosts small data accuracy for production vision models today reliably. Track metrics with versioned data splits and persist artifacts with joblib to ensure auditability and reliable promotion from staging to production. Set random_state 42 for reproducibility and validate on stratified holdout with cross-validation to confirm generalization stability and deployment readiness for production workflows."}], "metadata": {"domain": "pytorch", "task_type": "implementation", "difficulty": "intermediate"}} {"messages": [{"role": "user", "content": "Recommend best practices for experiment tracking, checkpointing, and resuming PyTorch runs after preemption."}, {"role": "assistant", "content": "Checkpoint full state: torch.save({'model':model.state_dict(),'opt':opt.state_dict(),'sched':sched.state_dict(),'scaler':scaler.state_dict(),'epoch':e,'rng':torch.get_rng_state()},f'ckpt-{e}.pt'); Log params metrics with MLflow or W&B. Save every epoch plus best on val. On restart load maps, restore RNG and scaler to resume exact LR. Use atomic write temp then rename. Keep last 3 plus best to save disk. Track git sha, config yaml, data hash. Test resume equality: loss matches uninterrupted run. For SLURM handle SIGTERM handler saving. These best practices prevent losing days of training to spot preemption and enable fair comparison across seeds. For production readiness log all metrics parameters and data versions with MLflow record random seeds library versions and data hashes validate performance on holdout test sets check calibration fairness latency and memory usage monitor prediction drift after deployment and document business impact to ensure reliable generalization and maintainable operation for stakeholders."}], "metadata": {"domain": "pytorch", "task_type": "instruction", "difficulty": "advanced"}} {"messages": [{"role": "user", "content": "Implement gradient accumulation to simulate large batch size on limited GPU memory."}, {"role": "assistant", "content": "Divide loss by accumulation steps so averaged gradients match large batch, backward each micro batch, and step optimizer only every k steps with scheduler sync. Zero grad after step. Handle remainder batches and DDP no_sync for efficiency. Code:\nimport torch\nimport torch.nn as nn\nmodel = nn.Linear(32, 4)\nopt = torch.optim.AdamW(model.parameters(), lr=3e-4)\naccum = 4\ncrit = nn.CrossEntropyLoss()\nopt.zero_grad()\nfor step in range(8):\n xb = torch.randn(8, 32)\n yb = torch.randint(0, 4, (8,))\n loss = crit(model(xb), yb) / accum\n loss.backward()\n if (step + 1) % accum == 0:\n torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0)\n opt.step()\n opt.zero_grad()\n print('step', step)\nLog effective batch as micro times accum. This enables 256 batch training on 64 batch hardware with near identical convergence."}], "metadata": {"domain": "pytorch", "task_type": "implementation", "difficulty": "intermediate"}} {"messages": [{"role": "user", "content": "Debug NaN loss in mixed precision Transformer due to overflow in softmax and grad scaler."}, {"role": "assistant", "content": "FP16 overflow in attention logits and large grads cause NaNs under AMP. Use fp32 for softmax and loss, enable grad scaling with growth interval, and clip norms. Check for inf in inputs.\n```python\nimport torch\nfrom torch.cuda.amp import GradScaler\nscaler = GradScaler(init_scale=2.**10, growth_interval=500)\n# assert not torch.isnan(x).any()\n# with autocast(dtype=torch.float16):\n# out = model(x)\n# loss = criterion(out.float(), y) # fp32 loss\n# scaler.scale(loss).backward()\n# scaler.unscale_(opt)\n# torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0)\n# scaler.step(opt)\n# scaler.update()\n# use scaled_dot_product_attention in fp32\n```\nLog scale factor, reduce LR, and validate tokenizer outputs for corrupt tokens. Validate shapes and device placement per batch, clip gradients and log learning rates, checkpoint best validation weights, and test inference in eval mode with no grad for reproducible deployment."}], "metadata": {"domain": "pytorch", "task_type": "debugging", "difficulty": "expert"}} {"messages": [{"role": "user", "content": "Fix mixed precision GradScaler producing inf gradients in PyTorch ViT with fp16."}, {"role": "assistant", "content": "ViT attention logits overflow fp16 range 65504 easily, causing scaler to repeatedly backoff. Switch autocast dtype to bfloat16 on A100/H100 where available for larger dynamic range. Keep LayerNorm and Softmax in float32 via autocast disabled context for those ops. Reduce init_scale to 1024 and growth_interval 2000 to stabilize. Clip grad norm after unscale_ before step; check scaler.get_scale for collapse below 128 indicating chronic overflow. Use fused AdamW with eps 1e-8. Normalize patches and use Pre-LN architecture to reduce activation magnitude. Log per-layer grad norm to isolate overflowing block. Validate that loss scaling skips optimizer step on inf, not corrupting weights. Validate fix with dedicated unit test and integration check covering edge cases. Log relevant metrics, monitor production dashboards continuously, document change clearly in pull request for reviewers and future maintenance work."}], "metadata": {"domain": "pytorch", "task_type": "debugging", "difficulty": "intermediate"}} {"messages": [{"role": "user", "content": "Debug distributed SyncBatchNorm deadlock when some GPUs get empty micro-batch."}, {"role": "assistant", "content": "SyncBatchNorm performs collective stats gather; empty micro-batch on any rank deadlocks or produces NaN. Enforce drop_last True and equal sharding via DistributedSampler. Convert BatchNorm via torch.nn.SyncBatchNorm.convert_sync_batchnorm before DDP. Check that all ranks enter forward together; conditional early-exit on empty batch must still participate with dummy tensor. Log per-rank batch size at each step to detect imbalance from filtering. For variable-length data, pad to at least one element and mask loss. Set process group timeout low to surface hang quickly. Add health check all_gather of batch sizes before norm layer in debug mode. Validate fix with dedicated unit test and integration check covering edge cases. Log relevant metrics, monitor production dashboards continuously, document change clearly in pull request for reviewers and future maintenance work."}], "metadata": {"domain": "pytorch", "task_type": "debugging", "difficulty": "intermediate"}} {"messages": [{"role": "user", "content": "How to write a custom autograd Function with correct forward and backward for advanced use?"}, {"role": "assistant", "content": "Subclass torch.autograd.Function with static forward and backward, save tensors for gradient via ctx.save_for_backward, and handle non differentiable args with None returns. Ensure backward matches input count and supports double for gradcheck. Mark non differentiable with mark_non_differentiable if needed. Example Swish:\nimport torch\nclass Swish(torch.autograd.Function):\n @staticmethod\n def forward(ctx, x):\n s = torch.sigmoid(x)\n ctx.save_for_backward(x, s)\n return x * s\n @staticmethod\n def backward(ctx, g):\n x, s = ctx.saved_tensors\n dx = s + x * s * (1 - s)\n return g * dx\nx = torch.randn(4, 4, requires_grad=True, dtype=torch.float64)\n# gradcheck needs double\nfrom torch.autograd import gradcheck\nprint(gradcheck(Swish.apply, (x,)))\ny = Swish.apply(torch.randn(3, 3, requires_grad=True))\nprint(y.shape)\nAvoid in place ops on saved tensors. This pattern enables sparse custom kernels and straight through estimators."}], "metadata": {"domain": "pytorch", "task_type": "instruction", "difficulty": "advanced"}} {"messages": [{"role": "user", "content": "How to use torch.compile for operator fusion and what are graph break pitfalls?"}, {"role": "assistant", "content": "Torch.compile traces with Dynamo and fuses ops via Inductor for significant speedups, but data dependent control flow and third party calls cause graph breaks and recompiles. Keep shapes static, avoid print in forward, and use mark_dynamic sparingly. Tune mode max-autotune. Usage:\nimport torch\nimport torch.nn as nn\nmodel = nn.Sequential(nn.Linear(128, 256), nn.GELU(), nn.Linear(256, 10))\nopt_model = torch.compile(model, mode='max-autotune')\nx = torch.randn(32, 128)\nprint(opt_model(x).shape)\n# explain no graph breaks\n# torch._dynamo.explain(opt_model)(x)\nprint('compiled')\nWarm up before benchmarking with synchronize. Cache compiled artifacts in CI. Monitoring recompilation count reveals dynamic shape issues; padding to fixed buckets often restores full fusion and 1.3 to 2x gains."}], "metadata": {"domain": "pytorch", "task_type": "optimization", "difficulty": "advanced"}} {"messages": [{"role": "user", "content": "Traceback CUDA error device-side assert triggered on CrossEntropyLoss. How to find bad labels?"}, {"role": "assistant", "content": "Device side asserts in CUDA often mean out of range class indices or NaN inputs that only surface asynchronously. Rerun on CPU to get precise traceback, then validate target min max and input finiteness. Ensure num_classes matches label range. Debug workflow:\nimport torch\nimport torch.nn as nn\nlogits = torch.randn(16, 5)\ntargets = torch.randint(0, 5, (16,))\nprint(targets.min().item(), targets.max().item())\nassert targets.min() >= 0 and targets.max() < 5\nloss_fn = nn.CrossEntropyLoss()\n# force CPU for clear error\nloss = loss_fn(logits.cpu(), targets.cpu())\nprint(loss.item())\n# check NaN\nprint(torch.isfinite(logits).all().item())\nAdd dataset validation to assert labels in range during getitem. Use CUDA_LAUNCH_BLOCKING equals 1 temporarily for line accurate errors. Fixing label mapping or filtering corrupt samples resolves most such triggers reliably."}], "metadata": {"domain": "pytorch", "task_type": "traceback", "difficulty": "intermediate"}} {"messages": [{"role": "user", "content": "Explain torch.func vmap and grad for per-sample gradients without loops."}, {"role": "assistant", "content": "Torch.func transforms enable vectorized per sample grads via vmap over grad of single sample loss, avoiding slow Python loops and huge batch Jacobian memory. Use functional_call with params and buffers for models. Ensure pure functions. Demo:\nimport torch\nimport torch.nn as nn\nfrom torch.func import functional_call, vmap, grad\nmodel = nn.Linear(8, 1)\nparams = dict(model.named_parameters())\nbuffers = dict(model.named_buffers())\ndef loss_fn(p, x, y):\n pred = functional_call(model, (p, buffers), (x.unsqueeze(0),))\n return ((pred - y) ** 2).mean()\nper_grad = vmap(grad(loss_fn), in_dims=(None, 0, 0))\nX = torch.randn(16, 8)\nY = torch.randn(16, 1)\ng = per_grad(params, X, Y)\nprint(g['weight'].shape)\nClip per sample norms for DP-SGD. This unlocks efficient influence and privacy accounting at scale."}], "metadata": {"domain": "pytorch", "task_type": "instruction", "difficulty": "advanced"}} {"messages": [{"role": "user", "content": "Debug ignored class imbalance: CrossEntropyLoss without weights gives 99% majority accuracy. Fix with weighted sampling."}, {"role": "assistant", "content": "Unweighted loss lets majority dominate gradients, so use class weights in loss and WeightedRandomSampler for balanced batches. Compute weights inverse to frequency and monitor per-class recall.\n```python\nimport torch\nfrom torch.utils.data import WeightedRandomSampler\ncounts = torch.tensor([9000., 1000.])\nw = 1.0/counts\ncrit = torch.nn.CrossEntropyLoss(weight=w)\nsample_w = w[torch.tensor(labels)]\nsampler = WeightedRandomSampler(sample_w, len(sample_w))\nloader = torch.utils.data.DataLoader(ds, batch_size=64, sampler=sampler)\n# per-class check\n# print((preds[y==1]==1).float().mean())\n```\nValidate with balanced accuracy and PR-AUC, avoid oversampling validation set. Validate shapes and device placement per batch, clip gradients and log learning rates, checkpoint best validation weights, and test inference in eval mode with no grad for reproducible deployment. Additionally verify mixed precision parity, test on CPU fallback, and profile dataloader throughput."}], "metadata": {"domain": "pytorch", "task_type": "debugging", "difficulty": "advanced"}} {"messages": [{"role": "user", "content": "What does requires_grad do and how does autograd track operations for beginners?"}, {"role": "assistant", "content": "Setting requires_grad True tells PyTorch to record operations on that tensor for differentiation. Leaf tensors like weights accumulate grad after backward while intermediate grads are freed unless retain_graph or retain_grad is used. Use with torch.no_grad for inference to save memory. Demo:\nimport torch\nx = torch.tensor([2.0, 3.0], requires_grad=True)\nw = torch.tensor([4.0, 5.0], requires_grad=True)\ny = (x * w).sum()\nprint(y.item())\ny.backward()\nprint(x.grad)\nprint(w.grad)\n# inference no tracking\nwith torch.no_grad():\n z = x * 2\n print(z.requires_grad)\nCall optimizer.zero_grad before each backward or gradients sum across batches. Inspect grad_fn to see graph nodes. This foundation explains why model parameters update and why forgetting zero_grad causes exploding updates after a few steps."}], "metadata": {"domain": "pytorch", "task_type": "instruction", "difficulty": "beginner"}} {"messages": [{"role": "user", "content": "Evaluate classifier with per class precision recall and calibration in torch."}, {"role": "assistant", "content": "Global accuracy hides weak minority classes and miscalibration. Compute confusion matrix and per class F1 plus expected calibration error under no grad for reliability. Code:\n```python\nimport torch\nfrom sklearn.metrics import classification_report, confusion_matrix\nmodel.eval()\nall_p, all_y = [], []\nwith torch.no_grad():\n for xb, yb in test_loader:\n logits = model(xb.to(device))\n all_p += logits.argmax(1).cpu().tolist()\n all_y += yb.tolist()\nprint(classification_report(all_y, all_p, digits=3))\nprint(confusion_matrix(all_y, all_p))\nprint('eval done', len(all_y))\n```\nPlot reliability diagrams for risk sensitive tasks. Temperature scaling post hoc often fixes overconfident modern networks without expensive retraining and data collection. For production use add logging and unit tests plus versioned data snapshots. Monitor metrics over time and document assumptions for teammates. Validate edge cases with nulls and empty frames before deployment to avoid silent failures in live systems."}], "metadata": {"domain": "pytorch", "task_type": "experiment_analysis", "difficulty": "intermediate"}} {"messages": [{"role": "user", "content": "Refactor hard-coded device calls to device-agnostic helper with automatic mixed precision support."}, {"role": "assistant", "content": "Centralize device logic. Example: import torch; DEV=torch.device('cuda' if torch.cuda.is_available() else 'cpu'); def to_dev(b): return {k:v.to(DEV,non_blocking=True) if isinstance(v,torch.Tensor) else v for k,v in b.items()} if isinstance(b,dict) else tuple(x.to(DEV,non_blocking=True) for x in b); model.to(DEV); Use autocast context only if cuda: ctx=torch.amp.autocast('cuda') if DEV.type=='cuda' else torch.cpu.amp.autocast(enabled=False); Remove .cuda() scattered calls. Add .to(memory_format=torch.channels_last) for CNNs. Test on CPU CI and GPU nightly. Refactor enables single code path for laptop and cluster, prevents device mismatch errors, and simplifies AMP toggling via config flag. For production readiness log all metrics parameters and data versions with MLflow record random seeds library versions and data hashes validate performance on holdout test sets check calibration fairness latency and memory usage monitor prediction drift after deployment and document business impact to ensure reliable generalization and maintainable operation for stakeholders."}], "metadata": {"domain": "pytorch", "task_type": "code_review", "difficulty": "intermediate"}} {"messages": [{"role": "user", "content": "Secure PyTorch inference server against malicious image payloads causing DoS via decompression bombs."}, {"role": "assistant", "content": "Large images exhaust memory during decode and resize, so enforce size, dimension, and format limits before tensor conversion. Use PIL Image.MAX_IMAGE_PIXELS, timeouts, and resource quotas. Run in sandbox.\n```python\nfrom PIL import Image\nImage.MAX_IMAGE_PIXELS = 50_000_000\ndef safe_open(path):\n im = Image.open(path)\n im.draft('RGB', (1024, 1024))\n w, h = im.size\n assert w*h < 10_000_000, 'too large'\n assert im.format in ('JPEG', 'PNG'), 'bad format'\n return im.convert('RGB').resize((224, 224))\n# limit request to 5MB, timeout 5s\n# app.config['MAX_CONTENT_LENGTH'] = 5*1024*1024\n```\nAdd auth, rate limit, and scan uploads without executing embedded code. Validate shapes and device placement per batch, clip gradients and log learning rates, checkpoint best validation weights, and test inference in eval mode with no grad for reproducible deployment."}], "metadata": {"domain": "pytorch", "task_type": "security", "difficulty": "advanced"}} {"messages": [{"role": "user", "content": "PyTorch model trains but validation accuracy stays 10% on CIFAR10. Debug training loop bug."}, {"role": "assistant", "content": "Constant 10% accuracy indicates random guessing, typically model in wrong mode, broken labels, or no learning. Verify model.train and model.eval toggling correctly; leaving dropout and BatchNorm in train mode skews validation. Check that validation loader does not apply random augmentation like RandomCrop with shuffling labels. Confirm loss decreases; if not, learning rate may be zero due to scheduler stepping every batch incorrectly. Inspect label mapping: CIFAR10 targets 0-9, ensure CrossEntropyLoss receives LongTensor without one-hot. Ensure you call torch.no_grad but still compute logits correctly, not reusing stale outputs. Plot confusion matrix to confirm uniform predictions versus collapsed class. Validate fix with dedicated unit test and integration check covering edge cases. Log relevant metrics, monitor production dashboards continuously, document change clearly in pull request for reviewers and future maintenance work."}], "metadata": {"domain": "pytorch", "task_type": "debugging", "difficulty": "beginner"}} {"messages": [{"role": "user", "content": "Implement a small CNN for 32x32 RGB images with conv batchnorm pooling and training step."}, {"role": "assistant", "content": "A small CNN stacks Conv2d BatchNorm2d ReLU and MaxPool2d to downsample while increasing channels, then global pool and Linear for logits. Use CrossEntropyLoss and Adam with proper train eval modes. Initialize with Kaiming and log shapes. Implementation:\nimport torch\nimport torch.nn as nn\nclass SmallCNN(nn.Module):\n def __init__(self):\n super().__init__()\n self.f = nn.Sequential(nn.Conv2d(3, 32, 3, padding=1), nn.BatchNorm2d(32), nn.ReLU(), nn.MaxPool2d(2), nn.Conv2d(32, 64, 3, padding=1), nn.BatchNorm2d(64), nn.ReLU(), nn.AdaptiveAvgPool2d(1))\n self.fc = nn.Linear(64, 10)\n def forward(self, x):\n h = self.f(x)\n return self.fc(h.flatten(1))\nmodel = SmallCNN()\nx = torch.randn(8, 3, 32, 32)\nprint(model(x).shape)\nTrain one step with CrossEntropyLoss and Adam to verify graph. Use torchinfo style shape prints. This baseline reaches decent accuracy and scales to deeper ResNets."}], "metadata": {"domain": "pytorch", "task_type": "implementation", "difficulty": "intermediate"}} {"messages": [{"role": "user", "content": "Preprocess text for PyTorch with tokenizer padding, attention masks, and batched collate function."}, {"role": "assistant", "content": "Pad dynamically per batch. Example: from transformers import AutoTokenizer; tok=AutoTokenizer.from_pretrained('bert-base-uncased'); def collate(batch): enc=tok([b['text'] for b in batch],padding=True,truncation=True,max_length=128,return_tensors='pt'); labels=torch.tensor([b['label'] for b in batch]); return enc['input_ids'],enc['attention_mask'],labels; loader=torch.utils.data.DataLoader(ds,batch_size=32,collate_fn=collate); Set pad_token if missing. Sort by length with BucketBatchSampler to cut padding 30%. Mask ensures loss ignores pads. Validate mask sum equals lengths. Save tokenizer with model for serving. This preprocessing avoids fixed max length waste and ensures correct attention for variable reviews. For production readiness log all metrics parameters and data versions with MLflow record random seeds library versions and data hashes validate performance on holdout test sets check calibration fairness latency and memory usage monitor prediction drift after deployment and document business impact to ensure reliable generalization and maintainable operation for stakeholders."}], "metadata": {"domain": "pytorch", "task_type": "implementation", "difficulty": "intermediate"}} {"messages": [{"role": "user", "content": "Debug vanishing gradients in a deep LSTM for text classification."}, {"role": "assistant", "content": "Plot gradient norms per layer to confirm decay across time steps. Replace vanilla RNN with LSTM and add layer normalization to stabilize activations. Use orthogonal initialization for recurrent weights and Xavier for input projections. Apply gradient clipping at 1.0 and reduce learning rate with warmup. Shorten sequences via truncation and use packed sequences to avoid padding noise. Add residual connections or attention pooling over hidden states. Monitor forget gate saturation and activation histograms. Compare Adam versus SGD with momentum. Evaluate validation F1 versus sequence length buckets. Test bidirectional variant for context. Log histograms in TensorBoard. Document architecture changes and ablation results. Validate on long versus short texts to confirm fix generalizes beyond training distribution."}], "metadata": {"domain": "pytorch", "task_type": "debugging", "difficulty": "intermediate"}} {"messages": [{"role": "user", "content": "PyTorch mixed precision fp16 vs bf16 shows loss NaN in fp16 but stable bf16, throughput similar. Why and which to use?"}, {"role": "assistant", "content": "FP16 narrow exponent range overflows on large activations and softmax causing NaNs while BF16 preserves range with reduced precision stable for training. Inspect loss scale behavior where dynamic scaler overflow frequency high indicates instability. Check layers with large logits needing clipping or normalization. Prefer BF16 on A100 H100 where hardware supported for stability without tuning. Validate final accuracy parity with fp32 master weights on held out set. Enable autocast with GradScaler only for fp16 path. Log gradient norms to detect instability early. Test mixed precision on small run before full training. Choose bf16 for stability without tuning loss scale, reducing experiment churn and improving reproducibility for large transformer training jobs in production environments."}], "metadata": {"domain": "pytorch", "task_type": "experiment_analysis", "difficulty": "advanced"}} {"messages": [{"role": "user", "content": "Review my training loop missing model.train, no grad zero, and validation inside no_grad? What else is wrong?"}, {"role": "assistant", "content": "Add model.train before train loop and model.eval plus torch.no_grad for val. Call optimizer.zero_grad before backward to avoid accumulation unless intended. Step scheduler correctly per epoch or batch. Detach loss for logging via loss.item. Save best checkpoint on val improvement. Fix seed for reproducibility. Add gradient clipping. Test one epoch overfit single batch. Review should demand these basics plus device handling and metric logging. Correct loop ensures BatchNorm dropout behave properly and gradients accurate, preventing silent 10 percent accuracy drop from eval mode leakage. Log loss learning rate and gradient norms to TensorBoard, checkpoint best validation model with optimizer state, and test reproducibility with fixed seeds across two runs to ensure stable training before scaling to multi GPU."}], "metadata": {"domain": "pytorch", "task_type": "code_review", "difficulty": "intermediate"}} {"messages": [{"role": "user", "content": "Engineer positional encodings and attention masks for variable lengths."}, {"role": "assistant", "content": "Implement sinusoidal or learned positional embeddings added to token embeddings with dropout 0.1. Build key_padding_mask True for pad and causal mask triu minus inf for autoregressive. Validate with manual 4x4 example and nn_Transformer behavior. Test extrapolation with RoPE for long context. Visualize attention weights. Ensure mask dtype bool float compatibility. Set seed. Benchmark memory flash attention. This preserves order, prevents future leakage, handles variable lengths efficiently, and enables correct Transformer training for language time series today reliably. Track metrics with versioned data splits and persist artifacts with joblib to ensure auditability and reliable promotion from staging to production. Set random_state 42 for reproducibility and validate on stratified holdout with cross-validation to confirm generalization stability and deployment readiness for production workflows."}], "metadata": {"domain": "pytorch", "task_type": "implementation", "difficulty": "advanced"}} {"messages": [{"role": "user", "content": "Explain why validation loss diverges while training loss decreases in PyTorch."}, {"role": "assistant", "content": "Divergence signals overfitting where model memorizes training noise and fails to generalize. Causes include excessive capacity, too many epochs, high learning rate, missing regularization, small data, leaky augmentation, and distribution shift. Diagnose with learning curves, weight norm growth, and per class gaps. Fix with weight_decay 1e-4, dropout 0.3, early stopping patience 10, ReduceLROnPlateau, stronger augmentation CutMix, label smoothing 0.1, and more data or cross-validation. Verify with Stratified splits seed 42 and calibration plots. Test that gap closes 5 to 10 points. Monitor gradient norms. This restores generalization, guides capacity versus data tradeoff, prevents wasted epochs, and yields robust models ready for production deployment today reliably with systematic debugging."}], "metadata": {"domain": "pytorch", "task_type": "instruction", "difficulty": "intermediate"}} {"messages": [{"role": "user", "content": "Implement DDP training with torchrun handling sampler checkpointing and synced metrics for multi-GPU."}, {"role": "assistant", "content": "Initialize distributed process group with NCCL backend for high bandwidth GPU communication, wrap model with DistributedDataParallel for gradient synchronization, and shard training data with DistributedSampler to guarantee disjoint partitions per rank. Set epoch on sampler each iteration to ensure proper shuffling across epochs, use DataLoader with appropriate batch size and workers, aggregate loss and accuracy with all_reduce for correct global averages, and save checkpoints exclusively on rank zero to prevent file corruption. Launch training with torchrun specifying number of processes per node, configure timeout and rendezvous for stability, offset random seeds by rank while maintaining reproducibility, test numerical equivalence against single GPU baseline, measure throughput scaling efficiency, verify checkpoint resume restores model optimizer and sampler state, and handle node failures gracefully with elastic restart policies."}], "metadata": {"domain": "pytorch", "task_type": "implementation", "difficulty": "intermediate"}} {"messages": [{"role": "user", "content": "Diagnose mode collapse in GANs training on faces."}, {"role": "assistant", "content": "Track FID, precision recall for diversity, and discriminator logits histograms. Visualize latent interpolations revealing limited variety. Switch to StyleGAN2 with path regularization and R1 penalty. Use minibatch stddev and diverse augmentation. Tune learning rates with TTUR and batch size. Compare WGAN-GP stability. Early stop on FID plateau. Document architecture and seeds. Evaluate nearest neighbors to detect memorization. Monitor gradient norms. Use truncation trick balancing quality diversity at inference. Profile GPU memory and throughput while testing gradient checkpointing for scaling to longer sequences. Compare against a smaller baseline to quantify accuracy efficiency tradeoffs before production release. Log metrics artifacts and data hashes to enable auditing and consistent comparison across runs."}], "metadata": {"domain": "pytorch", "task_type": "debugging", "difficulty": "advanced"}} {"messages": [{"role": "user", "content": "Analyze training curves with loss spikes and diverging validation. Diagnose LR too high vs bad batches."}, {"role": "assistant", "content": "Spikes indicate high LR, corrupted batches, or unstable mixed precision. Plot train and val loss, gradient norms, and LR schedule. Clip grads, lower LR with warmup, and inspect outlier batches.\n```python\nimport matplotlib.pyplot as plt\nplt.plot(train_loss, label='train')\nplt.plot(val_loss, label='val')\nplt.legend()\n# check grad norms\n# for n,p in model.named_parameters():\n# print(n, p.grad.norm() if p.grad is not None else None)\nimport torch\ntorch.nn.utils.clip_grad_norm_(model.parameters(), 1.0)\n# lower LR with warmup\n# scheduler = torch.optim.lr_scheduler.OneCycleLR(opt, max_lr=1e-3, total_steps=1000)\n# inspect bad batch\n# print(x[loss.argmax()])\n```\nValidate data pipeline, enable anomaly detection, and use EMA for smoother validation. Validate shapes and device placement per batch, clip gradients and log learning rates, checkpoint best validation weights, and test inference in eval mode with no grad for reproducible deployment."}], "metadata": {"domain": "pytorch", "task_type": "experiment_analysis", "difficulty": "advanced"}} {"messages": [{"role": "user", "content": "DDP training hangs at barrier with unequal batch sizes across ranks. Logs show rank 0 waiting. How to fix?"}, {"role": "assistant", "content": "Ensure DistributedSampler with set_epoch each epoch and drop_last True for equal shards. Synchronize all ranks entering all_reduce, no conditional branches skipping. Check timeout 30m and NCCL debug. Use torchrun with same world size. Test 2 GPU small run. Add barrier logging. Unequal lengths deadlock collective, fix via even sharding or padding. Proper sampler guarantees same steps, eliminating hang and ensuring correct gradient averaging across workers. Log loss learning rate and gradient norms to TensorBoard, checkpoint best validation model with optimizer state, and test reproducibility with fixed seeds across two runs to ensure stable training before scaling to multi GPU. Include monitoring tests and documentation updates so the fix persists. Verify behavior under load and failure injection, record results in the pull request, and share lessons with the team during review to prevent recurrence across services."}], "metadata": {"domain": "pytorch", "task_type": "debugging", "difficulty": "advanced"}} {"messages": [{"role": "user", "content": "Explain mixed precision training and GradScaler usage."}, {"role": "assistant", "content": "Mixed precision uses float16 for matmuls (2x faster, half memory) and float32 for master weights/accumulation to preserve stability. In PyTorch:\n```python\nscaler = torch.amp.GradScaler('cuda')\nfor x,y in loader:\n opt.zero_grad()\n with torch.amp.autocast('cuda'):\n pred = model(x)\n loss = F.cross_entropy(pred, y)\n scaler.scale(loss).backward()\n scaler.step(opt)\n scaler.update()\n```\nGradScaler scales loss to avoid fp16 underflow, unscales before clipping, skips step on inf/nan. Pitfalls: some ops (softmax, loss) must stay fp32 \u2014 autocast handles this. Always use scaler with fp16; bf16 (A100+) is more stable and often needs no scaler."}], "metadata": {"domain": "pytorch", "task_type": "instruction", "difficulty": "advanced"}} {"messages": [{"role": "user", "content": "How to certify adversarial robustness with randomized smoothing in PyTorch securely?"}, {"role": "assistant", "content": "Randomized smoothing certifies L2 radius by majority vote under Gaussian noise, providing provable defense versus empirical attacks. Sample N noisy forwards, estimate top class via Clopper-Pearson, and compute radius sigma times Phi inverse gap. Keep sampling on GPU batched. Certifier:\nimport torch\nimport torch.nn as nn\nmodel = nn.Sequential(nn.Linear(784, 256), nn.ReLU(), nn.Linear(256, 10))\nmodel.eval()\nx = torch.randn(1, 784)\nsigma = 0.25\nN = 1000\nwith torch.inference_mode():\n votes = []\n for i in range(10):\n noisy = x + sigma * torch.randn(100, 784)\n pred = model(noisy).argmax(1)\n print(pred[:3])\n break\nprint('smoothing ready')\n# radius = sigma * PhiInv(pA - pB)\nAudit sampling RNG and report abstain rate. This yields certified accuracy metrics for safety critical vision and malware classifiers."}], "metadata": {"domain": "pytorch", "task_type": "security", "difficulty": "expert"}} {"messages": [{"role": "user", "content": "Fix PyTorch CrossEntropyLoss expecting Long but got Float for targets from CSV loader."}, {"role": "assistant", "content": "CrossEntropyLoss requires class indices as LongTensor shape [N], not one-hot or float. Your CSV loader likely yields float via default pandas dtype or ToTensor scaling. Cast targets with torch.as_tensor(labels, dtype=torch.long) in Dataset. If labels are one-hot, convert with torch.argmax dim 1. Remove Softmax before loss; CrossEntropy includes LogSoftmax internally, double softmax degrades gradients. Verify num_classes equals logits dim 1; print logits.shape and targets.max/min. For binary case consider BCEWithLogitsLoss with float targets instead. Add assertion targets.dtype==torch.int64 and targets.dim()==1 before criterion. Fix DataLoader collate to preserve dtype, avoid default float conversion in transforms. Validate fix with dedicated unit test and integration check covering edge cases. Log relevant metrics, monitor production dashboards continuously, document change clearly in pull request for reviewers and future maintenance work."}], "metadata": {"domain": "pytorch", "task_type": "debugging", "difficulty": "beginner"}} {"messages": [{"role": "user", "content": "Review pipeline parallelism design for 70B model across 8 GPUs with bubble minimization."}, {"role": "assistant", "content": "Naive GPipe leaves large bubbles idle; use 1F1B schedule with microbatches to overlap forward backward, balance layers by profiled FLOPs not count, and add activation recomputation. Ensure deterministic dropout seeds per microbatch. Review points:\nimport torch\nimport torch.nn as nn\nlayers = nn.ModuleList([nn.TransformerEncoderLayer(4096, 32, 11008, batch_first=True) for _ in range(4)])\nprint(len(layers))\n# split into 2 stages\nstage0 = layers[:2]\nstage1 = layers[2:]\nx = torch.randn(2, 128, 4096)\nprint('stages ready')\n# 1F1B: schedule micro=8, checkpoint each stage\n# use torch.distributed.pipelining.stage_with_mutation\nCheck point to point bandwidth and add async send recv. Measure bubble ratio and adjust micro count. Proper pipelining achieves near linear scaling for LLM pretraining."}], "metadata": {"domain": "pytorch", "task_type": "code_review", "difficulty": "expert"}} {"messages": [{"role": "user", "content": "Debug silent weight decay on LayerNorm and biases degrading PyTorch BERT fine-tune."}, {"role": "assistant", "content": "Applying decay to LayerNorm and biases harms BERT fine-tuning by shrinking normalization scales. Create two param groups: decay 0.01 for weights, 0.0 for bias and LayerNorm.weight. Filter via name matching bias, LayerNorm.weight, layer_norm. Use AdamW correctly decoupled, not Adam with L2. Log parameter norms per group to confirm decay isolation. Tune lr 2e-5 with 10% warmup for GLUE tasks. Validate that HuggingFace Trainer auto handles this via get_decay_parameter_names. Add test asserting no weight_decay on norm parameters. Compare dev F1 with and without fix, expecting 1-2 point gain. Validate fix with dedicated unit test and integration check covering edge cases. Log relevant metrics, monitor production dashboards continuously, document change clearly in pull request for reviewers and future maintenance work."}], "metadata": {"domain": "pytorch", "task_type": "debugging", "difficulty": "intermediate"}} {"messages": [{"role": "user", "content": "How to defend PyTorch inference API against model extraction queries?"}, {"role": "assistant", "content": "Extraction attackers query repeatedly to clone model; rate limit per key, add query budgets, watermark outputs, and monitor embedding space coverage for scraping patterns. Return hard labels not logits where possible and add noise to low stakes scores. Defense:\nimport torch\nimport torch.nn as nn\nmodel = nn.Linear(32, 5)\nmodel.eval()\n# pseudo rate limiter\nbudgets = {}\ndef predict(uid, x):\n budgets[uid] = budgets.get(uid, 0) + 1\n assert budgets[uid] < 10000\n with torch.inference_mode():\n return model(x).argmax(-1)\nprint(predict('u1', torch.randn(2, 32)))\nLog query entropy and block anomalous clients. Require auth and TOS prohibiting distillation. These layers raise extraction cost while preserving legitimate user experience and auditability."}], "metadata": {"domain": "pytorch", "task_type": "security", "difficulty": "advanced"}} {"messages": [{"role": "user", "content": "Design a residual block for CIFAR ResNet and explain skip connections and dimensions."}, {"role": "assistant", "content": "Residual blocks learn F(x) plus x to ease gradient flow, allowing deeper nets without degradation. Use two 3x3 convs with BatchNorm and identity or 1x1 projection when channels or stride change. Keep pre versus post activation consistent. Reference design:\nimport torch\nimport torch.nn as nn\nclass BasicBlock(nn.Module):\n def __init__(self, c, stride=1):\n super().__init__()\n self.conv1 = nn.Conv2d(c, c, 3, stride, 1, bias=False)\n self.bn1 = nn.BatchNorm2d(c)\n self.conv2 = nn.Conv2d(c, c, 3, 1, 1, bias=False)\n self.bn2 = nn.BatchNorm2d(c)\n self.short = nn.Identity()\n def forward(self, x):\n h = torch.relu(self.bn1(self.conv1(x)))\n h = self.bn2(self.conv2(h))\n return torch.relu(h + self.short(x))\nblk = BasicBlock(32)\nprint(blk(torch.randn(4, 32, 16, 16)).shape)\nFor downsampling add projection Conv 1x1 stride 2. Stack blocks into stages. This pattern underpins ResNet18 and scales reliably."}], "metadata": {"domain": "pytorch", "task_type": "architecture", "difficulty": "intermediate"}} {"messages": [{"role": "user", "content": "Deploy TorchScript model with FastAPI and GPU inference."}, {"role": "assistant", "content": "Trace script with torch_jit trace example input strict False then freeze and optimize for inference. Build FastAPI with batch endpoint validating image size, running model half precision on CUDA with no_grad. Add health metrics latency Prometheus. Containerize CUDA runtime slim nonroot. Test golden outputs atol 1e-4 versus eager. Version artifacts in S3. Monitor drift. Set threads 1 per worker. This provides low latency serving, removes Python graph overhead, ensures validated inputs, and enables scalable production vision inference today reliably. Track metrics with versioned data splits and persist artifacts with joblib to ensure auditability and reliable promotion from staging to production. Set random_state 42 for reproducibility and validate on stratified holdout with cross-validation to confirm generalization stability and deployment readiness for production workflows."}], "metadata": {"domain": "pytorch", "task_type": "implementation", "difficulty": "intermediate"}} {"messages": [{"role": "user", "content": "Implement PyTorch Dataset and DataLoader for image classification from CSV paths with train validation split."}, {"role": "assistant", "content": "Build a lazy Dataset implementation that parses the CSV index once into memory while decoding image files on demand during training to avoid exhausting system RAM. Use PIL for robust decoding with convert RGB, torchvision transforms for augmentation and normalization, and stratified splitting to preserve class balance across train and validation partitions. Implement __len__ returning dataframe length and __getitem__ selecting row by iloc, opening path, applying transforms, and returning tensor plus integer label. Define training transforms with RandomResizedCrop, RandomHorizontalFlip, ToTensor, and Normalize using ImageNet statistics, while validation transforms remain deterministic with Resize and CenterCrop. Configure DataLoader with batch sixty four, four workers, pinned memory, persistent workers, and prefetch factor. Verify batch shapes, label distribution, throughput, augmentation variance, and worker stability before launching full experiments."}], "metadata": {"domain": "pytorch", "task_type": "implementation", "difficulty": "beginner"}} {"messages": [{"role": "user", "content": "RAG at 10M docs, 5k QPS, strict 300ms p99, GDPR deletion, drift. What expert architecture meets SLA?"}, {"role": "assistant", "content": "Deploy sharded Qdrant HNSW with quantization, replica 3, query caching, rerank only top 10, streaming LLM with early exit. Use Kafka ingestion, versioned indexes blue green, tombstone deletions for GDPR with nightly compaction. Monitor recall, latency HDR, drift via query clustering. Autoscale on queue. Test chaos killing shard. Hedged retrieval races replicas. This expert stack hits 200ms p99 at 5k QPS, handling scale, compliance, and evolution with measurable SLOs and cost control via tiered hot warm indexes. Log retrieved passages with scores for debugging, evaluate end to end faithfulness on golden queries weekly, and version indexes with rollback support so regressions in chunking or embeddings are quickly detected and reverted safely."}], "metadata": {"domain": "rag", "task_type": "architecture", "difficulty": "advanced"}} {"messages": [{"role": "user", "content": "Design chunking strategy for mixed PDF tables and code docs balancing context preservation and retrieval precision"}, {"role": "assistant", "content": "Use type-aware chunking: markdown headers split for docs, table-aware parser preserving rows with captions, code split by functions with 1500 characters and surrounding docstrings. Default 500 tokens with 15 percent overlap, smaller 300 for FAQ, larger 1000 for legal context. Preserve metadata page, section, table id, language. Add parent-child index storing small child for retrieval and large parent for generation to improve both precision and context. Evaluate recall and answer quality across chunk sizes, test table queries requiring full rows, code queries needing full functions, measure index size and latency, and implement config per collection with A-B testing and automated regression on golden queries."}], "metadata": {"domain": "rag", "task_type": "architecture", "difficulty": "intermediate"}} {"messages": [{"role": "user", "content": "Integrate RAG with Slack bot and permission-aware search securely."}, {"role": "assistant", "content": "Build a Slack Bolt app handling app mention and message events with user ID extraction for auth. Resolve user groups via Okta then apply metadata filters to vector search for allowed channels and docs. Retrieve top 5 chunks and generate answers with citations and links to source files. Post ephemeral responses for sensitive content and track feedback via emoji reactions. Implement rate limiting per workspace and async processing to meet three second Slack timeout with delayed updates. Cache frequent queries per tenant. Log queries, retrieved IDs, and user feedback. Test permission enforcement with 50 cross-team access cases and handle thread context up to 1000 tokens."}], "metadata": {"domain": "rag", "task_type": "implementation", "difficulty": "intermediate"}} {"messages": [{"role": "user", "content": "Implement hybrid search with OpenSearch combining BM25 and kNN vectors with RRF fusion and cross encoder reranking."}, {"role": "assistant", "content": "Create an index with text analyzer standard plus dense_vector field dimension seven hundred sixty eight using HNSW engine faiss for approximate search. Ingest chunks with bulk API in batches of five hundred, storing title, body, source url, and embedding from e5-base normalized to unit length. Query with hybrid DSL issuing match query on body and kNN query on embedding each returning top fifty, combining via RRF with rank constant sixty in a search pipeline. Fetch fused top twenty, rerank with SentenceTransformer cross encoder ms-marco-MiniLM-L6 scoring query passage pairs on GPU batched at thirty two, keep top five for generation. Implement Python client with OpenSearch-py, retry on 429 errors, cache embeddings with LRU, log latency per stage, add pytest with local Docker OpenSearch fixture validating recall on ten fixtures, and expose configuration for weights and cutoff thresholds for tuning."}], "metadata": {"domain": "rag", "task_type": "implementation", "difficulty": "intermediate"}} {"messages": [{"role": "user", "content": "Integrate Slack bot with RAG for internal Q&A."}, {"role": "assistant", "content": "Implement Slack Bolt app with socket mode, verifying signatures and handling retries. Map Slack user to enterprise identity for ACL-filtered retrieval. Support thread-aware context and explicit invocation via mention. Retrieve top 5 chunks and generate concise answer with source links. Add feedback buttons for helpful or not to collect labels. Enforce rate limits and redact secrets before posting. Handle long answers with truncation and link to full doc. Log channel, user, query, retrieved IDs, and feedback. Test permission enforcement across private channels. Monitor response latency, usage by team, and deflection rate. Document slash commands, onboarding, and data retention. Include audit logging with request IDs, token accounting, reproducible evaluation on golden sets, and rollback runbook to control quality and cost over time."}], "metadata": {"domain": "rag", "task_type": "code_review", "difficulty": "intermediate"}} {"messages": [{"role": "user", "content": "Implement metadata filtering for RAG over multi-year docs where old versions pollute answers. Show pattern."}, {"role": "assistant", "content": "Attach version, date, product, locale to each chunk at ingestion. At query time, extract filters via LLM or rules: e.g. user asks v3 API returns filter product API version 3. Use vector DB filtered search: Qdrant Filter must match version, range date. Code: retrieve with query_filter FieldCondition key version match value 3. Combine with hybrid search: pre-filter before vector scoring for efficiency. Fallback: if filtered set under 3 results, relax to nearest version and warn user. Evaluate on version-sensitive queries; filtering typically lifts precision 15 points. UI should show version badge and allow override. Maintain alias current to avoid reindexing. Test edge: docs missing metadata should not be silently dropped; backfill. This prevents outdated answers that erode trust in fast-moving products."}], "metadata": {"domain": "rag", "task_type": "implementation", "difficulty": "intermediate"}} {"messages": [{"role": "user", "content": "Diagnose retrieval failure for acronym-heavy queries where expansion missed domain synonyms in manufacturing docs"}, {"role": "assistant", "content": "Examine failed queries like CNC spindle alarm: original acronym not expanded, embeddings distant from spelled-out manual sections, BM25 missing because docs use full terms. Score analysis shows gold ranked beyond 50. Check synonym dictionary lacking manufacturing terms, query rewriter generic. Inspect tokenization splitting codes incorrectly. Fix with domain glossary for expansion, hybrid boosting exact codes, custom analyzer preserving alphanumeric tokens. Build test set 200 acronym queries, measure recall at 20 lift from 0.55 to 0.80 after fix. Log expansions per query, allow user feedback for missing synonyms, monitor tail queries weekly, and retrain rewriter on domain pairs to prevent recurrence."}], "metadata": {"domain": "rag", "task_type": "retrieval_analysis", "difficulty": "advanced"}} {"messages": [{"role": "user", "content": "Integrate RAG with Jira and Confluence with unified permissions."}, {"role": "assistant", "content": "Sync Jira issues and Confluence pages via APIs with incremental cursors, preserving project keys, spaces, and ACLs as metadata. Resolve user permissions at query time through OAuth group membership and enforce filters in the vector database. Retrieve top candidates across both sources then deduplicate linked issues and docs. Generate answers with deep links to tickets and pages plus status badges. Handle rich markup, comments, and attachments during parsing. Test with cross-project access cases to verify isolation. Monitor sync lag under five minutes and handle deletions via tombstones. Log access denials for audit. Evaluate helpfulness with engineering teams and track resolution time reduction after deployment to production environments."}], "metadata": {"domain": "rag", "task_type": "implementation", "difficulty": "intermediate"}} {"messages": [{"role": "user", "content": "My RAG system returns irrelevant chunks, how do I debug retrieval basics?"}, {"role": "assistant", "content": "Inspect the query embedding and top results with scores and text to see failure patterns. Check chunking for oversized chunks that dilute meaning or tiny chunks lacking context. Verify metadata filters are not too strict and document ingestion completed without errors. Test the same query with different top k values and without filters to isolate the cause. Try rephrasing queries manually to see if wording causes mismatch. Evaluate embedding model suitability by testing on ten known question-passage pairs. Log retrieval IDs and scores for every request to enable postmortem analysis. Add a keyword fallback using BM25 for exact terms like product codes."}], "metadata": {"domain": "rag", "task_type": "debugging", "difficulty": "beginner"}} {"messages": [{"role": "user", "content": "How to synthesize answers with calibrated uncertainty when retrieval is weak?"}, {"role": "assistant", "content": "Score retrieval confidence via max rerank score and score gap; if below threshold, trigger hedging behavior. Instruct the model to state confidence levels, list what was found versus missing, and suggest next steps or clarifications. Avoid fabricating details to fill gaps; explicitly say evidence is insufficient. Provide partial answers with citations for supported parts only. Implement a second verifier that checks claim support and forces abstention if support is low. Evaluate calibration by comparing stated confidence to actual accuracy on labeled sets. Display uncertainty badges in UI. Log low-confidence cases to prioritize corpus expansion. Tune thresholds to balance helpfulness versus hallucination risk, aiming to minimize unsupported claims while maintaining reasonable answer coverage."}], "metadata": {"domain": "rag", "task_type": "retrieval_analysis", "difficulty": "advanced"}} {"messages": [{"role": "user", "content": "Prevent prompt leakage through RAG retrieved chunks."}, {"role": "assistant", "content": "Treat system prompts and retrieved documents as separate trust zones. Never include secret instructions in retrievable documents. Wrap retrieved context with delimiters and instruct model not to reveal system or tool details. Filter chunks containing internal prompts, keys, or sensitive metadata before indexing. Add output scanner for system prompt verbatim repetition and block on match. Test with extraction attacks asking to repeat instructions or reveal documents. Limit chunk exposure in UI to relevant excerpts, not full raw. Log suspected leakage attempts. Rotate any secrets that appear in logs. Train evaluators to probe indirect injection where documents instruct model to disclose policy. Document what is safe to index versus restricted. Include audit logging with request IDs, token accounting, reproducible evaluation on golden sets, and rollback runbook to control quality and cost over time."}], "metadata": {"domain": "rag", "task_type": "implementation", "difficulty": "intermediate"}} {"messages": [{"role": "user", "content": "How to evaluate RAG safety against data exfiltration via clever queries?"}, {"role": "assistant", "content": "Build an access-control test suite where users with different roles query restricted documents and must be denied. Test direct requests, paraphrases, multi-turn extraction, and summarization tricks that attempt to leak PII or secrets. Enforce retrieval-time filtering by ACLs, not just generation-time refusal, so unauthorized chunks never enter context. Add output DLP scanning for emails, keys, and internal codenames with blocking. Log retrieved IDs per user to audit leaks. Red-team with prompt injections that ask to ignore access rules or encode output in base64. Measure attack success rate and require zero critical leaks before release. Review vector store permissions separately from application logic to catch misconfigured public indexes."}], "metadata": {"domain": "rag", "task_type": "security", "difficulty": "intermediate"}} {"messages": [{"role": "user", "content": "Evaluate RAGAS metrics reliability for enterprise QA use cases."}, {"role": "assistant", "content": "Run RAGAS faithfulness, answer relevancy, and context precision on 300 enterprise queries with human labels. Compute correlation with human judgments targeting Spearman above 0.7. Test stability across three runs with temperature zero to measure variance. Inspect failure cases where RAGAS overrates fluent hallucinations or penalizes concise correct answers. Calibrate prompts for your domain with few-shot examples. Compare RAGAS scores using large versus small evaluator models to assess cost-quality tradeoff. Segment by query type to reveal blind spots. Establish thresholds for CI gating based on ROC analysis. Complement with exact numeric checks and revalidate after model upgrades. Track metrics continuously and document learnings for future iterations across teams and releases."}], "metadata": {"domain": "rag", "task_type": "experiment_analysis", "difficulty": "advanced"}} {"messages": [{"role": "user", "content": "Analyze long-term RAG feedback loops for quality improvement and drift."}, {"role": "assistant", "content": "Collect explicit thumbs signals, correction edits, and implicit dwell and copy events linked to query, retrieved IDs, and prompt version. Aggregate weekly to mine hard negatives where users corrected answers and false positives with low ratings. Measure correlation between feedback volume and RAGAS faithfulness on sampled audits. Detect topic drift via embedding centroid shifts and emerging entities. Prioritize fixes by impact including high-traffic failures and compliance risks. Feed corrections into evaluation goldens and embedding fine-tuning sets. A-B test prompt or index changes on feedback cohorts before rollout. Report quality lift, cost, and latency tradeoffs to stakeholders. Govern privacy by redacting PII from feedback stores and enforcing retention limits."}], "metadata": {"domain": "rag", "task_type": "instruction", "difficulty": "expert"}} {"messages": [{"role": "user", "content": "Optimize RAG cost-latency Pareto where each query currently costs 8 cents and 3s. Need 2 cents and 1s at same quality."}, {"role": "assistant", "content": "Decompose cost: embeddings, retrieval, rerank, generation tokens. Cut generation by compressing 10 passages to 3 via rerank plus summarization, saving 60 percent tokens. Switch generator to 8B for draft with 70B fallback on low confidence, saving 50 percent. Cache 30 percent head queries semantically. Replace large reranker with distilled ColBERT for 5x cheaper with 1 point loss. Use smaller embeddings with Matryoshka 256 dims halving storage and latency. Batch embeddings and use spot GPUs for ingestion. Measure Pareto: plot cost versus faithfulness for configs A to D, pick knee meeting SLO. Implement adaptive: easy queries cheap path, hard full path via router. Result 1.8 cents 900ms with parity. Monitor quality weekly to catch drift from aggressive pruning."}], "metadata": {"domain": "rag", "task_type": "optimization", "difficulty": "expert"}} {"messages": [{"role": "user", "content": "What chunking strategy works best for code repositories in RAG?"}, {"role": "assistant", "content": "Chunk by syntactic units, not fixed tokens: functions, classes, and markdown sections with surrounding imports and docstrings. Keep 200 to 600 tokens per chunk to preserve context while maintaining embedding specificity. Include file path, language, symbol names, and commit hash as metadata for filtering and citation. Use AST parsing to avoid splitting functions and add overlapping context of parent class definitions where needed. For long files, create hierarchical chunks with file-level summary plus function-level details. Embed code and natural language queries with a code-aware model like CodeSage or Voyage Code. Evaluate by asking API usage and bug-fix questions and checking if correct functions are retrieved. Avoid chunking minified files or generated artifacts."}], "metadata": {"domain": "rag", "task_type": "retrieval_analysis", "difficulty": "intermediate"}} {"messages": [{"role": "user", "content": "Explain ColBERT late interaction for efficient reranking in RAG."}, {"role": "assistant", "content": "ColBERT encodes query and document tokens separately into contextual vectors, then scores via MaxSim summing max cosine per query token over doc tokens. This late interaction preserves token-level matching richer than single-vector bi-encoders while allowing precomputed doc vectors for fast search. For RAG, retrieve 200 candidates with bi-encoder, rescore top with ColBERT under 100ms via optimized index. Explain tradeoff versus cross-encoders: ColBERT is faster and indexable but slightly less accurate. Tune compression with residual quantization to fit 10M passages. Evaluate recall at ten versus latency on MS MARCO plus domain set. Implement with RAGatouille or Vespa. Understanding late interaction helps scale precise ranking to large corpora without prohibitive cross-encoder cost. Choose ColBERT when needing fine-grained matching for technical queries with many entities, where single-vector bottleneck loses discriminative details critical for distinguishing closely related procedures."}], "metadata": {"domain": "rag", "task_type": "instruction", "difficulty": "advanced"}} {"messages": [{"role": "user", "content": "Need multilingual RAG for 12 languages with code switching. Embeddings biased to English. How to design?"}, {"role": "assistant", "content": "Use multilingual e5-large or Cohere embed v3 with language balanced training, separate per language collections plus cross lingual fallback. Translate query expansion, detect language, filter by lang metadata. Rerank with multilingual cross encoder. Evaluate per language recall. Test code switched queries. Add transliteration normalization. This restores non English recall from 40 to 80. Monitor language distribution. Design acknowledges embedding bias requiring explicit multilingual models and routing not single English index. Log retrieved passages with scores for debugging, evaluate end to end faithfulness on golden queries weekly, and version indexes with rollback support so regressions in chunking or embeddings are quickly detected and reverted safely."}], "metadata": {"domain": "rag", "task_type": "architecture", "difficulty": "advanced"}} {"messages": [{"role": "user", "content": "Compare chunking strategies: fixed, semantic, and document-structure aware."}, {"role": "assistant", "content": "Fixed chunking splits every 500 tokens, simple and fast but breaks sentences and tables, hurting precision on structured docs. Semantic chunking groups sentences by embedding similarity, preserving topics and improving recall eight points but costing extra compute. Structure-aware uses headings, tables, and lists to keep logical units intact, best for manuals and legal docs with fifteen point gain but requires parser maintenance. Compare on your corpus of 200 QA measuring recall, answer F1, and ingestion time. Fixed suits logs and transcripts, semantic suits heterogeneous articles, structure suits technical docs. Hybrid uses structure first then semantic fallback for long sections. Choose based on doc type distribution and engineering capacity. Document strategy per collection. Proper comparison avoids one-size-fits-all that silently degrades quality on critical document types requiring layout fidelity for accurate grounding and citations."}], "metadata": {"domain": "rag", "task_type": "instruction", "difficulty": "intermediate"}} {"messages": [{"role": "user", "content": "Intermediate rag analysis task: compare dense versus sparse retrieval on technical documentation queries?"}, {"role": "assistant", "content": "Analyze both approaches on golden technical queries with code tokens, acronyms, and version numbers. Measure dense recall for semantic paraphrases versus sparse BM25 precision for exact identifiers. Inspect failure cases where embeddings miss rare terms or BM25 misses synonyms. Plot recall at k, MRR, and nDCG per method and fused hybrid. Review analyzer settings for code splitting, stemming, and case sensitivity. Recommend hybrid fusion with tuned weights, plus synonym lists for product terms. Log per query scores from each branch to explain wins and losses. Segment by query type to set adaptive strategy. Document dataset, metrics, and statistical significance. Automate comparison notebook for reruns after index changes. Monitor production feedback to refine tokenization and maintain balanced coverage across lexical and semantic needs."}], "metadata": {"domain": "rag", "task_type": "instruction", "difficulty": "intermediate"}} {"messages": [{"role": "user", "content": "How do I speed up embedding 5M passages from 2 days to hours? My current loop encodes one by one."}, {"role": "assistant", "content": "Batch and parallelize. Switch from single encoding to batch size 256 to 512 on A100, using fp16 and torch.compile for 3x speedup. Use DataLoader with num_workers 4 to pre-tokenize on CPU while GPU encodes. Shard across 4 GPUs with multiprocessing, each handling 1.25M. Pre-filter duplicates via MinHash to cut 20 percent. Use smaller model for first pass: bge-small is 4x faster than large with minor recall loss, then rerank. Persist in parquet with IDs to resume. Profile: tokenization often bottleneck, so set max_length 256 not 512 if passages short. Use ONNX or TensorRT for CPU fallback. With these, 5M passages drop from 48 hours to about 4 hours on single A100, under 1 hour on 8 GPUs. Monitor GPU utilization above 90 percent; if low, increase batch or workers. Version embeddings to avoid re-encoding on code changes."}], "metadata": {"domain": "rag", "task_type": "optimization", "difficulty": "intermediate"}} {"messages": [{"role": "user", "content": "OpenAI embeddings 429 no backoff large batches fail. Resilient client?"}, {"role": "assistant", "content": "Root cause is burst exceeding TPM RPM without backoff plus oversized payloads rejected. Batch 100 texts 8k tokens chunked, concurrency 5 with token bucket limiter. Implement exponential backoff jitter honoring Retry-After up to 60s, circuit breaker after 10 fails. Cache embeddings Redis keyed hash. Validate with 429 mock asserting retry success. Log usage headers remaining. Monitor throttle rate cost. Test resume from checkpoint on crash. Document quota per model. Prefer text-embedding-3-small with dimensions param. Result sustains high volume backfills without bans minimizing cost via caching while meeting throughput SLOs for production RAG ingestion pipelines. Validate incrementally with minimal reproduction, logging metrics before and after change, adding regression tests and monitoring dashboards for lasting stability and confidence in production."}], "metadata": {"domain": "rag", "task_type": "api_debugging", "difficulty": "expert"}} {"messages": [{"role": "user", "content": "Analyze retrieval quality when top-k results look relevant but exact answer span is often ranked fourth or fifth."}, {"role": "assistant", "content": "This pattern suggests decent recall but weak ranking precision. Measure recall at 5 versus MRR to confirm. Inspect chunking: large 1000-token chunks dilute signals, so try 300 tokens with 50 overlap. Check embedding model domain mismatch and consider fine-tuning on in-domain pairs. Add a cross-encoder reranker like MiniLM on top 20 to improve ordering with modest latency cost. Analyze query types that fail, such as exact entity versus paraphrase. Hybrid BM25 can boost exact matches. Log query, retrieved IDs, and relevance labels to build an eval set. Tune similarity metric and normalization. Test with different top-k values and measure downstream answer exact match. Iterate on one variable at a time and track statistical significance across at least 200 queries."}], "metadata": {"domain": "rag", "task_type": "retrieval_analysis", "difficulty": "beginner"}} {"messages": [{"role": "user", "content": "Cache frequent RAG queries to cut P95 latency and cost."}, {"role": "assistant", "content": "Implement two-tier cache: exact query hash to final answer with short TTL, and retrieval cache mapping normalized query to chunk IDs. Normalize by lowercasing, removing punctuation, and stripping session specifics. Set TTL based on corpus volatility: 1 hour for fast-changing, 24 hours for stable. Invalidate on document updates affecting cached chunks via dependency tracking. Measure hit rate, stale rate, and cost savings. Add tenant isolation to cache keys to prevent leakage. Serve stale-while-revalidate for high QPS patterns. Monitor cache size and eviction. Evaluate correctness impact by sampling cached answers for freshness. Document cacheability rules per query type; personalized queries should bypass. Maintain documentation for onboarding, troubleshooting guides, data retention policy, and compliance checks to ensure long term operability and governance."}], "metadata": {"domain": "rag", "task_type": "testing", "difficulty": "expert"}} {"messages": [{"role": "user", "content": "Implement query rewriting for RAG where user queries are vague like it is broken. How to expand with chat history?"}, {"role": "assistant", "content": "Rewrite vague query into standalone search query using conversation history and LLM. Prompt: given history and follow-up, output self-contained query with entities resolved, no pronouns. Example: history mentions printer XJ-200, follow-up it is broken becomes XJ-200 printer paper jam error troubleshooting. Set temperature 0, max 100 tokens. In code, call rewrite LLM before retrieval, keep original for generation audit. Add guard: if rewrite drifts, fallback to original plus last user entity. Evaluate on 100 multi-turn sessions measuring recall gain; rewriting typically adds 8 to 12 points. Cache rewrites for common patterns. For speed, use small 8B model for rewrite, large for answer. Log both queries to debug bad rewrites. Include time filter: if user says yesterday's invoice, resolve to date. This fixes coreference failure that kills naive RAG in chat."}], "metadata": {"domain": "rag", "task_type": "implementation", "difficulty": "intermediate"}} {"messages": [{"role": "user", "content": "Design enterprise RAG architecture with ingestion vector store reranker guardrails and observability for 10M docs"}, {"role": "assistant", "content": "Ingestion uses event-driven parsing with unstructured.io, chunking 500 tokens, embedding via batch GPU service, writing to sharded Qdrant with tenant payload indexes. Query path runs auth, query rewriting, hybrid retrieval top 100, cross-encoder rerank to top 8, prompt builder with budget, LLM generation with citations, guardrail checks, and response caching. Add Kafka for updates, S3 for raw docs, Postgres for metadata and feedback. Observability includes OpenTelemetry traces, retrieval recall dashboards, faithfulness sampling, cost per query, and drift alerts. Scale retrievers horizontally, isolate GPUs for embeddings and rerank, enforce ACL filtering at retrieval, and chaos test node failures and reindexing. Additionally track metrics dashboards and document operational lessons for reliable production maintenance over time."}], "metadata": {"domain": "rag", "task_type": "architecture", "difficulty": "intermediate"}} {"messages": [{"role": "user", "content": "Advanced rag evaluation task: measure citation faithfulness under adversarial distractors?"}, {"role": "assistant", "content": "Inject plausible but irrelevant distractor chunks with overlapping entities and dates into retrieval set to test grounding. Measure whether generator cites correct sources or gets misled, using claim level entailment and citation precision recall. Sweep distractor ratio and similarity to map robustness curve. Compare base prompt versus citation constrained and verification layered pipelines. Analyze failures for entity confusion and temporal errors. Log distractor ids, model reasoning, and verdicts. Use human adjudication for borderline cases. Version distractor sets and automate nightly stress evals. Set thresholds blocking promotion if misattribution exceeds tolerance. Document attack construction and mitigation like stronger reranking and source filtering. This evaluation reveals brittleness hidden by clean benchmarks, driving hardened prompts and retrieval for trustworthy deployment."}], "metadata": {"domain": "rag", "task_type": "experiment_analysis", "difficulty": "advanced"}} {"messages": [{"role": "user", "content": "Design RAG access control for multi-tenant SaaS knowledge base securely."}, {"role": "assistant", "content": "Enforce tenant isolation by adding tenant id to every chunk metadata and filtering at query time in the vector database. Separate public and private namespaces with distinct collections and encryption keys. Apply role-based filters for admin versus member documents after authentication in middleware. Prevent cross-tenant leakage by validating filters server-side, never trusting client parameters. Use attribute-based rules for time-bound or department-specific access. Audit every retrieval with user, query, and document IDs. Test with adversarial queries attempting to bypass filters via prompt injection. Evaluate leakage rate on 200 attack cases targeting zero success. Document compliance with SOC2 and GDPR requirements. Track metrics continuously and document learnings for future iterations across teams and releases."}], "metadata": {"domain": "rag", "task_type": "architecture", "difficulty": "intermediate"}} {"messages": [{"role": "user", "content": "Implement semantic chunking for technical PDFs to improve retrieval relevance."}, {"role": "assistant", "content": "Parse PDFs with layout preservation, extracting headings, tables, and code blocks separately. Avoid fixed 1000-character splits because they break procedures and definitions. Use recursive splitting on markdown structure: sections, then paragraphs, then sentences, targeting 400 to 600 tokens. Keep tables intact and attach surrounding caption as context. Add 10 to 15 percent overlap using sentence boundaries, not mid-word cuts. Enrich each chunk with document title, section path, page number, and preceding heading for context. Generate a one-sentence summary prefix for ambiguous chunks. Deduplicate boilerplate headers and footers. Evaluate by measuring recall at 5 on 50 representative queries before and after. Store parent document ID to enable parent-document retrieval for long context synthesis."}], "metadata": {"domain": "rag", "task_type": "optimization", "difficulty": "beginner"}} {"messages": [{"role": "user", "content": "Optimize RAG reranking with distilled cross-encoders and adaptive top-k selection."}, {"role": "assistant", "content": "Distill large cross-encoders into TinyBERT students using pseudo-labels from production logs to cut latency fivefold. Implement adaptive logic expanding rerank depth when initial scores have high entropy or low margins. Cache rerank scores for popular query-passage pairs. Batch rerank requests for GPU efficiency. Evaluate NDCG versus latency Pareto frontiers to select operating points. Deploy with ONNX quantization for CPU inference where GPUs are scarce. Monitor tail latency and fallback to bi-encoder ordering on timeouts. A/B test distilled versus full models on user satisfaction. Adaptive distilled reranking maintains quality while meeting interactive SLOs, reducing infrastructure costs and enabling broader deployment of high-precision retrieval across high-traffic RAG applications."}], "metadata": {"domain": "rag", "task_type": "optimization", "difficulty": "advanced"}} {"messages": [{"role": "user", "content": "Our RAG support bot retrieves irrelevant docs for short queries like refund status. How to fix retrieval?"}, {"role": "assistant", "content": "Short queries lack context, so expand them before retrieval using query rewriting or HyDE. Add metadata filters for intent, product, and recency to narrow the corpus. Use hybrid search combining BM25 for exact terms like refund with dense embeddings for semantics, then fuse with reciprocal rank fusion. Ensure your embeddings model is fine-tuned or chosen for short query-document asymmetry. Add a cross-encoder reranker on top 30 candidates. Evaluate with labeled pairs measuring recall at 5 and MRR. Log queries with zero relevant hits and create synonyms for refund, return, reimbursement. Finally, prepend conversation history and user profile to enrich the query embedding without leaking PII."}], "metadata": {"domain": "rag", "task_type": "implementation", "difficulty": "beginner"}} {"messages": [{"role": "user", "content": "How to fine-tune a generator LLM on RAG outputs to reduce verbosity?"}, {"role": "assistant", "content": "Collect preferred concise answers edited by experts from RAG logs, paired with verbose originals as rejected examples. Fine-tune with SFT then DPO to prefer brevity while preserving citations and factuality. Keep training prompts identical to production including chunk format so style transfers. Enforce length penalties and citation requirements in reward. Evaluate with brevity metrics like tokens per answer, faithfulness scores, and human preference for clarity. Guard against over-shortening that omits caveats by testing on complex queries. Version datasets and mix in general instruction data to prevent forgetting. Deploy as adapter for easy rollback. Monitor user follow-up rate: good conciseness should reduce clarification questions, not increase them due to missing details."}], "metadata": {"domain": "rag", "task_type": "implementation", "difficulty": "intermediate"}} {"messages": [{"role": "user", "content": "Debug embedding dimension mismatch after switching models without reindexing the vector database"}, {"role": "assistant", "content": "Dimension errors arise when query embedding size differs from indexed vectors, for example 384 versus 768 after model change. Validate by checking model config and sample vector lengths, inspect Qdrant collection vector size. Fix by versioning indexes per embedding model, maintaining dual indexes during migration, re-embedding all chunks with new model in batches, updating collection schema, and deploying with feature flag. Prevent recurrence with startup checks asserting dimensions, CI tests for model-index compatibility, manifest storing model name and version with index. Backfill with progress checkpointing, verify recall parity before cutover, and keep old index for rollback until new metrics stabilize in production."}], "metadata": {"domain": "rag", "task_type": "debugging", "difficulty": "intermediate"}} {"messages": [{"role": "user", "content": "Hybrid BM25 plus dense fusion underperforms dense alone. Score scales differ wildly. How to fuse correctly?"}, {"role": "assistant", "content": "Normalize scores with min max per query then weighted sum 0.6 dense 0.4 BM25 or reciprocal rank fusion k 60 avoiding scale issues. Tune weights on validation. Use cross encoder rerank top 30 fused. Test on keyword heavy queries where BM25 helps. Log both scores. Proper fusion gains 5 to 8 points. Avoid raw sum dominating. RRF is robust without tuning, ideal baseline before learned weights. Log retrieved passages with scores for debugging, evaluate end to end faithfulness on golden queries weekly, and version indexes with rollback support so regressions in chunking or embeddings are quickly detected and reverted safely."}], "metadata": {"domain": "rag", "task_type": "retrieval_analysis", "difficulty": "advanced"}} {"messages": [{"role": "user", "content": "Chroma query returns empty though docs inserted. No error. What beginner mistake causes this?"}, {"role": "assistant", "content": "Likely collection name mismatch, different persist path, or embedding function inconsistency between add and query. Verify count via collection.count, check persist directory and client same path. Ensure IDs unique and metadatas aligned. Log embedding dimension. Test minimal add then query same text expecting hit. Use PersistentClient with same path across runs. Fixing path and naming restores retrieval. Add startup check logging count. This common setup error mimics relevance failure but is storage isolation. Log retrieved passages with scores for debugging, evaluate end to end faithfulness on golden queries weekly, and version indexes with rollback support so regressions in chunking or embeddings are quickly detected and reverted safely."}], "metadata": {"domain": "rag", "task_type": "debugging", "difficulty": "beginner"}} {"messages": [{"role": "user", "content": "Intermediate rag documentation task: document hybrid search tuning with BM25 weights and fusion?"}, {"role": "assistant", "content": "Document hybrid pipeline combining BM25 lexical scores and dense cosine similarity via weighted sum or reciprocal rank fusion with configurable alpha. Explain normalization, top k per branch, and final cutoff selection. Provide code for OpenSearch, pgvector plus tsvector, or LangChain hybrid retriever with reproducible settings. Guide tuning by sweeping alpha from zero to one on golden queries and plotting recall and nDCG. Include troubleshooting for over stemming, stopwords, and domain synonyms. Show logging of per branch scores and fusion rank for debugging. Add evaluation checklist, versioning of index and analyzer settings, and rollback steps. Cover cost and latency tradeoffs, caching strategies, and monitoring of zero result rate. Provide copy paste notebooks and expected charts to help teams reproduce optimal balance."}], "metadata": {"domain": "rag", "task_type": "instruction", "difficulty": "intermediate"}} {"messages": [{"role": "user", "content": "Test retrieval recall for a legal RAG system before launch."}, {"role": "assistant", "content": "Build a golden set of 150 realistic lawyer queries mapped to known relevant clause IDs. Compute recall at 5, 10, 20 and MRR. Stratify by query type: exact citation lookup, conceptual question, and multi-hop reasoning. Test with and without metadata filters for jurisdiction and date. Ablate chunk size, overlap, embedding model, and reranker to identify bottlenecks. Log failure modes: missing document, bad chunk boundary, embedding miss, or over-filtering. Require recall at 10 above 0.85 for launch. Automate in CI so index changes trigger re-evaluation. Add negative queries with no relevant document to test correct abstention. Interview attorneys for 20 high-stakes queries to validate practical usefulness beyond metrics. Maintain documentation for onboarding, troubleshooting guides, data retention policy, and compliance checks to ensure long term operability and governance."}], "metadata": {"domain": "rag", "task_type": "optimization", "difficulty": "intermediate"}} {"messages": [{"role": "user", "content": "Analyze embedding model upgrade from MiniLM to BGE-large showing latency regression despite quality gains"}, {"role": "assistant", "content": "BGE-large improves recall 7 percent and NDCG 6 percent significant on 2000 queries, especially semantic paraphrases, but embedding latency 45ms versus 12ms and index memory 3x. P95 query up 120ms, indexing cost double. Segment keyword queries show no gain, suggesting hybrid could retain small model for those. Measure downstream answer faithfulness up only 2 percent, questioning ROI. Recommend distill or use Matryoshka truncation to 512 dims retaining 95 percent gain at lower cost, cache embeddings, quantize vectors. A-B test truncated variant, monitor GPU cost per million queries, and rollout to semantic-heavy collections first while keeping MiniLM for keyword-heavy tenants. Additionally track metrics dashboards and document operational lessons for reliable production maintenance over time."}], "metadata": {"domain": "rag", "task_type": "experiment_analysis", "difficulty": "intermediate"}} {"messages": [{"role": "user", "content": "Optimize vector search latency for 5M embeddings from 800ms to under 100ms P95."}, {"role": "assistant", "content": "Profile current brute-force search to confirm linear scaling bottleneck. Migrate to HNSW indexes with M sixteen and efSearch one hundred tuning recall versus speed. Implement product quantization to compress vectors and fit in memory, reducing I/O. Shard index across replicas with consistent hashing for parallel queries. Add caching for hot queries and precompute frequent embeddings. Use GPU acceleration with cuVS if CPU remains bottleneck. Tune efConstruction during build for quality. Benchmark with realistic query distributions measuring P50, P95, and recall at ten. Monitor memory usage and rebuild times. Consider IVF-PQ for even larger scales. These optimizations trade small recall loss for order-of-magnitude latency gains, enabling interactive RAG chat while controlling infrastructure costs through efficient indexing and caching strategies."}], "metadata": {"domain": "rag", "task_type": "optimization", "difficulty": "intermediate"}} {"messages": [{"role": "user", "content": "Explain dense versus sparse retrieval tradeoffs for RAG builders clearly."}, {"role": "assistant", "content": "Dense retrieval uses embeddings to capture semantics and handles paraphrases well but struggles with rare codes and exact names. Sparse BM25 uses term frequency and excels at keyword matching with no training needed. Dense requires GPU embedding inference and vector indexes like HNSW, while sparse runs efficiently on CPU with inverted indexes. Choose dense for natural questions, sparse for SKU or error code lookup, and hybrid for mixed workloads. Evaluate both on your queries measuring recall at 10 split by query type. Consider index size, update latency, and multilingual support. Fine-tune dense models for jargon when generic performance lags significantly."}], "metadata": {"domain": "rag", "task_type": "instruction", "difficulty": "intermediate"}} {"messages": [{"role": "user", "content": "Compare HyDE versus query expansion experiments for RAG recall."}, {"role": "assistant", "content": "HyDE generates hypothetical answer for embedding, while expansion generates multiple query variants. Test both on same 60 queries with fixed retriever. HyDE helps when query is short and conceptual, expansion helps for ambiguous terms. Log generated texts to check drift. Measure recall at 5 and latency; HyDE adds one LLM call, expansion adds multiple retrievals. Common mistake is using HyDE for exact code lookup where hallucinated terms hurt. Analyze per-type wins. Often fusion of original plus expanded queries beats HyDE alone with lower risk. Report mean plus per-category breakdown. Choose based on query distribution, not aggregate alone, and consider hybrid lexical fallback to mitigate HyDE drift."}], "metadata": {"domain": "rag", "task_type": "experiment_analysis", "difficulty": "intermediate"}} {"messages": [{"role": "user", "content": "How to analyze retrieval recall at k for RAG with labeled golden passages?"}, {"role": "assistant", "content": "Create dataset mapping each query to gold passage IDs. Retrieve top k for k equals 1 3 5 10 and compute recall as fraction where gold in retrieved set. Plot recall versus k to see plateau. Also compute MRR and nDCG for ranking quality. Slice by query type to find weak spots like keyword queries. Ensure IDs match exactly; whitespace differences cause false misses. Run analysis before tuning synthesis, as poor recall caps answer quality. Log per-query misses for manual review. Common mistake is evaluating only end answer, hiding retriever gaps. Systematic retrieval analysis guides whether to tune chunking, embeddings, hybrid weights, or reranking next."}], "metadata": {"domain": "rag", "task_type": "retrieval_analysis", "difficulty": "intermediate"}} {"messages": [{"role": "user", "content": "Advanced rag debugging task: trace lost table structure breaking financial QA accuracy?"}, {"role": "assistant", "content": "Tables lose structure when flattened to text, merging rows and misaligning columns. Debug by comparing raw PDF layout to extracted chunks, checking for missing delimiters and header repetition. Test structure aware parsers like Camelot, Unstructured, and vision models preserving markdown tables. Evaluate row level recall and numeric exact match on financial questions. Implement chunking keeping tables intact with captions and units. Add validation detecting table-like content needing special handling. Log parser choice, chunk samples, and QA scores. A B test extraction variants. Version parsers and monitor numeric error rate. Document preprocessing for merged cells and footnotes. This restores fidelity for financial reasoning where precise alignment matters, preventing costly misinterpretation from naive text splitting of structured data."}], "metadata": {"domain": "rag", "task_type": "debugging", "difficulty": "advanced"}} {"messages": [{"role": "user", "content": "My RAG recall@10 is 55 percent on support docs. How do I diagnose whether it is chunking, embeddings, or query issue?"}, {"role": "assistant", "content": "Run staged ablation. Create 100 queries with known gold chunks. Test full pipeline to confirm 55 percent. Then test oracle chunking: manually provide perfect chunks and see if generator answers; if yes, retrieval is culprit. Next test embeddings versus BM25: run both separately; if BM25 hits 70 percent on SKUs while vectors hit 50, you need hybrid. Inspect failures: if gold chunk split across two chunks, it is chunking; if paraphrase misses but keyword hits, embeddings weak; if vague pronouns, query rewrite needed. Visualize score distributions for hits versus misses. Check top-k sensitivity: if recall jumps to 80 at k 50, you need rerank not better embeddings. Log query types. Fix highest-impact slice first. Re-evaluate after each change with same split to avoid overfitting. This systematic triage prevents random tuning."}], "metadata": {"domain": "rag", "task_type": "retrieval_analysis", "difficulty": "intermediate"}} {"messages": [{"role": "user", "content": "Design a chunking strategy for a RAG system over 200-page technical PDFs with tables and code."}, {"role": "assistant", "content": "Don't use fixed 500-token chunks blindly. Recommended:\n1. Parse with structure awareness (PyMuPDF + layout detection); keep headings with content.\n2. Chunk by section with max ~800 tokens and 100-token overlap; never split mid-code-block or mid-table \u2014 keep tables atomic, serialize as markdown.\n3. Add metadata: doc_id, page, section title, chunk_type.\n4. Create two indexes: dense (e.g., bge-small) for semantics + BM25 for exact codes/error strings (hybrid).\n5. Add small-to-big: retrieve 512-token children, expand to parent section for generation.\nEvaluate with recall@k on 50 golden Q/A pairs. If tables are critical, also store them as separate retrievable objects with captions."}], "metadata": {"domain": "rag", "task_type": "architecture", "difficulty": "advanced"}} {"messages": [{"role": "user", "content": "Regression test RAG prompt template change: ensure no citation format drift across versions."}, {"role": "assistant", "content": "Snapshot test prompt v12 versus v13 on 100 QAs, diff citation regex \\[\\d+\\]. Assert format pass 100%, semantic similarity >0.95 via embedding. Flag drift like missing sources. Store golden outputs. Auto-approve if faithfulness stable. Log token delta. Rollback on >3% format failure. Document template changelog. Validate fix with dedicated unit test and integration check covering edge cases. Log relevant metrics, monitor production dashboards continuously, document change clearly in pull request for reviewers and future maintenance work. Include reproducible script, versioned config, seeded runs, ablation results, error analysis table, and follow-up monitoring plan to ensure durable improvement. Confirm with peer review and merge."}], "metadata": {"domain": "rag", "task_type": "testing", "difficulty": "expert"}} {"messages": [{"role": "user", "content": "Expand queries with LLM for better recall on acronym-heavy corpus."}, {"role": "assistant", "content": "Generate 3 to 5 expansions per query including synonyms, expanded acronyms, and related terms using few-shot prompt grounded in glossary. Use lightweight model to limit latency. Combine original and expansions via weighted retrieval or RRF fusion. Filter expansions with domain dictionary to avoid hallucinated terms. Evaluate recall at 20 on 150 acronym queries; target 10 percent lift. Cache expansions for frequent queries. Limit expansion length to avoid topic drift. Log expansions and per-variant scores for debugging. A-B test answer relevance. Provide kill switch to disable expansion on latency SLO breach. Document glossary source and update process as terminology evolves. Maintain documentation for onboarding, troubleshooting guides, data retention policy, and compliance checks to ensure long term operability and governance."}], "metadata": {"domain": "rag", "task_type": "testing", "difficulty": "advanced"}} {"messages": [{"role": "user", "content": "Intermediate rag evaluation task: run A B test comparing two retrievers in production?"}, {"role": "assistant", "content": "Randomize traffic splitting by user id between baseline and candidate retrievers with equal top k and generation fixed. Define primary metrics as answer faithfulness, citation precision, and user satisfaction plus guardrails for latency and zero results. Ensure sufficient sample size via power analysis and run for full weekly cycle. Log retriever version, scores, and outcomes per request. Analyze with statistical tests and segment by query type. Monitor for cross contamination and novelty effects. Implement feature flag for instant rollback. Require human review of significant failures. Document hypothesis, config, results, and decision. Share dashboard with stakeholders. Archive configs and data for reproducibility. This rigorous test validates improvements beyond offline evals, preventing regressions from distribution shift and ensuring production impact before full rollout."}], "metadata": {"domain": "rag", "task_type": "experiment_analysis", "difficulty": "intermediate"}} {"messages": [{"role": "user", "content": "Implement query rewriting for RAG to handle vague follow-up questions like tell me more."}, {"role": "assistant", "content": "Vague follow-ups fail because they lack context. Implement query rewriting that expands tell me more using chat history into standalone query. Use LLM with prompt to rewrite last user message given history, keeping entities explicit. Then retrieve with rewritten query, not original. Keep original for synthesis context. Test with multi-turn conversations where second query omits subject. Common mistake is rewriting too aggressively and losing intent; constrain to preserve question type. Log original versus rewritten queries. Evaluate recall improvement on 20 dialogues. Add fallback to original if rewrite is empty. This small component greatly improves conversational RAG without changing index or chunking strategy. Always validate on a held-out golden set, log node IDs with scores and prompts, compare recall plus faithfulness before promoting changes, and monitor latency plus cost in production to avoid regressions."}], "metadata": {"domain": "rag", "task_type": "implementation", "difficulty": "intermediate"}} {"messages": [{"role": "user", "content": "Design scalable RAG serving 10M docs 500 QPS with hybrid retrieval rerank and guardrails."}, {"role": "assistant", "content": "Separate ingestion, serving, and evaluation planes with versioned indexes and staged rollouts to meet strict latency and quality objectives at scale. Stream documents through Kafka into chunker with five twelve tokens, embed batches one twenty eight, upsert to sharded Qdrant six nodes replication two, serve queries via gateway performing rewrite plus hybrid retrieval top fifty plus cross encoder rerank top five plus grounded generation with citations, and cache frequent answers. Enforce PII filtering, hallucination detection thresholds, and refusal fallback for low confidence. Evaluate nightly with RAGAS on five hundred gold questions, autoscale embedder and vLLM generators, monitor recall faithfulness and queue depth, deploy indexes blue green with shadow prompts, and budget twenty milliseconds retrieval plus eight hundred milliseconds generation within p95 one point five seconds."}], "metadata": {"domain": "rag", "task_type": "architecture", "difficulty": "advanced"}} {"messages": [{"role": "user", "content": "Analyze query patterns to improve RAG caching and routing decisions."}, {"role": "assistant", "content": "Cluster 10000 production queries with embeddings to find frequent intents, paraphrase groups, and long-tail topics. Measure cache hit potential for head queries and route them to exact or semantic cache with TTL. Identify ambiguous queries needing rewriting versus direct retrieval by correlating reformulation rate with recall. Segment latency and cost by cluster to prioritize optimization for expensive cohorts. Recommend precomputed answers for top 100 FAQs and expanded indexes for underserved topics. Validate with A-B tests showing reduced p95 latency and cost per query. Build dashboards tracking cluster drift weekly and trigger prompt or index updates when new clusters emerge. Document taxonomy for product and support teams clearly."}], "metadata": {"domain": "rag", "task_type": "instruction", "difficulty": "intermediate"}} {"messages": [{"role": "user", "content": "Advanced rag documentation task: specify evaluation dataset curation for legal RAG compliance?"}, {"role": "assistant", "content": "Specify sourcing of contracts, statutes, and memos with license clearance, redaction of client data, and version control. Define question categories covering extraction, summarization, citation, and refusal for privileged content. Require gold answers with span level evidence and jurisdictional tags. Detail annotator qualifications, bar review, agreement thresholds, and adjudication. Address handling of outdated law and conflicting sources with as of dates. Provide storage with access controls and audit trails. Include metrics for faithfulness, citation exactness, and refusal correctness. Version datasets and document update cadence with change logs. Cover ethical use, bias checks, and disclaimer requirements. Provide templates for adding cases. This specification ensures legally sound evaluation reflecting real risk, supporting defensible deployment decisions and regulator confidence."}], "metadata": {"domain": "rag", "task_type": "instruction", "difficulty": "advanced"}} {"messages": [{"role": "user", "content": "Create privacy tests verifying ACL enforcement and PII redaction across retrieval and generation stages"}, {"role": "assistant", "content": "Build matrix of users with different roles querying restricted, public, and mixed docs, asserting only authorized chunks retrieved and cited. Test PII patterns emails, SSNs redacted in retrieved context and final answers, with no leakage in logs. Attempt cross-tenant prompt injection to access others data, verify blocked. Automate with synthetic corpus containing canaries unique per tenant detecting leakage. Measure false positives blocking legitimate public access under 2 percent. Run in CI on index or policy changes, audit logs for completeness, test permission updates propagate within 5 minutes. Document compliance mapping to SOC2 and GDPR, ensuring evidence for auditors and safe handling of regulated data."}], "metadata": {"domain": "rag", "task_type": "testing", "difficulty": "advanced"}} {"messages": [{"role": "user", "content": "Explain strategies for grounding LLM answers with citations to prevent hallucinations in enterprise search."}, {"role": "assistant", "content": "Require retriever to return chunk IDs with verbatim text, then constrain generator to cite every factual claim using inline references. Use extractive pre-step selecting relevant sentences before abstractive synthesis. Add faithfulness checker with NLI rejecting unsupported sentences triggering regeneration. Tune chunk size 300 tokens for precise attribution. Evaluate citation precision and recall on 500 queries. Implement UI showing sources with highlights for user verification. Log uncited answers for review. Handle conflicting sources by presenting both with dates. Test adversarial queries tempting hallucination. Document policy for abstention when retrieval confidence low, improving trust over coverage. Track metrics in dashboards with alerts for regressions to ensure safe rollout and documented runbooks for oncall review and audit."}], "metadata": {"domain": "rag", "task_type": "instruction", "difficulty": "expert"}} {"messages": [{"role": "user", "content": "How to defend RAG against indirect prompt injection hidden in web crawl data?"}, {"role": "assistant", "content": "Sanitize crawled docs with classifiers that detect imperative instructions, encoded payloads, and suspicious links, quarantining matches. Segment retrieved content with untrusted wrappers and system rules to never follow embedded instructions. Restrict agent tools so browsing content cannot trigger emails, purchases, or code execution without explicit user confirmation. Add output monitoring for data exfiltration patterns like base64 or external URLs. Maintain allowlists for trusted domains and treat others with higher scrutiny. Red-team with injections in various positions, languages, and encodings. Log and alert on detected attempts. Update filters regularly as attack techniques evolve. Educate users about risks and show source provenance so malicious content is traceable to its origin document."}], "metadata": {"domain": "rag", "task_type": "security", "difficulty": "advanced"}} {"messages": [{"role": "user", "content": "Fine tune reranker with listwise loss for multilingual enterprise search."}, {"role": "assistant", "content": "Train XLM RoBERTa reranker on 200k query passage triples across 8 languages with listwise softmax loss emphasizing top ranks. Use hard negatives from BM25 and dense retrievers. Batch 32 queries with 16 passages each on 4 GPUs, lr 2e-5. Evaluate NDCG at 10 per language and cross lingual transfer. Distill to 6 layer student for 80ms latency retaining 98 percent quality. Monitor language imbalance and upsample low resource. Deploy with Triton and A B test CTR lift. Document training data licenses and bias checks. Additionally track metrics in versioned experiments and document tradeoffs to guide rollout decisions and future tuning priorities effectively for production."}], "metadata": {"domain": "rag", "task_type": "implementation", "difficulty": "advanced"}} {"messages": [{"role": "user", "content": "Design RAG for real-time financial filings with minute-level freshness."}, {"role": "assistant", "content": "Design streaming ingestion from EDGAR webhooks, parsing filings in seconds, chunking by sections with XBRL tags preserved, embedding with finance-tuned model, upserting to vector DB with timestamp metadata. Query path filters by ticker and filing date, retrieves latest plus historical for comparison, reranks for numeric relevance, generates with table-aware prompt citing filing IDs. Add numeric validator checking figures against source to block hallucinations. Cache hot tickers in Redis. Monitor ingestion lag under 60s, retrieval recall on earnings questions, and numeric accuracy. Scale with Kafka partitioning by ticker. Implement corrections handling for amended filings superseding prior versions. This meets trader needs for speed and accuracy, preventing stale advice that causes financial loss. Audit trail of sources satisfies compliance. Version parsers carefully as filing formats evolve quarterly requiring rapid adaptation without downtime."}], "metadata": {"domain": "rag", "task_type": "architecture", "difficulty": "advanced"}} {"messages": [{"role": "user", "content": "Fix asyncpg UniqueViolation when concurrent ingestion upserts same chunk IDs without idempotency handling"}, {"role": "assistant", "content": "Concurrent workers inserting same doc chunks cause primary key conflicts. Inspect traceback showing duplicate chunk hash. Fix with INSERT ON CONFLICT DO UPDATE upsert semantics, deterministic IDs from doc hash plus chunk index, distributed lock per doc ID via Redis. Reproduce with 4 parallel ingests same file verifying no error after fix and single canonical rows. Add transaction retries on serialization failures, log conflicts counts. Test with crash mid-batch ensuring resume safe, validate vector store and DB consistent via reconciliation job. Document idempotency guarantees enabling safe retries and parallel scaling without manual deduplication for reliable ingestion pipelines. Additionally track metrics dashboards and document operational lessons for reliable production maintenance over time."}], "metadata": {"domain": "rag", "task_type": "traceback", "difficulty": "intermediate"}} {"messages": [{"role": "user", "content": "Secure RAG pipeline against prompt injection via retrieved docs: delimit, filter, and audit."}, {"role": "assistant", "content": "Treat retrieved docs as untrusted. Wrap in tags with instruction to ignore embedded directives. Filter with injection classifier threshold 0.9, quarantine hits. Enforce system privilege hierarchy via instruction hierarchy training. Log all injections to SIEM. Red-team monthly with 500 payloads. Test that ignore previous fails. Document incident response. Require human approval for tool actions triggered by docs. Validate fix with dedicated unit test and integration check covering edge cases. Log relevant metrics, monitor production dashboards continuously, document change clearly in pull request for reviewers and future maintenance work. Include reproducible script, versioned config, seeded runs, ablation results, error analysis table, and follow-up monitoring plan to ensure durable improvement."}], "metadata": {"domain": "rag", "task_type": "security", "difficulty": "expert"}} {"messages": [{"role": "user", "content": "JWT secret AWS keys committed public GitHub two days exposure. Incident response revocation audit and prevention steps"}, {"role": "assistant", "content": "Public exposure means assume compromise of all secrets in repository history including forks and clones. Immediately revoke IAM keys, rotate JWT signing keys forcing global re login, invalidate sessions and refresh tokens. Purge history with BFG only if no clones, otherwise rotate rather than rewrite, enable GitHub secret scanning plus push protection. Audit CloudTrail for unauthorized calls, billing spikes, created resources. Add precommit gitleaks, vault dynamic secrets, least privilege scoped keys. Notify stakeholders per incident policy and document timeline. Test new keys work old rejected. Monitor dark web and abuse. Conduct postmortem. This contains blast radius, prevents lateral movement, establishes guardrails avoiding plaintext secrets in version control, and improves detection with automated scanning and rotation procedures."}], "metadata": {"domain": "software_quality", "task_type": "security", "difficulty": "expert"}} {"messages": [{"role": "user", "content": "Teach robust checkpointing and resume logic for long PyTorch jobs on preemptible instances."}, {"role": "assistant", "content": "Save full state dict including model, optimizer, scheduler, scaler, epoch, global step, and RNG states every 30 minutes to durable storage. Write atomically to temp file then rename to avoid corruption. Keep last three checkpoints with best metric copy separately. On startup, detect latest checkpoint, map location, and restore strictly. Log resume event with loss continuity check. Handle preemption signal SIGTERM to trigger emergency save within 30 seconds. Test resume equivalence by comparing losses after 10 steps from fresh versus resumed. Use deterministic dataloader with saved sampler state to avoid data repetition. Monitor checkpoint size and upload time. Document recovery runbook and validate on spot interruption simulation."}], "metadata": {"domain": "software_quality", "task_type": "instruction", "difficulty": "advanced"}} {"messages": [{"role": "user", "content": "Establish SAST DAST supply chain gates for AI Python monorepo."}, {"role": "assistant", "content": "Gate PRs with Ruff, Bandit high severity block, Semgrep OWASP rules, pip-audit for CVEs, and Trivy image scan. Require SBOM via CycloneDX and Sigstore signing. Run DAST ZAP baseline nightly against staging. Block secrets with gitleaks. Enforce dependency pinning plus Renovate with vulnerability auto bump. Measure false positive rate and tune rules quarterly. Require security review for new network or pickle code. Dashboard mean time to remediate and open criticals. Gates cut exploitable issues 80 percent pre-merge while keeping build under 10 min via caching and parallel jobs, balancing velocity with assurance for production AI handling sensitive data.Add regression tests covering edge cases, log key metrics for observability, document versioned configs, and review failure modes in staging before promoting changes to production systems."}], "metadata": {"domain": "software_quality", "task_type": "security", "difficulty": "expert"}} {"messages": [{"role": "user", "content": "Optimize 40min flaky ML suite to 8min with parallelization selection and fixture reuse."}, {"role": "assistant", "content": "Accelerate feedback cycles by executing independent tests across all available cores, separating slow integration scenarios into nightly workflows, and sharing expensive model fixtures across tests within isolated sessions. Run pytest with xdist across eight workers using loadfile distribution, define session scoped fixture fitting model once, mark slow tests for exclusion from pull request runs, cache pip dependencies and model artifacts in CI layers, use tmpfs for temporary data, and parallelize linting versus testing jobs. Measure per-test durations to identify worst offenders, quarantine flaky cases with automatic retries, mock S3 interactions with moto, enforce five minute timeout per test, require deterministic seeds, ensure tmp_path isolation to prevent pollution, and document nightly versus pull request scope so contributors understand coverage guarantees and expected runtimes."}], "metadata": {"domain": "software_quality", "task_type": "optimization", "difficulty": "intermediate"}} {"messages": [{"role": "user", "content": "Implement mutation testing gate in CI to enforce meaningful backend test coverage."}, {"role": "assistant", "content": "Integrate mutmut or cosmic ray selecting critical modules, generating mutants for conditionals and returns, running relevant subset for speed. Gate on kill rate above threshold like 80 percent, failing PR on survived mutants in changed lines. Optimize with incremental analysis, parallel workers, timeout per mutant. Report survived mutants as annotations with suggested tests. Test gate itself with known weak suite. Monitor runtime cost, mutant counts. Document writing killable tests asserting behavior not implementation, avoiding trivial asserts. Keep config in repo, baseline file versioned. Provide local command to run mutants for changed files, developer guide for equivalent mutants, ensuring coverage numbers reflect real fault detection not just line hits."}], "metadata": {"domain": "software_quality", "task_type": "testing", "difficulty": "beginner"}} {"messages": [{"role": "user", "content": "Monitor ML feature pipeline for drift and null spikes in production."}, {"role": "assistant", "content": "Compute PSI and KS for distributions versus baseline, alert if PSI over 0.2. Track null rate, cardinality, schema changes with Evidently. Log predictions and features to lake. Dashboard shows drift per feature. Trigger retrain or rollback on breach. Test monitors with synthetic shift. Distinguish seasonal from real drift via windows. Early detection prevents accuracy decay, ensures data contracts, reduces debugging time, and maintains compliance. Runbook defines triage steps owner and mitigation. To harden for operations, integrate metrics and tracing, validate configuration schemas, enforce resource limits, document failure modes with runbooks, automate canary verification, and benchmark under realistic load ensuring reproducible results and sustainable maintainability across releases."}], "metadata": {"domain": "software_quality", "task_type": "implementation", "difficulty": "advanced"}} {"messages": [{"role": "user", "content": "Improve test failure messages with custom matchers and diff output for API responses."}, {"role": "assistant", "content": "Build custom Hamcrest style matcher asserting JSON subset with path specific diff showing expected versus actual values. Include request id and endpoint in message for quick log correlation. Pretty print JSON with sorted keys to highlight structural differences. Avoid assert True False without context; always include relevant payload snippet truncated to thousand chars. Capture response headers for auth failures to distinguish token versus permission issues. Integrate with pytest assertion rewriting for clean output. Test matcher itself with passing and failing cases verifying helpful output. Measure that improved messages cut debugging time from thirty to five minutes per failure. Document matcher library for team reuse. Clear failure diagnostics transform red builds from frustrating puzzles into actionable reports, especially for new developers unfamiliar with API shape, accelerating fix cycle and reducing repeated CI reruns to inspect logs."}], "metadata": {"domain": "software_quality", "task_type": "debugging", "difficulty": "intermediate"}} {"messages": [{"role": "user", "content": "Software quality SAST flags hardcoded OpenAI key in tests. How to fix without breaking CI pipelines?"}, {"role": "assistant", "content": "Hardcoded test keys trigger failures and risk quota abuse if leaked. Replace with fake keys like sk test dummy and mock OpenAI client with canned responses or VCR cassettes for determinism. Inject real key only in nightly e2e via secret manager env var on protected branch. Add gitleaks to precommit and allowlist dummy pattern to avoid noise. Rotate exposed key immediately and check usage logs for abuse. Update CI to run unit tests without secrets, e2e only with secrets available. Document secret handling for contributors in readme. Verify no real keys remain via full history scan. This restores green pipeline while eliminating leak vector and reducing external API costs during routine commits and pull requests."}], "metadata": {"domain": "software_quality", "task_type": "security", "difficulty": "intermediate"}} {"messages": [{"role": "user", "content": "Review concurrent list Python threads append shared while iterates RuntimeError. Fix approach with queue and snapshot isolation"}, {"role": "assistant", "content": "CPython list append is atomic due to GIL but iteration while mutating raises RuntimeError or yields inconsistent snapshot with missed or duplicated items. Fix by using queue Queue for producer consumer decoupling, or lock around mutation plus iteration over copy snapshot. Better use concurrent futures collecting results rather than shared mutation. Example with lock snapshot equals list shared then process snapshot outside lock to minimize contention. Test stress with thread pool and deterministic assertions. Consider multiprocessing manager if CPU bound. Document thread safety contract for module. This eliminates race, ensures deterministic processing, avoids intermittent crash difficult to reproduce under load, and clarifies concurrency design with safe collection handling and minimal locking overhead."}], "metadata": {"domain": "software_quality", "task_type": "code_review", "difficulty": "advanced"}} {"messages": [{"role": "user", "content": "Implement Pact contract tests for ML prediction service to block breaking schema changes in CI."}, {"role": "assistant", "content": "Define explicit consumer driven contracts that capture expected request shapes and response structures for prediction endpoints, then automatically verify provider compliance during continuous integration to prevent breaking evolution. Create consumer pact tests specifying POST path, required feature array length, content type headers, and response matchers for predicted label and probability types. Publish generated pacts to broker with branch versioning, run provider verification against staging deployment URL, enforce can-i-deploy gate before promotion, and fail pipelines on missing fields, type changes, or status code mismatches. Test additional scenarios for extra fields tolerance, null handling, error responses, and backward compatibility with older clients. Monitor contract drift over time, mandate additive only changes, clarify ownership between frontend and backend teams, and document deprecation timelines for safe API evolution."}], "metadata": {"domain": "software_quality", "task_type": "implementation", "difficulty": "intermediate"}} {"messages": [{"role": "user", "content": "Review test plan for GDPR deletion across vector and relational stores."}, {"role": "assistant", "content": "Verify plan covers Postgres rows, vector IDs, backups, logs, and caches. Check tombstoning versus hard delete semantics and propagation delay SLO. Test cascading deletes with foreign keys and orphan vector cleanup jobs. Assert audit logs retain deletion record without PII. Validate search no longer returns deleted content after compaction. Test partial failures with retry and reconciliation reports. Ensure backups expire per retention policy. For AI compliance, verify retraining datasets exclude deleted users. Review access controls for deletion tooling. Strong plan proves erasure completeness across heterogeneous storage. It prevents residual embeddings from leaking personal data through similarity search long after relational records disappear, satisfying regulatory and customer trust requirements."}], "metadata": {"domain": "software_quality", "task_type": "code_review", "difficulty": "advanced"}} {"messages": [{"role": "user", "content": "Distributed trace shows missing spans for Celery tasks, only API spans appear. Logs have different request IDs. How to propagate context?"}, {"role": "assistant", "content": "Context is lost at queue boundary because trace headers are not serialized with task args. Inject W3C traceparent and baggage into Celery headers via signal task_publish, extract on worker with custom base Task. Use OpenTelemetry instrumentation for Celery and requests ensuring propagator set. Correlate logs by adding trace_id to structlog context. Verify end to end in Jaeger showing API to worker to DB as single trace. Test with integration asserting child span parent equals API span. Handle async workers with contextvars. Standardized propagation restores causality, enabling latency breakdown and error correlation across services instead of disjoint fragments that hide queue delay as root cause."}], "metadata": {"domain": "software_quality", "task_type": "debugging", "difficulty": "advanced"}} {"messages": [{"role": "user", "content": "Set up load and chaos testing for an LLM gateway handling retries, caching, and provider failover."}, {"role": "assistant", "content": "Define SLOs for p95 latency, success rate, and cost per request. Load test with Locust simulating 500 RPS mixed chat and embedding traffic. Test cache hit scenarios with repeated prompts to verify Redis reduces provider calls. Inject chaos: provider 500 errors, latency spikes, and DNS failures to verify failover to secondary provider. Assert retries with jitter do not amplify load beyond budget. Monitor queue depth, token throughput, and circuit breaker state. Test quota exhaustion handling with graceful degradation. Automate tests in staging mirroring prod limits. Collect distributed traces to identify slow middleware. Document runbooks for manual failover and rollback. Require passing chaos suite before enabling new provider routes."}], "metadata": {"domain": "software_quality", "task_type": "testing", "difficulty": "intermediate"}} {"messages": [{"role": "user", "content": "Under load, DB pool exhausts with timeout acquiring connection, traceback at get_connection. Pool size 20, traffic 200 rps. How to tune?"}, {"role": "assistant", "content": "Pool starvation stems from long held connections or undersizing. Measure hold time, checkout wait, and leak via pool events. Set pool size to roughly 2 times CPU plus 1 per instance times instances, with max_overflow 10 and timeout 5s failing fast. Ensure connections released via context managers even on exception, and transactions short with no network calls inside. Enable pre_ping and recycle 30m. Add read replica for reads, caching for hot queries. Load test to find saturation point and autoscale. Alert on wait queue depth. Fix by reducing hold time first, then sizing, preventing queue buildup that causes cascading timeouts. Proper tuning balances concurrency, memory, and DB max_connections without masking leaks with huge pools."}], "metadata": {"domain": "software_quality", "task_type": "optimization", "difficulty": "advanced"}} {"messages": [{"role": "user", "content": "My async cache sometimes returns stale data under concurrent refresh. Two coroutines both miss, both fetch DB, last write wins stale. How to debug heisenbug?"}, {"role": "assistant", "content": "This is thundering herd with race on check then act. Reproduce deterministically with asyncio barriers forcing concurrent misses. Fix with singleflight pattern using per key asyncio.Lock or future coalescing so only first fetches while others await same result. Add version stamps and compare and swap on write to avoid stale overwrite. Log cache hit miss with request id and timing to trace interleaving. Use aiocache with lock or implement memoize with future dict cleaned in finally. Test with 50 concurrent tasks asserting single DB call via counter. Add metrics for stampede count. Proper coalescing ensures consistency, reduces DB load, and turns flaky timing bug into deterministic coordination with clear ownership of refresh responsibility."}], "metadata": {"domain": "software_quality", "task_type": "debugging", "difficulty": "intermediate"}} {"messages": [{"role": "user", "content": "Optimize flaky end-to-end tests for ML platform with model registry, feature store, and serving."}, {"role": "assistant", "content": "Flakiness comes from timing, external services, and non-determinism. Containerize dependencies with Testcontainers for Postgres and Redis. Mock model training with tiny fixture to cut runtime from hours to minutes. Use deterministic seeds and fixed data snapshots versioned in S3. Implement retry only for infra errors, not assertion failures. Parallelize suites with pytest-xdist and isolate state per test with fresh namespaces. Add health wait loops with timeouts instead of sleep. Track flaky rate dashboard and quarantine consistently failing tests. Measure coverage of critical paths. Require logs and artifacts on failure for diagnosis. Document environment parity between CI and prod. Track metrics in dashboards with alerts for regressions to ensure safe rollout and documented runbooks for oncall review and audit."}], "metadata": {"domain": "software_quality", "task_type": "optimization", "difficulty": "advanced"}} {"messages": [{"role": "user", "content": "Analyze whether shadow traffic faithfully replays production for model validation."}, {"role": "assistant", "content": "Compare feature distributions shadow versus live with KS test; divergence over 0.05 indicates sampling bias. Verify request ordering and burst patterns preserved. Check for PII redaction altering tokens affecting NLP models. Measure latency overhead of mirroring under 5ms. Evaluate label delay handling where shadow lacks outcomes for 24 hours. Run parity check where current model shadowed against itself should match 100%. Document gaps like authenticated context missing in replay. Require 99% fidelity before trusting shadow metrics for promotion. Integrate checks into CI with clear failure messages and ownership. Track defect escape rate and review effectiveness monthly for improvement. Record metrics in dashboards segmented by relevant cohorts. Require explicit approval when quality, cost, or latency regress beyond agreed thresholds."}], "metadata": {"domain": "software_quality", "task_type": "experiment_analysis", "difficulty": "expert"}} {"messages": [{"role": "user", "content": "Refactor brittle Selenium tests with hardcoded sleeps and XPath. Use page objects."}, {"role": "assistant", "content": "Introduce page object model encapsulating locators and actions per page. Replace sleeps with explicit WebDriverWait for visibility clickability. Use stable data-testid attributes instead of absolute XPath. Parameterize credentials and URLs via config. Extract setup teardown to fixtures ensuring browser cleanup. Group assertions by user journey not implementation steps. Add retry for known transient overlays with clear logging. Validate refactor by running suite multiple times measuring flake reduction and duration. Document pattern for new pages, locator review checklist, and migration plan converting legacy tests incrementally. Finally validate changes with automated tests peer review and staging verification to ensure correctness maintainability performance and alignment with project standards requirements and long term operational needs for production."}], "metadata": {"domain": "software_quality", "task_type": "code_review", "difficulty": "intermediate"}} {"messages": [{"role": "user", "content": "Traceback SVD did not converge in PCA on sparse TF-IDF. Diagnose scaling and sparsity issue."}, {"role": "assistant", "content": "SVD nonconvergence happens when TruncatedSVD receives NaN or infinite values from prior TFIDF with unhandled empty documents, or when components approach feature rank on ill conditioned matrix. Inspect input for zero rows and extreme idf weights. Fix by filtering empty docs, adding min df threshold, using appropriate solver with random state, and standardizing only with mean false for sparse data. Add test with degenerate corpus containing empty strings. Avoid dense PCA on large sparse matrices. Log explained variance and convergence warnings. Validate pipeline on subsample before full fit plus cross validation. Add regression coverage measuring latency, error budgets, and data drift with dashboards alerting on SLO breaches plus versioned runbook documentation for oncall response."}], "metadata": {"domain": "software_quality", "task_type": "traceback", "difficulty": "intermediate"}} {"messages": [{"role": "user", "content": "Apply differential testing to validate a pandas refactor from loops to vectorized code. Ensure identical outputs."}, {"role": "assistant", "content": "Run old and new implementations side by side on diverse inputs including edge cases like empty frames, all-null columns, and large random data. Compare outputs with assert_frame_equal using check_dtype and tolerance for floating errors, logging mismatches with minimal reproducers via Hypothesis shrinking. Automate in CI as a temporary dual-run stage measuring performance delta and correctness across 1000 sampled partitions. Analyze divergences by dtype promotion, NaN propagation, and index alignment differences. Require zero mismatches on golden datasets plus statistical parity on fuzzed inputs before switching. Keep the old path behind a flag for canary comparison in production. Document tolerance choices, known acceptable differences, and removal timeline for legacy code. Differential testing de-risks refactors while quantifying speedups confidently."}], "metadata": {"domain": "software_quality", "task_type": "optimization", "difficulty": "advanced"}} {"messages": [{"role": "user", "content": "Explain provable supply-chain security with reproducible builds, attestations, and transparency logs."}, {"role": "assistant", "content": "Provable supply chain links artifacts to source via verifiable evidence. Achieve reproducible builds with pinned toolchains, hermetic containers, and deterministic flags, verifying byte identical outputs. Generate SLSA attestations signing source, build, and dependencies with Sigstore. Publish to transparency logs like Rekor for tamper detection. Verify policies with admission controllers blocking unsigned images. Monitor key compromises and revocations. Test rebuilds across machines and audit SBOMs. Handle bootstrapping trust and secret zero. Document provenance for customers and regulators. This architecture detects injected backdoors, compromised builders, and dependency swaps. It transforms release trust from assertion to proof, strengthening software quality, compliance, and resilience against sophisticated nation state or insider threats targeting critical infrastructure and widely deployed applications."}], "metadata": {"domain": "software_quality", "task_type": "instruction", "difficulty": "expert"}} {"messages": [{"role": "user", "content": "Audit an ML API for OWASP risks including prompt injection, data exposure, and model stealing."}, {"role": "assistant", "content": "Map threats: injection via user prompts, sensitive data in logs, excessive data exposure, and bulk scraping for extraction. Test prompt injection with ignore previous instructions payloads and verify system constraints hold. Enforce input length limits, output filters, and role separation. Redact PII with detection before logging and set short retention. Add auth, rate limiting per key, and anomaly detection for high-volume embedding queries indicating stealing. Require authorization checks on document IDs. Scan dependencies and container images. Use WAF rules for malicious patterns. Conduct red-team exercises and review third-party model cards. Log security events centrally with alerts. Document remediation priorities, add SAST and DAST to CI, and schedule quarterly penetration tests."}], "metadata": {"domain": "software_quality", "task_type": "security", "difficulty": "intermediate"}} {"messages": [{"role": "user", "content": "How do I cut E2E test runtime for an LLM app from 40 minutes to under 10?"}, {"role": "assistant", "content": "Parallelize with pytest-xdist across 8 workers sharding by test file, achieving near-linear speedup. Mock LLM calls with cached responses for 80% of tests, reserving live calls for 5 smoke tests. Replace full Docker builds with prebuilt images and layer caching. Use ephemeral Postgres with tmpfs for 3x faster fixtures. Identify slowest 10 tests with durations report and split setup from assertions. Enable fail-fast locally but full run in CI. Cache pip and HuggingFace weights across runs. Monitor queue time versus execution to detect runner bottleneck. Keep nightly full suite with live models while PR runs use mocks. Integrate checks into CI with clear failure messages and ownership. Track defect escape rate and review effectiveness monthly for improvement. Record metrics in dashboards segmented by relevant cohorts. Require explicit approval when quality, cost, or latency regress beyond agreed thresholds."}], "metadata": {"domain": "software_quality", "task_type": "optimization", "difficulty": "advanced"}} {"messages": [{"role": "user", "content": "Describe code review etiquette and what to check for readability, correctness, and maintainability."}, {"role": "assistant", "content": "Effective reviews balance rigor with respect to improve quality and share knowledge. Check correctness first: logic, edge cases, error handling, concurrency, and security. Assess readability via names, structure, comments, and size. Verify tests cover behavior and CI passes. Suggest alternatives, ask questions, distinguish blocking versus nitpicks. Keep feedback specific, actionable, and kind, referencing standards. Review small diffs promptly, limit scope, and avoid style wars via automated formatters. Authors should describe context, link issues, and respond constructively. Track follow ups and learn patterns. Measure review latency and defect escape. Healthy etiquette builds trust, mentors juniors, and prevents defects. Consistent reviews raise maintainability, spread ownership, and reinforce software quality culture without creating bottlenecks or resentment across engineering organizations."}], "metadata": {"domain": "software_quality", "task_type": "instruction", "difficulty": "beginner"}} {"messages": [{"role": "user", "content": "Analyze embedding collapse in contrastive training with hard negatives and low temperature setting."}, {"role": "assistant", "content": "Excessively low temperature sharpens softmax causing gradient spikes and representation collapse to narrow cone. Hard negatives exacerbate anisotropy. Diagnose via alignment uniformity metrics and rank distribution of positives. Fix warming temperature from higher value, normalizing embeddings, using debiased loss, and monitoring effective rank. Test linear probe accuracy and retrieval recall. Log gradient norms per layer. Avoid in-batch negatives dominated by duplicates. Tune batch size versus negative diversity. Document training stability guidelines. Additional validation includes shadow deployment, gradual rollout, and automated rollback on metric regression ensuring reliability. Add dashboard tracking precision, recall, latency, and cost with alerts on regression plus documented rollback procedure ensuring operational readiness."}], "metadata": {"domain": "software_quality", "task_type": "experiment_analysis", "difficulty": "expert"}} {"messages": [{"role": "user", "content": "Architect observability for data quality in a 50-table ML warehouse."}, {"role": "assistant", "content": "Deploy Monte Carlo or Great Expectations profiling daily computing nulls, freshness, and schema changes. Emit metrics to Prometheus with alerts on 3-sigma deviations. Lineage with OpenLineage linking table to model performance. Quarantine bad partitions automatically preventing training. Dashboard shows health per table with history 90 days. Integrate with PagerDuty for critical tables. Require data owner ack within 4 hours. Test detectors with injected anomalies quarterly. Cost under $2k monthly by sampling 10% for large tables. Integrate checks into CI with clear failure messages and ownership. Track defect escape rate and review effectiveness monthly for improvement. Record metrics in dashboards segmented by relevant cohorts. Require explicit approval when quality, cost, or latency regress beyond agreed thresholds."}], "metadata": {"domain": "software_quality", "task_type": "architecture", "difficulty": "advanced"}} {"messages": [{"role": "user", "content": "Describe advanced fuzzing with coverage guidance and sanitizers for security-critical parsers."}, {"role": "assistant", "content": "Coverage guided fuzzing discovers parser crashes and vulnerabilities automatically. Harness with libFuzzer or AFL plus plus, feeding structured seeds and dictionaries. Compile with AddressSanitizer, UndefinedBehaviorSanitizer, and coverage instrumentation. Define grammars for formats like JSON or protobuf to reach deep states. Corpus minimize and deduplicate crashes, triaging exploitable faults first. Run continuously with time budgets and regression corpus in CI. Monitor edges covered, timeouts, and OOMs. Fix by validating lengths, bounds, and nesting depth. Add regression tests per finding. Document threat model and safe handling. Mature fuzzing finds memory errors humans miss, hardens attack surfaces, and demonstrates due diligence. It significantly raises software quality and security assurance for critical ingestion, media, and protocol code."}], "metadata": {"domain": "software_quality", "task_type": "instruction", "difficulty": "advanced"}} {"messages": [{"role": "user", "content": "OAuth refresh fails invalid grant after 24h. App stores refresh token localStorage reuses concurrently. How to fix rotation race securely"}, {"role": "assistant", "content": "Providers with rotating refresh tokens invalidate prior token on use, so concurrent refresh races cause invalid grant and lockout. Browser localStorage is also XSS exposed and shared unsafely across tabs. Fix by serializing refresh with single flight promise, storing tokens in httpOnly secure cookies or memory behind backend proxy. Implement mutex: if refreshing, queue requests and retry original with new access token once. Handle 401 once then refresh, else logout and clear state. Persist latest rotation atomically, detect reuse, and telemetry failures. Test parallel 401 triggers asserting single token endpoint call and all retries succeed. Add exponential backoff. Document rotation semantics per OAuth RFC. This prevents lockout and reduces attack surface."}], "metadata": {"domain": "software_quality", "task_type": "debugging", "difficulty": "intermediate"}} {"messages": [{"role": "user", "content": "Design a mutation testing strategy that enforces meaningful assertions across a monorepo."}, {"role": "assistant", "content": "Mutation strategy proves tests assert behavior by introducing small faults. Select mutmut or cosmic ray, scope to changed packages for speed with nightly full runs. Configure operators for conditionals, returns, and arithmetic. Require kill thresholds per service in CI, failing weak suites. Triage survivors by adding oracles, not just coverage. Cache results, shard by package, and parallelize workers. Exclude generated code with justification. Track mutation score trends, runtime cost, and flake. Educate teams interpreting reports. Integrate with code review checklists. Over time, enforce rising baselines. Effective mutation testing eliminates vacuous tests, strengthens refactoring safety, and focuses effort on high risk logic. It elevates software quality from line execution to genuine fault detection across large monorepos with diverse languages and ownership boundaries."}], "metadata": {"domain": "software_quality", "task_type": "instruction", "difficulty": "advanced"}} {"messages": [{"role": "user", "content": "Fix OpenAPI schema mismatch causing SDK generation failures."}, {"role": "assistant", "content": "Validate spec with spectral and redocly to locate invalid refs and polymorphic errors. Align nullable vs required and date formats with generator expectations. Simplify oneOf where tooling lacks support, using discriminators explicitly. Regenerate SDK in CI to catch drift early. Test generated client against live server for roundtrip correctness. Version spec alongside server and publish changelog. For AI APIs, document streaming extensions clearly. Fixing schema restores client builds and prevents runtime type errors. It establishes contract as source of truth, reducing manual client patches and support tickets from mismatched field names or enum values across language ecosystems. Always keep backward compatibility notes updated for client teams."}], "metadata": {"domain": "software_quality", "task_type": "api_debugging", "difficulty": "advanced"}} {"messages": [{"role": "user", "content": "Prove backend release safety with formal deployment verification, canary analysis, auto rollback."}, {"role": "assistant", "content": "Verify release via automated canary comparing golden signals error rate latency business KPI between baseline and canary with Mann Whitney test requiring no regression. Enforce preflight checks migrations backward compatible, feature flags default off, config validated. Progress stepwise 1 10 50 percent with automatic rollback on SLO breach within minutes. Test rollback rehearsal, DB downgrade safety, flag cleanup. Monitor deployment metrics, log decisions. Document promotion criteria, manual judgment points, incident abort authority. Provide pipeline templates with policy as code, audit trail of approvals. Require load plus chaos pre prod, ensuring mathematically grounded confidence beyond manual QA, enabling high frequency safe releases at scale."}], "metadata": {"domain": "software_quality", "task_type": "testing", "difficulty": "expert"}} {"messages": [{"role": "user", "content": "Validate ETL output quality with Great Expectations suites and data docs."}, {"role": "assistant", "content": "Create expectation suite asserting row count range and email uniqueness and age between zero and 120 for customer table. Run validation after each ETL batch failing pipeline on critical expectations while warning on soft ones. Publish Data Docs HTML to S3 for stakeholder review of pass rates and failed rows sample. Version suites in Git alongside pipeline code to track rule evolution. Test suite itself with known good and bad fixtures to ensure detection. Integrate with Airflow sensor blocking downstream on failure to prevent dirty data propagation. Monitor expectation stability to tune thresholds avoiding false alarms. Document adding new rule workflow requiring data owner approval. Automated data quality gates catch schema drift and upstream bugs early, preventing dashboards and models training on corrupted inputs that cause costly business misdecisions and difficult backfills after late detection."}], "metadata": {"domain": "software_quality", "task_type": "implementation", "difficulty": "intermediate"}} {"messages": [{"role": "user", "content": "Explain flaky test management with quarantine, retries, and root-cause analysis practices."}, {"role": "assistant", "content": "Flaky tests erode trust and must be managed systematically. Detect via reruns, historical pass rates, and CI analytics tagging unreliable cases. Quarantine into separate suites blocking investigation but not merges, with expiry and owners. Allow limited retries only for infrastructure, never hiding product bugs. Root cause timing, concurrency, shared state, randomness, and external dependencies using logs and deterministic seeds. Fix with waits on conditions, isolation via containers, and clock control. Track flake budget and defect escape. Celebrate deletions of low value brittle tests. Document patterns and prevention checklists. Disciplined management restores signal, speeds pipelines, and improves morale. It transforms flakiness from accepted noise into actionable software quality data driving stable, deterministic, and trustworthy test suites across teams and repositories."}], "metadata": {"domain": "software_quality", "task_type": "instruction", "difficulty": "intermediate"}} {"messages": [{"role": "user", "content": "Write test for LlamaIndex Postgres ingestion handling duplicate document identifiers with versioning."}, {"role": "assistant", "content": "Create test ingesting same document identifier twice with different content versions, asserting upsert replaces vector and metadata while preserving version history. Verify unique constraint on identifier plus version and query returns latest by default. Include edge where concurrent ingests race requiring transactional upsert with conflict handling. Check embedding recomputation only when text hash changes saving cost. Assert old version retrievable via explicit version filter. Log ingestion identifier and timestamp. Test deletion tombstone preventing resurrected stale vectors. Measure ingestion latency under bulk load. Additional validation includes shadow deployment, gradual rollout, and automated rollback on metric regression ensuring reliability. Add dashboard tracking precision, recall, latency, and cost with alerts on regression plus documented rollback procedure ensuring operational readiness."}], "metadata": {"domain": "software_quality", "task_type": "testing", "difficulty": "advanced"}} {"messages": [{"role": "user", "content": "How do I test eventual consistency where read-after-write may lag 2 seconds? My integration test flakes asserting immediate visibility."}, {"role": "assistant", "content": "Replace fixed sleeps with polling assertions using awaitility pattern. Implement assert_eventually helper retrying every 100ms up to 5s checking read model projection. Isolate tests with unique IDs to avoid cross talk. Use testcontainers for real DB and message bus, not mocks, to capture lag. Tag as integration and run separately from unit suite. Log projection lag metrics to tune timeout. For determinism, expose test hook to force projection flush. Assert both convergence and monotonicity. This acknowledges CAP tradeoffs, eliminates timing flakes, and documents SLA for consistency. Add chaos test delaying consumer to verify timeout handling. The suite becomes reliable while still validating distributed behavior rather than assuming strong consistency that production does not provide."}], "metadata": {"domain": "software_quality", "task_type": "testing", "difficulty": "advanced"}} {"messages": [{"role": "user", "content": "How do I write a bug report for irreproducible training loss spikes?"}, {"role": "assistant", "content": "Include git hash, data hash, seed, hyperparameters, and loss curve screenshot. Attach logs with step numbers and gradient norms. List hardware type and NCCL version. Provide minimal repro script with 1% data subset. Note frequency 1 in 5 runs and last good commit. Tag with loss-spike label and assign to training infra. Avoid vague reports without artifacts; require template fields. Link to W&B run for full trace. Update issue with bisection results. Integrate checks into CI with clear failure messages and ownership. Track defect escape rate and review effectiveness monthly for improvement. Record metrics in dashboards segmented by relevant cohorts. Require explicit approval when quality, cost, or latency regress beyond agreed thresholds."}], "metadata": {"domain": "software_quality", "task_type": "instruction", "difficulty": "advanced"}} {"messages": [{"role": "user", "content": "Debug flaky Cypress test failing intermittently due to timing and network stub issues."}, {"role": "assistant", "content": "Replace fixed cy.wait(2000) with cy.intercept alias and cy.wait('@api') for deterministic sync. Stabilize selectors using data-testid instead of CSS that changes. Isolate state by resetting DB before each test. Quarantine flaky test, collect retries with videos. Check for race where assertion runs before render; add retryable should assertions. Mock clock for timers. Run 50 iterations to confirm stability. Analyze CI resources causing slowness. Fixing waits, selectors, and isolation removes most flakiness, improves signal, reduces reruns, and restores trust. Document pattern banning arbitrary waits via lint rule and require intercept for all network dependencies. For reliable operations, include peer review checklists, security scanning in continuous integration, versioned configuration management, clear error messages improving debuggability, automated recovery checks, and load validation with reproducible measurements without exposing sensitive internals."}], "metadata": {"domain": "software_quality", "task_type": "debugging", "difficulty": "intermediate"}} {"messages": [{"role": "user", "content": "Compare Lambda versus Kappa architectures for ML streaming features. Recommend one for 50k events per second."}, {"role": "assistant", "content": "Evaluate Lambda with separate batch and speed layers versus Kappa with a single streaming log for all processing. Lambda offers accurate batch recomputation but doubles logic maintenance and risks divergence between layers. Kappa simplifies to one Flink or Spark Streaming codebase reading Kafka with replay for backfills, reducing skew and operational burden. For 50k events per second with need for low freshness and frequent logic changes, recommend Kappa with tiered storage: Kafka retention 7 days plus S3 archive for long replay. Ensure exactly-once checkpoints, schema registry, and versioned jobs for reproducibility. Benchmark operational cost, code duplication, and recovery time, showing Kappa cuts maintenance by 40 percent. Retain batch jobs only for heavy historical training, not serving. Document tradeoffs and migration steps from existing Lambda to unified streaming."}], "metadata": {"domain": "system_design", "task_type": "architecture", "difficulty": "advanced"}} {"messages": [{"role": "user", "content": "Test chaos for payment system: kill leader DB and partition AZ. Define plan."}, {"role": "assistant", "content": "Inject faults with controlled blast radius in staging mirroring prod topology, killing primary then observing automatic failover under 30s with zero data loss via synchronous replication. Partition AZ to verify quorum and retry behavior. Assert idempotent payments with no double charge via reconciliation job. Measure MTTR plus error budget burn. Automate rollback on SLO breach. Document learnings. This proves resilience before real outages today with game days plus runbooks and monitoring for failover lag reliably. Code:\n# chaos mesh: kill pod db-primary\n# assert: SELECT pg_is_in_recovery()=false on new primary\n# reconcile: SELECT count(*) FROM payments GROUP BY idem_key HAVING count(*)>1"}], "metadata": {"domain": "system_design", "task_type": "testing", "difficulty": "advanced"}} {"messages": [{"role": "user", "content": "Debug non-reproducible RAG answers due to nondeterministic GPU kernels."}, {"role": "assistant", "content": "Isolate randomness setting temperature zero still varies, enable deterministic algorithms torch use_deterministic_algorithms True, fix seeds across Python, CUDA, track batching effects on attention, log logits for diffing, reproduce with single stream versus batched, handle vLLM scheduler nondeterminism by pinning config, test 100 runs measuring exact match rate, document residual nondeterminism sources, version deterministic configs, monitor production variance, implement eval tolerating minor variations via semantic match, secure logs, review performance cost 10 percent slower, train team, automate determinism check in CI failing on unexpected divergence for quality assurance. Ongoing governance requires versioned configs, automated regression tests, monitored latency dashboards, and quarterly security reviews for durability and compliance."}], "metadata": {"domain": "system_design", "task_type": "debugging", "difficulty": "expert"}} {"messages": [{"role": "user", "content": "System design with Kafka between ingestion API and embedding workers shows lag growing to 100k messages. How to tell if bottleneck is API, Kafka, or workers?"}, {"role": "assistant", "content": "Check consumer lag per partition, produce rate, and worker processing time separately to localize bottleneck. If produce exceeds consume while CPU low, workers blocked on embedding API calls. Inspect Kafka exporter for under replicated partitions and request latency to rule out broker disk or network issues. Profile workers for synchronous calls without batching; switch to bulk embed batch size 96 and async concurrency 8. Scale partitions to match worker concurrency, tune acks and linger for throughput, and add dead letter queue for poison messages blocking progress. Enable autoscaling on lag metric, add backpressure returning 429 from ingestion when lag exceeds threshold. Load test with replay to verify lag drains and p95 embed latency stays stable under sustained production load."}], "metadata": {"domain": "system_design", "task_type": "api_debugging", "difficulty": "advanced"}} {"messages": [{"role": "user", "content": "Explain rotary versus ALiBi positional encodings for long-context extension tradeoffs in transformers."}, {"role": "assistant", "content": "Rotary embeddings encode relative positions via rotation matrices extrapolating moderately but degrading beyond training length, while ALiBi biases attention linearly favoring recency with better zero-shot extension. Choose rotary with NTK scaling for precise order tasks, ALiBi for very long contexts with recency bias tolerance. Evaluate perplexity versus context length curves. Test needle-in-haystack retrieval. Monitor attention entropy shift. Avoid naive truncation breaking positional continuity. Document scaling parameters and calibration. Additional validation includes shadow deployment, gradual rollout, and automated rollback on metric regression ensuring reliability. Add dashboard tracking precision, recall, latency, and cost with alerts on regression plus documented rollback procedure ensuring operational readiness."}], "metadata": {"domain": "system_design", "task_type": "instruction", "difficulty": "expert"}} {"messages": [{"role": "user", "content": "Write organization-wide RFC for standardized AI gateway and model governance."}, {"role": "assistant", "content": "Propose a unified gateway centralizing authentication, rate limiting, semantic caching, observability, routing, and cost attribution for all product teams. Specify APIs, SDKs, migration phases, ownership, and support rotations over multiple quarters. Compare centralized versus decentralized alternatives analyzing cost, agility, and compliance tradeoffs with quantitative prototype evidence. Define service objectives, security controls, data retention, and chargeback mechanisms. Address latency overhead concerns demonstrating minimal impact and extensibility for future models. Outline pilot validation with representative teams before broad rollout. Solicit structured feedback through design reviews and decision logs. Conclude with success metrics, risk assessments, and mitigation plans providing executives and engineers a clear path toward consistent, safe, and economical AI adoption across the enterprise."}], "metadata": {"domain": "system_design", "task_type": "instruction", "difficulty": "expert"}} {"messages": [{"role": "user", "content": "Kubernetes GPU sharing via time-slicing causes noisy neighbor latency. Alternative?"}, {"role": "assistant", "content": "Replace time-slicing with MIG partitioning A100 into 3x20GB slices isolating memory bandwidth and compute, assign latency-sensitive decode to dedicated slices and batch jobs to remainder. Use NVIDIA device plugin with nvidia.com/mig-3g.20gb labels, Kueue queues with priority preemption, and MPS only for cooperative multi-tenant inference with 30 percent cap. Monitor SM util, memory throttle, and P99 per pod to detect contention, autoscale with separate node pools for interactive versus batch. Benchmark isolation showing P99 variance drop 60 percent versus slicing, test failover on slice failure cordoning node. Document slice topology, version driver 550, and chargeback by slice-hours. For H100, use dynamic MIG reconfiguration nightly. This provides predictable latency under 500ms while improving utilization to 75 percent without noisy interference. Add dashboards, alerts, runbooks, versioning, rollback tests, audits, and cost tracking to sustain production reliability."}], "metadata": {"domain": "system_design", "task_type": "architecture", "difficulty": "advanced"}} {"messages": [{"role": "user", "content": "Design observability stack for AI services with logs metrics traces evals"}, {"role": "assistant", "content": "Unify operational and quality signals. Logs use structured JSON with trace tenant prompt hash model tokens latency retrieval ids in Loki thirty day retention PII redaction. Metrics use Prometheus counters for requests errors histograms for latency gauges for queue cost per hour. Traces use OpenTelemetry spans for rewrite retrieval rerank generate exported to Tempo. Evals run nightly faithfulness recall stored in warehouse with Grafana trends. Alerts trigger on p95 over SLO error over one percent cost spike twice eval drop three points. Link panels to trace exemplars so oncall jumps from spike to root cause one click. Version configs. Validate on staging with realistic traffic, monitor dashboards, document version changes, and require human review before promoting observability changes to production for safety."}], "metadata": {"domain": "system_design", "task_type": "architecture", "difficulty": "intermediate"}} {"messages": [{"role": "user", "content": "Deploy multi-region active-active AI search with consistency tradeoffs."}, {"role": "assistant", "content": "Deploy full stack in us-east and eu-west with regional vector DB replicas asynchronously replicated with lag under 30 seconds. Route users to nearest region via latency-based DNS. Accept eventual consistency for document freshness, surfacing last-indexed timestamp. Use CRDT or version vectors to resolve conflicting doc updates. Replicate prompt configs via GitOps. Monitor cross-region lag and failover with synthetic probes. Test regional outage by draining traffic. Provide data residency controls pinning EU tenants to EU region. Active-active design cuts global latency, survives regional failures, respects sovereignty requirements, scales capacity geographically, and trades strict freshness for availability with transparent UX about indexing delays."}], "metadata": {"domain": "system_design", "task_type": "implementation", "difficulty": "intermediate"}} {"messages": [{"role": "user", "content": "Implement simple LLM API gateway with authentication and logging."}, {"role": "assistant", "content": "Build FastAPI gateway validating API keys via middleware and enforcing per-key quotas in Redis. Route to OpenAI or self-hosted backend based on path. Log requests with hashed user IDs, tokens, and latency to centralized store. Add health and metrics endpoints for Prometheus. Containerize with Docker and deploy single replica initially. Configure TLS termination at ingress. Implement retry with timeout for backend calls. Provide client SDK example. This minimal gateway centralizes security, observability, and routing before scaling to advanced traffic management. Architecturally ensure horizontal scalability with sharded stateless services, asynchronous ingestion via durable queues, health checks with autoscaling policies, encrypted storage with audit logging, and chaos testing to validate resilience under partial failures. Document implementation procedures, thresholds, owners, and rollback steps in runbooks while tracking improvements through dashboards and postmortems for continuous reliability."}], "metadata": {"domain": "system_design", "task_type": "implementation", "difficulty": "beginner"}} {"messages": [{"role": "user", "content": "Threat model firmware supply chain with remote attestation and reproducible builds."}, {"role": "assistant", "content": "Model attacker injecting backdoor at build or update server, requiring reproducible builds with signed SBOM plus transparency log and TPM attestation before boot. Verify hash chain from source to binary in CI with independent rebuilders. Revoke compromised keys via succinct CRL. Pentest with malicious mirror asserting client rejection. Monitor attestation failures. Document incident response. This secures expert supply chain today with cryptographic provenance plus hardware root of trust and rapid revocation reliably always. Code:\n# cosign sign --key k bundle\n# tpm_quote verify nonce Add capacity planning with headroom for peak plus multi AZ failover drills plus latency SLO dashboards to keep global services resilient and observable in production environments daily. Include runbook steps for partition recovery and overload shedding to ensure safe operation under flash traffic today reliably."}], "metadata": {"domain": "system_design", "task_type": "security", "difficulty": "expert"}} {"messages": [{"role": "user", "content": "What are the main components of an AI eval pipeline for a support chatbot"}, {"role": "assistant", "content": "An eval pipeline needs datasets metrics runners and regression gates. Start with 100 to 300 golden examples covering happy path edge cases adversarial and out of scope queries, each with expected answer required citations and context docs. Metrics include faithfulness answer relevance context recall citation precision latency and cost per query. Runner is nightly job replaying dataset against staging, storing outputs with prompt version model version and embedding version. Use deterministic checks like regex for citations plus judge with fixed rubric for quality. Gate merges on delta and fail if faithfulness drops more than two points. Dashboard trends over time with sampled human review for low confidence judgments. Version everything so you can bisect regressions to prompt or data change. Validate on staging, monitor dashboards, and require human review before promotion."}], "metadata": {"domain": "system_design", "task_type": "instruction", "difficulty": "beginner"}} {"messages": [{"role": "user", "content": "Design scalable RAG architecture for 100M documents and 1000 QPS."}, {"role": "assistant", "content": "Partition corpus by tenant and topic across sharded Qdrant clusters with replication factor three. Front with CDN caching frequent queries and Redis semantic cache. Deploy stateless query services in Kubernetes with HPA on latency. Use message queue for async ingestion with backpressure. Implement tiered retrieval coarse then rerank to bound cost. Add LLM gateway with load balancing and failover. Monitor shard balance and hot keys. Conduct capacity planning with load tests. This achieves horizontal scalability, fault tolerance, and predictable p95 under high concurrency. Architecturally ensure horizontal scalability with sharded stateless services, asynchronous ingestion via durable queues, health checks with autoscaling policies, encrypted storage with audit logging, and chaos testing to validate resilience under partial failures. Document design procedures, thresholds, owners, and rollback steps in runbooks while tracking improvements through dashboards and postmortems for continuous reliability."}], "metadata": {"domain": "system_design", "task_type": "architecture", "difficulty": "beginner"}} {"messages": [{"role": "user", "content": "Load test multi-tenant RAG with noisy neighbor isolation."}, {"role": "assistant", "content": "Generate per-tenant workloads mixing heavy and light queries. Measure fairness ensuring heavy tenant does not starve others. Validate quotas and priority queues enforce isolation. Monitor per-tenant latency breakdown. Tune CPU shares and connection pools. Test burst handling with backpressure. Automate regression in staging. Adjust limits based on results. This guarantees SLOs under contention. Architecturally ensure horizontal scalability with sharded stateless services, asynchronous ingestion via durable queues, health checks with autoscaling policies, encrypted storage with audit logging, and chaos testing to validate resilience under partial failures. Document testing procedures, thresholds, owners, and rollback steps in runbooks while tracking improvements through dashboards and postmortems for continuous reliability. Document testing procedures, thresholds, owners, and rollback steps in runbooks while tracking improvements through dashboards and postmortems for continuous reliability."}], "metadata": {"domain": "system_design", "task_type": "testing", "difficulty": "advanced"}} {"messages": [{"role": "user", "content": "Secure service mesh mTLS with rotation and least privilege authorization."}, {"role": "assistant", "content": "Enforce STRICT mTLS with Istio PeerAuthentication plus short lived certs rotated 24h via SDS and AuthorizationPolicy per service method. Deny by default and allowlist callers with JWT claims. Audit policy violations and rotate root CA with overlap. Test expired cert plus unauthorized caller denied. Monitor handshake failures. Document onboarding. This achieves zero trust east west today with automated rotation plus fine grained access and compliance logs reliably. Code:\n# apiVersion: security.istio.io/v1\n# kind: PeerAuthentication\n# metadata: name: default\n# spec: mtls: mode: STRICT Add capacity planning with headroom for peak plus multi AZ failover drills plus latency SLO dashboards to keep global services resilient and observable in production environments daily. Include runbook steps for partition recovery and overload shedding to ensure safe operation under flash traffic today reliably."}], "metadata": {"domain": "system_design", "task_type": "security", "difficulty": "advanced"}} {"messages": [{"role": "user", "content": "Analyze RAG hallucinations despite relevant retrieval to separate reranker versus generator faults."}, {"role": "assistant", "content": "Diagnose grounding failures by inspecting retrieved contexts for answer coverage, examining reranker scores for ranking quality, and testing generator adherence with controlled prompt variations. Sample sixty failing queries, label whether top five contexts contain correct spans, compute RAGAS faithfulness versus context recall to isolate components, and run ablation removing reranker versus strengthening grounding instruction. Often sixty percent failures show correct context but model adds external knowledge, indicating prompt weakness rather than retrieval gaps. Fix with strict citation requirement, temperature zero, context denoising to top three passages, and refusal threshold when maximum similarity below point three. Validate faithfulness improvement from point sixty two to point eighty eight on holdout, A/B test prompt variants, log contexts plus scores for auditability, and monitor hallucination rate weekly."}], "metadata": {"domain": "system_design", "task_type": "experiment_analysis", "difficulty": "advanced"}} {"messages": [{"role": "user", "content": "Design zero trust network with SPIFFE identities and short lived certs."}, {"role": "assistant", "content": "Issue per workload SPIFFE IDs via attested agents with 1h certs auto rotated, enforcing mTLS plus per method authz. Log every decision with identity for audit. Rotate trust bundle with overlap and test revocation within 5m. Monitor unauthenticated attempts. Onboard via secure introduction. This minimizes lateral movement today with strong identity plus least privilege and continuous verification reliably. Code:\n# spiffe id: spiffe://prod/api/checkout\n# fetch: /workload/api --socket unix:///spiffe.sock Add capacity planning with headroom for peak plus multi AZ failover drills plus latency SLO dashboards to keep global services resilient and observable in production environments daily. Include runbook steps for partition recovery and overload shedding to ensure safe operation under flash traffic today reliably."}], "metadata": {"domain": "system_design", "task_type": "security", "difficulty": "advanced"}} {"messages": [{"role": "user", "content": "Design architecture for a real-time fraud detection system scoring transactions in under 100ms with model updates."}, {"role": "assistant", "content": "Ingest transactions via Kafka with exactly-once semantics. Use Flink for streaming feature computation like velocity and amount aggregates over sliding windows. Serve features from Redis with precomputed profiles keyed by user and card. Deploy a lightweight gradient boosting model via ONNX in a stateless FastAPI service autoscaled on CPU and latency. Keep p95 under 100ms by colocating feature store and inference in same region and avoiding external calls in critical path. Log decisions to S3 for training. Retrain daily on labeled outcomes in Spark, validate with time-based splits, and push to registry after shadow testing. Use feature flags for model versions and fallback rules if service degrades. Monitor drift, precision, recall, and business loss prevented."}], "metadata": {"domain": "system_design", "task_type": "architecture", "difficulty": "intermediate"}} {"messages": [{"role": "user", "content": "Debug RAG returning outdated answers after doc updates."}, {"role": "assistant", "content": "Staleness from cached vectors or missed reindex. Check ingestion timestamp vs query time; verify delta pipeline processed update. Inspect docstore version and vector payload updated_at. Clear Redis cache for affected queries or version keys by index id. Ensure upsert overwrites not duplicates; query by doc id count. Add freshness metric lag hours alert over 2h. Implement versioned alias switching after batch. Test by updating one doc and querying immediately. Add UI showing last updated. Root cause often cache TTL too long or failed queue message; fixing invalidation restores freshness without full rebuild. Design note: include HA with three replicas across zones, daily encrypted backups with restore drill, per-tenant quotas and audit logs, plus eval-gated deploy checking faithfulness and p95 latency to prevent regressions in production."}], "metadata": {"domain": "system_design", "task_type": "debugging", "difficulty": "intermediate"}} {"messages": [{"role": "user", "content": "Prove global RAG meets 99.99 percent availability with formal fault tree analysis."}, {"role": "assistant", "content": "Construct fault tree with leaf MTBF for gateway, embedding, vector DB, LLM, cache. Calculate availability via inclusion exclusion showing 99.99 with triple redundancy and cache serving stale on LLM outage. Prove failover time under 30s using Markov model with detection 5s plus DNS 10s. Verify with chaos 100 fault injections measuring recovery within SLO. Handle correlated failures AZ loss via multi region. Document assumptions independent failures and tested backups. Provide monitoring proving error budget compliance 52 min yearly downtime. Recommend additional replica for vector primary to reach 99.995. Include maintenance windows excluded via live migration. Present to auditors with evidence load tests and incident history validating theoretical model against operational reality."}], "metadata": {"domain": "system_design", "task_type": "experiment_analysis", "difficulty": "expert"}} {"messages": [{"role": "user", "content": "Debug QUIC handshake failures with ECN blackholes and version negotiation."}, {"role": "assistant", "content": "Blackholes drop ECN marked UDP causing timeout plus version mismatch triggers fallback loops. Capture qlog plus tcpdump showing ECN drops and version packets. Disable ECN probing on affected ASNs and pin version with grease handling. Test across networks asserting handshake under 200ms. Monitor handshake success by ASN. Deploy gradual rollout. This fixes expert UDP transport today with measurement driven fallbacks plus version agility and telemetry reliably always. Code:\n# quiche config disable_ecn=True\n# log: handshake_time.observe(dur) Add capacity planning with headroom for peak plus multi AZ failover drills plus latency SLO dashboards to keep global services resilient and observable in production environments daily. Include runbook steps for partition recovery and overload shedding to ensure safe operation under flash traffic today reliably."}], "metadata": {"domain": "system_design", "task_type": "api_debugging", "difficulty": "expert"}} {"messages": [{"role": "user", "content": "Debug OpenAI embeddings 429 with zero retry-after during nightly backfill and quota reset."}, {"role": "assistant", "content": "Zero retry-after indicates burst limit without precise reset time causing immediate retry loops prolonging throttling. Nightly backfill concurrency spikes tokens beyond quota. Inspect usage headers for limit versus remaining and schedule backfill with token bucket pacing. Fix implementing capped exponential backoff with jitter plus minimum delay floor, reducing batch size, and prioritizing incremental updates. Cache embeddings by content hash avoiding rework. Add test mocking 429 with zero header asserting delayed retry. Monitor quota dashboards alerting before saturation. Implement dead-letter replay. Additional validation includes shadow deployment, gradual rollout, and automated rollback on metric regression ensuring reliability. Add dashboard tracking precision, recall, latency, and cost with alerts on regression plus documented rollback procedure ensuring operational readiness."}], "metadata": {"domain": "system_design", "task_type": "security", "difficulty": "advanced"}} {"messages": [{"role": "user", "content": "Explain how to design embedding chunking and metadata strategy for multi-tenant SaaS documentation search."}, {"role": "assistant", "content": "Chunk by semantic sections rather than fixed tokens, targeting 300 to 500 tokens with 10 percent overlap to preserve context. Attach metadata for tenant_id, doc_version, language, product_area, and access_role. Enforce tenant filter at query time in vector DB to prevent cross-tenant leakage. Store parent document reference to enable parent-child retrieval where small chunks retrieve but larger context generates. Normalize code blocks and tables separately. Version embeddings with model name to allow reindexing. Evaluate chunk sizes on tenant-specific queries using recall and faithfulness. Implement per-tenant namespaces or collections for isolation and easier deletion. Log tenant query patterns to tune boosting. Document retention and purge policies for compliance."}], "metadata": {"domain": "system_design", "task_type": "instruction", "difficulty": "intermediate"}} {"messages": [{"role": "user", "content": "Integrate Kafka for async document ingestion into RAG index."}, {"role": "assistant", "content": "Publish document events to Kafka topic with schema registry validation. Consume with scalable workers performing parsing, chunking, embedding, and upsert. Implement idempotent processing via doc_id and dead-letter queue for failures. Scale partitions by throughput. Monitor consumer lag and retry metrics. Secure with mTLS and ACLs. Enable exactly-once where needed. This decouples upload from indexing, handling bursts and backpressure reliably. Architecturally ensure horizontal scalability with sharded stateless services, asynchronous ingestion via durable queues, health checks with autoscaling policies, encrypted storage with audit logging, and chaos testing to validate resilience under partial failures. Document integration procedures, thresholds, owners, and rollback steps in runbooks while tracking improvements through dashboards and postmortems for continuous reliability. Document integration procedures, thresholds, owners, and rollback steps in runbooks while tracking improvements through dashboards and postmortems for continuous reliability."}], "metadata": {"domain": "system_design", "task_type": "implementation", "difficulty": "intermediate"}} {"messages": [{"role": "user", "content": "Kubernetes liveness probe kills LLM inference pod during model warmup. Debug slow startup versus failure detection."}, {"role": "assistant", "content": "Liveness probe starts too early and treats prolonged weight loading as deadlock, triggering restart loop preventing readiness. Model download plus CUDA initialization can exceed default initial delay seconds. Inspect kubelet events and container startup duration histograms. Fix by separating startup probe with generous failure threshold from liveness probe, using exec checking model ready file or HTTP ready endpoint. Set readiness to fail until tokenizer and weights loaded. Add prestop hook for graceful drain and test with cold node cache. Avoid same endpoint for liveness and readiness when warmup is heavy. Monitor GPU memory pressure causing OOM killed misclassified as probe failure plus alerting."}], "metadata": {"domain": "system_design", "task_type": "debugging", "difficulty": "intermediate"}} {"messages": [{"role": "user", "content": "Optimize Kafka partition count and batching for 500k events per second."}, {"role": "assistant", "content": "Size partitions as max of throughput divided by 10MB per partition and consumer parallelism, starting 48 per topic with replication 3. Tune linger 20ms plus batch 64KB plus compression lz4 for throughput. Monitor under replicated plus ISR shrink. Test 500k RPS sustained. Avoid over partitioning causing rebalance storms. Document retention. This sustains high volume streaming today with balanced latency plus cost and operability reliably. Code:\n# kafka-topics --create --partitions 48 --replication-factor 3\n# producer: linger.ms=20, batch.size=65536, compression.type=lz4 Add capacity planning with headroom for peak plus multi AZ failover drills plus latency SLO dashboards to keep global services resilient and observable in production environments daily. Include runbook steps for partition recovery and overload shedding to ensure safe operation under flash traffic today reliably."}], "metadata": {"domain": "system_design", "task_type": "optimization", "difficulty": "advanced"}} {"messages": [{"role": "user", "content": "My system design uses API gateway routing to three LLM microservices, but I see cascading 504s when one model is slow. How to debug gateway timeouts and prevent cascade?"}, {"role": "assistant", "content": "Root pattern is synchronous gateway waiting on slowest downstream without isolation, so worker pool exhaustion propagates 504s to healthy routes. Trace gateway access logs for upstream response time per service and correlate with worker saturation metrics. Implement per route timeouts like 8s for classifier and 45s for generator, plus bulkhead pools so slow service cannot starve others. Add retries only for idempotent calls on 502 and 503 with jitter, never blindly on generation POST. Use hedged requests or fallback to smaller model when p99 exceeds SLO. Enable OpenTelemetry to visualize gateway versus LLM spans clearly. Fix with Envoy circuit breaker, outlier detection ejecting unhealthy hosts, and queue with backpressure returning 429 early. Load test with chaos delay injection and alert on gateway p95 and error ratio."}], "metadata": {"domain": "system_design", "task_type": "api_debugging", "difficulty": "intermediate"}} {"messages": [{"role": "user", "content": "Implement consistent hashing with virtual nodes for cache cluster scaling."}, {"role": "assistant", "content": "Map 200 virtual nodes per physical node on ring with murmur hash to spread load evenly and minimize remap to 1 slash N on growth. Lookup walks clockwise to first node and replicates to next two for fault tolerance. Test adding node asserting only 10 percent keys move. Monitor imbalance plus hot keys with separate replication. Handle node failure via hinted handoff. This enables elastic caching today with smooth scaling plus minimal disruption and predictable load distribution reliably. Code:\nimport hashlib, bisect\nring=[]\n# for node in nodes:\n# for i in range(200):\n# h=int(hashlib.md5(f'{node}-{i}'.encode()).hexdigest(),16)\n# ring.append((h,node))\n# ring.sort() Add capacity planning with headroom for peak plus multi AZ failover drills plus latency SLO dashboards to keep global services resilient and observable in production environments daily. Include runbook steps for partition recovery and overload shedding to ensure safe operation under flash traffic today reliably."}], "metadata": {"domain": "system_design", "task_type": "implementation", "difficulty": "advanced"}} {"messages": [{"role": "user", "content": "Test fault tolerance of distributed LLM inference cluster."}, {"role": "assistant", "content": "Simulate node failures, network partitions, and GPU errors in staging. Verify requests reroute to healthy replicas without data loss. Measure recovery time and error rate during chaos. Test leader election for scheduler and queue durability. Validate idempotent retries prevent duplicate billing. Automate with chaos mesh scenarios in CI. Review single points of failure like load balancer. Document RTO and RPO. Strengthen replication and alerts based on findings. Regular testing ensures production resilience. Architecturally ensure horizontal scalability with sharded stateless services, asynchronous ingestion via durable queues, health checks with autoscaling policies, encrypted storage with audit logging, and chaos testing to validate resilience under partial failures. Document testing procedures, thresholds, owners, and rollback steps in runbooks while tracking improvements through dashboards and postmortems for continuous reliability. Document testing procedures, thresholds, owners, and rollback steps in runbooks while tracking improvements through dashboards and postmortems for continuous reliability."}], "metadata": {"domain": "system_design", "task_type": "testing", "difficulty": "intermediate"}} {"messages": [{"role": "user", "content": "Our distributed LLM serving mesh shows cascading timeouts during peak bursts. How do I diagnose root cause?"}, {"role": "assistant", "content": "Map the failure cascade from edge to GPUs using correlated traces before changing capacity. Compare gateway queue time, retriever latency, vector DB saturation, and LLM prefill versus decode waits across the incident window. Check for retry storms amplifying load, connection pool exhaustion, and autoscaler lag behind burst arrival. Inspect GPU KV cache pressure, throttled provider quotas, and noisy-tenant hotspots skewing shard latency. Enable hedging for slow embedding calls, enforce deadlines with graceful degradation to cached answers, and shed low-priority batch traffic first. Reproduce with burst replay at peak plus thirty percent, validating circuit breakers and bulkheads isolate faults. Document per-replica capacity, add alerts on queue depth and timeout propagation, and require burst tests before raising limits or adding new tenants."}], "metadata": {"domain": "system_design", "task_type": "debugging", "difficulty": "expert"}} {"messages": [{"role": "user", "content": "Design an event-driven labeling pipeline to continuously improve a vision model."}, {"role": "assistant", "content": "Stream low-confidence predictions below 0.6 to labeling queue in Label Studio via webhook. Prioritize with uncertainty plus diversity sampling using k-means on embeddings to avoid duplicates. Assign to annotators with quality checks via gold tasks and inter-annotator agreement over 0.85. Version labels with DVC and trigger retraining when 5k new labels accumulate. Evaluate per-slice accuracy to target weak classes. Close loop by redeploying challenger in shadow and measuring lift. Track labeling latency and cost per label. Handle disagreement with adjudication workflow. Ensure PII blurring before outsourcing annotation. Document capacity assumptions, failure modes, and runbooks for on-call. Validate with load replay and chaos drills before production promotion. Record metrics in dashboards segmented by relevant cohorts. Require explicit approval when quality, cost, or latency regress beyond agreed thresholds."}], "metadata": {"domain": "system_design", "task_type": "architecture", "difficulty": "intermediate"}} {"messages": [{"role": "user", "content": "Design streaming architecture for LLM chat with low time to first token."}, {"role": "assistant", "content": "Place gateway maintaining WebSocket connections and forwarding token streams via SSE. Keep retrieval synchronous but parallelize embedding and vector lookup. Start LLM streaming immediately after context assembly. Use async non-blocking I/O throughout to handle thousands of connections. Buffer tokens for smooth rendering. Add edge caching for static prompts. Scale streaming workers separately from batch jobs. Monitor TTFT and disconnect rates. Handle backpressure by dropping slow clients gracefully. This minimizes perceived latency and supports interactive user experience at scale. Architecturally ensure horizontal scalability with sharded stateless services, asynchronous ingestion via durable queues, health checks with autoscaling policies, encrypted storage with audit logging, and chaos testing to validate resilience under partial failures. Document design procedures, thresholds, owners, and rollback steps in runbooks while tracking improvements through dashboards and postmortems for continuous reliability."}], "metadata": {"domain": "system_design", "task_type": "architecture", "difficulty": "intermediate"}} {"messages": [{"role": "user", "content": "Design high-level RAG system with ingestion, vector DB, and query path components."}, {"role": "assistant", "content": "Propose ingestion workers loading PDFs, chunking 512 tokens, embedding, writing to Pinecone with metadata. Use S3 for raw docs and Postgres for metadata. Query path FastAPI validates input, retrieves top 5, reranks, synthesizes with GPT-4o-mini, returns answer plus citations. Add Redis semantic cache for repeats. Include batch evaluation job nightly on golden set. Secure with Auth0, tenant filters, PII redaction. Monitor latency, cost, faithfulness via Grafana. Handle scaling with Kubernetes HPA on queue length. Document data flow diagram, API contracts, and failure modes. Estimate cost per 1M queries. Provide phased MVP to production roadmap with canary, observability, and rollback procedures ensuring reliable launch for internal knowledge assistant use case."}], "metadata": {"domain": "system_design", "task_type": "architecture", "difficulty": "intermediate"}} {"messages": [{"role": "user", "content": "Test disaster recovery for RAG with vector snapshot restore and RPO validation."}, {"role": "assistant", "content": "Define RPO 15 min RTO 1 hour for knowledge service. Automate hourly Qdrant snapshots to S3 with cross region copy. Test restore quarterly in isolated VPC measuring time and recall parity. Validate metadata Postgres PITR aligns with vector snapshot via version IDs. Simulate region loss failing over DNS to secondary serving stale snapshot with banner. Document steps snapshot select, volume restore, index load, smoke tests. Monitor backup success alerting on failure. Handle partial restore with reconciliation job re-embedding missing docs. Provide runbook roles and approvals. Measure cost of storage versus risk. Ensure encryption and access logs for backups. Report compliance evidence for SOC2 requiring tested recovery procedures."}], "metadata": {"domain": "system_design", "task_type": "testing", "difficulty": "intermediate"}} {"messages": [{"role": "user", "content": "Secure RAG against indirect prompt injection via poisoned docs."}, {"role": "assistant", "content": "Sanitize ingestion stripping instructions patterns, markdown links, hidden text. Delimit retrieved context with tags and system instruction to ignore embedded commands. Run guardrail LLM scoring docs suspicious before indexing. Restrict tools to read-only for RAG agent. Log tool actions. Red-team with poisoned PDF containing exfiltrate instruction. Require approval for external calls triggered by retrieval. Monitor for anomalous tool sequences. This defense in depth prevents single malicious doc from hijacking copilot to leak data or perform actions. Design note: include HA with three replicas across zones, daily encrypted backups with restore drill, per-tenant quotas and audit logs, plus eval-gated deploy checking faithfulness and p95 latency to prevent regressions in production."}], "metadata": {"domain": "system_design", "task_type": "security", "difficulty": "advanced"}} {"messages": [{"role": "user", "content": "Refactor RAG monolith into microservices for retrieval and generation."}, {"role": "assistant", "content": "Extract ingestion, embedding, vector search, reranking, and generation into separate services with gRPC contracts. Introduce API gateway orchestrating calls with timeouts and retries. Decouple via message queue for async indexing. Containerize independently enabling separate scaling. Add contract tests to prevent breaking changes. Centralize logging with correlation IDs. Migrate incrementally using strangler pattern. Measure deployment frequency improvement. This increases agility, fault isolation, and allows team ownership per component. Architecturally ensure horizontal scalability with sharded stateless services, asynchronous ingestion via durable queues, health checks with autoscaling policies, encrypted storage with audit logging, and chaos testing to validate resilience under partial failures. Document refactoring procedures, thresholds, owners, and rollback steps in runbooks while tracking improvements through dashboards and postmortems for continuous reliability. Document refactoring procedures, thresholds, owners, and rollback steps in runbooks while tracking improvements through dashboards and postmortems for continuous reliability."}], "metadata": {"domain": "system_design", "task_type": "code_review", "difficulty": "intermediate"}} {"messages": [{"role": "user", "content": "Design edge caching for LLM responses with semantic similarity at CDN layer."}, {"role": "assistant", "content": "Deploy Cloudflare Workers computing query embeddings via small model, checking KV semantic cache threshold 0.96. Serve hits at edge under 50ms saving origin cost. Misses forward to origin with cache write on success. Handle tenant isolation via namespaced keys. Manage PII by excluding flagged queries from edge cache. Monitor hit rate and false positive helpfulness via sampling. Invalidate by version on reindex. Test with paraphrased queries measuring precision. Document privacy as edge stores only embeddings hashes. Provide fallback to exact match if embedding service down. Estimate 50 percent cost saving on FAQs. Include security signed requests preventing cache poisoning. Plan gradual rollout 10 percent edge validation before global enablement."}], "metadata": {"domain": "system_design", "task_type": "architecture", "difficulty": "intermediate"}} {"messages": [{"role": "user", "content": "Explain GDPR right to be forgotten in RAG vector stores."}, {"role": "assistant", "content": "Must delete user docs from docstore, vectors, caches, and backups on request within 30 days. Design doc id mapping to vector ids for targeted delete via Qdrant delete by filter user_id. Purge Redis cache keys and embedding cache. Tombstone in ingestion log. Verify via query asserting no hits. Handle backups expiring within 90 days with documented process. Provide admin API delete_user_data. Audit log deletion. Test quarterly. Failure risks fines; building deletion from day one avoids full reindex cost later. Note LLM memorization out of scope but retrieval deletion suffices for RAG compliance. Design note: include HA with three replicas across zones, daily encrypted backups with restore drill, per-tenant quotas and audit logs, plus eval-gated deploy checking faithfulness and p95 latency to prevent regressions in production."}], "metadata": {"domain": "system_design", "task_type": "instruction", "difficulty": "intermediate"}} {"messages": [{"role": "user", "content": "Design RAG platform serving 10k tenants with strict isolation and 1s SLO."}, {"role": "assistant", "content": "Partition Qdrant collections per enterprise tenant and namespaces per SMB, route via gateway validating JWT tenant_id, enforce metadata filters server side, autoscale vLLM pools with HPA on queue depth, cache head queries in Redis with tenant scoped keys TTL 1h, set timeouts retriever 300ms LLM 700ms, fallback to cached answers, monitor per tenant latency and cost, handle noisy neighbor with rate limits, version indexes per tenant, deploy multi region active active, test isolation with chaos, document onboarding, secure encryption per tenant KMS, implement usage billing, audit access and ensure GDPR deletion propagates to vectors within 24h. Ongoing governance requires versioned configs, automated regression tests, monitored latency dashboards, and quarterly security reviews for durability and compliance."}], "metadata": {"domain": "system_design", "task_type": "architecture", "difficulty": "advanced"}}