{"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Optimize while preserving behavior.\n\nFile: ibt7mbl.py\n```python\ndef pwl2n6qpry7z(xs):\n out = []\n for x in xs:\n if x not in out:\n out.append(x)\n return out\n```\n\nRequirements: preserve first-seen order; O(n) average; add types + docstring.\n\n# ibt7mbl.py\nfrom __future__ import annotations\nfrom typing import Iterable, List, Set, TypeVar\n\nT = TypeVar(\"T\")\n\ndef pwl2n6qpry7z(xs: Iterable[T]) -> List[T]:\n \"\"\"Return unique items preserving first-seen order.\"\"\"\n seen: Set[T] = set()\n out: List[T] = []\n for x in xs:\n if x in seen:\n continue\n seen.add(x)\n out.append(x)\n return out", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Build an elite-grade solution in the domain of databases for scenario: event ingestion.\nPrimary language: go.\nDifficulty: hard.\nConstraints: include tests or verification strategy, make the interface contract explicit, provide rollout and rollback guidance, assume untrusted inputs; validate and sanitize, design for backward compatibility and migrations.\nComponent: component_qpwhvnt.\nAssume compliance requires data deletion with proofs.\nTask: Design an application-level protocol (framing, retries, timeouts, backpressure). Provide client/server skeleton and test vectors.\n\nOutput: elite-grade engineering answer with contracts, edge cases, and verification.\nOutput: protocol framing + retry policy + client/server skeleton.\n\n**Framing**\n- Length-prefixed: uint32_be length + payload\n- Payload: msgpack/json; include request_id, type, and optional checksum\n\n**Reliability**\n- Retries only for idempotent ops; exponential backoff + jitter.\n- Timeouts: connect, read, overall; enforce max in-flight to provide backpressure.\n\n**Test vectors**\n- Corrupted length / truncated frame rejected\n- Duplicate request_id returns cached response\n- Slowloris protection by read deadlines\n\n\nHard checks: failure injection tests and performance regressions gated.", "source": "WithinUsAI/Elite_GOD_Coder_100k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Refactor to modern typed Python with immutability and tests.\n\nFile: wydb7164.py\n```python\nclass W015Aq20Qc3:\n def __init__(self, name, values):\n self.name = name\n self.values = list(values)\n def add(self, v):\n self.values.append(v)\n def mean(self):\n s = 0\n for x in self.values:\n s += x\n return s / len(self.values)\n```\n\nReturn full new wydb7164.py and test_wydb7164.py.\n\n# wydb7164.py\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom typing import Iterable, Tuple\n\n@dataclass(frozen=True)\nclass W015Aq20Qc3:\n name: str\n values: Tuple[float, ...]\n\n @staticmethod\n def create(name: str, values: Iterable[float]) -> \"W015Aq20Qc3\":\n vals = tuple(float(v) for v in values)\n if not vals:\n raise ValueError(\"values must be non-empty\")\n return W015Aq20Qc3(name=name, values=vals)\n\n def add(self, v: float) -> \"W015Aq20Qc3\":\n return W015Aq20Qc3(name=self.name, values=self.values + (float(v),))\n\n def mean(self) -> float:\n return sum(self.values) / len(self.values)\n\n# test_wydb7164.py\nimport pytest\nfrom wydb7164 import W015Aq20Qc3\n\ndef test_mean_and_add():\n c = W015Aq20Qc3.create(\"a\", [1, 2, 3])\n assert c.mean() == 2.0\n assert c.add(5).mean() == (1 + 2 + 3 + 5) / 4\n\ndef test_empty_raises():\n with pytest.raises(ValueError):\n W015Aq20Qc3.create(\"x\", [])", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: Project stack: FastAPI, PostgreSQL, Redis, Celery, pytest, Docker\nLanguage: YAML\nDependency challenge: timezone bug in reporting\nTask type: version_conflict_resolution\nDifficulty: hard\n\nFix this as a senior engineer.\nRequired:\n- identify the version or compatibility failure mode\n- produce the corrected config/code/build patch\n- explain rollback-safe migration notes\n- add regression tests or reproducibility checks\n- include concrete verification commands\n\nRepository sketch:\nrepo/\n .github/workflows/ci.yml\n docker-compose.yml\n deploy/\n app.yaml\n\nFocus: Focus on versioning, migrations, lockfiles, runtime compatibility, and secure dependency handling.\n\nassistant: Diagnosis:\n- Root cause: the issue around timezone bug in reporting is a dependency, migration, or runtime-compatibility mismatch that needs a rollback-safe patch.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```yaml\nname: ci\non: [push, pull_request]\njobs:\n test:\n runs-on: ubuntu-latest\n steps:\n - uses: actions/checkout@v4\n - name: Validate\n run: echo \"validated\"\n```\n\nTests:\n```yaml\n# Verification:\n# - validate syntax\n# - run smoke workflow\n# - fail fast on broken config\n```\n\nVerification:\n- `validate workflow syntax`\n- `run CI smoke job`\n\nEngineering notes:\n- Language: YAML\n- Framework/tooling: GitHub Actions\n- Stack context: FastAPI, PostgreSQL, Redis, Celery, pytest, Docker\n- Domain: team dashboard\n- Task type: version_conflict_resolution\n- Difficulty: hard\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Produce an offline-first self-evolving code assistant architecture named `u2d971r`.\nMust include: module layout, patch-safety policy, evaluation gates (tests/lint/types), versioned memory index.\n\nArchitecture: `u2d971r` (offline-first, self-evolving)\n\nModules\n- core/loop.py: evolve → validate → accept/reject (bounded iterations)\n- patching/: diff builder, safe apply, atomic writes, rollback points\n- policy/: allowlist paths, deny globs (.git/, __pycache__/, binaries), patch size caps\n- signals/: parse pytest/ruff/mypy into normalized findings\n- memory/index.jsonl: append-only snapshots (hashes, metrics, rationale)\n\nSafety gates\n- refuse path traversal/symlink escapes; never edit binaries\n- accept only if tests/lint/types stay green or improve", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Write pytest tests for `f34390`.\n\n```python\ndef f34390(a: int, b: int) -> int:\n return a*a + b*b\n```\nInclude edge cases and a property-style check.\n\n```python\nimport random\nfrom m47770 import f34390\n\ndef test_known():\n assert f34390(3,4) == 25\n\ndef test_zero():\n assert f34390(0,0) == 0\n\ndef test_property_nonnegative():\n for _ in range(200):\n a=random.randint(-50,50)\n b=random.randint(-50,50)\n assert f34390(a,b) >= 0\n```", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Refactor a Python module used for event dispatching into a clean, extensible design.\nRequirements: outline the new architecture briefly, then provide the refactored code and tests.\nConstraints: must include type hints, must be easy to extend, must provide clear error messages.\nDifficulty: expert. Handle empty inputs and malformed records gracefully.\n\nDeliverable: corrected code and verification tests.\nArchitecture:\n- Public facade class coordinating concerns (parsing, validation, persistence)\n- Small pure functions for testability\n- No global state; dependency injection for filesystem I/O\n\n```python\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom pathlib import Path\nfrom typing import Protocol, Iterable\nimport json\n\nclass Store(Protocol):\n def write_text(self, path: Path, data: str) -> None: ...\n\nclass FSStore:\n def write_text(self, path: Path, data: str) -> None:\n path.parent.mkdir(parents=True, exist_ok=True)\n path.write_text(data, encoding=\"utf-8\")\n\n@dataclass(frozen=True, slots=True)\nclass Item:\n name: str\n qty: int\n\ndef parse_items(lines: Iterable[str]) -> list[Item]:\n out: list[Item] = []\n for i, line in enumerate(lines, 1):\n s = line.strip()\n if not s:\n continue\n obj = json.loads(s)\n if not isinstance(obj, dict):\n raise ValueError(f\"line {i}: expected object\")\n name = obj.get(\"name\")\n qty = obj.get(\"qty\")\n if not isinstance(name, str) or not name:\n raise ValueError(f\"line {i}: name must be str\")\n if not isinstance(qty, int) or qty < 0:\n raise ValueError(f\"line {i}: qty must be non-negative int\")\n out.append(Item(name, qty))\n return out\n\nclass InventoryWriter:\n def __init__(self, base_dir: Path, store: Store | None = None) -> None:\n self._base = base_dir\n self._store: Store = store or FSStore()\n\n def write(self, rel_path: str, items: list[Item]) -> Path:\n dst = (self._base / rel_path).resolve()\n base = self._base.resolve()\n if dst != base and base not in dst.parents:\n raise ValueError(\"unsafe path traversal\")\n payload = json.dumps([item.__dict__ for item in items], ensure_ascii=False)\n self._store.write_text(dst, payload)\n return dst\n```\n\n```python\nimport json\nfrom pathlib import Path\nimport pytest\nfrom module_under_test import InventoryWriter, parse_items\n\ndef test_parse_items_valid():\n lines = [json.dumps({\"name\":\"x\",\"qty\":1})]\n assert parse_items(lines)[0].name == \"x\"\n\ndef test_writer_blocks_traversal(tmp_path: Path):\n w = InventoryWriter(tmp_path)\n with pytest.raises(ValueError):\n w.write(\"../evil.json\", [])\n```", "source": "WithinUsAI/python_GOD_coder_100k"} {"text": "Write a thorough test suite for a Python component used for CLI tooling.\nRequirements: cover edge cases, invalid inputs, and behavior invariants.\nConstraints: must be memory-efficient, must include tests, must be easy to extend, must be streaming-friendly.\nDifficulty: medium. Provide helpful exceptions with actionable messages.\n\nDeliverable: implementation + tests.\n```python\n# tests (pytest-style) for a module providing: normalize(), parse_lines(), compute_stats()\nimport math\nimport pytest\n\ndef test_normalize_idempotent(module_under_test):\n x = \" A\\tB \"\n assert module_under_test.normalize(module_under_test.normalize(x)) == module_under_test.normalize(x)\n\ndef test_parse_lines_rejects_invalid(module_under_test):\n with pytest.raises(ValueError):\n module_under_test.parse_lines([\"\", \"???\", None]) # type: ignore[arg-type]\n\ndef test_compute_stats_basic(module_under_test):\n data = [1, 2, 3, 4]\n s = module_under_test.compute_stats(data)\n assert s.count == 4\n assert s.total == 10\n assert math.isclose(s.mean, 2.5)\n```", "source": "WithinUsAI/python_GOD_coder_100k"} {"text": "Build an elite-grade solution in the domain of stream processing for scenario: event ingestion.\nPrimary language: bash.\nDifficulty: expert.\nConstraints: make the interface contract explicit, document performance characteristics, include invariants and failure modes, provide rollout and rollback guidance, assume untrusted inputs; validate and sanitize.\nComponent: component_aiyqxdb.\nAssume crash-only design; recovery must be deterministic.\nTask: Provide SLOs, alerting, dashboards, runbooks, and incident playbook. Include chaos testing and safe rollout strategy.\n\nOutput: elite-grade engineering answer with contracts, edge cases, and verification.\nOutput: SLOs + alerts + runbooks + chaos strategy.\n\n**SLOs**\n- Availability: 99.9% monthly\n- Latency: p95 < 200ms, p99 < 400ms\n- Error rate: < 0.1%\n\n**Alerts**\n- Burn-rate alerts for SLOs (fast/slow windows)\n- Saturation: CPU, memory, queue depth, DB connections\n- Dependency health: cache hit rate drop, downstream timeouts\n\n**Runbooks**\n- Triage: identify blast radius, feature-flag rollback, capacity mitigation\n- Post-incident: timeline, contributing factors, action items\n\n**Chaos**\n- Inject latency, partial outages, and restarts in staging; verify steady-state SLOs.\n\n\nExpert checks: state-machine reasoning, concurrency stress, and upgrade/rollback validated.", "source": "WithinUsAI/Elite_GOD_Coder_100k"} {"text": "Improve typing and robustness of a Python module used for event dispatching.\nRequirements: provide type-safe APIs (generics/protocols where appropriate) and include tests.\nConstraints: must provide clear error messages, stdlib-only.\nDifficulty: expert. Guarantee deterministic output ordering.\n\nDeliverable: corrected code and verification tests.\n```python\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom typing import Callable, Generic, Iterable, Protocol, TypeVar\n\nT = TypeVar(\"T\")\nR = TypeVar(\"R\")\n\nclass Mapper(Protocol[T, R]):\n def __call__(self, x: T) -> R: ...\n\n@dataclass(frozen=True, slots=True)\nclass Batch(Generic[T]):\n items: tuple[T, ...]\n\ndef map_batch(batch: Batch[T], fn: Mapper[T, R]) -> Batch[R]:\n return Batch(items=tuple(fn(x) for x in batch.items))\n\ndef chunked(xs: Iterable[T], size: int) -> Iterable[Batch[T]]:\n if size <= 0:\n raise ValueError(\"size must be > 0\")\n buf: list[T] = []\n for x in xs:\n buf.append(x)\n if len(buf) == size:\n yield Batch(items=tuple(buf))\n buf.clear()\n if buf:\n yield Batch(items=tuple(buf))\n```\n\n```python\nimport pytest\nfrom module_under_test import Batch, map_batch, chunked\n\ndef test_map_batch():\n b = Batch(items=(1,2,3))\n assert map_batch(b, lambda x: x*2).items == (2,4,6)\n\ndef test_chunked():\n out = list(chunked([1,2,3,4,5], 2))\n assert [b.items for b in out] == [(1,2),(3,4),(5,)]\n```", "source": "WithinUsAI/python_GOD_coder_100k"} {"text": "Task type: ml_system_design\nScenario: document indexing pipeline\nDomain focus: secure enclaves (defensive)\nPrimary language: python\nDifficulty: expert\nScale/SLO: p99 < 150ms\nComponent: component_klqvsxzw\nConstraints: include failure modes and recovery, explicit contracts and invariants, include test vectors and fuzz strategy, include verification strategy, include deterministic replay plan, include backward compatibility and migration plan\nAssume hostile inputs and targeted abuse patterns.\nDeliverable: Design end-to-end ML system: data contracts, training, evaluation, registry, serving, monitoring, and rollback.\n\nOutput: contract-first solution with failure modes, security posture, and test/verification strategy.\n**Contract**\n- Inputs validated at the boundary; explicit error taxonomy.\n- Idempotency for side effects via request_id; deterministic replay.\n- Backward compatibility: additive changes by default; versioned breaking changes.\n**Invariants**\n- Safety: state transitions preserve invariants; no partial commit leaks.\n- Determinism: replay of the same event log yields identical outputs.\n- Isolation: tenant boundary enforced; no cross-tenant reads/writes.\n**Failure modes & recovery**\n- Data corruption: checksums + scrubber; quarantine and rebuild from replicas/snapshots.\n- Crash during commit: WAL replay completes or transaction aborts; no torn writes.\n- Network partition: minority cannot commit; clients receive retriable errors.\n**Security posture (defensive)**\n- Threat model: auth/authz, injection, replay/abuse, supply chain.\n- Least privilege; secrets in managed store; audit logs for sensitive ops.\n- Input normalization, parameterized queries, path traversal protections.\n**Verification strategy**\n- Fuzzing of parsers/framers/validators with corpus seeds.\n- Deterministic simulation with fault injection (crash/partition/latency).\n- Property tests against a pure reference model (state machine).\n\n**Snippet**\n```text\nImplementation sketch: factor pure state-machine core; adapters for I/O; add deterministic replay log.\n```\nExpert checks: state-machine proof sketch + model checking; upgrade/rollback rehearsed.", "source": "WithinUsAI/Omega_Genesis_Coder_100k"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: Language: Bash\nFramework/tooling: awk\nDomain: document processing API\nLogic challenge: log redaction failure\nTask type: multi_file_migration_repair\nDifficulty: expert\n\nReturn a rigorous engineering answer:\n- identify the hidden root cause or logical failure\n- present the corrected implementation\n- add tests that prove the fix\n- list verification commands\n- explain why naive fixes are insufficient when relevant\n\nRepository sketch:\nrepo/\n scripts/\n run.sh\n deploy.sh\n tests/\n smoke.sh\n\nFocus: Focus on staff-level problem solving with multi-file patches, rollout implications, performance and security tradeoffs.\n\nassistant: Diagnosis:\n- Staff-level diagnosis: log redaction failure impacts correctness, operability, and future maintenance, so the fix must be minimal where possible but complete where necessary.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```bash\n#!/usr/bin/env bash\nset -euo pipefail\n\ninput=\"${1:-}\"\nif [[ -z \"$input\" ]]; then\n echo \"missing input\" >&2\n exit 1\nfi\n\nprintf '%s\n' \"$input\" | tr -d '\r'\n```\n\nTests:\n```bash\noutput=\"$(bash scripts/run.sh \"abc\")\"\ntest \"$output\" = \"abc\"\n```\n\nVerification:\n- `bash tests/smoke.sh`\n- `shellcheck scripts/*.sh`\n\nEngineering notes:\n- Language: Bash\n- Framework/tooling: awk\n- Stack context: GitHub Actions, Docker Compose, Kubernetes, Terraform\n- Domain: document processing API\n- Task type: multi_file_migration_repair\n- Difficulty: expert\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "Fix a subtle bug in a Python module used for ETL pipelines.\nRequirements: explain root cause briefly, provide corrected code, and add regression tests.\nConstraints: must avoid global state, must include type hints, must provide clear error messages.\nDifficulty: easy. Guarantee deterministic output ordering.\n\nDeliverable: corrected code and verification tests.\n```python\nfrom __future__ import annotations\n\nfrom dataclasses import dataclass\nfrom pathlib import Path\nfrom typing import Iterable\nimport json\n\n\nclass ValidationError(ValueError):\n \"\"\"Raised when input validation fails.\"\"\"\n\n\ndef safe_join(base: Path, *parts: str) -> Path:\n \"\"\"Join paths while preventing traversal outside base.\"\"\"\n b = base.resolve()\n p = (b / Path(*parts)).resolve()\n if p != b and b not in p.parents:\n raise ValidationError(f\"unsafe path: {p}\")\n return p\n\n\n@dataclass(frozen=True, slots=True)\nclass Record:\n key: str\n value: int\n\n\ndef parse_jsonl(lines: Iterable[str]) -> list[Record]:\n out: list[Record] = []\n for idx, line in enumerate(lines, 1):\n s = line.strip()\n if not s:\n continue\n try:\n obj = json.loads(s)\n except json.JSONDecodeError as e:\n raise ValidationError(f\"line {idx}: invalid json\") from e\n if not isinstance(obj, dict):\n raise ValidationError(f\"line {idx}: expected object\")\n key = obj.get(\"key\")\n val = obj.get(\"value\")\n if not isinstance(key, str) or not key:\n raise ValidationError(f\"line {idx}: key must be non-empty str\")\n if not isinstance(val, int):\n raise ValidationError(f\"line {idx}: value must be int\")\n out.append(Record(key, val))\n return out\n\n\ndef write_jsonl(base: Path, rel: str, records: Iterable[Record]) -> Path:\n base.mkdir(parents=True, exist_ok=True)\n dst = safe_join(base, rel)\n dst.parent.mkdir(parents=True, exist_ok=True)\n with dst.open(\"w\", encoding=\"utf-8\", newline=\"\\n\") as f:\n for r in records:\n f.write(json.dumps({\"key\": r.key, \"value\": r.value}, ensure_ascii=False) + \"\\n\")\n return dst\n```\n\n```python\n# tests (pytest-style)\nimport json\nfrom pathlib import Path\nimport pytest\nfrom module_under_test import ValidationError, Record, parse_jsonl, write_jsonl\n\ndef test_parse_ok():\n lines = [json.dumps({\"key\":\"a\",\"value\":1}), json.dumps({\"key\":\"b\",\"value\":2})]\n assert parse_jsonl(lines) == [Record(\"a\",1), Record(\"b\",2)]\n\ndef test_parse_rejects_bad_json():\n with pytest.raises(ValidationError):\n parse_jsonl([\"{not json}\"])\n\ndef test_safe_join_blocks_traversal(tmp_path: Path):\n with pytest.raises(ValidationError):\n write_jsonl(tmp_path, \"../x.jsonl\", [Record(\"a\",1)])\n```", "source": "WithinUsAI/python_GOD_coder_100k"} {"text": "Build an elite-grade solution in the domain of gpu compute for scenario: edge sync.\nPrimary language: rust.\nDifficulty: hard.\nConstraints: provide rollout and rollback guidance, include invariants and failure modes, assume untrusted inputs; validate and sanitize, avoid undefined behavior and data races.\nComponent: component_mcyuvax.\nAssume partial network partitions occur weekly.\nTask: Provide threat model, secure-by-default design, and defensive implementation patterns. No offensive/exploit content; focus on prevention and detection.\n\nOutput: elite-grade engineering answer with contracts, edge cases, and verification.\nOutput: threat model + defensive design + detection.\n\n**Threat model**\n- Auth: token theft → short-lived tokens, rotation, audience checks\n- AuthZ: privilege escalation → centralized policy checks, tenant isolation tests\n- Input: injection → strict validation, parameterized queries, output encoding\n- Supply chain: dependencies → lockfiles, signature verification, SBOM\n\n**Defensive patterns**\n- Idempotency keys for side effects; replay-safe handlers\n- Secrets in managed store; never logs\n- Audit logging for sensitive ops; tamper-evident storage\n\n**Detection**\n- Alert on unusual auth failures, access pattern anomalies, and data exfil signals.\n\n\nHard checks: failure injection tests and performance regressions gated.", "source": "WithinUsAI/Elite_GOD_Coder_100k"} {"text": "Build an elite-grade solution in the domain of stream processing for scenario: feature flagging.\nPrimary language: go.\nDifficulty: expert.\nConstraints: assume untrusted inputs; validate and sanitize, document performance characteristics, include tests or verification strategy, avoid undefined behavior and data races, provide rollout and rollback guidance.\nComponent: component_qdyalxw.\nAssume strict auditability and replayable history.\nTask: Define a small DSL, implement tokenizer/parser, IR, and a codegen or interpreter. Include tests and complexity notes.\n\nOutput: rigorous solution with invariants, failure modes, and performance notes.\nOutput: DSL + parser + IR + interpreter/codegen + tests.\n\n**DSL**\n- Expressions: integers, identifiers, `+ - * /`, let-binding: `let x = expr in expr`\n- Example: `let x = 2+3 in x*10`\n\n**Pipeline**\n1. Tokenize\n2. Parse into AST\n3. Lower into IR (stack ops) or interpret AST directly\n\n**Reference (Rust-style outline)**\n- `enum Expr { Int(i64), Var(String), Bin(Op, Box, Box), Let(String, Box, Box) }`\n- Parser: Pratt or recursive descent.\n\n**Tests**\n- Golden tests for parse trees.\n- Property: pretty-print(parse(x)) round-trips for a corpus.\n- Eval tests for precedence and scoping.\n\n\nExpert checks: state-machine reasoning, concurrency stress, and upgrade/rollback validated.", "source": "WithinUsAI/Elite_GOD_Coder_100k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Fix a bug and add tests.\n\nFile: azeehpw.py\n```python\ndef xivq42(n: int) -> int:\n \"\"\"Sum 1..n inclusive.\"\"\"\n if n < 0:\n raise ValueError(\"n must be non-negative\")\n total = 0\n for k in range(n): # BUG: should include n\n total += k\n return total\n```\n\nReturn unified diffs for azeehpw.py and test_azeehpw.py (pytest).\n\n*** Begin Patch\n*** Update File: azeehpw.py\n@@\n def xivq42(n: int) -> int:\n@@\n total = 0\n- for k in range(n): # BUG: should include n\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_azeehpw.py\n+import pytest\n+from azeehpw import xivq42\n+\n+def test_zero():\n+ assert xivq42(0) == 0\n+\n+def test_one():\n+ assert xivq42(1) == 1\n+\n+def test_small():\n+ assert xivq42(7) == 28\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ xivq42(-1)\n+\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Fix a bug and add tests.\n\nFile: d1jwnwk23d.py\n```python\ndef srs57t(n: int) -> int:\n \"\"\"Sum 1..n inclusive.\"\"\"\n if n < 0:\n raise ValueError(\"n must be non-negative\")\n total = 0\n for k in range(n): # BUG: should include n\n total += k\n return total\n```\n\nReturn unified diffs for d1jwnwk23d.py and test_d1jwnwk23d.py (pytest).\n\n*** Begin Patch\n*** Update File: d1jwnwk23d.py\n@@\n def srs57t(n: int) -> int:\n@@\n total = 0\n- for k in range(n): # BUG: should include n\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_d1jwnwk23d.py\n+import pytest\n+from d1jwnwk23d import srs57t\n+\n+def test_zero():\n+ assert srs57t(0) == 0\n+\n+def test_one():\n+ assert srs57t(1) == 1\n+\n+def test_small():\n+ assert srs57t(7) == 28\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ srs57t(-1)\n+\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Refactor to modern typed Python with immutability and tests.\n\nFile: bwkp_5j.py\n```python\nclass Ei1F59Vo:\n def __init__(self, name, values):\n self.name = name\n self.values = list(values)\n def add(self, v):\n self.values.append(v)\n def mean(self):\n s = 0\n for x in self.values:\n s += x\n return s / len(self.values)\n```\n\nReturn full new bwkp_5j.py and test_bwkp_5j.py.\n\n# bwkp_5j.py\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom typing import Iterable, Tuple\n\n@dataclass(frozen=True)\nclass Ei1F59Vo:\n name: str\n values: Tuple[float, ...]\n\n @staticmethod\n def create(name: str, values: Iterable[float]) -> \"Ei1F59Vo\":\n vals = tuple(float(v) for v in values)\n if not vals:\n raise ValueError(\"values must be non-empty\")\n return Ei1F59Vo(name=name, values=vals)\n\n def add(self, v: float) -> \"Ei1F59Vo\":\n return Ei1F59Vo(name=self.name, values=self.values + (float(v),))\n\n def mean(self) -> float:\n return sum(self.values) / len(self.values)\n\n# test_bwkp_5j.py\nimport pytest\nfrom bwkp_5j import Ei1F59Vo\n\ndef test_mean_and_add():\n c = Ei1F59Vo.create(\"a\", [1, 2, 3])\n assert c.mean() == 2.0\n assert c.add(5).mean() == (1 + 2 + 3 + 5) / 4\n\ndef test_empty_raises():\n with pytest.raises(ValueError):\n Ei1F59Vo.create(\"x\", [])", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Task type: compiler_frontend\nScenario: payment ledger\nDomain focus: fault injection & chaos engineering\nPrimary language: rust\nDifficulty: hard\nScale/SLO: p99 < 50ms\nComponent: component_nqeueyfp\nConstraints: include failure modes and recovery, include backward compatibility and migration plan, include security threat model (defensive only), include verification strategy, explicit contracts and invariants, include test vectors and fuzz strategy, include performance model and limits\nAssume crash-only processes; recovery must be deterministic.\nDeliverable: Design a DSL language frontend: lexer/parser, AST, type checking, error reporting, and tests.\n\nOutput: elite engineering answer optimized for correctness, performance, and operability.\n**Contract**\n- Inputs validated at the boundary; explicit error taxonomy.\n- Idempotency for side effects via request_id; deterministic replay.\n- Backward compatibility: additive changes by default; versioned breaking changes.\n**Invariants**\n- Determinism: replay of the same event log yields identical outputs.\n- Liveness: under bounded faults and stable network, progress occurs.\n- Safety: state transitions preserve invariants; no partial commit leaks.\n**Failure modes & recovery**\n- Data corruption: checksums + scrubber; quarantine and rebuild from replicas/snapshots.\n- Crash during commit: WAL replay completes or transaction aborts; no torn writes.\n- Network partition: minority cannot commit; clients receive retriable errors.\n**Security posture (defensive)**\n- Threat model: auth/authz, injection, replay/abuse, supply chain.\n- Least privilege; secrets in managed store; audit logs for sensitive ops.\n- Input normalization, parameterized queries, path traversal protections.\n**Verification strategy**\n- Fuzzing of parsers/framers/validators with corpus seeds.\n- Deterministic simulation with fault injection (crash/partition/latency).\n- Property tests against a pure reference model (state machine).\n\n**Snippet**\n```text\nImplementation sketch: factor pure state-machine core; adapters for I/O; add deterministic replay log.\n```\nHard checks: fault injection tests gate merges; perf thresholds enforced in CI.", "source": "WithinUsAI/Omega_Genesis_Coder_100k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Fix a bug and add tests.\n\nFile: gsjq9n.py\n```python\ndef d53109c86m(n: int) -> int:\n \"\"\"Sum 1..n inclusive.\"\"\"\n if n < 0:\n raise ValueError(\"n must be non-negative\")\n total = 0\n for k in range(n): # BUG: should include n\n total += k\n return total\n```\n\nReturn unified diffs for gsjq9n.py and test_gsjq9n.py (pytest).\n\n*** Begin Patch\n*** Update File: gsjq9n.py\n@@\n def d53109c86m(n: int) -> int:\n@@\n total = 0\n- for k in range(n): # BUG: should include n\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_gsjq9n.py\n+import pytest\n+from gsjq9n import d53109c86m\n+\n+def test_zero():\n+ assert d53109c86m(0) == 0\n+\n+def test_one():\n+ assert d53109c86m(1) == 1\n+\n+def test_small():\n+ assert d53109c86m(7) == 28\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ d53109c86m(-1)\n+\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Add a clear docstring and type hints to this function:\n\n```python\ndef f59537(s):\n return ''.join(x for x in s if x.isalnum()).lower()\n```\n\n```python\nfrom __future__ import annotations\n\ndef f59537(s: str) -> str:\n \"\"\"Normalize a string: keep only alphanumerics and lowercase the result.\"\"\"\n return \"\".join(ch for ch in s if ch.isalnum()).lower()\n```", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Task type: ml_system_design\nScenario: real-time notification hub\nDomain focus: stream processing\nPrimary language: rust\nDifficulty: expert+\nScale/SLO: p99 < 150ms\nComponent: component_bpcqzskz\nConstraints: include performance model and limits, include failure modes and recovery, avoid data races and undefined behavior, include backward compatibility and migration plan, include security threat model (defensive only), include verification strategy, explicit contracts and invariants\nAssume crash-only processes; recovery must be deterministic.\nDeliverable: Design end-to-end ML system: data contracts, training, evaluation, registry, serving, monitoring, and rollback.\n\nOutput: rigorous design + invariants + verification plan + implementation sketch.\n**Contract**\n- Inputs validated at the boundary; explicit error taxonomy.\n- Idempotency for side effects via request_id; deterministic replay.\n- Backward compatibility: additive changes by default; versioned breaking changes.\n**Invariants**\n- Liveness: under bounded faults and stable network, progress occurs.\n- Safety: state transitions preserve invariants; no partial commit leaks.\n- Isolation: tenant boundary enforced; no cross-tenant reads/writes.\n**Failure modes & recovery**\n- Network partition: minority cannot commit; clients receive retriable errors.\n- Crash during commit: WAL replay completes or transaction aborts; no torn writes.\n- Data corruption: checksums + scrubber; quarantine and rebuild from replicas/snapshots.\n**Security posture (defensive)**\n- Threat model: auth/authz, injection, replay/abuse, supply chain.\n- Least privilege; secrets in managed store; audit logs for sensitive ops.\n- Input normalization, parameterized queries, path traversal protections.\n**Verification strategy**\n- Deterministic simulation with fault injection (crash/partition/latency).\n- Canary + shadow traffic; invariants checked in production via assertions/metrics.\n- Property tests against a pure reference model (state machine).\n\n**Snippet**\n```text\nImplementation sketch: factor pure state-machine core; adapters for I/O; add deterministic replay log.\n```\nExpert+ checks: mechanized invariants (or exhaustive model checking), adversarial fuzzing, and multi-region failure drills.", "source": "WithinUsAI/Omega_Genesis_Coder_100k"} {"text": "Task type: query_optimizer\nScenario: document indexing pipeline\nDomain focus: compiler toolchains\nPrimary language: typescript\nDifficulty: expert+\nScale/SLO: 1M msgs/min\nComponent: component_elnpvrer\nConstraints: assume adversarial inputs; validate everything, include security threat model (defensive only), include test vectors and fuzz strategy, include performance model and limits, explicit contracts and invariants, include verification strategy\nAssume crash-only processes; recovery must be deterministic.\nDeliverable: Design a cost-based optimizer slice: logical rules, physical operators, and cost model. Include regression tests and query-plan explain examples.\n\nOutput: rigorous design + invariants + verification plan + implementation sketch.\n**Contract**\n- Inputs validated at the boundary; explicit error taxonomy.\n- Idempotency for side effects via request_id; deterministic replay.\n- Backward compatibility: additive changes by default; versioned breaking changes.\n**Invariants**\n- Determinism: replay of the same event log yields identical outputs.\n- Isolation: tenant boundary enforced; no cross-tenant reads/writes.\n- Safety: state transitions preserve invariants; no partial commit leaks.\n**Failure modes & recovery**\n- Network partition: minority cannot commit; clients receive retriable errors.\n- Crash during commit: WAL replay completes or transaction aborts; no torn writes.\n- Data corruption: checksums + scrubber; quarantine and rebuild from replicas/snapshots.\n**Security posture (defensive)**\n- Threat model: auth/authz, injection, replay/abuse, supply chain.\n- Least privilege; secrets in managed store; audit logs for sensitive ops.\n- Input normalization, parameterized queries, path traversal protections.\n**Verification strategy**\n- Fuzzing of parsers/framers/validators with corpus seeds.\n- Canary + shadow traffic; invariants checked in production via assertions/metrics.\n- Property tests against a pure reference model (state machine).\n\n**Snippet**\n```python\n# Minimal cost model skeleton\nfrom dataclasses import dataclass\n\n@dataclass(frozen=True)\nclass Plan:\n op: str\n cost: float\n children: tuple[\"Plan\", ...] = ()\n\ndef choose_best(plans: list[Plan]) -> Plan:\n return min(plans, key=lambda p: p.cost)\n```\n\nExpert+ checks: mechanized invariants (or exhaustive model checking), adversarial fuzzing, and multi-region failure drills.", "source": "WithinUsAI/Omega_Genesis_Coder_100k"} {"text": "Implement an ML engineering workflow for gaming focusing on search + pagination.\nTarget platform: ML (training + serving).\nRequirements: data contract, training loop, evaluation, model registry, serving API, monitoring.\nConstraints: must be observable (logs/metrics/traces), must include type hints where applicable, must include clear error handling, must be production-ready, must be secure-by-default.\nDifficulty: hard. Include rollback strategy.\n\nOutput: design + implementation guidance suitable for shipping.\nDeliverable: ML engineering blueprint (training + serving + monitoring), safe and production-oriented.\n\n**Data contract**\n- Define feature schema + ranges; validate at training and serving.\n\n**Training**\n- Deterministic split; baseline model; track metrics (AUC/F1/latency).\n- Store artifacts: model, config, feature stats.\n\n**Registry**\n- Promote models via approval gates; record lineage.\n\n**Serving**\n- Separate inference service with `/predict`.\n- Input validation + default handling; timeouts.\n\n**Monitoring**\n- Data drift: feature distribution checks.\n- Performance: online metrics + periodic labels; alert on regression.\n\nMinimal serving skeleton (FastAPI-ish):\n```python\n# validate input -> vectorize -> model.predict_proba -> return\n```\n\n\nHard-mode checks: concurrency safety, idempotency, and rollback validated; add chaos tests where feasible.", "source": "WithinUsAI/GOD_Coder_100k"} {"text": "Build an elite-grade solution in the domain of sre/observability for scenario: payment processing.\nPrimary language: rust.\nDifficulty: medium.\nConstraints: include invariants and failure modes, make the interface contract explicit, document performance characteristics, avoid undefined behavior and data races, provide rollout and rollback guidance.\nComponent: component_egkmhgb.\nAssume crash-only design; recovery must be deterministic.\nTask: Provide threat model, secure-by-default design, and defensive implementation patterns. No offensive/exploit content; focus on prevention and detection.\n\nOutput: elite-grade engineering answer with contracts, edge cases, and verification.\nOutput: threat model + defensive design + detection.\n\n**Threat model**\n- Auth: token theft → short-lived tokens, rotation, audience checks\n- AuthZ: privilege escalation → centralized policy checks, tenant isolation tests\n- Input: injection → strict validation, parameterized queries, output encoding\n- Supply chain: dependencies → lockfiles, signature verification, SBOM\n\n**Defensive patterns**\n- Idempotency keys for side effects; replay-safe handlers\n- Secrets in managed store; never logs\n- Audit logging for sensitive ops; tamper-evident storage\n\n**Detection**\n- Alert on unusual auth failures, access pattern anomalies, and data exfil signals.\n\n\nChecks: boundary validation and deterministic behavior verified.", "source": "WithinUsAI/Elite_GOD_Coder_100k"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: Project domain: job scheduler\nImplementation stack: ASP.NET Core, SQL Server, EF Core, xUnit, Docker\nSoftware delivery problem: dead-letter queue replay\nTask type: incident_to_remediation\nDifficulty: medium\n\nReturn a complete delivery-grade response with:\n- diagnosis or design reasoning\n- implementation\n- test plan or tests\n- rollout plan\n- rollback or compatibility note\n- verification commands\n\nRepository sketch:\nrepo/\n scripts/\n run.sh\n deploy.sh\n tests/\n smoke.sh\n\nFocus: Focus on shipping production software with rollout safety, acceptance criteria, telemetry, and maintenance quality.\n\nassistant: Diagnosis:\n- Root cause or delivery blocker: dead-letter queue replay needs both implementation work and a safe shipping plan.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```bash\n#!/usr/bin/env bash\nset -euo pipefail\n\ninput=\"${1:-}\"\nif [[ -z \"$input\" ]]; then\n echo \"missing input\" >&2\n exit 1\nfi\n\nprintf '%s\n' \"$input\" | tr -d '\r'\n```\n\nTests:\n```bash\noutput=\"$(bash scripts/run.sh \"abc\")\"\ntest \"$output\" = \"abc\"\n```\n\nVerification:\n- `bash tests/smoke.sh`\n- `shellcheck scripts/*.sh`\n\nEngineering notes:\n- Language: Bash\n- Framework/tooling: GNU coreutils\n- Stack context: ASP.NET Core, SQL Server, EF Core, xUnit, Docker\n- Domain: job scheduler\n- Task type: incident_to_remediation\n- Difficulty: medium\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "Create a comprehensive test plan and automated tests for A/B experimentation in a enterprise SaaS product.\nTarget platform: mobile (iOS Swift).\nRequirements: unit/integration tests, edge cases, load tests strategy, and CI gates.\nConstraints: must avoid global state, must be secure-by-default, must include clear error handling.\nDifficulty: hard. Assume mobile clients are occasionally offline.\n\nOutput: production-oriented blueprint with code where appropriate.\nDeliverable: test plan + automation guidance.\n\n**Unit tests**\n- Validation: malformed payloads rejected with correct codes.\n- AuthZ: tenant boundary enforced.\n- Idempotency: replay returns same response; conflicting reuse yields 409.\n\n**Integration tests**\n- DB transaction behavior; unique constraints.\n- Cache behavior: correctness under concurrent requests.\n\n**Load tests**\n- 10k RPS target: measure p95 latency, error rate, saturation.\n\n**CI gates**\n- Lint + typecheck + unit tests required.\n- Coverage threshold for critical modules.\n- Block merge on flaky test detection.\n\n\nHard-mode checks: concurrency safety, idempotency, and rollback validated; add chaos tests where feasible.", "source": "WithinUsAI/GOD_Coder_100k"} {"text": "Design a small, production-grade Python API for CLI tooling.\nRequirements: define data models and interfaces, implement reference version, include tests.\nConstraints: must avoid global state, must include docstrings.\nDifficulty: medium. Support both Windows and POSIX paths correctly.\n\nDeliverable: production-ready reference solution.\nArchitecture:\n- Public facade class coordinating concerns (parsing, validation, persistence)\n- Small pure functions for testability\n- No global state; dependency injection for filesystem I/O\n\n```python\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom pathlib import Path\nfrom typing import Protocol, Iterable\nimport json\n\nclass Store(Protocol):\n def write_text(self, path: Path, data: str) -> None: ...\n\nclass FSStore:\n def write_text(self, path: Path, data: str) -> None:\n path.parent.mkdir(parents=True, exist_ok=True)\n path.write_text(data, encoding=\"utf-8\")\n\n@dataclass(frozen=True, slots=True)\nclass Item:\n name: str\n qty: int\n\ndef parse_items(lines: Iterable[str]) -> list[Item]:\n out: list[Item] = []\n for i, line in enumerate(lines, 1):\n s = line.strip()\n if not s:\n continue\n obj = json.loads(s)\n if not isinstance(obj, dict):\n raise ValueError(f\"line {i}: expected object\")\n name = obj.get(\"name\")\n qty = obj.get(\"qty\")\n if not isinstance(name, str) or not name:\n raise ValueError(f\"line {i}: name must be str\")\n if not isinstance(qty, int) or qty < 0:\n raise ValueError(f\"line {i}: qty must be non-negative int\")\n out.append(Item(name, qty))\n return out\n\nclass InventoryWriter:\n def __init__(self, base_dir: Path, store: Store | None = None) -> None:\n self._base = base_dir\n self._store: Store = store or FSStore()\n\n def write(self, rel_path: str, items: list[Item]) -> Path:\n dst = (self._base / rel_path).resolve()\n base = self._base.resolve()\n if dst != base and base not in dst.parents:\n raise ValueError(\"unsafe path traversal\")\n payload = json.dumps([item.__dict__ for item in items], ensure_ascii=False)\n self._store.write_text(dst, payload)\n return dst\n```\n\n```python\nimport json\nfrom pathlib import Path\nimport pytest\nfrom module_under_test import InventoryWriter, parse_items\n\ndef test_parse_items_valid():\n lines = [json.dumps({\"name\":\"x\",\"qty\":1})]\n assert parse_items(lines)[0].name == \"x\"\n\ndef test_writer_blocks_traversal(tmp_path: Path):\n w = InventoryWriter(tmp_path)\n with pytest.raises(ValueError):\n w.write(\"../evil.json\", [])\n```", "source": "WithinUsAI/python_GOD_coder_100k"} {"text": "Build an elite-grade solution in the domain of operating systems for scenario: event ingestion.\nPrimary language: python.\nDifficulty: hard.\nConstraints: make the interface contract explicit, provide rollout and rollback guidance, document performance characteristics.\nComponent: component_qcuhxeh.\nAssume schema changes every sprint; must be backward compatible.\nTask: Implement a concurrency primitive or subsystem (lock-free queue, thread pool, async runtime component). Explain memory ordering and correctness arguments; include stress tests.\n\nOutput: rigorous solution with invariants, failure modes, and performance notes.\nOutput: correctness-focused concurrency primitive + stress tests.\n\n**Primitive**\n- Bounded MPMC queue with backpressure (blocking push/pop) OR lock-free SPSC ring buffer.\n\n**Correctness notes**\n- For lock-free: use acquire/release semantics on head/tail indices.\n- Avoid ABA by monotonic counters; ring index = counter % capacity.\n\n**Stress tests**\n- Multi-thread producers/consumers; assert item multiset preserved.\n- Use time-bounded randomized schedules; detect deadlocks.\n\n\nHard checks: failure injection tests and performance regressions gated.", "source": "WithinUsAI/Elite_GOD_Coder_100k"} {"text": "Write pytest tests for `f89535`.\n\n```python\ndef f89535(a: int, b: int) -> int:\n return a*a + b*b\n```\nInclude edge cases and a property-style check.\n\n```python\nimport random\nfrom m98505 import f89535\n\ndef test_known():\n assert f89535(3,4) == 25\n\ndef test_zero():\n assert f89535(0,0) == 0\n\ndef test_property_nonnegative():\n for _ in range(200):\n a=random.randint(-50,50)\n b=random.randint(-50,50)\n assert f89535(a,b) >= 0\n```", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Write pytest tests for `f85305`.\n\n```python\ndef f85305(a: int, b: int) -> int:\n return a*a + b*b\n```\nInclude edge cases and a property-style check.\n\n```python\nimport random\nfrom m83615 import f85305\n\ndef test_known():\n assert f85305(3,4) == 25\n\ndef test_zero():\n assert f85305(0,0) == 0\n\ndef test_property_nonnegative():\n for _ in range(200):\n a=random.randint(-50,50)\n b=random.randint(-50,50)\n assert f85305(a,b) >= 0\n```", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Write pytest tests for `f97014`.\n\n```python\ndef f97014(a: int, b: int) -> int:\n return a*a + b*b\n```\nInclude edge cases and a property-style check.\n\n```python\nimport random\nfrom m71002 import f97014\n\ndef test_known():\n assert f97014(3,4) == 25\n\ndef test_zero():\n assert f97014(0,0) == 0\n\ndef test_property_nonnegative():\n for _ in range(200):\n a=random.randint(-50,50)\n b=random.randint(-50,50)\n assert f97014(a,b) >= 0\n```", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Write pytest tests for `f72294`.\n\n```python\ndef f72294(a: int, b: int) -> int:\n return a*a + b*b\n```\nInclude edge cases and a property-style check.\n\n```python\nimport random\nfrom m96042 import f72294\n\ndef test_known():\n assert f72294(3,4) == 25\n\ndef test_zero():\n assert f72294(0,0) == 0\n\ndef test_property_nonnegative():\n for _ in range(200):\n a=random.randint(-50,50)\n b=random.randint(-50,50)\n assert f72294(a,b) >= 0\n```", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Task type: perf_microarchitecture\nScenario: rate limit gateway\nDomain focus: program synthesis (safe)\nPrimary language: go\nDifficulty: expert+\nScale/SLO: multi-region active-active\nComponent: component_nknrdsil\nConstraints: include security threat model (defensive only), include verification strategy, include backward compatibility and migration plan, include performance model and limits, assume adversarial inputs; validate everything, include test vectors and fuzz strategy\nAssume strict auditability and replayable history.\nDeliverable: Provide performance engineering plan: profiling, hot-path redesign, cache behavior assumptions, and microbench harness.\n\nOutput: rigorous design + invariants + verification plan + implementation sketch.\n**Contract**\n- Inputs validated at the boundary; explicit error taxonomy.\n- Idempotency for side effects via request_id; deterministic replay.\n- Backward compatibility: additive changes by default; versioned breaking changes.\n**Invariants**\n- Safety: state transitions preserve invariants; no partial commit leaks.\n- Determinism: replay of the same event log yields identical outputs.\n- Isolation: tenant boundary enforced; no cross-tenant reads/writes.\n**Failure modes & recovery**\n- Duplicate requests: de-duplicate by (tenant, request_id) returning cached response.\n- Data corruption: checksums + scrubber; quarantine and rebuild from replicas/snapshots.\n- Crash during commit: WAL replay completes or transaction aborts; no torn writes.\n**Security posture (defensive)**\n- Threat model: auth/authz, injection, replay/abuse, supply chain.\n- Least privilege; secrets in managed store; audit logs for sensitive ops.\n- Input normalization, parameterized queries, path traversal protections.\n**Verification strategy**\n- Fuzzing of parsers/framers/validators with corpus seeds.\n- Deterministic simulation with fault injection (crash/partition/latency).\n- Property tests against a pure reference model (state machine).\n\n**Snippet**\n```text\nImplementation sketch: factor pure state-machine core; adapters for I/O; add deterministic replay log.\n```\nExpert+ checks: mechanized invariants (or exhaustive model checking), adversarial fuzzing, and multi-region failure drills.", "source": "WithinUsAI/Omega_Genesis_Coder_100k"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: Project stack: Airflow, dbt, DuckDB, MinIO, pytest\nLanguage: C++\nDependency challenge: N+1 query explosion\nTask type: version_conflict_resolution\nDifficulty: hard\n\nFix this as a senior engineer.\nRequired:\n- identify the version or compatibility failure mode\n- produce the corrected config/code/build patch\n- explain rollback-safe migration notes\n- add regression tests or reproducibility checks\n- include concrete verification commands\n\nRepository sketch:\nrepo/\n src/main.cpp\n src/service.cpp\n include/service.h\n tests/test_service.cpp\n CMakeLists.txt\n\nFocus: Focus on versioning, migrations, lockfiles, runtime compatibility, and secure dependency handling.\n\nassistant: Diagnosis:\n- Root cause: the issue around N+1 query explosion is a dependency, migration, or runtime-compatibility mismatch that needs a rollback-safe patch.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```cpp\n#include \n#include \n\nusing Payload = std::unordered_map;\n\nPayload normalize_payload(const Payload& in) {\n Payload out;\n for (const auto& [k, v] : in) {\n if (!v.empty()) out[k] = v;\n }\n return out;\n}\n```\n\nTests:\n```cpp\nTEST_CASE(\"normalize_payload filters empty values\") {\n Payload in{{\"id\",\"7\"},{\"name\",\"\"}};\n auto out = normalize_payload(in);\n REQUIRE(out.count(\"id\") == 1);\n REQUIRE(out.count(\"name\") == 0);\n}\n```\n\nVerification:\n- `cmake --build build`\n- `ctest --test-dir build`\n\nEngineering notes:\n- Language: C++\n- Framework/tooling: CMake\n- Stack context: Airflow, dbt, DuckDB, MinIO, pytest\n- Domain: job scheduler\n- Task type: version_conflict_resolution\n- Difficulty: hard\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "Build an elite-grade solution in the domain of ml systems for scenario: payment processing.\nPrimary language: sql.\nDifficulty: expert.\nConstraints: make the interface contract explicit, assume untrusted inputs; validate and sanitize, include tests or verification strategy.\nComponent: component_dmgsxnf.\nAssume 50k RPS and p99 < 250ms.\nTask: Optimize a hot path with profiling-driven approach; propose micro/meso optimizations, and supply a benchmark harness with acceptance thresholds.\n\nOutput: elite-grade engineering answer with contracts, edge cases, and verification.\nOutput: profiling-first optimization + benchmark harness.\n\n**Plan**\n1. Establish baseline with microbench + representative dataset.\n2. Profile (CPU, allocations, syscalls).\n3. Apply optimizations: reduce allocations, reuse buffers, batch I/O, vectorize parsing where safe.\n4. Validate with regression suite and perf thresholds.\n\n**Benchmark guidance**\n- Use p50/p95 and throughput; pin CPU frequency if possible.\n- Acceptance: p95 improves ≥ X% with no correctness regressions.\n\n\nExpert checks: state-machine reasoning, concurrency stress, and upgrade/rollback validated.", "source": "WithinUsAI/Elite_GOD_Coder_100k"} {"text": "Refactor to typed, mostly-immutable Python and add minimal tests.\n\n```python\nclass C16904:\n def __init__(self, values): self.values=list(values)\n def mean(self): return sum(self.values)/len(self.values)\n```\nReturn `m93608.py` and `test_m93608.py`.\n\n```python\n# m93608.py\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom typing import Iterable, Tuple\n\n@dataclass(frozen=True)\nclass C16904:\n values: Tuple[float, ...]\n\n @staticmethod\n def create(values: Iterable[float]) -> \"C16904\":\n vals = tuple(float(v) for v in values)\n if not vals: raise ValueError(\"empty\")\n return C16904(vals)\n\n def mean(self) -> float:\n return sum(self.values)/len(self.values)\n```\n\n```python\n# test_m93608.py\nimport pytest\nfrom m93608 import C16904\n\ndef test_mean():\n assert C16904.create([1,2,3]).mean() == 2.0\ndef test_empty():\n with pytest.raises(ValueError):\n C16904.create([])\n```", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Optimize while preserving behavior.\n\nFile: p2_om0iz3ltq.py\n```python\ndef p6fe_lw0_5i(xs):\n out = []\n for x in xs:\n if x not in out:\n out.append(x)\n return out\n```\n\nRequirements: preserve first-seen order; O(n) average; add types + docstring.\n\n# p2_om0iz3ltq.py\nfrom __future__ import annotations\nfrom typing import Iterable, List, Set, TypeVar\n\nT = TypeVar(\"T\")\n\ndef p6fe_lw0_5i(xs: Iterable[T]) -> List[T]:\n \"\"\"Return unique items preserving first-seen order.\"\"\"\n seen: Set[T] = set()\n out: List[T] = []\n for x in xs:\n if x in seen:\n continue\n seen.add(x)\n out.append(x)\n return out", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: Language: Go\nFramework/tooling: Fiber\nDomain: payments platform\nLogic challenge: race condition on worker shutdown\nTask type: parser_validation_logic\nDifficulty: medium\n\nReturn a rigorous engineering answer:\n- identify the hidden root cause or logical failure\n- present the corrected implementation\n- add tests that prove the fix\n- list verification commands\n- explain why naive fixes are insufficient when relevant\n\nRepository sketch:\nrepo/\n cmd/server/main.go\n internal/service/service.go\n internal/store/store.go\n internal/api/api.go\n service_test.go\n go.mod\n\nFocus: Focus on strong structured logic with edge cases, data validation, and concurrency safety.\n\nassistant: Diagnosis:\n- Root cause: the failure around race condition on worker shutdown is caused by missing validation, weak edge-case handling, or unsafe lifecycle behavior in the current implementation.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```go\npackage service\n\nimport \"fmt\"\n\nfunc NormalizePayload(payload map[string]any) map[string]any {\n\tout := make(map[string]any)\n\tfor k, v := range payload {\n\t\tif v == nil {\n\t\t\tcontinue\n\t\t}\n\t\tout[k] = v\n\t}\n\treturn out\n}\n\nfunc Handle(payload map[string]any) (map[string]any, error) {\n\tclean := NormalizePayload(payload)\n\tif _, ok := clean[\"id\"]; !ok {\n\t\treturn nil, fmt.Errorf(\"missing id\")\n\t}\n\treturn map[string]any{\"ok\": true, \"data\": clean}, nil\n}\n```\n\nTests:\n```go\npackage service\n\nimport \"testing\"\n\nfunc TestHandle(t *testing.T) {\n\tgot, err := Handle(map[string]any{\"id\": 7, \"name\": \"ok\", \"unused\": nil})\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tif got[\"ok\"] != true {\n\t\tt.Fatalf(\"expected ok=true\")\n\t}\n\tif _, err := Handle(map[string]any{\"name\": \"x\"}); err == nil {\n\t\tt.Fatalf(\"expected missing id error\")\n\t}\n}\n```\n\nVerification:\n- `go test ./...`\n- `go vet ./...`\n\nEngineering notes:\n- Language: Go\n- Framework/tooling: Fiber\n- Stack context: Airflow, dbt, DuckDB, MinIO, pytest\n- Domain: payments platform\n- Task type: parser_validation_logic\n- Difficulty: medium\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "Fix the bug and add pytest tests.\n\n```python\ndef f98255(n: int) -> int:\n # sum 1..n inclusive\n if n < 0: raise ValueError\n total = 0\n for k in range(n): # BUG\n total += k\n return total\n```\nReturn unified diffs for `m85465.py` and `test_m85465.py`.\n\n*** Begin Patch\n*** Update File: m85465.py\n@@\n def f98255(n: int) -> int:\n@@\n- for k in range(n): # BUG\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_m85465.py\n+import pytest\n+from m85465 import f98255\n+\n+def test_small():\n+ assert f98255(7) == 28\n+\n+def test_zero():\n+ assert f98255(0) == 0\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ f98255(-1)\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Fix a bug and add tests.\n\nFile: n2spou.py\n```python\ndef dn8wi43arpy7(n: int) -> int:\n \"\"\"Sum 1..n inclusive.\"\"\"\n if n < 0:\n raise ValueError(\"n must be non-negative\")\n total = 0\n for k in range(n): # BUG: should include n\n total += k\n return total\n```\n\nReturn unified diffs for n2spou.py and test_n2spou.py (pytest).\n\n*** Begin Patch\n*** Update File: n2spou.py\n@@\n def dn8wi43arpy7(n: int) -> int:\n@@\n total = 0\n- for k in range(n): # BUG: should include n\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_n2spou.py\n+import pytest\n+from n2spou import dn8wi43arpy7\n+\n+def test_zero():\n+ assert dn8wi43arpy7(0) == 0\n+\n+def test_one():\n+ assert dn8wi43arpy7(1) == 1\n+\n+def test_small():\n+ assert dn8wi43arpy7(7) == 28\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ dn8wi43arpy7(-1)\n+\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Build an elite-grade solution in the domain of sre/observability for scenario: inventory & ordering.\nPrimary language: go.\nDifficulty: hard.\nConstraints: avoid undefined behavior and data races, design for backward compatibility and migrations, assume untrusted inputs; validate and sanitize, include invariants and failure modes, include tests or verification strategy.\nComponent: component_avtkmej.\nAssume strict auditability and replayable history.\nTask: Implement or outline a storage/indexing subsystem (LSM/B-Tree, WAL, snapshots). Include transaction/consistency considerations and benchmark plan.\n\nOutput: production blueprint plus correctness arguments and test strategy.\nOutput: storage design + WAL + compaction + benchmarks.\n\n**Design**\n- WAL (append-only) for durability; fsync policy configurable.\n- Memtable (in-memory) → flush to immutable SSTables.\n- LSM compaction tiers; bloom filters per SSTable for point-lookups.\n- Manifest tracks SSTable set; atomic pointer swap on updates.\n\n**Correctness**\n- Crash recovery: replay WAL to rebuild memtable; manifest ensures last consistent set.\n- Reads: merge memtable + SSTables newest→oldest; tombstones override older values.\n\n**Bench plan**\n- Workloads: write-heavy, read-heavy, mixed; measure p50/p95 latency and write amplification.\n- Track compaction debt and space amplification.\n\n**Test plan**\n- Fuzz crash points: kill after WAL append / after manifest update; verify invariants on restart.\n\n\nHard checks: failure injection tests and performance regressions gated.", "source": "WithinUsAI/Elite_GOD_Coder_100k"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: System domain: reporting engine\nStack: Spring Boot, PostgreSQL, JUnit, Gradle, Docker, GitHub Actions\nCross-layer incident: unsafe deserialization\nTask type: observability_debug_fix\nDifficulty: hard\n\nSolve this as a complete-project engineer.\nOutput must include:\n- root cause across layers\n- final implementation patch\n- tests touching at least two layers\n- deployment or observability note\n- verification commands\n\nRepository sketch:\nrepo/\n src/\n api.ts\n service.ts\n schema.ts\n tests/\n api.test.ts\n package.json\n\nFocus: Focus on multi-layer debugging across frontend, backend, database, CI, caching, and deployment.\n\nassistant: Diagnosis:\n- Root cause: unsafe deserialization crosses service boundaries, so the fix must align code, contracts, tests, and deployment behavior.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```ts\ntype Payload = Record;\n\nexport function normalizePayload(payload: Payload): Payload {\n if (!payload || typeof payload !== \"object\" || Array.isArray(payload)) {\n throw new TypeError(\"payload must be a plain object\");\n }\n return Object.fromEntries(\n Object.entries(payload)\n .filter(([, value]) => value !== null && value !== undefined)\n .map(([key, value]) => [String(key).trim(), value])\n );\n}\n\nexport function handleUnsafeDeserialization(payload: Payload) {\n const clean = normalizePayload(payload);\n if (!(\"id\" in clean)) {\n return { ok: false, data: {}, error: \"missing id\" };\n }\n return { ok: true, data: clean, error: null };\n}\n```\n\nTests:\n```ts\nimport { describe, it, expect } from \"vitest\";\nimport { handleUnsafeDeserialization } from \"../src/service\";\n\ndescribe(\"handler\", () => {\n it(\"accepts valid input\", () => {\n expect(handleUnsafeDeserialization({ id: 7, name: \"ok\", unused: null })).toEqual({\n ok: true,\n data: { id: 7, name: \"ok\" },\n error: null\n });\n });\n\n it(\"rejects missing id\", () => {\n expect(handleUnsafeDeserialization({ name: \"x\" }).error).toMatch(/missing id/);\n });\n});\n```\n\nVerification:\n- `npm test`\n- `npm run typecheck`\n- `npm run lint`\n\nEngineering notes:\n- Language: TypeScript\n- Framework/tooling: Node.js\n- Stack context: Spring Boot, PostgreSQL, JUnit, Gradle, Docker, GitHub Actions\n- Domain: reporting engine\n- Task type: observability_debug_fix\n- Difficulty: hard\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "Build an elite-grade solution in the domain of stream processing for scenario: document indexing.\nPrimary language: rust.\nDifficulty: hard.\nConstraints: document performance characteristics, make the interface contract explicit, design for backward compatibility and migrations, assume untrusted inputs; validate and sanitize, include tests or verification strategy.\nComponent: component_wbolyps.\nAssume compliance requires data deletion with proofs.\nTask: Design a replication/consistency approach (e.g., leader-based, quorum reads/writes). Provide message flows, failure handling, and a minimal reference implementation skeleton.\n\nOutput: production blueprint plus correctness arguments and test strategy.\nOutput: replication design + failure handling + minimal skeleton.\n\n**Model**\n- Leader-based replication with term + log index.\n- Quorum acks for durability: write committed when majority acks.\n- Read options: leader-read (linearizable) or quorum-read (monotonic if using read-index).\n\n**Message flow (write)**\n1. Client → Leader: Put(request_id, payload)\n2. Leader appends to log, sends AppendEntries to followers\n3. Followers append + ack\n4. On majority ack: commit index advances; apply to state machine; respond to client\n\n**Failure modes**\n- Leader crash: new election; uncommitted entries may be rolled back.\n- Partition: minority side cannot commit.\n- Duplicate requests: deduplicate by request_id stored in state.\n\n**Skeleton (Go pseudo)**\n```go\ntype Entry struct { Term uint64; Index uint64; Cmd []byte }\ntype Node struct {\n id int\n term uint64\n log []Entry\n commit uint64\n seen map[string][]byte // request_id -> response\n}\n```\n\n**Verification**\n- Invariant: committed index never decreases.\n- Property: if a write is committed, all future leaders contain it.\n- Test with simulated partitions and crash/restart.\n\n\nHard checks: failure injection tests and performance regressions gated.", "source": "WithinUsAI/Elite_GOD_Coder_100k"} {"text": "Write a thorough test suite for a Python component used for metrics aggregation.\nRequirements: cover edge cases, invalid inputs, and behavior invariants.\nConstraints: must be streaming-friendly, must include tests, must provide clear error messages.\nDifficulty: hard. Handle empty inputs and malformed records gracefully.\n\nDeliverable: corrected code and verification tests.\n```python\n# tests (pytest-style) for a module providing: normalize(), parse_lines(), compute_stats()\nimport math\nimport pytest\n\ndef test_normalize_idempotent(module_under_test):\n x = \" A\\tB \"\n assert module_under_test.normalize(module_under_test.normalize(x)) == module_under_test.normalize(x)\n\ndef test_parse_lines_rejects_invalid(module_under_test):\n with pytest.raises(ValueError):\n module_under_test.parse_lines([\"\", \"???\", None]) # type: ignore[arg-type]\n\ndef test_compute_stats_basic(module_under_test):\n data = [1, 2, 3, 4]\n s = module_under_test.compute_stats(data)\n assert s.count == 4\n assert s.total == 10\n assert math.isclose(s.mean, 2.5)\n```", "source": "WithinUsAI/python_GOD_coder_100k"} {"text": "Optimize while preserving behavior and order.\n\n```python\ndef f01564(xs):\n out=[]\n for x in xs:\n if x not in out: out.append(x)\n return out\n```\nReturn `m71652.py` with types and O(n) average.\n\n```python\n# m71652.py\nfrom __future__ import annotations\nfrom typing import Iterable, List, Set, TypeVar\nT=TypeVar(\"T\")\n\ndef f01564(xs: Iterable[T]) -> List[T]:\n \"\"\"Unique items preserving first-seen order.\"\"\"\n seen: Set[T]=set()\n out: List[T]=[]\n for x in xs:\n if x in seen: continue\n seen.add(x); out.append(x)\n return out\n```", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Refactor to typed, mostly-immutable Python and add minimal tests.\n\n```python\nclass C37347:\n def __init__(self, values): self.values=list(values)\n def mean(self): return sum(self.values)/len(self.values)\n```\nReturn `m56719.py` and `test_m56719.py`.\n\n```python\n# m56719.py\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom typing import Iterable, Tuple\n\n@dataclass(frozen=True)\nclass C37347:\n values: Tuple[float, ...]\n\n @staticmethod\n def create(values: Iterable[float]) -> \"C37347\":\n vals = tuple(float(v) for v in values)\n if not vals: raise ValueError(\"empty\")\n return C37347(vals)\n\n def mean(self) -> float:\n return sum(self.values)/len(self.values)\n```\n\n```python\n# test_m56719.py\nimport pytest\nfrom m56719 import C37347\n\ndef test_mean():\n assert C37347.create([1,2,3]).mean() == 2.0\ndef test_empty():\n with pytest.raises(ValueError):\n C37347.create([])\n```", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Design a small, production-grade Python API for log processing.\nRequirements: define data models and interfaces, implement reference version, include tests.\nConstraints: stdlib-only, must handle Windows paths safely.\nDifficulty: easy. Support both Windows and POSIX paths correctly.\n\nDeliverable: implementation + tests.\nArchitecture:\n- Public facade class coordinating concerns (parsing, validation, persistence)\n- Small pure functions for testability\n- No global state; dependency injection for filesystem I/O\n\n```python\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom pathlib import Path\nfrom typing import Protocol, Iterable\nimport json\n\nclass Store(Protocol):\n def write_text(self, path: Path, data: str) -> None: ...\n\nclass FSStore:\n def write_text(self, path: Path, data: str) -> None:\n path.parent.mkdir(parents=True, exist_ok=True)\n path.write_text(data, encoding=\"utf-8\")\n\n@dataclass(frozen=True, slots=True)\nclass Item:\n name: str\n qty: int\n\ndef parse_items(lines: Iterable[str]) -> list[Item]:\n out: list[Item] = []\n for i, line in enumerate(lines, 1):\n s = line.strip()\n if not s:\n continue\n obj = json.loads(s)\n if not isinstance(obj, dict):\n raise ValueError(f\"line {i}: expected object\")\n name = obj.get(\"name\")\n qty = obj.get(\"qty\")\n if not isinstance(name, str) or not name:\n raise ValueError(f\"line {i}: name must be str\")\n if not isinstance(qty, int) or qty < 0:\n raise ValueError(f\"line {i}: qty must be non-negative int\")\n out.append(Item(name, qty))\n return out\n\nclass InventoryWriter:\n def __init__(self, base_dir: Path, store: Store | None = None) -> None:\n self._base = base_dir\n self._store: Store = store or FSStore()\n\n def write(self, rel_path: str, items: list[Item]) -> Path:\n dst = (self._base / rel_path).resolve()\n base = self._base.resolve()\n if dst != base and base not in dst.parents:\n raise ValueError(\"unsafe path traversal\")\n payload = json.dumps([item.__dict__ for item in items], ensure_ascii=False)\n self._store.write_text(dst, payload)\n return dst\n```\n\n```python\nimport json\nfrom pathlib import Path\nimport pytest\nfrom module_under_test import InventoryWriter, parse_items\n\ndef test_parse_items_valid():\n lines = [json.dumps({\"name\":\"x\",\"qty\":1})]\n assert parse_items(lines)[0].name == \"x\"\n\ndef test_writer_blocks_traversal(tmp_path: Path):\n w = InventoryWriter(tmp_path)\n with pytest.raises(ValueError):\n w.write(\"../evil.json\", [])\n```", "source": "WithinUsAI/python_GOD_coder_100k"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: Repository domain: data pipeline\nPrimary language: Go\nFramework/tooling: sqlc\nReported problem: timezone bug in reporting\nTask type: feature_delivery\nDifficulty: medium\n\nProduce a complete professional engineering response:\n1. Diagnose the root cause.\n2. Provide the corrected implementation or patch.\n3. Add tests.\n4. Add verification commands.\n5. Note edge cases and any migration or rollback risk.\n\nRepository sketch:\nrepo/\n cmd/server/main.go\n internal/service/service.go\n internal/store/store.go\n internal/api/api.go\n service_test.go\n go.mod\n\nQuality target:\n- Minimal diff unless redesign is clearly required\n- Production-ready code\n- No placeholders\n- Secure defaults\n- Clear acceptance of failure cases\n\nFocus: Focus on complete implementation quality, patch correctness, tests, and production readiness.\n\nassistant: Diagnosis:\n- Root cause: the failure around timezone bug in reporting is caused by missing validation, weak edge-case handling, or unsafe lifecycle behavior in the current implementation.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```go\npackage service\n\nimport \"fmt\"\n\nfunc NormalizePayload(payload map[string]any) map[string]any {\n\tout := make(map[string]any)\n\tfor k, v := range payload {\n\t\tif v == nil {\n\t\t\tcontinue\n\t\t}\n\t\tout[k] = v\n\t}\n\treturn out\n}\n\nfunc Handle(payload map[string]any) (map[string]any, error) {\n\tclean := NormalizePayload(payload)\n\tif _, ok := clean[\"id\"]; !ok {\n\t\treturn nil, fmt.Errorf(\"missing id\")\n\t}\n\treturn map[string]any{\"ok\": true, \"data\": clean}, nil\n}\n```\n\nTests:\n```go\npackage service\n\nimport \"testing\"\n\nfunc TestHandle(t *testing.T) {\n\tgot, err := Handle(map[string]any{\"id\": 7, \"name\": \"ok\", \"unused\": nil})\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tif got[\"ok\"] != true {\n\t\tt.Fatalf(\"expected ok=true\")\n\t}\n\tif _, err := Handle(map[string]any{\"name\": \"x\"}); err == nil {\n\t\tt.Fatalf(\"expected missing id error\")\n\t}\n}\n```\n\nVerification:\n- `go test ./...`\n- `go vet ./...`\n\nEngineering notes:\n- Language: Go\n- Framework/tooling: sqlc\n- Stack context: Airflow, dbt, DuckDB, MinIO, pytest\n- Domain: data pipeline\n- Task type: feature_delivery\n- Difficulty: medium\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "Build a data pipeline for a IoT telemetry product around webhooks.\nTarget platform: data (SQL + Python).\nRequirements: schema, ingestion, validation, backfills, and tests.\nConstraints: must be observable (logs/metrics/traces), must be production-ready, must include documentation/comments.\nDifficulty: expert. Assume untrusted input; validate everything.\n\nOutput: design + implementation guidance suitable for shipping.\nDeliverable: schema + ingestion + validation + backfill strategy.\n\n**Schema (example)**\n- events(event_id TEXT PK, tenant_id TEXT, ts TIMESTAMP, type TEXT, payload JSONB)\n\n**Ingestion**\n- Write to raw table first; validate; then materialize to curated tables.\n- Idempotency by event_id; enforce uniqueness.\n\n**Validation**\n- Reject missing tenant_id/type/ts.\n- Quarantine bad records with reason.\n\n**Backfills**\n- Re-run deterministic transforms from raw → curated.\n- Version transformations; store transform_version with outputs.\n\n**Tests**\n- Unit tests for validators and transforms.\n- Integration test: sample raw batch produces expected curated rows.\n\n\nHard-mode checks: concurrency safety, idempotency, and rollback validated; add chaos tests where feasible.", "source": "WithinUsAI/GOD_Coder_100k"} {"text": "Write a thorough test suite for a Python component used for file synchronization.\nRequirements: cover edge cases, invalid inputs, and behavior invariants.\nConstraints: must include type hints, must include docstrings, stdlib-only, must include tests.\nDifficulty: expert. Avoid quadratic behavior on large inputs.\n\nDeliverable: corrected code and verification tests.\n```python\n# tests (pytest-style) for a module providing: normalize(), parse_lines(), compute_stats()\nimport math\nimport pytest\n\ndef test_normalize_idempotent(module_under_test):\n x = \" A\\tB \"\n assert module_under_test.normalize(module_under_test.normalize(x)) == module_under_test.normalize(x)\n\ndef test_parse_lines_rejects_invalid(module_under_test):\n with pytest.raises(ValueError):\n module_under_test.parse_lines([\"\", \"???\", None]) # type: ignore[arg-type]\n\ndef test_compute_stats_basic(module_under_test):\n data = [1, 2, 3, 4]\n s = module_under_test.compute_stats(data)\n assert s.count == 4\n assert s.total == 10\n assert math.isclose(s.mean, 2.5)\n```", "source": "WithinUsAI/python_GOD_coder_100k"} {"text": "Improve typing and robustness of a Python module used for telemetry ingestion.\nRequirements: provide type-safe APIs (generics/protocols where appropriate) and include tests.\nConstraints: must include type hints, must be easy to extend, must handle Windows paths safely, must include tests.\nDifficulty: expert. Handle empty inputs and malformed records gracefully.\n\nDeliverable: production-ready reference solution.\n```python\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom typing import Callable, Generic, Iterable, Protocol, TypeVar\n\nT = TypeVar(\"T\")\nR = TypeVar(\"R\")\n\nclass Mapper(Protocol[T, R]):\n def __call__(self, x: T) -> R: ...\n\n@dataclass(frozen=True, slots=True)\nclass Batch(Generic[T]):\n items: tuple[T, ...]\n\ndef map_batch(batch: Batch[T], fn: Mapper[T, R]) -> Batch[R]:\n return Batch(items=tuple(fn(x) for x in batch.items))\n\ndef chunked(xs: Iterable[T], size: int) -> Iterable[Batch[T]]:\n if size <= 0:\n raise ValueError(\"size must be > 0\")\n buf: list[T] = []\n for x in xs:\n buf.append(x)\n if len(buf) == size:\n yield Batch(items=tuple(buf))\n buf.clear()\n if buf:\n yield Batch(items=tuple(buf))\n```\n\n```python\nimport pytest\nfrom module_under_test import Batch, map_batch, chunked\n\ndef test_map_batch():\n b = Batch(items=(1,2,3))\n assert map_batch(b, lambda x: x*2).items == (2,4,6)\n\ndef test_chunked():\n out = list(chunked([1,2,3,4,5], 2))\n assert [b.items for b in out] == [(1,2),(3,4),(5,)]\n```", "source": "WithinUsAI/python_GOD_coder_100k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Refactor to modern typed Python with immutability and tests.\n\nFile: rr7dgy.py\n```python\nclass H57Yzvuhi:\n def __init__(self, name, values):\n self.name = name\n self.values = list(values)\n def add(self, v):\n self.values.append(v)\n def mean(self):\n s = 0\n for x in self.values:\n s += x\n return s / len(self.values)\n```\n\nReturn full new rr7dgy.py and test_rr7dgy.py.\n\n# rr7dgy.py\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom typing import Iterable, Tuple\n\n@dataclass(frozen=True)\nclass H57Yzvuhi:\n name: str\n values: Tuple[float, ...]\n\n @staticmethod\n def create(name: str, values: Iterable[float]) -> \"H57Yzvuhi\":\n vals = tuple(float(v) for v in values)\n if not vals:\n raise ValueError(\"values must be non-empty\")\n return H57Yzvuhi(name=name, values=vals)\n\n def add(self, v: float) -> \"H57Yzvuhi\":\n return H57Yzvuhi(name=self.name, values=self.values + (float(v),))\n\n def mean(self) -> float:\n return sum(self.values) / len(self.values)\n\n# test_rr7dgy.py\nimport pytest\nfrom rr7dgy import H57Yzvuhi\n\ndef test_mean_and_add():\n c = H57Yzvuhi.create(\"a\", [1, 2, 3])\n assert c.mean() == 2.0\n assert c.add(5).mean() == (1 + 2 + 3 + 5) / 4\n\ndef test_empty_raises():\n with pytest.raises(ValueError):\n H57Yzvuhi.create(\"x\", [])", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Refactor to modern typed Python with immutability and tests.\n\nFile: ix0cmek.py\n```python\nclass I9Jw0G9:\n def __init__(self, name, values):\n self.name = name\n self.values = list(values)\n def add(self, v):\n self.values.append(v)\n def mean(self):\n s = 0\n for x in self.values:\n s += x\n return s / len(self.values)\n```\n\nReturn full new ix0cmek.py and test_ix0cmek.py.\n\n# ix0cmek.py\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom typing import Iterable, Tuple\n\n@dataclass(frozen=True)\nclass I9Jw0G9:\n name: str\n values: Tuple[float, ...]\n\n @staticmethod\n def create(name: str, values: Iterable[float]) -> \"I9Jw0G9\":\n vals = tuple(float(v) for v in values)\n if not vals:\n raise ValueError(\"values must be non-empty\")\n return I9Jw0G9(name=name, values=vals)\n\n def add(self, v: float) -> \"I9Jw0G9\":\n return I9Jw0G9(name=self.name, values=self.values + (float(v),))\n\n def mean(self) -> float:\n return sum(self.values) / len(self.values)\n\n# test_ix0cmek.py\nimport pytest\nfrom ix0cmek import I9Jw0G9\n\ndef test_mean_and_add():\n c = I9Jw0G9.create(\"a\", [1, 2, 3])\n assert c.mean() == 2.0\n assert c.add(5).mean() == (1 + 2 + 3 + 5) / 4\n\ndef test_empty_raises():\n with pytest.raises(ValueError):\n I9Jw0G9.create(\"x\", [])", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: Language: Rust\nFramework/tooling: Tokio\nDomain: team dashboard\nLogic challenge: path traversal on downloads\nTask type: cross_stack_outage_fix\nDifficulty: expert\n\nReturn a rigorous engineering answer:\n- identify the hidden root cause or logical failure\n- present the corrected implementation\n- add tests that prove the fix\n- list verification commands\n- explain why naive fixes are insufficient when relevant\n\nRepository sketch:\nrepo/\n src/main.rs\n src/lib.rs\n src/service.rs\n src/store.rs\n tests/integration.rs\n Cargo.toml\n\nFocus: Focus on staff-level problem solving with multi-file patches, rollout implications, performance and security tradeoffs.\n\nassistant: Diagnosis:\n- Staff-level diagnosis: path traversal on downloads impacts correctness, operability, and future maintenance, so the fix must be minimal where possible but complete where necessary.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```rust\nuse std::collections::HashMap;\n\npub fn normalize_payload(payload: HashMap) -> HashMap {\n payload\n .into_iter()\n .filter(|(_, v)| !v.trim().is_empty())\n .collect()\n}\n```\n\nTests:\n```rust\n#[test]\nfn normalize_payload_filters_empty_values() {\n use std::collections::HashMap;\n let mut payload = HashMap::new();\n payload.insert(\"id\".to_string(), \"7\".to_string());\n payload.insert(\"name\".to_string(), \"\".to_string());\n let out = normalize_payload(payload);\n assert!(out.contains_key(\"id\"));\n assert!(!out.contains_key(\"name\"));\n}\n```\n\nVerification:\n- `cargo test`\n- `cargo clippy -- -D warnings`\n\nEngineering notes:\n- Language: Rust\n- Framework/tooling: Tokio\n- Stack context: FastAPI, PostgreSQL, Redis, Celery, pytest, Docker\n- Domain: team dashboard\n- Task type: cross_stack_outage_fix\n- Difficulty: expert\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "Secure-by-default implementation for event-driven workflows in a content moderation product.\nTarget platform: data (SQL + Python).\nRequirements: threat model, input validation, authz/authn guidance, safe storage, tests.\nConstraints: must include documentation/comments, must be observable (logs/metrics/traces), must be secure-by-default, must be production-ready.\nDifficulty: expert. Assume untrusted input; validate everything.\n\nOutput: design + implementation guidance suitable for shipping.\nDeliverable: threat model + secure patterns (no offensive content).\n\n**Threat model**\n- Input: untrusted clients → validation required\n- Auth: token theft / privilege escalation → short-lived tokens + RBAC checks\n- Data: PII exposure → encryption at rest + access logging + least privilege\n- Webhooks/callbacks: SSRF → allowlist destinations + timeouts + egress controls\n\n**Secure implementation patterns**\n- Validate and normalize inputs at boundaries (API/CLI/file).\n- Use parameterized SQL; never string interpolate.\n- Prevent path traversal when writing files (resolve + base containment).\n- Use idempotency keys for side-effecting endpoints; safe retries.\n- Centralize authorization checks in one layer; test them.\n\n**Test checklist**\n- Invalid inputs rejected with clear error messages.\n- AuthZ tests for tenant boundary violations.\n- Replay/idempotency conflict test.\n\n\nHard-mode checks: concurrency safety, idempotency, and rollback validated; add chaos tests where feasible.", "source": "WithinUsAI/GOD_Coder_100k"} {"text": "Fix the bug and add pytest tests.\n\n```python\ndef f66125(n: int) -> int:\n # sum 1..n inclusive\n if n < 0: raise ValueError\n total = 0\n for k in range(n): # BUG\n total += k\n return total\n```\nReturn unified diffs for `m80875.py` and `test_m80875.py`.\n\n*** Begin Patch\n*** Update File: m80875.py\n@@\n def f66125(n: int) -> int:\n@@\n- for k in range(n): # BUG\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_m80875.py\n+import pytest\n+from m80875 import f66125\n+\n+def test_small():\n+ assert f66125(7) == 28\n+\n+def test_zero():\n+ assert f66125(0) == 0\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ f66125(-1)\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Refactor to modern typed Python with immutability and tests.\n\nFile: uax8cmgp09rz.py\n```python\nclass VyqwV5Jcu:\n def __init__(self, name, values):\n self.name = name\n self.values = list(values)\n def add(self, v):\n self.values.append(v)\n def mean(self):\n s = 0\n for x in self.values:\n s += x\n return s / len(self.values)\n```\n\nReturn full new uax8cmgp09rz.py and test_uax8cmgp09rz.py.\n\n# uax8cmgp09rz.py\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom typing import Iterable, Tuple\n\n@dataclass(frozen=True)\nclass VyqwV5Jcu:\n name: str\n values: Tuple[float, ...]\n\n @staticmethod\n def create(name: str, values: Iterable[float]) -> \"VyqwV5Jcu\":\n vals = tuple(float(v) for v in values)\n if not vals:\n raise ValueError(\"values must be non-empty\")\n return VyqwV5Jcu(name=name, values=vals)\n\n def add(self, v: float) -> \"VyqwV5Jcu\":\n return VyqwV5Jcu(name=self.name, values=self.values + (float(v),))\n\n def mean(self) -> float:\n return sum(self.values) / len(self.values)\n\n# test_uax8cmgp09rz.py\nimport pytest\nfrom uax8cmgp09rz import VyqwV5Jcu\n\ndef test_mean_and_add():\n c = VyqwV5Jcu.create(\"a\", [1, 2, 3])\n assert c.mean() == 2.0\n assert c.add(5).mean() == (1 + 2 + 3 + 5) / 4\n\ndef test_empty_raises():\n with pytest.raises(ValueError):\n VyqwV5Jcu.create(\"x\", [])", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Build an elite-grade solution in the domain of edge/IoT for scenario: multi-tenant SaaS.\nPrimary language: go.\nDifficulty: hard.\nConstraints: include tests or verification strategy, assume untrusted inputs; validate and sanitize, provide rollout and rollback guidance.\nComponent: component_afrwfvm.\nAssume strict auditability and replayable history.\nTask: Define properties/invariants and implement property-based tests (or generative tests) with a reference model and edge-case generators.\n\nOutput: rigorous solution with invariants, failure modes, and performance notes.\nOutput: properties + reference model + generative tests.\n\n**Properties**\n- Idempotency: replayed command yields same result.\n- Monotonicity: versions only increase.\n- Conservation: for queues, produced items == consumed items (multiset) under no-loss assumption.\n\n**Approach**\n- Write a small reference model (pure function).\n- Generate random sequences of operations; compare implementation outputs to model.\n\n\nHard checks: failure injection tests and performance regressions gated.", "source": "WithinUsAI/Elite_GOD_Coder_100k"} {"text": "Optimize while preserving behavior and order.\n\n```python\ndef f16289(xs):\n out=[]\n for x in xs:\n if x not in out: out.append(x)\n return out\n```\nReturn `m02327.py` with types and O(n) average.\n\n```python\n# m02327.py\nfrom __future__ import annotations\nfrom typing import Iterable, List, Set, TypeVar\nT=TypeVar(\"T\")\n\ndef f16289(xs: Iterable[T]) -> List[T]:\n \"\"\"Unique items preserving first-seen order.\"\"\"\n seen: Set[T]=set()\n out: List[T]=[]\n for x in xs:\n if x in seen: continue\n seen.add(x); out.append(x)\n return out\n```", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Fix a bug and add tests.\n\nFile: g6un6mim1.py\n```python\ndef h7qpvki4x(n: int) -> int:\n \"\"\"Sum 1..n inclusive.\"\"\"\n if n < 0:\n raise ValueError(\"n must be non-negative\")\n total = 0\n for k in range(n): # BUG: should include n\n total += k\n return total\n```\n\nReturn unified diffs for g6un6mim1.py and test_g6un6mim1.py (pytest).\n\n*** Begin Patch\n*** Update File: g6un6mim1.py\n@@\n def h7qpvki4x(n: int) -> int:\n@@\n total = 0\n- for k in range(n): # BUG: should include n\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_g6un6mim1.py\n+import pytest\n+from g6un6mim1 import h7qpvki4x\n+\n+def test_zero():\n+ assert h7qpvki4x(0) == 0\n+\n+def test_one():\n+ assert h7qpvki4x(1) == 1\n+\n+def test_small():\n+ assert h7qpvki4x(7) == 28\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ h7qpvki4x(-1)\n+\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Fix a bug and add tests.\n\nFile: pslpxkk_3.py\n```python\ndef pv301o_(n: int) -> int:\n \"\"\"Sum 1..n inclusive.\"\"\"\n if n < 0:\n raise ValueError(\"n must be non-negative\")\n total = 0\n for k in range(n): # BUG: should include n\n total += k\n return total\n```\n\nReturn unified diffs for pslpxkk_3.py and test_pslpxkk_3.py (pytest).\n\n*** Begin Patch\n*** Update File: pslpxkk_3.py\n@@\n def pv301o_(n: int) -> int:\n@@\n total = 0\n- for k in range(n): # BUG: should include n\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_pslpxkk_3.py\n+import pytest\n+from pslpxkk_3 import pv301o_\n+\n+def test_zero():\n+ assert pv301o_(0) == 0\n+\n+def test_one():\n+ assert pv301o_(1) == 1\n+\n+def test_small():\n+ assert pv301o_(7) == 28\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ pv301o_(-1)\n+\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Build an elite-grade solution in the domain of edge/IoT for scenario: event ingestion.\nPrimary language: rust.\nDifficulty: medium.\nConstraints: provide rollout and rollback guidance, include tests or verification strategy, design for backward compatibility and migrations, make the interface contract explicit, assume untrusted inputs; validate and sanitize.\nComponent: component_zfkqeam.\nAssume crash-only design; recovery must be deterministic.\nTask: Design a replication/consistency approach (e.g., leader-based, quorum reads/writes). Provide message flows, failure handling, and a minimal reference implementation skeleton.\n\nOutput: rigorous solution with invariants, failure modes, and performance notes.\nOutput: replication design + failure handling + minimal skeleton.\n\n**Model**\n- Leader-based replication with term + log index.\n- Quorum acks for durability: write committed when majority acks.\n- Read options: leader-read (linearizable) or quorum-read (monotonic if using read-index).\n\n**Message flow (write)**\n1. Client → Leader: Put(request_id, payload)\n2. Leader appends to log, sends AppendEntries to followers\n3. Followers append + ack\n4. On majority ack: commit index advances; apply to state machine; respond to client\n\n**Failure modes**\n- Leader crash: new election; uncommitted entries may be rolled back.\n- Partition: minority side cannot commit.\n- Duplicate requests: deduplicate by request_id stored in state.\n\n**Skeleton (Go pseudo)**\n```go\ntype Entry struct { Term uint64; Index uint64; Cmd []byte }\ntype Node struct {\n id int\n term uint64\n log []Entry\n commit uint64\n seen map[string][]byte // request_id -> response\n}\n```\n\n**Verification**\n- Invariant: committed index never decreases.\n- Property: if a write is committed, all future leaders contain it.\n- Test with simulated partitions and crash/restart.\n\n\nChecks: boundary validation and deterministic behavior verified.", "source": "WithinUsAI/Elite_GOD_Coder_100k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Optimize while preserving behavior.\n\nFile: rgf1cs6j.py\n```python\ndef bodywhcpc2(xs):\n out = []\n for x in xs:\n if x not in out:\n out.append(x)\n return out\n```\n\nRequirements: preserve first-seen order; O(n) average; add types + docstring.\n\n# rgf1cs6j.py\nfrom __future__ import annotations\nfrom typing import Iterable, List, Set, TypeVar\n\nT = TypeVar(\"T\")\n\ndef bodywhcpc2(xs: Iterable[T]) -> List[T]:\n \"\"\"Return unique items preserving first-seen order.\"\"\"\n seen: Set[T] = set()\n out: List[T] = []\n for x in xs:\n if x in seen:\n continue\n seen.add(x)\n out.append(x)\n return out", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Optimize while preserving behavior.\n\nFile: eltrwkk2qfxy.py\n```python\ndef r6nn4ht(xs):\n out = []\n for x in xs:\n if x not in out:\n out.append(x)\n return out\n```\n\nRequirements: preserve first-seen order; O(n) average; add types + docstring.\n\n# eltrwkk2qfxy.py\nfrom __future__ import annotations\nfrom typing import Iterable, List, Set, TypeVar\n\nT = TypeVar(\"T\")\n\ndef r6nn4ht(xs: Iterable[T]) -> List[T]:\n \"\"\"Return unique items preserving first-seen order.\"\"\"\n seen: Set[T] = set()\n out: List[T] = []\n for x in xs:\n if x in seen:\n continue\n seen.add(x)\n out.append(x)\n return out", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Fix a bug and add tests.\n\nFile: djyzgv3.py\n```python\ndef rt5o51vrko5x(n: int) -> int:\n \"\"\"Sum 1..n inclusive.\"\"\"\n if n < 0:\n raise ValueError(\"n must be non-negative\")\n total = 0\n for k in range(n): # BUG: should include n\n total += k\n return total\n```\n\nReturn unified diffs for djyzgv3.py and test_djyzgv3.py (pytest).\n\n*** Begin Patch\n*** Update File: djyzgv3.py\n@@\n def rt5o51vrko5x(n: int) -> int:\n@@\n total = 0\n- for k in range(n): # BUG: should include n\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_djyzgv3.py\n+import pytest\n+from djyzgv3 import rt5o51vrko5x\n+\n+def test_zero():\n+ assert rt5o51vrko5x(0) == 0\n+\n+def test_one():\n+ assert rt5o51vrko5x(1) == 1\n+\n+def test_small():\n+ assert rt5o51vrko5x(7) == 28\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ rt5o51vrko5x(-1)\n+\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Design and implement an algorithm for telemetry ingestion.\nRequirements: define inputs/outputs, implement solution with complexity analysis, and include tests.\nConstraints: must be easy to extend, must handle Windows paths safely, must include docstrings, must avoid global state.\nDifficulty: easy. Avoid quadratic behavior on large inputs.\n\nDeliverable: corrected code and verification tests.\nProblem: compute rolling sums over events (ts:int,value:int) with window W seconds. Events may be out-of-order.\n\nComplexity: sorting O(n log n); window maintenance O(n); memory O(k).\n\n```python\nfrom __future__ import annotations\nfrom collections import deque\nfrom dataclasses import dataclass\nfrom typing import Iterable, List, Tuple\n\n@dataclass(frozen=True, slots=True)\nclass Event:\n ts: int\n value: int\n\ndef rolling_sum(events: Iterable[Event], window_s: int) -> List[Tuple[int,int]]:\n if window_s < 0:\n raise ValueError(\"window_s must be >= 0\")\n evs = sorted(events, key=lambda e: e.ts)\n q: deque[Event] = deque()\n s = 0\n out: List[Tuple[int,int]] = []\n for e in evs:\n q.append(e)\n s += e.value\n cutoff = e.ts - window_s\n while q and q[0].ts < cutoff:\n old = q.popleft()\n s -= old.value\n out.append((e.ts, s))\n return out\n```\n\n```python\nimport pytest\nfrom module_under_test import Event, rolling_sum\n\ndef test_rolling_sum():\n ev = [Event(10,1), Event(11,2), Event(20,5)]\n assert rolling_sum(ev, 5) == [(10,1),(11,3),(20,5)]\n```", "source": "WithinUsAI/python_GOD_coder_100k"} {"text": "Build an elite-grade solution in the domain of ml systems for scenario: multi-tenant SaaS.\nPrimary language: python.\nDifficulty: expert.\nConstraints: assume untrusted inputs; validate and sanitize, provide rollout and rollback guidance, document performance characteristics, avoid undefined behavior and data races.\nComponent: component_ddslxln.\nAssume 50k RPS and p99 < 250ms.\nTask: Provide a cross-language reference (API contract + implementation in two languages) and compatibility tests.\n\nOutput: elite-grade engineering answer with contracts, edge cases, and verification.\nOutput: API contract + two implementations + compat tests.\n\n**Contract**\n- JSON schema for request/response; strict field validation; explicit version.\n\n**Example**\n- Implement validator + handler in Python and TypeScript.\n- Compatibility tests: same inputs produce equivalent outputs; reject unknown fields when in strict mode.\n\n\nExpert checks: state-machine reasoning, concurrency stress, and upgrade/rollback validated.", "source": "WithinUsAI/Elite_GOD_Coder_100k"} {"text": "Fix the bug and add pytest tests.\n\n```python\ndef f99193(n: int) -> int:\n # sum 1..n inclusive\n if n < 0: raise ValueError\n total = 0\n for k in range(n): # BUG\n total += k\n return total\n```\nReturn unified diffs for `m85599.py` and `test_m85599.py`.\n\n*** Begin Patch\n*** Update File: m85599.py\n@@\n def f99193(n: int) -> int:\n@@\n- for k in range(n): # BUG\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_m85599.py\n+import pytest\n+from m85599 import f99193\n+\n+def test_small():\n+ assert f99193(7) == 28\n+\n+def test_zero():\n+ assert f99193(0) == 0\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ f99193(-1)\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Build an elite-grade solution in the domain of gpu compute for scenario: feature flagging.\nPrimary language: python.\nDifficulty: medium.\nConstraints: provide rollout and rollback guidance, assume untrusted inputs; validate and sanitize, design for backward compatibility and migrations.\nComponent: component_huyecna.\nAssume partial network partitions occur weekly.\nTask: Provide SLOs, alerting, dashboards, runbooks, and incident playbook. Include chaos testing and safe rollout strategy.\n\nOutput: elite-grade engineering answer with contracts, edge cases, and verification.\nOutput: SLOs + alerts + runbooks + chaos strategy.\n\n**SLOs**\n- Availability: 99.9% monthly\n- Latency: p95 < 200ms, p99 < 400ms\n- Error rate: < 0.1%\n\n**Alerts**\n- Burn-rate alerts for SLOs (fast/slow windows)\n- Saturation: CPU, memory, queue depth, DB connections\n- Dependency health: cache hit rate drop, downstream timeouts\n\n**Runbooks**\n- Triage: identify blast radius, feature-flag rollback, capacity mitigation\n- Post-incident: timeline, contributing factors, action items\n\n**Chaos**\n- Inject latency, partial outages, and restarts in staging; verify steady-state SLOs.\n\n\nChecks: boundary validation and deterministic behavior verified.", "source": "WithinUsAI/Elite_GOD_Coder_100k"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: Language: JavaScript\nFramework/tooling: Vite\nDomain: artifact registry\nLogic challenge: streaming timeout handling\nTask type: monorepo_toolchain_recovery\nDifficulty: expert\n\nReturn a rigorous engineering answer:\n- identify the hidden root cause or logical failure\n- present the corrected implementation\n- add tests that prove the fix\n- list verification commands\n- explain why naive fixes are insufficient when relevant\n\nRepository sketch:\nrepo/\n src/\n api.js\n service.js\n utils.js\n tests/\n api.test.js\n package.json\n\nFocus: Focus on staff-level problem solving with multi-file patches, rollout implications, performance and security tradeoffs.\n\nassistant: Diagnosis:\n- Staff-level diagnosis: streaming timeout handling impacts correctness, operability, and future maintenance, so the fix must be minimal where possible but complete where necessary.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```javascript\ntype Payload = Record;\n\nexport function normalizePayload(payload: Payload): Payload {\n if (!payload || typeof payload !== \"object\" || Array.isArray(payload)) {\n throw new TypeError(\"payload must be a plain object\");\n }\n return Object.fromEntries(\n Object.entries(payload)\n .filter(([, value]) => value !== null && value !== undefined)\n .map(([key, value]) => [String(key).trim(), value])\n );\n}\n\nexport function handleStreamingTimeoutHandling(payload: Payload) {\n const clean = normalizePayload(payload);\n if (!(\"id\" in clean)) {\n return { ok: false, data: {}, error: \"missing id\" };\n }\n return { ok: true, data: clean, error: null };\n}\n```\n\nTests:\n```javascript\nimport { describe, it, expect } from \"vitest\";\nimport { handleStreamingTimeoutHandling } from \"../src/service\";\n\ndescribe(\"handler\", () => {\n it(\"accepts valid input\", () => {\n expect(handleStreamingTimeoutHandling({ id: 7, name: \"ok\", unused: null })).toEqual({\n ok: true,\n data: { id: 7, name: \"ok\" },\n error: null\n });\n });\n\n it(\"rejects missing id\", () => {\n expect(handleStreamingTimeoutHandling({ name: \"x\" }).error).toMatch(/missing id/);\n });\n});\n```\n\nVerification:\n- `npm test`\n- `npm run lint`\n\nEngineering notes:\n- Language: JavaScript\n- Framework/tooling: Vite\n- Stack context: FastAPI, PostgreSQL, Redis, Celery, pytest, Docker\n- Domain: artifact registry\n- Task type: monorepo_toolchain_recovery\n- Difficulty: expert\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: Project stack: Rust, Axum, SQLx, Redis, Tokio, Docker\nLanguage: Java\nDependency challenge: CI failures after dependency upgrade\nTask type: build_reproducibility_fix\nDifficulty: hard\n\nFix this as a senior engineer.\nRequired:\n- identify the version or compatibility failure mode\n- produce the corrected config/code/build patch\n- explain rollback-safe migration notes\n- add regression tests or reproducibility checks\n- include concrete verification commands\n\nRepository sketch:\nrepo/\n src/main/java/com/acme/App.java\n src/main/java/com/acme/Service.java\n src/test/java/com/acme/AppTest.java\n pom.xml\n\nFocus: Focus on versioning, migrations, lockfiles, runtime compatibility, and secure dependency handling.\n\nassistant: Diagnosis:\n- Root cause: the issue around CI failures after dependency upgrade is a dependency, migration, or runtime-compatibility mismatch that needs a rollback-safe patch.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```java\nimport java.util.HashMap;\nimport java.util.Map;\n\npublic final class RequestHandler {\n public static Map handleRequest(Map payload) {\n Map clean = new HashMap<>();\n for (Map.Entry entry : payload.entrySet()) {\n if (entry.getValue() != null) clean.put(entry.getKey().trim(), entry.getValue());\n }\n if (!clean.containsKey(\"id\")) throw new IllegalArgumentException(\"missing id\");\n return Map.of(\"ok\", true, \"data\", clean);\n }\n}\n```\n\nTests:\n```java\nimport static org.junit.jupiter.api.Assertions.*;\nimport java.util.Map;\nimport org.junit.jupiter.api.Test;\n\nclass RequestHandlerTest {\n @Test\n void requiresId() {\n assertThrows(IllegalArgumentException.class, () -> RequestHandler.handleRequest(Map.of(\"name\", \"x\")));\n }\n}\n```\n\nVerification:\n- `./gradlew test`\n- `mvn test`\n\nEngineering notes:\n- Language: Java\n- Framework/tooling: JUnit\n- Stack context: Rust, Axum, SQLx, Redis, Tokio, Docker\n- Domain: reporting engine\n- Task type: build_reproducibility_fix\n- Difficulty: hard\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "Write a thorough test suite for a Python component used for caching layer.\nRequirements: cover edge cases, invalid inputs, and behavior invariants.\nConstraints: must include type hints, must be streaming-friendly, must be memory-efficient, must handle Windows paths safely.\nDifficulty: expert. Guarantee deterministic output ordering.\n\nDeliverable: production-ready reference solution.\n```python\n# tests (pytest-style) for a module providing: normalize(), parse_lines(), compute_stats()\nimport math\nimport pytest\n\ndef test_normalize_idempotent(module_under_test):\n x = \" A\\tB \"\n assert module_under_test.normalize(module_under_test.normalize(x)) == module_under_test.normalize(x)\n\ndef test_parse_lines_rejects_invalid(module_under_test):\n with pytest.raises(ValueError):\n module_under_test.parse_lines([\"\", \"???\", None]) # type: ignore[arg-type]\n\ndef test_compute_stats_basic(module_under_test):\n data = [1, 2, 3, 4]\n s = module_under_test.compute_stats(data)\n assert s.count == 4\n assert s.total == 10\n assert math.isclose(s.mean, 2.5)\n```", "source": "WithinUsAI/python_GOD_coder_100k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Refactor to modern typed Python with immutability and tests.\n\nFile: c_bw46c.py\n```python\nclass O3Sz2V:\n def __init__(self, name, values):\n self.name = name\n self.values = list(values)\n def add(self, v):\n self.values.append(v)\n def mean(self):\n s = 0\n for x in self.values:\n s += x\n return s / len(self.values)\n```\n\nReturn full new c_bw46c.py and test_c_bw46c.py.\n\n# c_bw46c.py\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom typing import Iterable, Tuple\n\n@dataclass(frozen=True)\nclass O3Sz2V:\n name: str\n values: Tuple[float, ...]\n\n @staticmethod\n def create(name: str, values: Iterable[float]) -> \"O3Sz2V\":\n vals = tuple(float(v) for v in values)\n if not vals:\n raise ValueError(\"values must be non-empty\")\n return O3Sz2V(name=name, values=vals)\n\n def add(self, v: float) -> \"O3Sz2V\":\n return O3Sz2V(name=self.name, values=self.values + (float(v),))\n\n def mean(self) -> float:\n return sum(self.values) / len(self.values)\n\n# test_c_bw46c.py\nimport pytest\nfrom c_bw46c import O3Sz2V\n\ndef test_mean_and_add():\n c = O3Sz2V.create(\"a\", [1, 2, 3])\n assert c.mean() == 2.0\n assert c.add(5).mean() == (1 + 2 + 3 + 5) / 4\n\ndef test_empty_raises():\n with pytest.raises(ValueError):\n O3Sz2V.create(\"x\", [])", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Refactor to typed, mostly-immutable Python and add minimal tests.\n\n```python\nclass C64425:\n def __init__(self, values): self.values=list(values)\n def mean(self): return sum(self.values)/len(self.values)\n```\nReturn `m35725.py` and `test_m35725.py`.\n\n```python\n# m35725.py\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom typing import Iterable, Tuple\n\n@dataclass(frozen=True)\nclass C64425:\n values: Tuple[float, ...]\n\n @staticmethod\n def create(values: Iterable[float]) -> \"C64425\":\n vals = tuple(float(v) for v in values)\n if not vals: raise ValueError(\"empty\")\n return C64425(vals)\n\n def mean(self) -> float:\n return sum(self.values)/len(self.values)\n```\n\n```python\n# test_m35725.py\nimport pytest\nfrom m35725 import C64425\n\ndef test_mean():\n assert C64425.create([1,2,3]).mean() == 2.0\ndef test_empty():\n with pytest.raises(ValueError):\n C64425.create([])\n```", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Build an elite-grade solution in the domain of networking for scenario: rate limiting gateway.\nPrimary language: python.\nDifficulty: expert.\nConstraints: avoid undefined behavior and data races, document performance characteristics, design for backward compatibility and migrations, assume untrusted inputs; validate and sanitize, include invariants and failure modes.\nComponent: component_lzbyafq.\nAssume partial network partitions occur weekly.\nTask: Implement a concurrency primitive or subsystem (lock-free queue, thread pool, async runtime component). Explain memory ordering and correctness arguments; include stress tests.\n\nOutput: elite-grade engineering answer with contracts, edge cases, and verification.\nOutput: correctness-focused concurrency primitive + stress tests.\n\n**Primitive**\n- Bounded MPMC queue with backpressure (blocking push/pop) OR lock-free SPSC ring buffer.\n\n**Correctness notes**\n- For lock-free: use acquire/release semantics on head/tail indices.\n- Avoid ABA by monotonic counters; ring index = counter % capacity.\n\n**Stress tests**\n- Multi-thread producers/consumers; assert item multiset preserved.\n- Use time-bounded randomized schedules; detect deadlocks.\n\n\nExpert checks: state-machine reasoning, concurrency stress, and upgrade/rollback validated.", "source": "WithinUsAI/Elite_GOD_Coder_100k"} {"text": "Build an elite-grade solution in the domain of realtime systems for scenario: job scheduler.\nPrimary language: sql.\nDifficulty: hard.\nConstraints: include tests or verification strategy, document performance characteristics, design for backward compatibility and migrations, assume untrusted inputs; validate and sanitize, avoid undefined behavior and data races.\nComponent: component_hglicfj.\nAssume compliance requires data deletion with proofs.\nTask: Write a precise interface contract, list invariants, and provide a lightweight formal/spec-style description (pseudo-TLA+/state machine) plus reference implementation skeleton and tests.\n\nOutput: elite-grade engineering answer with contracts, edge cases, and verification.\nOutput: contract + invariants + spec + reference skeleton.\n\n**Interface contract**\n- Commands: `Put(key, value, expected_version?)`, `Get(key)`, `Delete(key, expected_version?)`\n- Responses: `Ok(version, value?)`, `NotFound`, `Conflict(current_version)`, `InvalidInput`\n- Idempotency: client supplies `request_id`; server must de-duplicate per (tenant_id, request_id).\n\n**Invariants**\n1. Monotonic version per key (strictly increases on successful writes).\n2. Reads return latest committed value for a given consistency level.\n3. Exactly-once effect for a given `request_id` (at-most-once execution + replay response).\n4. Tenant isolation: keys are scoped by tenant_id.\n\n**State machine (pseudo)**\nState:\n- store: map[(tenant,key)] -> (version:int, value:bytes|tombstone)\n- seen: map[(tenant,request_id)] -> response\nTransition Put:\n- if request_id in seen: return seen[...]\n- validate input; if expected_version set and != current version -> Conflict\n- version' = version + 1; store[...] := (version', value); seen[...] := Ok(version', value)\n\n**Reference skeleton (Python)**\n```python\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom typing import Dict, Optional, Tuple\n\nclass Conflict(Exception): pass\nclass InvalidInput(ValueError): pass\n\n@dataclass(frozen=True, slots=True)\nclass Value:\n version: int\n data: Optional[bytes] # None == tombstone\n\n@dataclass(frozen=True, slots=True)\nclass Reply:\n kind: str\n version: Optional[int] = None\n data: Optional[bytes] = None\n\nclass KV:\n def __init__(self) -> None:\n self._store: Dict[Tuple[str,str], Value] = {}\n self._seen: Dict[Tuple[str,str], Reply] = {}\n\n def put(self, tenant: str, request_id: str, key: str, data: bytes, expected_version: Optional[int]=None) -> Reply:\n if not tenant or not request_id or not key:\n raise InvalidInput(\"tenant/request_id/key required\")\n de = self._seen.get((tenant, request_id))\n if de: \n return de\n cur = self._store.get((tenant, key), Value(0, None))\n if expected_version is not None and expected_version != cur.version:\n r = Reply(\"conflict\", version=cur.version)\n self._seen[(tenant, request_id)] = r\n return r\n nxt = Value(cur.version + 1, data)\n self._store[(tenant, key)] = nxt\n r = Reply(\"ok\", version=nxt.version)\n self._seen[(tenant, request_id)] = r\n return r\n```\n\n**Tests**\n- Determinism: same request_id → same reply.\n- Conflict detection and version monotonicity.\n\n\nHard checks: failure injection tests and performance regressions gated.", "source": "WithinUsAI/Elite_GOD_Coder_100k"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: Repository domain: search service\nPrimary language: Java\nFramework/tooling: Hibernate\nReported problem: optimistic locking conflict\nTask type: test_repair\nDifficulty: medium\n\nProduce a complete professional engineering response:\n1. Diagnose the root cause.\n2. Provide the corrected implementation or patch.\n3. Add tests.\n4. Add verification commands.\n5. Note edge cases and any migration or rollback risk.\n\nRepository sketch:\nrepo/\n src/main/java/com/acme/App.java\n src/main/java/com/acme/Service.java\n src/test/java/com/acme/AppTest.java\n pom.xml\n\nQuality target:\n- Minimal diff unless redesign is clearly required\n- Production-ready code\n- No placeholders\n- Secure defaults\n- Clear acceptance of failure cases\n\nFocus: Focus on complete implementation quality, patch correctness, tests, and production readiness.\n\nassistant: Diagnosis:\n- Root cause: the failure around optimistic locking conflict is caused by missing validation, weak edge-case handling, or unsafe lifecycle behavior in the current implementation.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```java\nimport java.util.HashMap;\nimport java.util.Map;\n\npublic final class RequestHandler {\n public static Map handleRequest(Map payload) {\n Map clean = new HashMap<>();\n for (Map.Entry entry : payload.entrySet()) {\n if (entry.getValue() != null) clean.put(entry.getKey().trim(), entry.getValue());\n }\n if (!clean.containsKey(\"id\")) throw new IllegalArgumentException(\"missing id\");\n return Map.of(\"ok\", true, \"data\", clean);\n }\n}\n```\n\nTests:\n```java\nimport static org.junit.jupiter.api.Assertions.*;\nimport java.util.Map;\nimport org.junit.jupiter.api.Test;\n\nclass RequestHandlerTest {\n @Test\n void requiresId() {\n assertThrows(IllegalArgumentException.class, () -> RequestHandler.handleRequest(Map.of(\"name\", \"x\")));\n }\n}\n```\n\nVerification:\n- `./gradlew test`\n- `mvn test`\n\nEngineering notes:\n- Language: Java\n- Framework/tooling: Hibernate\n- Stack context: Spring Boot, PostgreSQL, JUnit, Gradle, Docker, GitHub Actions\n- Domain: search service\n- Task type: test_repair\n- Difficulty: medium\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "Task type: network_protocol\nScenario: feature-flag evaluation\nDomain focus: real-time scheduling\nPrimary language: go\nDifficulty: expert+\nScale/SLO: 99.99% availability\nComponent: component_kgrsnrpp\nConstraints: include failure modes and recovery, include security threat model (defensive only), include test vectors and fuzz strategy, include verification strategy, assume adversarial inputs; validate everything, avoid data races and undefined behavior, include deterministic replay plan\nAssume hostile inputs and targeted abuse patterns.\nDeliverable: Design an application protocol: framing, retries, backpressure, timeouts; include client/server skeleton and test vectors.\n\nOutput: elite engineering answer optimized for correctness, performance, and operability.\n**Contract**\n- Inputs validated at the boundary; explicit error taxonomy.\n- Idempotency for side effects via request_id; deterministic replay.\n- Backward compatibility: additive changes by default; versioned breaking changes.\n**Invariants**\n- Isolation: tenant boundary enforced; no cross-tenant reads/writes.\n- Liveness: under bounded faults and stable network, progress occurs.\n- Determinism: replay of the same event log yields identical outputs.\n**Failure modes & recovery**\n- Crash during commit: WAL replay completes or transaction aborts; no torn writes.\n- Duplicate requests: de-duplicate by (tenant, request_id) returning cached response.\n- Network partition: minority cannot commit; clients receive retriable errors.\n**Security posture (defensive)**\n- Threat model: auth/authz, injection, replay/abuse, supply chain.\n- Least privilege; secrets in managed store; audit logs for sensitive ops.\n- Input normalization, parameterized queries, path traversal protections.\n**Verification strategy**\n- Fuzzing of parsers/framers/validators with corpus seeds.\n- Property tests against a pure reference model (state machine).\n- Canary + shadow traffic; invariants checked in production via assertions/metrics.\n\n**Snippet**\n```text\nImplementation sketch: factor pure state-machine core; adapters for I/O; add deterministic replay log.\n```\nExpert+ checks: mechanized invariants (or exhaustive model checking), adversarial fuzzing, and multi-region failure drills.", "source": "WithinUsAI/Omega_Genesis_Coder_100k"} {"text": "Fix a subtle bug in a Python module used for configuration loading.\nRequirements: explain root cause briefly, provide corrected code, and add regression tests.\nConstraints: must include docstrings, must be memory-efficient.\nDifficulty: medium. Ensure the API is testable via dependency injection.\n\nDeliverable: production-ready reference solution.\n```python\nfrom __future__ import annotations\n\nfrom dataclasses import dataclass\nfrom pathlib import Path\nfrom typing import Iterable\nimport json\n\n\nclass ValidationError(ValueError):\n \"\"\"Raised when input validation fails.\"\"\"\n\n\ndef safe_join(base: Path, *parts: str) -> Path:\n \"\"\"Join paths while preventing traversal outside base.\"\"\"\n b = base.resolve()\n p = (b / Path(*parts)).resolve()\n if p != b and b not in p.parents:\n raise ValidationError(f\"unsafe path: {p}\")\n return p\n\n\n@dataclass(frozen=True, slots=True)\nclass Record:\n key: str\n value: int\n\n\ndef parse_jsonl(lines: Iterable[str]) -> list[Record]:\n out: list[Record] = []\n for idx, line in enumerate(lines, 1):\n s = line.strip()\n if not s:\n continue\n try:\n obj = json.loads(s)\n except json.JSONDecodeError as e:\n raise ValidationError(f\"line {idx}: invalid json\") from e\n if not isinstance(obj, dict):\n raise ValidationError(f\"line {idx}: expected object\")\n key = obj.get(\"key\")\n val = obj.get(\"value\")\n if not isinstance(key, str) or not key:\n raise ValidationError(f\"line {idx}: key must be non-empty str\")\n if not isinstance(val, int):\n raise ValidationError(f\"line {idx}: value must be int\")\n out.append(Record(key, val))\n return out\n\n\ndef write_jsonl(base: Path, rel: str, records: Iterable[Record]) -> Path:\n base.mkdir(parents=True, exist_ok=True)\n dst = safe_join(base, rel)\n dst.parent.mkdir(parents=True, exist_ok=True)\n with dst.open(\"w\", encoding=\"utf-8\", newline=\"\\n\") as f:\n for r in records:\n f.write(json.dumps({\"key\": r.key, \"value\": r.value}, ensure_ascii=False) + \"\\n\")\n return dst\n```\n\n```python\n# tests (pytest-style)\nimport json\nfrom pathlib import Path\nimport pytest\nfrom module_under_test import ValidationError, Record, parse_jsonl, write_jsonl\n\ndef test_parse_ok():\n lines = [json.dumps({\"key\":\"a\",\"value\":1}), json.dumps({\"key\":\"b\",\"value\":2})]\n assert parse_jsonl(lines) == [Record(\"a\",1), Record(\"b\",2)]\n\ndef test_parse_rejects_bad_json():\n with pytest.raises(ValidationError):\n parse_jsonl([\"{not json}\"])\n\ndef test_safe_join_blocks_traversal(tmp_path: Path):\n with pytest.raises(ValidationError):\n write_jsonl(tmp_path, \"../x.jsonl\", [Record(\"a\",1)])\n```", "source": "WithinUsAI/python_GOD_coder_100k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Fix a bug and add tests.\n\nFile: plu7491o.py\n```python\ndef e6i6jgh_byv(n: int) -> int:\n \"\"\"Sum 1..n inclusive.\"\"\"\n if n < 0:\n raise ValueError(\"n must be non-negative\")\n total = 0\n for k in range(n): # BUG: should include n\n total += k\n return total\n```\n\nReturn unified diffs for plu7491o.py and test_plu7491o.py (pytest).\n\n*** Begin Patch\n*** Update File: plu7491o.py\n@@\n def e6i6jgh_byv(n: int) -> int:\n@@\n total = 0\n- for k in range(n): # BUG: should include n\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_plu7491o.py\n+import pytest\n+from plu7491o import e6i6jgh_byv\n+\n+def test_zero():\n+ assert e6i6jgh_byv(0) == 0\n+\n+def test_one():\n+ assert e6i6jgh_byv(1) == 1\n+\n+def test_small():\n+ assert e6i6jgh_byv(7) == 28\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ e6i6jgh_byv(-1)\n+\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Refactor to modern typed Python with immutability and tests.\n\nFile: qsxmz6imjmu.py\n```python\nclass Lh89Rh0:\n def __init__(self, name, values):\n self.name = name\n self.values = list(values)\n def add(self, v):\n self.values.append(v)\n def mean(self):\n s = 0\n for x in self.values:\n s += x\n return s / len(self.values)\n```\n\nReturn full new qsxmz6imjmu.py and test_qsxmz6imjmu.py.\n\n# qsxmz6imjmu.py\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom typing import Iterable, Tuple\n\n@dataclass(frozen=True)\nclass Lh89Rh0:\n name: str\n values: Tuple[float, ...]\n\n @staticmethod\n def create(name: str, values: Iterable[float]) -> \"Lh89Rh0\":\n vals = tuple(float(v) for v in values)\n if not vals:\n raise ValueError(\"values must be non-empty\")\n return Lh89Rh0(name=name, values=vals)\n\n def add(self, v: float) -> \"Lh89Rh0\":\n return Lh89Rh0(name=self.name, values=self.values + (float(v),))\n\n def mean(self) -> float:\n return sum(self.values) / len(self.values)\n\n# test_qsxmz6imjmu.py\nimport pytest\nfrom qsxmz6imjmu import Lh89Rh0\n\ndef test_mean_and_add():\n c = Lh89Rh0.create(\"a\", [1, 2, 3])\n assert c.mean() == 2.0\n assert c.add(5).mean() == (1 + 2 + 3 + 5) / 4\n\ndef test_empty_raises():\n with pytest.raises(ValueError):\n Lh89Rh0.create(\"x\", [])", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Build an elite-grade solution in the domain of gpu compute for scenario: chat messaging.\nPrimary language: go.\nDifficulty: hard.\nConstraints: make the interface contract explicit, document performance characteristics, design for backward compatibility and migrations.\nComponent: component_xhebgpc.\nAssume crash-only design; recovery must be deterministic.\nTask: Implement or outline a storage/indexing subsystem (LSM/B-Tree, WAL, snapshots). Include transaction/consistency considerations and benchmark plan.\n\nOutput: production blueprint plus correctness arguments and test strategy.\nOutput: storage design + WAL + compaction + benchmarks.\n\n**Design**\n- WAL (append-only) for durability; fsync policy configurable.\n- Memtable (in-memory) → flush to immutable SSTables.\n- LSM compaction tiers; bloom filters per SSTable for point-lookups.\n- Manifest tracks SSTable set; atomic pointer swap on updates.\n\n**Correctness**\n- Crash recovery: replay WAL to rebuild memtable; manifest ensures last consistent set.\n- Reads: merge memtable + SSTables newest→oldest; tombstones override older values.\n\n**Bench plan**\n- Workloads: write-heavy, read-heavy, mixed; measure p50/p95 latency and write amplification.\n- Track compaction debt and space amplification.\n\n**Test plan**\n- Fuzz crash points: kill after WAL append / after manifest update; verify invariants on restart.\n\n\nHard checks: failure injection tests and performance regressions gated.", "source": "WithinUsAI/Elite_GOD_Coder_100k"} {"text": "Fix the bug and add pytest tests.\n\n```python\ndef f64605(n: int) -> int:\n # sum 1..n inclusive\n if n < 0: raise ValueError\n total = 0\n for k in range(n): # BUG\n total += k\n return total\n```\nReturn unified diffs for `m23515.py` and `test_m23515.py`.\n\n*** Begin Patch\n*** Update File: m23515.py\n@@\n def f64605(n: int) -> int:\n@@\n- for k in range(n): # BUG\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_m23515.py\n+import pytest\n+from m23515 import f64605\n+\n+def test_small():\n+ assert f64605(7) == 28\n+\n+def test_zero():\n+ assert f64605(0) == 0\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ f64605(-1)\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: Project domain: repo automation\nImplementation stack: GitHub Actions, Docker Compose, Kubernetes, Terraform\nSoftware delivery problem: mismatched API contract\nTask type: release_engineering_fix\nDifficulty: hard\n\nReturn a complete delivery-grade response with:\n- diagnosis or design reasoning\n- implementation\n- test plan or tests\n- rollout plan\n- rollback or compatibility note\n- verification commands\n\nRepository sketch:\nrepo/\n app/\n api.py\n service.py\n models.py\n tests/\n test_api.py\n pyproject.toml\n\nFocus: Focus on shipping production software with rollout safety, acceptance criteria, telemetry, and maintenance quality.\n\nassistant: Diagnosis:\n- Root cause or delivery blocker: mismatched API contract needs both implementation work and a safe shipping plan.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```python\nfrom __future__ import annotations\n\nfrom dataclasses import dataclass\nfrom typing import Any\n\n@dataclass\nclass ServiceResult:\n ok: bool\n data: dict[str, Any]\n error: str | None = None\n\ndef normalize_payload(payload: dict[str, Any]) -> dict[str, Any]:\n if not isinstance(payload, dict):\n raise TypeError(\"payload must be a dict\")\n clean: dict[str, Any] = {}\n for key, value in payload.items():\n if value is None:\n continue\n clean[str(key).strip()] = value\n return clean\n\ndef handle_mismatched_api_contract(payload: dict[str, Any]) -> ServiceResult:\n clean = normalize_payload(payload)\n if \"id\" not in clean:\n return ServiceResult(ok=False, data={}, error=\"missing id\")\n return ServiceResult(ok=True, data=clean)\n```\n\nTests:\n```python\nimport pytest\nfrom app.service import handle_jwt_refresh_token_rotation as handler\n\ndef test_handler_accepts_valid_payload():\n result = handler({\"id\": 7, \"name\": \"ok\", \"unused\": None})\n assert result.ok is True\n assert result.data == {\"id\": 7, \"name\": \"ok\"}\n\ndef test_handler_rejects_missing_id():\n result = handler({\"name\": \"x\"})\n assert result.ok is False\n assert result.error == \"missing id\"\n```\n\nVerification:\n- `pytest -q`\n- `ruff check .`\n- `python -m compileall .`\n\nEngineering notes:\n- Language: Python\n- Framework/tooling: FastAPI\n- Stack context: GitHub Actions, Docker Compose, Kubernetes, Terraform\n- Domain: repo automation\n- Task type: release_engineering_fix\n- Difficulty: hard\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "Optimize while preserving behavior and order.\n\n```python\ndef f36446(xs):\n out=[]\n for x in xs:\n if x not in out: out.append(x)\n return out\n```\nReturn `m33778.py` with types and O(n) average.\n\n```python\n# m33778.py\nfrom __future__ import annotations\nfrom typing import Iterable, List, Set, TypeVar\nT=TypeVar(\"T\")\n\ndef f36446(xs: Iterable[T]) -> List[T]:\n \"\"\"Unique items preserving first-seen order.\"\"\"\n seen: Set[T]=set()\n out: List[T]=[]\n for x in xs:\n if x in seen: continue\n seen.add(x); out.append(x)\n return out\n```", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Build an elite-grade solution in the domain of databases for scenario: multi-tenant SaaS.\nPrimary language: go.\nDifficulty: medium.\nConstraints: document performance characteristics, make the interface contract explicit, avoid undefined behavior and data races, provide rollout and rollback guidance, include invariants and failure modes.\nComponent: component_ryvgvgb.\nAssume strict auditability and replayable history.\nTask: Design a replication/consistency approach (e.g., leader-based, quorum reads/writes). Provide message flows, failure handling, and a minimal reference implementation skeleton.\n\nOutput: production blueprint plus correctness arguments and test strategy.\nOutput: replication design + failure handling + minimal skeleton.\n\n**Model**\n- Leader-based replication with term + log index.\n- Quorum acks for durability: write committed when majority acks.\n- Read options: leader-read (linearizable) or quorum-read (monotonic if using read-index).\n\n**Message flow (write)**\n1. Client → Leader: Put(request_id, payload)\n2. Leader appends to log, sends AppendEntries to followers\n3. Followers append + ack\n4. On majority ack: commit index advances; apply to state machine; respond to client\n\n**Failure modes**\n- Leader crash: new election; uncommitted entries may be rolled back.\n- Partition: minority side cannot commit.\n- Duplicate requests: deduplicate by request_id stored in state.\n\n**Skeleton (Go pseudo)**\n```go\ntype Entry struct { Term uint64; Index uint64; Cmd []byte }\ntype Node struct {\n id int\n term uint64\n log []Entry\n commit uint64\n seen map[string][]byte // request_id -> response\n}\n```\n\n**Verification**\n- Invariant: committed index never decreases.\n- Property: if a write is committed, all future leaders contain it.\n- Test with simulated partitions and crash/restart.\n\n\nChecks: boundary validation and deterministic behavior verified.", "source": "WithinUsAI/Elite_GOD_Coder_100k"} {"text": "Refactor to typed, mostly-immutable Python and add minimal tests.\n\n```python\nclass C08397:\n def __init__(self, values): self.values=list(values)\n def mean(self): return sum(self.values)/len(self.values)\n```\nReturn `m77569.py` and `test_m77569.py`.\n\n```python\n# m77569.py\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom typing import Iterable, Tuple\n\n@dataclass(frozen=True)\nclass C08397:\n values: Tuple[float, ...]\n\n @staticmethod\n def create(values: Iterable[float]) -> \"C08397\":\n vals = tuple(float(v) for v in values)\n if not vals: raise ValueError(\"empty\")\n return C08397(vals)\n\n def mean(self) -> float:\n return sum(self.values)/len(self.values)\n```\n\n```python\n# test_m77569.py\nimport pytest\nfrom m77569 import C08397\n\ndef test_mean():\n assert C08397.create([1,2,3]).mean() == 2.0\ndef test_empty():\n with pytest.raises(ValueError):\n C08397.create([])\n```", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Fix the bug and add pytest tests.\n\n```python\ndef f56424(n: int) -> int:\n # sum 1..n inclusive\n if n < 0: raise ValueError\n total = 0\n for k in range(n): # BUG\n total += k\n return total\n```\nReturn unified diffs for `m36632.py` and `test_m36632.py`.\n\n*** Begin Patch\n*** Update File: m36632.py\n@@\n def f56424(n: int) -> int:\n@@\n- for k in range(n): # BUG\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_m36632.py\n+import pytest\n+from m36632 import f56424\n+\n+def test_small():\n+ assert f56424(7) == 28\n+\n+def test_zero():\n+ assert f56424(0) == 0\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ f56424(-1)\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Add a clear docstring and type hints to this function:\n\n```python\ndef f60441(s):\n return ''.join(x for x in s if x.isalnum()).lower()\n```\n\n```python\nfrom __future__ import annotations\n\ndef f60441(s: str) -> str:\n \"\"\"Normalize a string: keep only alphanumerics and lowercase the result.\"\"\"\n return \"\".join(ch for ch in s if ch.isalnum()).lower()\n```", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Optimize a Python workflow for report generation.\nRequirements: provide an optimized implementation and a small benchmark harness.\nConstraints: must include type hints, stdlib-only.\nDifficulty: easy. Avoid quadratic behavior on large inputs.\n\nDeliverable: API + reference implementation + tests.\nStrategy:\n- Avoid repeated parsing; precompile regex if needed; use local variables; stream processing.\n\n```python\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom typing import Iterable\nimport time\n\n@dataclass(frozen=True, slots=True)\nclass Stats:\n count: int\n total: int\n\ndef compute_stats_stream(values: Iterable[int]) -> Stats:\n c = 0\n t = 0\n for v in values:\n c += 1\n t += v\n return Stats(c, t)\n\ndef bench(n: int = 1_000_00) -> float:\n data = range(n)\n t0 = time.perf_counter()\n _ = compute_stats_stream(data)\n return time.perf_counter() - t0\n```\n\n```python\nfrom module_under_test import bench\ndef test_bench_runs_fast_enough():\n # Sanity: should run quickly on typical machines; adjust threshold for CI.\n assert bench(50_000) < 0.5\n```", "source": "WithinUsAI/python_GOD_coder_100k"} {"text": "Task type: tla_state_machine\nScenario: feature-flag evaluation\nDomain focus: model checking\nPrimary language: tla+\nDifficulty: expert\nScale/SLO: p99 < 50ms\nComponent: component_turrdxtm\nConstraints: include test vectors and fuzz strategy, include failure modes and recovery, avoid data races and undefined behavior, explicit contracts and invariants, include backward compatibility and migration plan, include security threat model (defensive only), include performance model and limits\nAssume crash-only processes; recovery must be deterministic.\nDeliverable: Provide a TLA+-style state machine (pseudo), safety/liveness properties, and a model-checking strategy. Include an implementation sketch and test vectors.\n\nOutput: contract-first solution with failure modes, security posture, and test/verification strategy.\n**Contract**\n- Inputs validated at the boundary; explicit error taxonomy.\n- Idempotency for side effects via request_id; deterministic replay.\n- Backward compatibility: additive changes by default; versioned breaking changes.\n**Invariants**\n- Safety: state transitions preserve invariants; no partial commit leaks.\n- Isolation: tenant boundary enforced; no cross-tenant reads/writes.\n- Liveness: under bounded faults and stable network, progress occurs.\n**Failure modes & recovery**\n- Network partition: minority cannot commit; clients receive retriable errors.\n- Data corruption: checksums + scrubber; quarantine and rebuild from replicas/snapshots.\n- Crash during commit: WAL replay completes or transaction aborts; no torn writes.\n**Security posture (defensive)**\n- Threat model: auth/authz, injection, replay/abuse, supply chain.\n- Least privilege; secrets in managed store; audit logs for sensitive ops.\n- Input normalization, parameterized queries, path traversal protections.\n**Verification strategy**\n- Canary + shadow traffic; invariants checked in production via assertions/metrics.\n- Property tests against a pure reference model (state machine).\n- Deterministic simulation with fault injection (crash/partition/latency).\n\n**Snippet**\n```tla\nVARIABLES state, log, seen\n\nInit == state = [k \\in Keys |-> <<0, NULL>>] /\\ log = << >> /\\ seen = [r \\in ReqIds |-> NULL]\n\nPut(req, k, v) ==\n IF seen[req] # NULL THEN UNCHANGED <>\n ELSE\n LET ver == state[k][1] + 1 IN\n /\\ state' = [state EXCEPT ![k] = <>]\n /\\ log' = Append(log, <>)\n /\\ seen' = [seen EXCEPT ![req] = <<\"ok\", ver>>]\n\nSafety == \\A k \\in Keys: state[k][1] >= 0\n```\n\nExpert checks: state-machine proof sketch + model checking; upgrade/rollback rehearsed.", "source": "WithinUsAI/Omega_Genesis_Coder_100k"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: Language: Go\nFramework/tooling: net/http\nDomain: auth service\nLogic challenge: monorepo toolchain skew\nTask type: parser_validation_logic\nDifficulty: medium\n\nReturn a rigorous engineering answer:\n- identify the hidden root cause or logical failure\n- present the corrected implementation\n- add tests that prove the fix\n- list verification commands\n- explain why naive fixes are insufficient when relevant\n\nRepository sketch:\nrepo/\n cmd/server/main.go\n internal/service/service.go\n internal/store/store.go\n internal/api/api.go\n service_test.go\n go.mod\n\nFocus: Focus on strong structured logic with edge cases, data validation, and concurrency safety.\n\nassistant: Diagnosis:\n- Root cause: the failure around monorepo toolchain skew is caused by missing validation, weak edge-case handling, or unsafe lifecycle behavior in the current implementation.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```go\npackage service\n\nimport \"fmt\"\n\nfunc NormalizePayload(payload map[string]any) map[string]any {\n\tout := make(map[string]any)\n\tfor k, v := range payload {\n\t\tif v == nil {\n\t\t\tcontinue\n\t\t}\n\t\tout[k] = v\n\t}\n\treturn out\n}\n\nfunc Handle(payload map[string]any) (map[string]any, error) {\n\tclean := NormalizePayload(payload)\n\tif _, ok := clean[\"id\"]; !ok {\n\t\treturn nil, fmt.Errorf(\"missing id\")\n\t}\n\treturn map[string]any{\"ok\": true, \"data\": clean}, nil\n}\n```\n\nTests:\n```go\npackage service\n\nimport \"testing\"\n\nfunc TestHandle(t *testing.T) {\n\tgot, err := Handle(map[string]any{\"id\": 7, \"name\": \"ok\", \"unused\": nil})\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tif got[\"ok\"] != true {\n\t\tt.Fatalf(\"expected ok=true\")\n\t}\n\tif _, err := Handle(map[string]any{\"name\": \"x\"}); err == nil {\n\t\tt.Fatalf(\"expected missing id error\")\n\t}\n}\n```\n\nVerification:\n- `go test ./...`\n- `go vet ./...`\n\nEngineering notes:\n- Language: Go\n- Framework/tooling: net/http\n- Stack context: Spring Boot, PostgreSQL, JUnit, Gradle, Docker, GitHub Actions\n- Domain: auth service\n- Task type: parser_validation_logic\n- Difficulty: medium\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "Add a clear docstring and type hints to this function:\n\n```python\ndef f68087(s):\n return ''.join(x for x in s if x.isalnum()).lower()\n```\n\n```python\nfrom __future__ import annotations\n\ndef f68087(s: str) -> str:\n \"\"\"Normalize a string: keep only alphanumerics and lowercase the result.\"\"\"\n return \"\".join(ch for ch in s if ch.isalnum()).lower()\n```", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: Language: Java\nFramework/tooling: Spring Boot\nDomain: document processing API\nLogic challenge: JWT refresh token rotation\nTask type: security_logic_interaction\nDifficulty: hard\n\nReturn a rigorous engineering answer:\n- identify the hidden root cause or logical failure\n- present the corrected implementation\n- add tests that prove the fix\n- list verification commands\n- explain why naive fixes are insufficient when relevant\n\nRepository sketch:\nrepo/\n src/main/java/com/acme/App.java\n src/main/java/com/acme/Service.java\n src/test/java/com/acme/AppTest.java\n pom.xml\n\nFocus: Focus on ambiguity, misleading symptoms, hidden root causes, and high-stakes debugging.\n\nassistant: Diagnosis:\n- Hidden root cause: JWT refresh token rotation presents misleading symptoms, so the patch must target the actual logic boundary rather than the first visible failure.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```java\nimport java.util.HashMap;\nimport java.util.Map;\n\npublic final class RequestHandler {\n public static Map handleRequest(Map payload) {\n Map clean = new HashMap<>();\n for (Map.Entry entry : payload.entrySet()) {\n if (entry.getValue() != null) clean.put(entry.getKey().trim(), entry.getValue());\n }\n if (!clean.containsKey(\"id\")) throw new IllegalArgumentException(\"missing id\");\n return Map.of(\"ok\", true, \"data\", clean);\n }\n}\n```\n\nTests:\n```java\nimport static org.junit.jupiter.api.Assertions.*;\nimport java.util.Map;\nimport org.junit.jupiter.api.Test;\n\nclass RequestHandlerTest {\n @Test\n void requiresId() {\n assertThrows(IllegalArgumentException.class, () -> RequestHandler.handleRequest(Map.of(\"name\", \"x\")));\n }\n}\n```\n\nVerification:\n- `./gradlew test`\n- `mvn test`\n\nEngineering notes:\n- Language: Java\n- Framework/tooling: Spring Boot\n- Stack context: Spring Boot, PostgreSQL, JUnit, Gradle, Docker, GitHub Actions\n- Domain: document processing API\n- Task type: security_logic_interaction\n- Difficulty: hard\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: Repository domain: document processing API\nPrimary language: Python\nFramework/tooling: FastAPI\nReported problem: S3-compatible upload inconsistency\nTask type: test_repair\nDifficulty: medium\n\nProduce a complete professional engineering response:\n1. Diagnose the root cause.\n2. Provide the corrected implementation or patch.\n3. Add tests.\n4. Add verification commands.\n5. Note edge cases and any migration or rollback risk.\n\nRepository sketch:\nrepo/\n app/\n api.py\n service.py\n models.py\n tests/\n test_api.py\n pyproject.toml\n\nQuality target:\n- Minimal diff unless redesign is clearly required\n- Production-ready code\n- No placeholders\n- Secure defaults\n- Clear acceptance of failure cases\n\nFocus: Focus on complete implementation quality, patch correctness, tests, and production readiness.\n\nassistant: Diagnosis:\n- Root cause: the failure around S3-compatible upload inconsistency is caused by missing validation, weak edge-case handling, or unsafe lifecycle behavior in the current implementation.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```python\nfrom __future__ import annotations\n\nfrom dataclasses import dataclass\nfrom typing import Any\n\n@dataclass\nclass ServiceResult:\n ok: bool\n data: dict[str, Any]\n error: str | None = None\n\ndef normalize_payload(payload: dict[str, Any]) -> dict[str, Any]:\n if not isinstance(payload, dict):\n raise TypeError(\"payload must be a dict\")\n clean: dict[str, Any] = {}\n for key, value in payload.items():\n if value is None:\n continue\n clean[str(key).strip()] = value\n return clean\n\ndef handle_s3_compatible_upload_inconsistency(payload: dict[str, Any]) -> ServiceResult:\n clean = normalize_payload(payload)\n if \"id\" not in clean:\n return ServiceResult(ok=False, data={}, error=\"missing id\")\n return ServiceResult(ok=True, data=clean)\n```\n\nTests:\n```python\nimport pytest\nfrom app.service import handle_jwt_refresh_token_rotation as handler\n\ndef test_handler_accepts_valid_payload():\n result = handler({\"id\": 7, \"name\": \"ok\", \"unused\": None})\n assert result.ok is True\n assert result.data == {\"id\": 7, \"name\": \"ok\"}\n\ndef test_handler_rejects_missing_id():\n result = handler({\"name\": \"x\"})\n assert result.ok is False\n assert result.error == \"missing id\"\n```\n\nVerification:\n- `pytest -q`\n- `ruff check .`\n- `python -m compileall .`\n\nEngineering notes:\n- Language: Python\n- Framework/tooling: FastAPI\n- Stack context: Spring Boot, PostgreSQL, JUnit, Gradle, Docker, GitHub Actions\n- Domain: document processing API\n- Task type: test_repair\n- Difficulty: medium\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "Refactor to typed, mostly-immutable Python and add minimal tests.\n\n```python\nclass C70735:\n def __init__(self, values): self.values=list(values)\n def mean(self): return sum(self.values)/len(self.values)\n```\nReturn `m51595.py` and `test_m51595.py`.\n\n```python\n# m51595.py\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom typing import Iterable, Tuple\n\n@dataclass(frozen=True)\nclass C70735:\n values: Tuple[float, ...]\n\n @staticmethod\n def create(values: Iterable[float]) -> \"C70735\":\n vals = tuple(float(v) for v in values)\n if not vals: raise ValueError(\"empty\")\n return C70735(vals)\n\n def mean(self) -> float:\n return sum(self.values)/len(self.values)\n```\n\n```python\n# test_m51595.py\nimport pytest\nfrom m51595 import C70735\n\ndef test_mean():\n assert C70735.create([1,2,3]).mean() == 2.0\ndef test_empty():\n with pytest.raises(ValueError):\n C70735.create([])\n```", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: Repository domain: document processing API\nPrimary language: YAML\nFramework/tooling: Kubernetes\nReported problem: S3-compatible upload inconsistency\nTask type: repo_issue_patch\nDifficulty: hard\n\nProduce a complete professional engineering response:\n1. Diagnose the root cause.\n2. Provide the corrected implementation or patch.\n3. Add tests.\n4. Add verification commands.\n5. Note edge cases and any migration or rollback risk.\n\nRepository sketch:\nrepo/\n .github/workflows/ci.yml\n docker-compose.yml\n deploy/\n app.yaml\n\nQuality target:\n- Minimal diff unless redesign is clearly required\n- Production-ready code\n- No placeholders\n- Secure defaults\n- Clear acceptance of failure cases\n\nFocus: Focus on complete implementation quality, patch correctness, tests, and production readiness.\n\nassistant: Diagnosis:\n- Root cause: the failure around S3-compatible upload inconsistency is caused by missing validation, weak edge-case handling, or unsafe lifecycle behavior in the current implementation.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```yaml\nname: ci\non: [push, pull_request]\njobs:\n test:\n runs-on: ubuntu-latest\n steps:\n - uses: actions/checkout@v4\n - name: Validate\n run: echo \"validated\"\n```\n\nTests:\n```yaml\n# Verification:\n# - validate syntax\n# - run smoke workflow\n# - fail fast on broken config\n```\n\nVerification:\n- `validate workflow syntax`\n- `run CI smoke job`\n\nEngineering notes:\n- Language: YAML\n- Framework/tooling: Kubernetes\n- Stack context: Spring Boot, PostgreSQL, JUnit, Gradle, Docker, GitHub Actions\n- Domain: document processing API\n- Task type: repo_issue_patch\n- Difficulty: hard\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "Build an elite-grade solution in the domain of databases for scenario: document indexing.\nPrimary language: typescript.\nDifficulty: expert.\nConstraints: avoid undefined behavior and data races, make the interface contract explicit, document performance characteristics, assume untrusted inputs; validate and sanitize.\nComponent: component_dojmvka.\nAssume schema changes every sprint; must be backward compatible.\nTask: Provide SLOs, alerting, dashboards, runbooks, and incident playbook. Include chaos testing and safe rollout strategy.\n\nOutput: rigorous solution with invariants, failure modes, and performance notes.\nOutput: SLOs + alerts + runbooks + chaos strategy.\n\n**SLOs**\n- Availability: 99.9% monthly\n- Latency: p95 < 200ms, p99 < 400ms\n- Error rate: < 0.1%\n\n**Alerts**\n- Burn-rate alerts for SLOs (fast/slow windows)\n- Saturation: CPU, memory, queue depth, DB connections\n- Dependency health: cache hit rate drop, downstream timeouts\n\n**Runbooks**\n- Triage: identify blast radius, feature-flag rollback, capacity mitigation\n- Post-incident: timeline, contributing factors, action items\n\n**Chaos**\n- Inject latency, partial outages, and restarts in staging; verify steady-state SLOs.\n\n\nExpert checks: state-machine reasoning, concurrency stress, and upgrade/rollback validated.", "source": "WithinUsAI/Elite_GOD_Coder_100k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Fix a bug and add tests.\n\nFile: r7ke1x.py\n```python\ndef fmsvjwbtd(n: int) -> int:\n \"\"\"Sum 1..n inclusive.\"\"\"\n if n < 0:\n raise ValueError(\"n must be non-negative\")\n total = 0\n for k in range(n): # BUG: should include n\n total += k\n return total\n```\n\nReturn unified diffs for r7ke1x.py and test_r7ke1x.py (pytest).\n\n*** Begin Patch\n*** Update File: r7ke1x.py\n@@\n def fmsvjwbtd(n: int) -> int:\n@@\n total = 0\n- for k in range(n): # BUG: should include n\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_r7ke1x.py\n+import pytest\n+from r7ke1x import fmsvjwbtd\n+\n+def test_zero():\n+ assert fmsvjwbtd(0) == 0\n+\n+def test_one():\n+ assert fmsvjwbtd(1) == 1\n+\n+def test_small():\n+ assert fmsvjwbtd(7) == 28\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ fmsvjwbtd(-1)\n+\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: System domain: search service\nStack: Airflow, dbt, DuckDB, MinIO, pytest\nCross-layer incident: path traversal on downloads\nTask type: deploy_runtime_patch\nDifficulty: hard\n\nSolve this as a complete-project engineer.\nOutput must include:\n- root cause across layers\n- final implementation patch\n- tests touching at least two layers\n- deployment or observability note\n- verification commands\n\nRepository sketch:\nrepo/\n src/main.cpp\n src/service.cpp\n include/service.h\n tests/test_service.cpp\n CMakeLists.txt\n\nFocus: Focus on multi-layer debugging across frontend, backend, database, CI, caching, and deployment.\n\nassistant: Diagnosis:\n- Root cause: path traversal on downloads crosses service boundaries, so the fix must align code, contracts, tests, and deployment behavior.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```cpp\n#include \n#include \n\nusing Payload = std::unordered_map;\n\nPayload normalize_payload(const Payload& in) {\n Payload out;\n for (const auto& [k, v] : in) {\n if (!v.empty()) out[k] = v;\n }\n return out;\n}\n```\n\nTests:\n```cpp\nTEST_CASE(\"normalize_payload filters empty values\") {\n Payload in{{\"id\",\"7\"},{\"name\",\"\"}};\n auto out = normalize_payload(in);\n REQUIRE(out.count(\"id\") == 1);\n REQUIRE(out.count(\"name\") == 0);\n}\n```\n\nVerification:\n- `cmake --build build`\n- `ctest --test-dir build`\n\nEngineering notes:\n- Language: C++\n- Framework/tooling: STL\n- Stack context: Airflow, dbt, DuckDB, MinIO, pytest\n- Domain: search service\n- Task type: deploy_runtime_patch\n- Difficulty: hard\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Produce an offline-first self-evolving code assistant architecture named `q4h9rv4o_fj7`.\nMust include: module layout, patch-safety policy, evaluation gates (tests/lint/types), versioned memory index.\n\nArchitecture: `q4h9rv4o_fj7` (offline-first, self-evolving)\n\nModules\n- core/loop.py: evolve → validate → accept/reject (bounded iterations)\n- patching/: diff builder, safe apply, atomic writes, rollback points\n- policy/: allowlist paths, deny globs (.git/, __pycache__/, binaries), patch size caps\n- signals/: parse pytest/ruff/mypy into normalized findings\n- memory/index.jsonl: append-only snapshots (hashes, metrics, rationale)\n\nSafety gates\n- refuse path traversal/symlink escapes; never edit binaries\n- accept only if tests/lint/types stay green or improve", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: Repository domain: team dashboard\nPrimary language: C++\nFramework/tooling: STL\nReported problem: N+1 query explosion\nTask type: test_repair\nDifficulty: medium\n\nProduce a complete professional engineering response:\n1. Diagnose the root cause.\n2. Provide the corrected implementation or patch.\n3. Add tests.\n4. Add verification commands.\n5. Note edge cases and any migration or rollback risk.\n\nRepository sketch:\nrepo/\n src/main.cpp\n src/service.cpp\n include/service.h\n tests/test_service.cpp\n CMakeLists.txt\n\nQuality target:\n- Minimal diff unless redesign is clearly required\n- Production-ready code\n- No placeholders\n- Secure defaults\n- Clear acceptance of failure cases\n\nFocus: Focus on complete implementation quality, patch correctness, tests, and production readiness.\n\nassistant: Diagnosis:\n- Root cause: the failure around N+1 query explosion is caused by missing validation, weak edge-case handling, or unsafe lifecycle behavior in the current implementation.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```cpp\n#include \n#include \n\nusing Payload = std::unordered_map;\n\nPayload normalize_payload(const Payload& in) {\n Payload out;\n for (const auto& [k, v] : in) {\n if (!v.empty()) out[k] = v;\n }\n return out;\n}\n```\n\nTests:\n```cpp\nTEST_CASE(\"normalize_payload filters empty values\") {\n Payload in{{\"id\",\"7\"},{\"name\",\"\"}};\n auto out = normalize_payload(in);\n REQUIRE(out.count(\"id\") == 1);\n REQUIRE(out.count(\"name\") == 0);\n}\n```\n\nVerification:\n- `cmake --build build`\n- `ctest --test-dir build`\n\nEngineering notes:\n- Language: C++\n- Framework/tooling: STL\n- Stack context: Next.js, Node.js, Prisma, PostgreSQL, Playwright, Docker\n- Domain: team dashboard\n- Task type: test_repair\n- Difficulty: medium\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "Build an elite-grade solution in the domain of stream processing for scenario: chat messaging.\nPrimary language: python.\nDifficulty: hard.\nConstraints: document performance characteristics, assume untrusted inputs; validate and sanitize, include invariants and failure modes.\nComponent: component_ysfmwwd.\nAssume cold-start and memory limits are tight.\nTask: Provide a cross-language reference (API contract + implementation in two languages) and compatibility tests.\n\nOutput: production blueprint plus correctness arguments and test strategy.\nOutput: API contract + two implementations + compat tests.\n\n**Contract**\n- JSON schema for request/response; strict field validation; explicit version.\n\n**Example**\n- Implement validator + handler in Python and TypeScript.\n- Compatibility tests: same inputs produce equivalent outputs; reject unknown fields when in strict mode.\n\n\nHard checks: failure injection tests and performance regressions gated.", "source": "WithinUsAI/Elite_GOD_Coder_100k"} {"text": "Create a comprehensive test plan and automated tests for rate limiting in a document processing product.\nTarget platform: backend (Python FastAPI).\nRequirements: unit/integration tests, edge cases, load tests strategy, and CI gates.\nConstraints: must be easy to extend, must be performant under load, must include type hints where applicable, must be observable (logs/metrics/traces), must include clear error handling.\nDifficulty: expert. Assume schema evolves frequently; design for migrations.\n\nOutput: engineering-grade answer with edge cases covered.\nDeliverable: test plan + automation guidance.\n\n**Unit tests**\n- Validation: malformed payloads rejected with correct codes.\n- AuthZ: tenant boundary enforced.\n- Idempotency: replay returns same response; conflicting reuse yields 409.\n\n**Integration tests**\n- DB transaction behavior; unique constraints.\n- Cache behavior: correctness under concurrent requests.\n\n**Load tests**\n- 10k RPS target: measure p95 latency, error rate, saturation.\n\n**CI gates**\n- Lint + typecheck + unit tests required.\n- Coverage threshold for critical modules.\n- Block merge on flaky test detection.\n\n\nHard-mode checks: concurrency safety, idempotency, and rollback validated; add chaos tests where feasible.", "source": "WithinUsAI/GOD_Coder_100k"} {"text": "Refactor a Python module used for parsing into a clean, extensible design.\nRequirements: outline the new architecture briefly, then provide the refactored code and tests.\nConstraints: must handle Windows paths safely, must include type hints.\nDifficulty: medium. Ensure the API is testable via dependency injection.\n\nDeliverable: corrected code and verification tests.\nArchitecture:\n- Public facade class coordinating concerns (parsing, validation, persistence)\n- Small pure functions for testability\n- No global state; dependency injection for filesystem I/O\n\n```python\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom pathlib import Path\nfrom typing import Protocol, Iterable\nimport json\n\nclass Store(Protocol):\n def write_text(self, path: Path, data: str) -> None: ...\n\nclass FSStore:\n def write_text(self, path: Path, data: str) -> None:\n path.parent.mkdir(parents=True, exist_ok=True)\n path.write_text(data, encoding=\"utf-8\")\n\n@dataclass(frozen=True, slots=True)\nclass Item:\n name: str\n qty: int\n\ndef parse_items(lines: Iterable[str]) -> list[Item]:\n out: list[Item] = []\n for i, line in enumerate(lines, 1):\n s = line.strip()\n if not s:\n continue\n obj = json.loads(s)\n if not isinstance(obj, dict):\n raise ValueError(f\"line {i}: expected object\")\n name = obj.get(\"name\")\n qty = obj.get(\"qty\")\n if not isinstance(name, str) or not name:\n raise ValueError(f\"line {i}: name must be str\")\n if not isinstance(qty, int) or qty < 0:\n raise ValueError(f\"line {i}: qty must be non-negative int\")\n out.append(Item(name, qty))\n return out\n\nclass InventoryWriter:\n def __init__(self, base_dir: Path, store: Store | None = None) -> None:\n self._base = base_dir\n self._store: Store = store or FSStore()\n\n def write(self, rel_path: str, items: list[Item]) -> Path:\n dst = (self._base / rel_path).resolve()\n base = self._base.resolve()\n if dst != base and base not in dst.parents:\n raise ValueError(\"unsafe path traversal\")\n payload = json.dumps([item.__dict__ for item in items], ensure_ascii=False)\n self._store.write_text(dst, payload)\n return dst\n```\n\n```python\nimport json\nfrom pathlib import Path\nimport pytest\nfrom module_under_test import InventoryWriter, parse_items\n\ndef test_parse_items_valid():\n lines = [json.dumps({\"name\":\"x\",\"qty\":1})]\n assert parse_items(lines)[0].name == \"x\"\n\ndef test_writer_blocks_traversal(tmp_path: Path):\n w = InventoryWriter(tmp_path)\n with pytest.raises(ValueError):\n w.write(\"../evil.json\", [])\n```", "source": "WithinUsAI/python_GOD_coder_100k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Produce an offline-first self-evolving code assistant architecture named `i7tcyaxsg5j9`.\nMust include: module layout, patch-safety policy, evaluation gates (tests/lint/types), versioned memory index.\n\nArchitecture: `i7tcyaxsg5j9` (offline-first, self-evolving)\n\nModules\n- core/loop.py: evolve → validate → accept/reject (bounded iterations)\n- patching/: diff builder, safe apply, atomic writes, rollback points\n- policy/: allowlist paths, deny globs (.git/, __pycache__/, binaries), patch size caps\n- signals/: parse pytest/ruff/mypy into normalized findings\n- memory/index.jsonl: append-only snapshots (hashes, metrics, rationale)\n\nSafety gates\n- refuse path traversal/symlink escapes; never edit binaries\n- accept only if tests/lint/types stay green or improve", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Build an elite-grade solution in the domain of gpu compute for scenario: job scheduler.\nPrimary language: python.\nDifficulty: medium.\nConstraints: design for backward compatibility and migrations, include invariants and failure modes, assume untrusted inputs; validate and sanitize.\nComponent: component_hjzhsfg.\nAssume 50k RPS and p99 < 250ms.\nTask: Define properties/invariants and implement property-based tests (or generative tests) with a reference model and edge-case generators.\n\nOutput: rigorous solution with invariants, failure modes, and performance notes.\nOutput: properties + reference model + generative tests.\n\n**Properties**\n- Idempotency: replayed command yields same result.\n- Monotonicity: versions only increase.\n- Conservation: for queues, produced items == consumed items (multiset) under no-loss assumption.\n\n**Approach**\n- Write a small reference model (pure function).\n- Generate random sequences of operations; compare implementation outputs to model.\n\n\nChecks: boundary validation and deterministic behavior verified.", "source": "WithinUsAI/Elite_GOD_Coder_100k"} {"text": "Write pytest tests for `f11811`.\n\n```python\ndef f11811(a: int, b: int) -> int:\n return a*a + b*b\n```\nInclude edge cases and a property-style check.\n\n```python\nimport random\nfrom m15973 import f11811\n\ndef test_known():\n assert f11811(3,4) == 25\n\ndef test_zero():\n assert f11811(0,0) == 0\n\ndef test_property_nonnegative():\n for _ in range(200):\n a=random.randint(-50,50)\n b=random.randint(-50,50)\n assert f11811(a,b) >= 0\n```", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Task type: compiler_frontend\nScenario: identity and access\nDomain focus: GPU serving\nPrimary language: go\nDifficulty: expert\nScale/SLO: p99 < 50ms\nComponent: component_vyikafeq\nConstraints: explicit contracts and invariants, include performance model and limits, include failure modes and recovery, assume adversarial inputs; validate everything, include verification strategy, include test vectors and fuzz strategy\nAssume schema changes every sprint; must be backward compatible.\nDeliverable: Design a DSL language frontend: lexer/parser, AST, type checking, error reporting, and tests.\n\nOutput: rigorous design + invariants + verification plan + implementation sketch.\n**Contract**\n- Inputs validated at the boundary; explicit error taxonomy.\n- Idempotency for side effects via request_id; deterministic replay.\n- Backward compatibility: additive changes by default; versioned breaking changes.\n**Invariants**\n- Determinism: replay of the same event log yields identical outputs.\n- Liveness: under bounded faults and stable network, progress occurs.\n- Safety: state transitions preserve invariants; no partial commit leaks.\n**Failure modes & recovery**\n- Network partition: minority cannot commit; clients receive retriable errors.\n- Duplicate requests: de-duplicate by (tenant, request_id) returning cached response.\n- Crash during commit: WAL replay completes or transaction aborts; no torn writes.\n**Security posture (defensive)**\n- Threat model: auth/authz, injection, replay/abuse, supply chain.\n- Least privilege; secrets in managed store; audit logs for sensitive ops.\n- Input normalization, parameterized queries, path traversal protections.\n**Verification strategy**\n- Canary + shadow traffic; invariants checked in production via assertions/metrics.\n- Deterministic simulation with fault injection (crash/partition/latency).\n- Fuzzing of parsers/framers/validators with corpus seeds.\n\n**Snippet**\n```text\nImplementation sketch: factor pure state-machine core; adapters for I/O; add deterministic replay log.\n```\nExpert checks: state-machine proof sketch + model checking; upgrade/rollback rehearsed.", "source": "WithinUsAI/Omega_Genesis_Coder_100k"} {"text": "Task type: network_protocol\nScenario: feature-flag evaluation\nDomain focus: compiler toolchains\nPrimary language: typescript\nDifficulty: expert+\nScale/SLO: 100k RPS peak\nComponent: component_emkguohf\nConstraints: include performance model and limits, include security threat model (defensive only), include failure modes and recovery, include test vectors and fuzz strategy, include deterministic replay plan\nAssume strict auditability and replayable history.\nDeliverable: Design an application protocol: framing, retries, backpressure, timeouts; include client/server skeleton and test vectors.\n\nOutput: elite engineering answer optimized for correctness, performance, and operability.\n**Contract**\n- Inputs validated at the boundary; explicit error taxonomy.\n- Idempotency for side effects via request_id; deterministic replay.\n- Backward compatibility: additive changes by default; versioned breaking changes.\n**Invariants**\n- Isolation: tenant boundary enforced; no cross-tenant reads/writes.\n- Liveness: under bounded faults and stable network, progress occurs.\n- Determinism: replay of the same event log yields identical outputs.\n**Failure modes & recovery**\n- Network partition: minority cannot commit; clients receive retriable errors.\n- Duplicate requests: de-duplicate by (tenant, request_id) returning cached response.\n- Crash during commit: WAL replay completes or transaction aborts; no torn writes.\n**Security posture (defensive)**\n- Threat model: auth/authz, injection, replay/abuse, supply chain.\n- Least privilege; secrets in managed store; audit logs for sensitive ops.\n- Input normalization, parameterized queries, path traversal protections.\n**Verification strategy**\n- Fuzzing of parsers/framers/validators with corpus seeds.\n- Property tests against a pure reference model (state machine).\n- Canary + shadow traffic; invariants checked in production via assertions/metrics.\n\n**Snippet**\n```text\nImplementation sketch: factor pure state-machine core; adapters for I/O; add deterministic replay log.\n```\nExpert+ checks: mechanized invariants (or exhaustive model checking), adversarial fuzzing, and multi-region failure drills.", "source": "WithinUsAI/Omega_Genesis_Coder_100k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Fix a bug and add tests.\n\nFile: o_yl2_.py\n```python\ndef a40p3wejhzsy(n: int) -> int:\n \"\"\"Sum 1..n inclusive.\"\"\"\n if n < 0:\n raise ValueError(\"n must be non-negative\")\n total = 0\n for k in range(n): # BUG: should include n\n total += k\n return total\n```\n\nReturn unified diffs for o_yl2_.py and test_o_yl2_.py (pytest).\n\n*** Begin Patch\n*** Update File: o_yl2_.py\n@@\n def a40p3wejhzsy(n: int) -> int:\n@@\n total = 0\n- for k in range(n): # BUG: should include n\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_o_yl2_.py\n+import pytest\n+from o_yl2_ import a40p3wejhzsy\n+\n+def test_zero():\n+ assert a40p3wejhzsy(0) == 0\n+\n+def test_one():\n+ assert a40p3wejhzsy(1) == 1\n+\n+def test_small():\n+ assert a40p3wejhzsy(7) == 28\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ a40p3wejhzsy(-1)\n+\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Design a production system for social media supporting offline-first sync.\nTarget platform: CI (GitHub Actions).\nRequirements: APIs, data model, scaling strategy, failure modes, and security.\nConstraints: must include documentation/comments, must avoid global state, must be performant under load, must include type hints where applicable, must be easy to extend.\nDifficulty: medium. Assume schema evolves frequently; design for migrations.\n\nOutput: engineering-grade answer with edge cases covered.\nDeliverable: system design with APIs, data model, and operational plan.\n\n**High-level architecture**\n- Edge: API Gateway + WAF\n- Core service: stateless app pods behind L7 LB\n- Data: Postgres (primary), Redis (cache + rate limit tokens), Object storage (uploads if needed)\n- Async: message queue (e.g., SQS/Rabbit) + worker pool for background jobs\n- Observability: structured logs + metrics + tracing\n\n**APIs (example)**\n- `POST /v1/{resource}` create (idempotent via `Idempotency-Key`)\n- `GET /v1/{resource}/{id}` read\n- `POST /v1/{resource}/{id}:action` command endpoint when side effects exist\n\n**Data model (Postgres)**\n- `resources(id UUID PK, tenant_id UUID, status TEXT, payload JSONB, created_at, updated_at)`\n- Unique constraint for idempotency: `(tenant_id, idempotency_key)` in a separate table:\n - `idempotency(tenant_id, key TEXT, request_hash TEXT, response JSONB, created_at, PRIMARY KEY(tenant_id,key))`\n\n**Scaling**\n- App layer scales horizontally; keep sessions out of process.\n- Cache reads in Redis; write-through invalidation on mutations.\n- Use connection pooling; consider read replicas for heavy reads.\n\n**Failure modes**\n- Retries: only for safe/ idempotent operations; exponential backoff + jitter.\n- Partial failures: background jobs must be idempotent; use a de-dup key.\n\n**Security**\n- AuthN: JWT/OIDC; AuthZ: RBAC/ABAC with tenant isolation\n- Validate all inputs; enforce per-tenant quotas/rate limits.\n\n**Rollout**\n- Dark launch + feature flags; canary; rapid rollback by toggling flags.\n\n\nChecks: input validation, tests, and safe defaults included.", "source": "WithinUsAI/GOD_Coder_100k"} {"text": "Task type: static_analyzer\nScenario: rate limit gateway\nDomain focus: data lineage & governance\nPrimary language: typescript\nDifficulty: expert\nScale/SLO: p99 < 50ms\nComponent: component_hllquxgn\nConstraints: include security threat model (defensive only), include test vectors and fuzz strategy, include failure modes and recovery, explicit contracts and invariants, avoid data races and undefined behavior\nAssume tight memory budget and cold-start constraints.\nDeliverable: Design a static analyzer for a safety property (e.g., taint/SQLi prevention); include rule set, false-positive strategy, and tests.\n\nOutput: elite engineering answer optimized for correctness, performance, and operability.\n**Contract**\n- Inputs validated at the boundary; explicit error taxonomy.\n- Idempotency for side effects via request_id; deterministic replay.\n- Backward compatibility: additive changes by default; versioned breaking changes.\n**Invariants**\n- Isolation: tenant boundary enforced; no cross-tenant reads/writes.\n- Safety: state transitions preserve invariants; no partial commit leaks.\n- Liveness: under bounded faults and stable network, progress occurs.\n**Failure modes & recovery**\n- Duplicate requests: de-duplicate by (tenant, request_id) returning cached response.\n- Network partition: minority cannot commit; clients receive retriable errors.\n- Crash during commit: WAL replay completes or transaction aborts; no torn writes.\n**Security posture (defensive)**\n- Threat model: auth/authz, injection, replay/abuse, supply chain.\n- Least privilege; secrets in managed store; audit logs for sensitive ops.\n- Input normalization, parameterized queries, path traversal protections.\n**Verification strategy**\n- Property tests against a pure reference model (state machine).\n- Canary + shadow traffic; invariants checked in production via assertions/metrics.\n- Deterministic simulation with fault injection (crash/partition/latency).\n\n**Snippet**\n```text\nImplementation sketch: factor pure state-machine core; adapters for I/O; add deterministic replay log.\n```\nExpert checks: state-machine proof sketch + model checking; upgrade/rollback rehearsed.", "source": "WithinUsAI/Omega_Genesis_Coder_100k"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: Language: TypeScript\nFramework/tooling: Express\nDomain: data pipeline\nLogic challenge: stale cache invalidation\nTask type: distributed_debug\nDifficulty: hard\n\nReturn a rigorous engineering answer:\n- identify the hidden root cause or logical failure\n- present the corrected implementation\n- add tests that prove the fix\n- list verification commands\n- explain why naive fixes are insufficient when relevant\n\nRepository sketch:\nrepo/\n src/\n api.ts\n service.ts\n schema.ts\n tests/\n api.test.ts\n package.json\n\nFocus: Focus on ambiguity, misleading symptoms, hidden root causes, and high-stakes debugging.\n\nassistant: Diagnosis:\n- Hidden root cause: stale cache invalidation presents misleading symptoms, so the patch must target the actual logic boundary rather than the first visible failure.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```ts\ntype Payload = Record;\n\nexport function normalizePayload(payload: Payload): Payload {\n if (!payload || typeof payload !== \"object\" || Array.isArray(payload)) {\n throw new TypeError(\"payload must be a plain object\");\n }\n return Object.fromEntries(\n Object.entries(payload)\n .filter(([, value]) => value !== null && value !== undefined)\n .map(([key, value]) => [String(key).trim(), value])\n );\n}\n\nexport function handleStaleCacheInvalidation(payload: Payload) {\n const clean = normalizePayload(payload);\n if (!(\"id\" in clean)) {\n return { ok: false, data: {}, error: \"missing id\" };\n }\n return { ok: true, data: clean, error: null };\n}\n```\n\nTests:\n```ts\nimport { describe, it, expect } from \"vitest\";\nimport { handleStaleCacheInvalidation } from \"../src/service\";\n\ndescribe(\"handler\", () => {\n it(\"accepts valid input\", () => {\n expect(handleStaleCacheInvalidation({ id: 7, name: \"ok\", unused: null })).toEqual({\n ok: true,\n data: { id: 7, name: \"ok\" },\n error: null\n });\n });\n\n it(\"rejects missing id\", () => {\n expect(handleStaleCacheInvalidation({ name: \"x\" }).error).toMatch(/missing id/);\n });\n});\n```\n\nVerification:\n- `npm test`\n- `npm run typecheck`\n- `npm run lint`\n\nEngineering notes:\n- Language: TypeScript\n- Framework/tooling: Express\n- Stack context: Next.js, Node.js, Prisma, PostgreSQL, Playwright, Docker\n- Domain: data pipeline\n- Task type: distributed_debug\n- Difficulty: hard\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "Build an elite-grade solution in the domain of realtime systems for scenario: multi-tenant SaaS.\nPrimary language: rust.\nDifficulty: hard.\nConstraints: make the interface contract explicit, provide rollout and rollback guidance, avoid undefined behavior and data races.\nComponent: component_qfuooce.\nAssume compliance requires data deletion with proofs.\nTask: Provide threat model, secure-by-default design, and defensive implementation patterns. No offensive/exploit content; focus on prevention and detection.\n\nOutput: elite-grade engineering answer with contracts, edge cases, and verification.\nOutput: threat model + defensive design + detection.\n\n**Threat model**\n- Auth: token theft → short-lived tokens, rotation, audience checks\n- AuthZ: privilege escalation → centralized policy checks, tenant isolation tests\n- Input: injection → strict validation, parameterized queries, output encoding\n- Supply chain: dependencies → lockfiles, signature verification, SBOM\n\n**Defensive patterns**\n- Idempotency keys for side effects; replay-safe handlers\n- Secrets in managed store; never logs\n- Audit logging for sensitive ops; tamper-evident storage\n\n**Detection**\n- Alert on unusual auth failures, access pattern anomalies, and data exfil signals.\n\n\nHard checks: failure injection tests and performance regressions gated.", "source": "WithinUsAI/Elite_GOD_Coder_100k"} {"text": "Refactor to typed, mostly-immutable Python and add minimal tests.\n\n```python\nclass C45631:\n def __init__(self, values): self.values=list(values)\n def mean(self): return sum(self.values)/len(self.values)\n```\nReturn `m26587.py` and `test_m26587.py`.\n\n```python\n# m26587.py\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom typing import Iterable, Tuple\n\n@dataclass(frozen=True)\nclass C45631:\n values: Tuple[float, ...]\n\n @staticmethod\n def create(values: Iterable[float]) -> \"C45631\":\n vals = tuple(float(v) for v in values)\n if not vals: raise ValueError(\"empty\")\n return C45631(vals)\n\n def mean(self) -> float:\n return sum(self.values)/len(self.values)\n```\n\n```python\n# test_m26587.py\nimport pytest\nfrom m26587 import C45631\n\ndef test_mean():\n assert C45631.create([1,2,3]).mean() == 2.0\ndef test_empty():\n with pytest.raises(ValueError):\n C45631.create([])\n```", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Optimize while preserving behavior and order.\n\n```python\ndef f60861(xs):\n out=[]\n for x in xs:\n if x not in out: out.append(x)\n return out\n```\nReturn `m80123.py` with types and O(n) average.\n\n```python\n# m80123.py\nfrom __future__ import annotations\nfrom typing import Iterable, List, Set, TypeVar\nT=TypeVar(\"T\")\n\ndef f60861(xs: Iterable[T]) -> List[T]:\n \"\"\"Unique items preserving first-seen order.\"\"\"\n seen: Set[T]=set()\n out: List[T]=[]\n for x in xs:\n if x in seen: continue\n seen.add(x); out.append(x)\n return out\n```", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Write pytest tests for `f80749`.\n\n```python\ndef f80749(a: int, b: int) -> int:\n return a*a + b*b\n```\nInclude edge cases and a property-style check.\n\n```python\nimport random\nfrom m40107 import f80749\n\ndef test_known():\n assert f80749(3,4) == 25\n\ndef test_zero():\n assert f80749(0,0) == 0\n\ndef test_property_nonnegative():\n for _ in range(200):\n a=random.randint(-50,50)\n b=random.randint(-50,50)\n assert f80749(a,b) >= 0\n```", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Refactor to modern typed Python with immutability and tests.\n\nFile: ibvpu1rv7.py\n```python\nclass Vgmu5Ltcoewe:\n def __init__(self, name, values):\n self.name = name\n self.values = list(values)\n def add(self, v):\n self.values.append(v)\n def mean(self):\n s = 0\n for x in self.values:\n s += x\n return s / len(self.values)\n```\n\nReturn full new ibvpu1rv7.py and test_ibvpu1rv7.py.\n\n# ibvpu1rv7.py\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom typing import Iterable, Tuple\n\n@dataclass(frozen=True)\nclass Vgmu5Ltcoewe:\n name: str\n values: Tuple[float, ...]\n\n @staticmethod\n def create(name: str, values: Iterable[float]) -> \"Vgmu5Ltcoewe\":\n vals = tuple(float(v) for v in values)\n if not vals:\n raise ValueError(\"values must be non-empty\")\n return Vgmu5Ltcoewe(name=name, values=vals)\n\n def add(self, v: float) -> \"Vgmu5Ltcoewe\":\n return Vgmu5Ltcoewe(name=self.name, values=self.values + (float(v),))\n\n def mean(self) -> float:\n return sum(self.values) / len(self.values)\n\n# test_ibvpu1rv7.py\nimport pytest\nfrom ibvpu1rv7 import Vgmu5Ltcoewe\n\ndef test_mean_and_add():\n c = Vgmu5Ltcoewe.create(\"a\", [1, 2, 3])\n assert c.mean() == 2.0\n assert c.add(5).mean() == (1 + 2 + 3 + 5) / 4\n\ndef test_empty_raises():\n with pytest.raises(ValueError):\n Vgmu5Ltcoewe.create(\"x\", [])", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: Language: C++\nFramework/tooling: CMake\nDomain: benchmark harness\nLogic challenge: streaming timeout handling\nTask type: multi_service_security_patch\nDifficulty: expert\n\nReturn a rigorous engineering answer:\n- identify the hidden root cause or logical failure\n- present the corrected implementation\n- add tests that prove the fix\n- list verification commands\n- explain why naive fixes are insufficient when relevant\n\nRepository sketch:\nrepo/\n src/main.cpp\n src/service.cpp\n include/service.h\n tests/test_service.cpp\n CMakeLists.txt\n\nFocus: Focus on staff-level problem solving with multi-file patches, rollout implications, performance and security tradeoffs.\n\nassistant: Diagnosis:\n- Staff-level diagnosis: streaming timeout handling impacts correctness, operability, and future maintenance, so the fix must be minimal where possible but complete where necessary.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```cpp\n#include \n#include \n\nusing Payload = std::unordered_map;\n\nPayload normalize_payload(const Payload& in) {\n Payload out;\n for (const auto& [k, v] : in) {\n if (!v.empty()) out[k] = v;\n }\n return out;\n}\n```\n\nTests:\n```cpp\nTEST_CASE(\"normalize_payload filters empty values\") {\n Payload in{{\"id\",\"7\"},{\"name\",\"\"}};\n auto out = normalize_payload(in);\n REQUIRE(out.count(\"id\") == 1);\n REQUIRE(out.count(\"name\") == 0);\n}\n```\n\nVerification:\n- `cmake --build build`\n- `ctest --test-dir build`\n\nEngineering notes:\n- Language: C++\n- Framework/tooling: CMake\n- Stack context: Spring Boot, PostgreSQL, JUnit, Gradle, Docker, GitHub Actions\n- Domain: benchmark harness\n- Task type: multi_service_security_patch\n- Difficulty: expert\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "Write pytest tests for `f91684`.\n\n```python\ndef f91684(a: int, b: int) -> int:\n return a*a + b*b\n```\nInclude edge cases and a property-style check.\n\n```python\nimport random\nfrom m98812 import f91684\n\ndef test_known():\n assert f91684(3,4) == 25\n\ndef test_zero():\n assert f91684(0,0) == 0\n\ndef test_property_nonnegative():\n for _ in range(200):\n a=random.randint(-50,50)\n b=random.randint(-50,50)\n assert f91684(a,b) >= 0\n```", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Design and implement an algorithm for rate limiting.\nRequirements: define inputs/outputs, implement solution with complexity analysis, and include tests.\nConstraints: must be memory-efficient, must include tests.\nDifficulty: hard. Ensure the API is testable via dependency injection.\n\nDeliverable: implementation + tests.\nProblem: compute rolling sums over events (ts:int,value:int) with window W seconds. Events may be out-of-order.\n\nComplexity: sorting O(n log n); window maintenance O(n); memory O(k).\n\n```python\nfrom __future__ import annotations\nfrom collections import deque\nfrom dataclasses import dataclass\nfrom typing import Iterable, List, Tuple\n\n@dataclass(frozen=True, slots=True)\nclass Event:\n ts: int\n value: int\n\ndef rolling_sum(events: Iterable[Event], window_s: int) -> List[Tuple[int,int]]:\n if window_s < 0:\n raise ValueError(\"window_s must be >= 0\")\n evs = sorted(events, key=lambda e: e.ts)\n q: deque[Event] = deque()\n s = 0\n out: List[Tuple[int,int]] = []\n for e in evs:\n q.append(e)\n s += e.value\n cutoff = e.ts - window_s\n while q and q[0].ts < cutoff:\n old = q.popleft()\n s -= old.value\n out.append((e.ts, s))\n return out\n```\n\n```python\nimport pytest\nfrom module_under_test import Event, rolling_sum\n\ndef test_rolling_sum():\n ev = [Event(10,1), Event(11,2), Event(20,5)]\n assert rolling_sum(ev, 5) == [(10,1),(11,3),(20,5)]\n```", "source": "WithinUsAI/python_GOD_coder_100k"} {"text": "Fix the bug and add pytest tests.\n\n```python\ndef f62399(n: int) -> int:\n # sum 1..n inclusive\n if n < 0: raise ValueError\n total = 0\n for k in range(n): # BUG\n total += k\n return total\n```\nReturn unified diffs for `m66057.py` and `test_m66057.py`.\n\n*** Begin Patch\n*** Update File: m66057.py\n@@\n def f62399(n: int) -> int:\n@@\n- for k in range(n): # BUG\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_m66057.py\n+import pytest\n+from m66057 import f62399\n+\n+def test_small():\n+ assert f62399(7) == 28\n+\n+def test_zero():\n+ assert f62399(0) == 0\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ f62399(-1)\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Add a clear docstring and type hints to this function:\n\n```python\ndef f31572(s):\n return ''.join(x for x in s if x.isalnum()).lower()\n```\n\n```python\nfrom __future__ import annotations\n\ndef f31572(s: str) -> str:\n \"\"\"Normalize a string: keep only alphanumerics and lowercase the result.\"\"\"\n return \"\".join(ch for ch in s if ch.isalnum()).lower()\n```", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: System domain: document processing API\nStack: Spring Boot, PostgreSQL, JUnit, Gradle, Docker, GitHub Actions\nCross-layer incident: broken pagination cursor\nTask type: observability_debug_fix\nDifficulty: hard\n\nSolve this as a complete-project engineer.\nOutput must include:\n- root cause across layers\n- final implementation patch\n- tests touching at least two layers\n- deployment or observability note\n- verification commands\n\nRepository sketch:\nrepo/\n src/main.cpp\n src/service.cpp\n include/service.h\n tests/test_service.cpp\n CMakeLists.txt\n\nFocus: Focus on multi-layer debugging across frontend, backend, database, CI, caching, and deployment.\n\nassistant: Diagnosis:\n- Root cause: broken pagination cursor crosses service boundaries, so the fix must align code, contracts, tests, and deployment behavior.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```cpp\n#include \n#include \n\nusing Payload = std::unordered_map;\n\nPayload normalize_payload(const Payload& in) {\n Payload out;\n for (const auto& [k, v] : in) {\n if (!v.empty()) out[k] = v;\n }\n return out;\n}\n```\n\nTests:\n```cpp\nTEST_CASE(\"normalize_payload filters empty values\") {\n Payload in{{\"id\",\"7\"},{\"name\",\"\"}};\n auto out = normalize_payload(in);\n REQUIRE(out.count(\"id\") == 1);\n REQUIRE(out.count(\"name\") == 0);\n}\n```\n\nVerification:\n- `cmake --build build`\n- `ctest --test-dir build`\n\nEngineering notes:\n- Language: C++\n- Framework/tooling: Catch2\n- Stack context: Spring Boot, PostgreSQL, JUnit, Gradle, Docker, GitHub Actions\n- Domain: document processing API\n- Task type: observability_debug_fix\n- Difficulty: hard\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "Fix the bug and add pytest tests.\n\n```python\ndef f02701(n: int) -> int:\n # sum 1..n inclusive\n if n < 0: raise ValueError\n total = 0\n for k in range(n): # BUG\n total += k\n return total\n```\nReturn unified diffs for `m43243.py` and `test_m43243.py`.\n\n*** Begin Patch\n*** Update File: m43243.py\n@@\n def f02701(n: int) -> int:\n@@\n- for k in range(n): # BUG\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_m43243.py\n+import pytest\n+from m43243 import f02701\n+\n+def test_small():\n+ assert f02701(7) == 28\n+\n+def test_zero():\n+ assert f02701(0) == 0\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ f02701(-1)\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Implement a web feature for fintech: A/B experimentation.\nTarget platform: web (React + TypeScript).\nRequirements: accessible UI, API integration, and tests.\nConstraints: must include documentation/comments, must include clear error handling, must be secure-by-default, must include type hints where applicable.\nDifficulty: expert. Assume GDPR-style deletion requests must be supported.\n\nOutput: engineering-grade answer with edge cases covered.\nDeliverable: accessible React + TypeScript feature skeleton with tests.\n\n```tsx\n// Feature.tsx\nimport React, { useEffect, useMemo, useState } from \"react\";\n\ntype Item = { id: string; label: string };\n\nexport function Feature({ fetchItems }: { fetchItems: () => Promise }) {\n const [items, setItems] = useState([]);\n const [q, setQ] = useState(\"\");\n const filtered = useMemo(\n () => items.filter(i => i.label.toLowerCase().includes(q.toLowerCase())),\n [items, q]\n );\n\n useEffect(() => {\n let cancelled = false;\n fetchItems().then(xs => { if (!cancelled) setItems(xs); });\n return () => { cancelled = true; };\n }, [fetchItems]);\n\n return (\n
\n \n
    \n {filtered.map(i =>
  • {i.label}
  • )}\n
\n
\n );\n}\n```\n\n```tsx\n// Feature.test.tsx (vitest + testing-library)\nimport { render, screen } from \"@testing-library/react\";\nimport userEvent from \"@testing-library/user-event\";\nimport { Feature } from \"./Feature\";\n\ntest(\"filters items\", async () => {\n const fetchItems = async () => [{ id:\"1\", label:\"Alpha\" }, { id:\"2\", label:\"Beta\" }];\n render();\n expect(await screen.findByText(\"Alpha\")).toBeInTheDocument();\n await userEvent.type(screen.getByLabelText(\"Search\"), \"be\");\n expect(screen.queryByText(\"Alpha\")).toBeNull();\n expect(screen.getByText(\"Beta\")).toBeInTheDocument();\n});\n```\n\n\nHard-mode checks: concurrency safety, idempotency, and rollback validated; add chaos tests where feasible.", "source": "WithinUsAI/GOD_Coder_100k"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: Language: Python\nFramework/tooling: FastAPI\nDomain: feature flag service\nLogic challenge: unsafe deserialization\nTask type: algorithmic_correctness\nDifficulty: hard\n\nReturn a rigorous engineering answer:\n- identify the hidden root cause or logical failure\n- present the corrected implementation\n- add tests that prove the fix\n- list verification commands\n- explain why naive fixes are insufficient when relevant\n\nRepository sketch:\nrepo/\n app/\n api.py\n service.py\n models.py\n tests/\n test_api.py\n pyproject.toml\n\nFocus: Focus on strong structured logic with edge cases, data validation, and concurrency safety.\n\nassistant: Diagnosis:\n- Root cause: the failure around unsafe deserialization is caused by missing validation, weak edge-case handling, or unsafe lifecycle behavior in the current implementation.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```python\nfrom __future__ import annotations\n\nfrom dataclasses import dataclass\nfrom typing import Any\n\n@dataclass\nclass ServiceResult:\n ok: bool\n data: dict[str, Any]\n error: str | None = None\n\ndef normalize_payload(payload: dict[str, Any]) -> dict[str, Any]:\n if not isinstance(payload, dict):\n raise TypeError(\"payload must be a dict\")\n clean: dict[str, Any] = {}\n for key, value in payload.items():\n if value is None:\n continue\n clean[str(key).strip()] = value\n return clean\n\ndef handle_unsafe_deserialization(payload: dict[str, Any]) -> ServiceResult:\n clean = normalize_payload(payload)\n if \"id\" not in clean:\n return ServiceResult(ok=False, data={}, error=\"missing id\")\n return ServiceResult(ok=True, data=clean)\n```\n\nTests:\n```python\nimport pytest\nfrom app.service import handle_jwt_refresh_token_rotation as handler\n\ndef test_handler_accepts_valid_payload():\n result = handler({\"id\": 7, \"name\": \"ok\", \"unused\": None})\n assert result.ok is True\n assert result.data == {\"id\": 7, \"name\": \"ok\"}\n\ndef test_handler_rejects_missing_id():\n result = handler({\"name\": \"x\"})\n assert result.ok is False\n assert result.error == \"missing id\"\n```\n\nVerification:\n- `pytest -q`\n- `ruff check .`\n- `python -m compileall .`\n\nEngineering notes:\n- Language: Python\n- Framework/tooling: FastAPI\n- Stack context: Go, Gin, PostgreSQL, gRPC, Prometheus, Docker\n- Domain: feature flag service\n- Task type: algorithmic_correctness\n- Difficulty: hard\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "Design and implement an algorithm for log processing.\nRequirements: define inputs/outputs, implement solution with complexity analysis, and include tests.\nConstraints: must include tests, must include type hints, must avoid global state, must be streaming-friendly.\nDifficulty: easy. Support both Windows and POSIX paths correctly.\n\nDeliverable: production-ready reference solution.\nProblem: compute rolling sums over events (ts:int,value:int) with window W seconds. Events may be out-of-order.\n\nComplexity: sorting O(n log n); window maintenance O(n); memory O(k).\n\n```python\nfrom __future__ import annotations\nfrom collections import deque\nfrom dataclasses import dataclass\nfrom typing import Iterable, List, Tuple\n\n@dataclass(frozen=True, slots=True)\nclass Event:\n ts: int\n value: int\n\ndef rolling_sum(events: Iterable[Event], window_s: int) -> List[Tuple[int,int]]:\n if window_s < 0:\n raise ValueError(\"window_s must be >= 0\")\n evs = sorted(events, key=lambda e: e.ts)\n q: deque[Event] = deque()\n s = 0\n out: List[Tuple[int,int]] = []\n for e in evs:\n q.append(e)\n s += e.value\n cutoff = e.ts - window_s\n while q and q[0].ts < cutoff:\n old = q.popleft()\n s -= old.value\n out.append((e.ts, s))\n return out\n```\n\n```python\nimport pytest\nfrom module_under_test import Event, rolling_sum\n\ndef test_rolling_sum():\n ev = [Event(10,1), Event(11,2), Event(20,5)]\n assert rolling_sum(ev, 5) == [(10,1),(11,3),(20,5)]\n```", "source": "WithinUsAI/python_GOD_coder_100k"} {"text": "Build an elite-grade solution in the domain of operating systems for scenario: rate limiting gateway.\nPrimary language: rust.\nDifficulty: hard.\nConstraints: assume untrusted inputs; validate and sanitize, design for backward compatibility and migrations, document performance characteristics.\nComponent: component_qvnrqdk.\nAssume crash-only design; recovery must be deterministic.\nTask: Design a replication/consistency approach (e.g., leader-based, quorum reads/writes). Provide message flows, failure handling, and a minimal reference implementation skeleton.\n\nOutput: rigorous solution with invariants, failure modes, and performance notes.\nOutput: replication design + failure handling + minimal skeleton.\n\n**Model**\n- Leader-based replication with term + log index.\n- Quorum acks for durability: write committed when majority acks.\n- Read options: leader-read (linearizable) or quorum-read (monotonic if using read-index).\n\n**Message flow (write)**\n1. Client → Leader: Put(request_id, payload)\n2. Leader appends to log, sends AppendEntries to followers\n3. Followers append + ack\n4. On majority ack: commit index advances; apply to state machine; respond to client\n\n**Failure modes**\n- Leader crash: new election; uncommitted entries may be rolled back.\n- Partition: minority side cannot commit.\n- Duplicate requests: deduplicate by request_id stored in state.\n\n**Skeleton (Go pseudo)**\n```go\ntype Entry struct { Term uint64; Index uint64; Cmd []byte }\ntype Node struct {\n id int\n term uint64\n log []Entry\n commit uint64\n seen map[string][]byte // request_id -> response\n}\n```\n\n**Verification**\n- Invariant: committed index never decreases.\n- Property: if a write is committed, all future leaders contain it.\n- Test with simulated partitions and crash/restart.\n\n\nHard checks: failure injection tests and performance regressions gated.", "source": "WithinUsAI/Elite_GOD_Coder_100k"} {"text": "Task type: program_synthesis_safe\nScenario: document indexing pipeline\nDomain focus: program synthesis (safe)\nPrimary language: python\nDifficulty: expert+\nScale/SLO: p99 < 150ms\nComponent: component_fbryendf\nConstraints: include test vectors and fuzz strategy, include deterministic replay plan, explicit contracts and invariants, include security threat model (defensive only), include failure modes and recovery\nAssume weekly network partitions.\nDeliverable: Design a program-synthesis workflow that generates code from specs safely; include guardrails and verification.\n\nOutput: rigorous design + invariants + verification plan + implementation sketch.\n**Contract**\n- Inputs validated at the boundary; explicit error taxonomy.\n- Idempotency for side effects via request_id; deterministic replay.\n- Backward compatibility: additive changes by default; versioned breaking changes.\n**Invariants**\n- Determinism: replay of the same event log yields identical outputs.\n- Safety: state transitions preserve invariants; no partial commit leaks.\n- Liveness: under bounded faults and stable network, progress occurs.\n**Failure modes & recovery**\n- Crash during commit: WAL replay completes or transaction aborts; no torn writes.\n- Data corruption: checksums + scrubber; quarantine and rebuild from replicas/snapshots.\n- Duplicate requests: de-duplicate by (tenant, request_id) returning cached response.\n**Security posture (defensive)**\n- Threat model: auth/authz, injection, replay/abuse, supply chain.\n- Least privilege; secrets in managed store; audit logs for sensitive ops.\n- Input normalization, parameterized queries, path traversal protections.\n**Verification strategy**\n- Deterministic simulation with fault injection (crash/partition/latency).\n- Fuzzing of parsers/framers/validators with corpus seeds.\n- Canary + shadow traffic; invariants checked in production via assertions/metrics.\n\n**Snippet**\n```text\nImplementation sketch: factor pure state-machine core; adapters for I/O; add deterministic replay log.\n```\nExpert+ checks: mechanized invariants (or exhaustive model checking), adversarial fuzzing, and multi-region failure drills.", "source": "WithinUsAI/Omega_Genesis_Coder_100k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Refactor to modern typed Python with immutability and tests.\n\nFile: avcww0_nf1z1.py\n```python\nclass Bsl74Lzlu:\n def __init__(self, name, values):\n self.name = name\n self.values = list(values)\n def add(self, v):\n self.values.append(v)\n def mean(self):\n s = 0\n for x in self.values:\n s += x\n return s / len(self.values)\n```\n\nReturn full new avcww0_nf1z1.py and test_avcww0_nf1z1.py.\n\n# avcww0_nf1z1.py\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom typing import Iterable, Tuple\n\n@dataclass(frozen=True)\nclass Bsl74Lzlu:\n name: str\n values: Tuple[float, ...]\n\n @staticmethod\n def create(name: str, values: Iterable[float]) -> \"Bsl74Lzlu\":\n vals = tuple(float(v) for v in values)\n if not vals:\n raise ValueError(\"values must be non-empty\")\n return Bsl74Lzlu(name=name, values=vals)\n\n def add(self, v: float) -> \"Bsl74Lzlu\":\n return Bsl74Lzlu(name=self.name, values=self.values + (float(v),))\n\n def mean(self) -> float:\n return sum(self.values) / len(self.values)\n\n# test_avcww0_nf1z1.py\nimport pytest\nfrom avcww0_nf1z1 import Bsl74Lzlu\n\ndef test_mean_and_add():\n c = Bsl74Lzlu.create(\"a\", [1, 2, 3])\n assert c.mean() == 2.0\n assert c.add(5).mean() == (1 + 2 + 3 + 5) / 4\n\ndef test_empty_raises():\n with pytest.raises(ValueError):\n Bsl74Lzlu.create(\"x\", [])", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: Project domain: observability collector\nImplementation stack: Next.js, Node.js, Prisma, PostgreSQL, Playwright, Docker\nSoftware delivery problem: CI failures after dependency upgrade\nTask type: incident_to_remediation\nDifficulty: hard\n\nReturn a complete delivery-grade response with:\n- diagnosis or design reasoning\n- implementation\n- test plan or tests\n- rollout plan\n- rollback or compatibility note\n- verification commands\n\nRepository sketch:\nrepo/\n cmd/server/main.go\n internal/service/service.go\n internal/store/store.go\n internal/api/api.go\n service_test.go\n go.mod\n\nFocus: Focus on shipping production software with rollout safety, acceptance criteria, telemetry, and maintenance quality.\n\nassistant: Diagnosis:\n- Root cause or delivery blocker: CI failures after dependency upgrade needs both implementation work and a safe shipping plan.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```go\npackage service\n\nimport \"fmt\"\n\nfunc NormalizePayload(payload map[string]any) map[string]any {\n\tout := make(map[string]any)\n\tfor k, v := range payload {\n\t\tif v == nil {\n\t\t\tcontinue\n\t\t}\n\t\tout[k] = v\n\t}\n\treturn out\n}\n\nfunc Handle(payload map[string]any) (map[string]any, error) {\n\tclean := NormalizePayload(payload)\n\tif _, ok := clean[\"id\"]; !ok {\n\t\treturn nil, fmt.Errorf(\"missing id\")\n\t}\n\treturn map[string]any{\"ok\": true, \"data\": clean}, nil\n}\n```\n\nTests:\n```go\npackage service\n\nimport \"testing\"\n\nfunc TestHandle(t *testing.T) {\n\tgot, err := Handle(map[string]any{\"id\": 7, \"name\": \"ok\", \"unused\": nil})\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tif got[\"ok\"] != true {\n\t\tt.Fatalf(\"expected ok=true\")\n\t}\n\tif _, err := Handle(map[string]any{\"name\": \"x\"}); err == nil {\n\t\tt.Fatalf(\"expected missing id error\")\n\t}\n}\n```\n\nVerification:\n- `go test ./...`\n- `go vet ./...`\n\nEngineering notes:\n- Language: Go\n- Framework/tooling: gRPC\n- Stack context: Next.js, Node.js, Prisma, PostgreSQL, Playwright, Docker\n- Domain: observability collector\n- Task type: incident_to_remediation\n- Difficulty: hard\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "Optimize while preserving behavior and order.\n\n```python\ndef f62687(xs):\n out=[]\n for x in xs:\n if x not in out: out.append(x)\n return out\n```\nReturn `m23241.py` with types and O(n) average.\n\n```python\n# m23241.py\nfrom __future__ import annotations\nfrom typing import Iterable, List, Set, TypeVar\nT=TypeVar(\"T\")\n\ndef f62687(xs: Iterable[T]) -> List[T]:\n \"\"\"Unique items preserving first-seen order.\"\"\"\n seen: Set[T]=set()\n out: List[T]=[]\n for x in xs:\n if x in seen: continue\n seen.add(x); out.append(x)\n return out\n```", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Produce an offline-first self-evolving code assistant architecture named `kal9jgfblpq`.\nMust include: module layout, patch-safety policy, evaluation gates (tests/lint/types), versioned memory index.\n\nArchitecture: `kal9jgfblpq` (offline-first, self-evolving)\n\nModules\n- core/loop.py: evolve → validate → accept/reject (bounded iterations)\n- patching/: diff builder, safe apply, atomic writes, rollback points\n- policy/: allowlist paths, deny globs (.git/, __pycache__/, binaries), patch size caps\n- signals/: parse pytest/ruff/mypy into normalized findings\n- memory/index.jsonl: append-only snapshots (hashes, metrics, rationale)\n\nSafety gates\n- refuse path traversal/symlink escapes; never edit binaries\n- accept only if tests/lint/types stay green or improve", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Build an elite-grade solution in the domain of gpu compute for scenario: document indexing.\nPrimary language: typescript.\nDifficulty: hard.\nConstraints: avoid undefined behavior and data races, provide rollout and rollback guidance, document performance characteristics.\nComponent: component_rtkivmu.\nAssume compliance requires data deletion with proofs.\nTask: Provide SLOs, alerting, dashboards, runbooks, and incident playbook. Include chaos testing and safe rollout strategy.\n\nOutput: production blueprint plus correctness arguments and test strategy.\nOutput: SLOs + alerts + runbooks + chaos strategy.\n\n**SLOs**\n- Availability: 99.9% monthly\n- Latency: p95 < 200ms, p99 < 400ms\n- Error rate: < 0.1%\n\n**Alerts**\n- Burn-rate alerts for SLOs (fast/slow windows)\n- Saturation: CPU, memory, queue depth, DB connections\n- Dependency health: cache hit rate drop, downstream timeouts\n\n**Runbooks**\n- Triage: identify blast radius, feature-flag rollback, capacity mitigation\n- Post-incident: timeline, contributing factors, action items\n\n**Chaos**\n- Inject latency, partial outages, and restarts in staging; verify steady-state SLOs.\n\n\nHard checks: failure injection tests and performance regressions gated.", "source": "WithinUsAI/Elite_GOD_Coder_100k"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: Language: Rust\nFramework/tooling: Axum\nDomain: benchmark harness\nLogic challenge: N+1 query explosion\nTask type: multi_file_migration_repair\nDifficulty: expert\n\nReturn a rigorous engineering answer:\n- identify the hidden root cause or logical failure\n- present the corrected implementation\n- add tests that prove the fix\n- list verification commands\n- explain why naive fixes are insufficient when relevant\n\nRepository sketch:\nrepo/\n src/main.rs\n src/lib.rs\n src/service.rs\n src/store.rs\n tests/integration.rs\n Cargo.toml\n\nFocus: Focus on staff-level problem solving with multi-file patches, rollout implications, performance and security tradeoffs.\n\nassistant: Diagnosis:\n- Staff-level diagnosis: N+1 query explosion impacts correctness, operability, and future maintenance, so the fix must be minimal where possible but complete where necessary.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```rust\nuse std::collections::HashMap;\n\npub fn normalize_payload(payload: HashMap) -> HashMap {\n payload\n .into_iter()\n .filter(|(_, v)| !v.trim().is_empty())\n .collect()\n}\n```\n\nTests:\n```rust\n#[test]\nfn normalize_payload_filters_empty_values() {\n use std::collections::HashMap;\n let mut payload = HashMap::new();\n payload.insert(\"id\".to_string(), \"7\".to_string());\n payload.insert(\"name\".to_string(), \"\".to_string());\n let out = normalize_payload(payload);\n assert!(out.contains_key(\"id\"));\n assert!(!out.contains_key(\"name\"));\n}\n```\n\nVerification:\n- `cargo test`\n- `cargo clippy -- -D warnings`\n\nEngineering notes:\n- Language: Rust\n- Framework/tooling: Axum\n- Stack context: GitHub Actions, Docker Compose, Kubernetes, Terraform\n- Domain: benchmark harness\n- Task type: multi_file_migration_repair\n- Difficulty: expert\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Optimize while preserving behavior.\n\nFile: ne_e4z.py\n```python\ndef qwnw98b(xs):\n out = []\n for x in xs:\n if x not in out:\n out.append(x)\n return out\n```\n\nRequirements: preserve first-seen order; O(n) average; add types + docstring.\n\n# ne_e4z.py\nfrom __future__ import annotations\nfrom typing import Iterable, List, Set, TypeVar\n\nT = TypeVar(\"T\")\n\ndef qwnw98b(xs: Iterable[T]) -> List[T]:\n \"\"\"Return unique items preserving first-seen order.\"\"\"\n seen: Set[T] = set()\n out: List[T] = []\n for x in xs:\n if x in seen:\n continue\n seen.add(x)\n out.append(x)\n return out", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Fix a bug and add tests.\n\nFile: uyant82ego.py\n```python\ndef zzkzp285(n: int) -> int:\n \"\"\"Sum 1..n inclusive.\"\"\"\n if n < 0:\n raise ValueError(\"n must be non-negative\")\n total = 0\n for k in range(n): # BUG: should include n\n total += k\n return total\n```\n\nReturn unified diffs for uyant82ego.py and test_uyant82ego.py (pytest).\n\n*** Begin Patch\n*** Update File: uyant82ego.py\n@@\n def zzkzp285(n: int) -> int:\n@@\n total = 0\n- for k in range(n): # BUG: should include n\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_uyant82ego.py\n+import pytest\n+from uyant82ego import zzkzp285\n+\n+def test_zero():\n+ assert zzkzp285(0) == 0\n+\n+def test_one():\n+ assert zzkzp285(1) == 1\n+\n+def test_small():\n+ assert zzkzp285(7) == 28\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ zzkzp285(-1)\n+\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Produce an offline-first self-evolving code assistant architecture named `z1mzh0dp`.\nMust include: module layout, patch-safety policy, evaluation gates (tests/lint/types), versioned memory index.\n\nArchitecture: `z1mzh0dp` (offline-first, self-evolving)\n\nModules\n- core/loop.py: evolve → validate → accept/reject (bounded iterations)\n- patching/: diff builder, safe apply, atomic writes, rollback points\n- policy/: allowlist paths, deny globs (.git/, __pycache__/, binaries), patch size caps\n- signals/: parse pytest/ruff/mypy into normalized findings\n- memory/index.jsonl: append-only snapshots (hashes, metrics, rationale)\n\nSafety gates\n- refuse path traversal/symlink escapes; never edit binaries\n- accept only if tests/lint/types stay green or improve", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Add a clear docstring and type hints to this function:\n\n```python\ndef f21381(s):\n return ''.join(x for x in s if x.isalnum()).lower()\n```\n\n```python\nfrom __future__ import annotations\n\ndef f21381(s: str) -> str:\n \"\"\"Normalize a string: keep only alphanumerics and lowercase the result.\"\"\"\n return \"\".join(ch for ch in s if ch.isalnum()).lower()\n```", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Fix a bug and add tests.\n\nFile: aezmw19b4kit.py\n```python\ndef nj42g_ou(n: int) -> int:\n \"\"\"Sum 1..n inclusive.\"\"\"\n if n < 0:\n raise ValueError(\"n must be non-negative\")\n total = 0\n for k in range(n): # BUG: should include n\n total += k\n return total\n```\n\nReturn unified diffs for aezmw19b4kit.py and test_aezmw19b4kit.py (pytest).\n\n*** Begin Patch\n*** Update File: aezmw19b4kit.py\n@@\n def nj42g_ou(n: int) -> int:\n@@\n total = 0\n- for k in range(n): # BUG: should include n\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_aezmw19b4kit.py\n+import pytest\n+from aezmw19b4kit import nj42g_ou\n+\n+def test_zero():\n+ assert nj42g_ou(0) == 0\n+\n+def test_one():\n+ assert nj42g_ou(1) == 1\n+\n+def test_small():\n+ assert nj42g_ou(7) == 28\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ nj42g_ou(-1)\n+\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: System domain: repo automation\nStack: Rust, Axum, SQLx, Redis, Tokio, Docker\nCross-layer incident: log redaction failure\nTask type: full_stack_bug_fix\nDifficulty: hard\n\nSolve this as a complete-project engineer.\nOutput must include:\n- root cause across layers\n- final implementation patch\n- tests touching at least two layers\n- deployment or observability note\n- verification commands\n\nRepository sketch:\nrepo/\n cmd/server/main.go\n internal/service/service.go\n internal/store/store.go\n internal/api/api.go\n service_test.go\n go.mod\n\nFocus: Focus on multi-layer debugging across frontend, backend, database, CI, caching, and deployment.\n\nassistant: Diagnosis:\n- Root cause: log redaction failure crosses service boundaries, so the fix must align code, contracts, tests, and deployment behavior.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```go\npackage service\n\nimport \"fmt\"\n\nfunc NormalizePayload(payload map[string]any) map[string]any {\n\tout := make(map[string]any)\n\tfor k, v := range payload {\n\t\tif v == nil {\n\t\t\tcontinue\n\t\t}\n\t\tout[k] = v\n\t}\n\treturn out\n}\n\nfunc Handle(payload map[string]any) (map[string]any, error) {\n\tclean := NormalizePayload(payload)\n\tif _, ok := clean[\"id\"]; !ok {\n\t\treturn nil, fmt.Errorf(\"missing id\")\n\t}\n\treturn map[string]any{\"ok\": true, \"data\": clean}, nil\n}\n```\n\nTests:\n```go\npackage service\n\nimport \"testing\"\n\nfunc TestHandle(t *testing.T) {\n\tgot, err := Handle(map[string]any{\"id\": 7, \"name\": \"ok\", \"unused\": nil})\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tif got[\"ok\"] != true {\n\t\tt.Fatalf(\"expected ok=true\")\n\t}\n\tif _, err := Handle(map[string]any{\"name\": \"x\"}); err == nil {\n\t\tt.Fatalf(\"expected missing id error\")\n\t}\n}\n```\n\nVerification:\n- `go test ./...`\n- `go vet ./...`\n\nEngineering notes:\n- Language: Go\n- Framework/tooling: net/http\n- Stack context: Rust, Axum, SQLx, Redis, Tokio, Docker\n- Domain: repo automation\n- Task type: full_stack_bug_fix\n- Difficulty: hard\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: Language: Java\nFramework/tooling: Gradle\nDomain: job scheduler\nLogic challenge: memory leak in AST cache\nTask type: monorepo_toolchain_recovery\nDifficulty: hard\n\nReturn a rigorous engineering answer:\n- identify the hidden root cause or logical failure\n- present the corrected implementation\n- add tests that prove the fix\n- list verification commands\n- explain why naive fixes are insufficient when relevant\n\nRepository sketch:\nrepo/\n src/main/java/com/acme/App.java\n src/main/java/com/acme/Service.java\n src/test/java/com/acme/AppTest.java\n pom.xml\n\nFocus: Focus on staff-level problem solving with multi-file patches, rollout implications, performance and security tradeoffs.\n\nassistant: Diagnosis:\n- Staff-level diagnosis: memory leak in AST cache impacts correctness, operability, and future maintenance, so the fix must be minimal where possible but complete where necessary.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```java\nimport java.util.HashMap;\nimport java.util.Map;\n\npublic final class RequestHandler {\n public static Map handleRequest(Map payload) {\n Map clean = new HashMap<>();\n for (Map.Entry entry : payload.entrySet()) {\n if (entry.getValue() != null) clean.put(entry.getKey().trim(), entry.getValue());\n }\n if (!clean.containsKey(\"id\")) throw new IllegalArgumentException(\"missing id\");\n return Map.of(\"ok\", true, \"data\", clean);\n }\n}\n```\n\nTests:\n```java\nimport static org.junit.jupiter.api.Assertions.*;\nimport java.util.Map;\nimport org.junit.jupiter.api.Test;\n\nclass RequestHandlerTest {\n @Test\n void requiresId() {\n assertThrows(IllegalArgumentException.class, () -> RequestHandler.handleRequest(Map.of(\"name\", \"x\")));\n }\n}\n```\n\nVerification:\n- `./gradlew test`\n- `mvn test`\n\nEngineering notes:\n- Language: Java\n- Framework/tooling: Gradle\n- Stack context: GitHub Actions, Docker Compose, Kubernetes, Terraform\n- Domain: job scheduler\n- Task type: monorepo_toolchain_recovery\n- Difficulty: hard\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "Design a production system for logistics supporting analytics pipeline.\nTarget platform: infra (Terraform).\nRequirements: APIs, data model, scaling strategy, failure modes, and security.\nConstraints: must include clear error handling, must include type hints where applicable, must be easy to extend.\nDifficulty: hard. Assume untrusted input; validate everything.\n\nOutput: engineering-grade answer with edge cases covered.\nDeliverable: system design with APIs, data model, and operational plan.\n\n**High-level architecture**\n- Edge: API Gateway + WAF\n- Core service: stateless app pods behind L7 LB\n- Data: Postgres (primary), Redis (cache + rate limit tokens), Object storage (uploads if needed)\n- Async: message queue (e.g., SQS/Rabbit) + worker pool for background jobs\n- Observability: structured logs + metrics + tracing\n\n**APIs (example)**\n- `POST /v1/{resource}` create (idempotent via `Idempotency-Key`)\n- `GET /v1/{resource}/{id}` read\n- `POST /v1/{resource}/{id}:action` command endpoint when side effects exist\n\n**Data model (Postgres)**\n- `resources(id UUID PK, tenant_id UUID, status TEXT, payload JSONB, created_at, updated_at)`\n- Unique constraint for idempotency: `(tenant_id, idempotency_key)` in a separate table:\n - `idempotency(tenant_id, key TEXT, request_hash TEXT, response JSONB, created_at, PRIMARY KEY(tenant_id,key))`\n\n**Scaling**\n- App layer scales horizontally; keep sessions out of process.\n- Cache reads in Redis; write-through invalidation on mutations.\n- Use connection pooling; consider read replicas for heavy reads.\n\n**Failure modes**\n- Retries: only for safe/ idempotent operations; exponential backoff + jitter.\n- Partial failures: background jobs must be idempotent; use a de-dup key.\n\n**Security**\n- AuthN: JWT/OIDC; AuthZ: RBAC/ABAC with tenant isolation\n- Validate all inputs; enforce per-tenant quotas/rate limits.\n\n**Rollout**\n- Dark launch + feature flags; canary; rapid rollback by toggling flags.\n\n\nHard-mode checks: concurrency safety, idempotency, and rollback validated; add chaos tests where feasible.", "source": "WithinUsAI/GOD_Coder_100k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Fix a bug and add tests.\n\nFile: l_xlfs7.py\n```python\ndef aecd4b5(n: int) -> int:\n \"\"\"Sum 1..n inclusive.\"\"\"\n if n < 0:\n raise ValueError(\"n must be non-negative\")\n total = 0\n for k in range(n): # BUG: should include n\n total += k\n return total\n```\n\nReturn unified diffs for l_xlfs7.py and test_l_xlfs7.py (pytest).\n\n*** Begin Patch\n*** Update File: l_xlfs7.py\n@@\n def aecd4b5(n: int) -> int:\n@@\n total = 0\n- for k in range(n): # BUG: should include n\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_l_xlfs7.py\n+import pytest\n+from l_xlfs7 import aecd4b5\n+\n+def test_zero():\n+ assert aecd4b5(0) == 0\n+\n+def test_one():\n+ assert aecd4b5(1) == 1\n+\n+def test_small():\n+ assert aecd4b5(7) == 28\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ aecd4b5(-1)\n+\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Improve typing and robustness of a Python module used for file synchronization.\nRequirements: provide type-safe APIs (generics/protocols where appropriate) and include tests.\nConstraints: must provide clear error messages, must include docstrings, must handle Windows paths safely.\nDifficulty: easy. Support both Windows and POSIX paths correctly.\n\nDeliverable: implementation + tests.\n```python\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom typing import Callable, Generic, Iterable, Protocol, TypeVar\n\nT = TypeVar(\"T\")\nR = TypeVar(\"R\")\n\nclass Mapper(Protocol[T, R]):\n def __call__(self, x: T) -> R: ...\n\n@dataclass(frozen=True, slots=True)\nclass Batch(Generic[T]):\n items: tuple[T, ...]\n\ndef map_batch(batch: Batch[T], fn: Mapper[T, R]) -> Batch[R]:\n return Batch(items=tuple(fn(x) for x in batch.items))\n\ndef chunked(xs: Iterable[T], size: int) -> Iterable[Batch[T]]:\n if size <= 0:\n raise ValueError(\"size must be > 0\")\n buf: list[T] = []\n for x in xs:\n buf.append(x)\n if len(buf) == size:\n yield Batch(items=tuple(buf))\n buf.clear()\n if buf:\n yield Batch(items=tuple(buf))\n```\n\n```python\nimport pytest\nfrom module_under_test import Batch, map_batch, chunked\n\ndef test_map_batch():\n b = Batch(items=(1,2,3))\n assert map_batch(b, lambda x: x*2).items == (2,4,6)\n\ndef test_chunked():\n out = list(chunked([1,2,3,4,5], 2))\n assert [b.items for b in out] == [(1,2),(3,4),(5,)]\n```", "source": "WithinUsAI/python_GOD_coder_100k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Refactor to modern typed Python with immutability and tests.\n\nFile: l_4c1qph9f.py\n```python\nclass Q7M5Mpcmioh:\n def __init__(self, name, values):\n self.name = name\n self.values = list(values)\n def add(self, v):\n self.values.append(v)\n def mean(self):\n s = 0\n for x in self.values:\n s += x\n return s / len(self.values)\n```\n\nReturn full new l_4c1qph9f.py and test_l_4c1qph9f.py.\n\n# l_4c1qph9f.py\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom typing import Iterable, Tuple\n\n@dataclass(frozen=True)\nclass Q7M5Mpcmioh:\n name: str\n values: Tuple[float, ...]\n\n @staticmethod\n def create(name: str, values: Iterable[float]) -> \"Q7M5Mpcmioh\":\n vals = tuple(float(v) for v in values)\n if not vals:\n raise ValueError(\"values must be non-empty\")\n return Q7M5Mpcmioh(name=name, values=vals)\n\n def add(self, v: float) -> \"Q7M5Mpcmioh\":\n return Q7M5Mpcmioh(name=self.name, values=self.values + (float(v),))\n\n def mean(self) -> float:\n return sum(self.values) / len(self.values)\n\n# test_l_4c1qph9f.py\nimport pytest\nfrom l_4c1qph9f import Q7M5Mpcmioh\n\ndef test_mean_and_add():\n c = Q7M5Mpcmioh.create(\"a\", [1, 2, 3])\n assert c.mean() == 2.0\n assert c.add(5).mean() == (1 + 2 + 3 + 5) / 4\n\ndef test_empty_raises():\n with pytest.raises(ValueError):\n Q7M5Mpcmioh.create(\"x\", [])", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: Language: Bash\nFramework/tooling: GNU coreutils\nDomain: model serving gateway\nLogic challenge: rate-limit bypass\nTask type: parser_validation_logic\nDifficulty: hard\n\nReturn a rigorous engineering answer:\n- identify the hidden root cause or logical failure\n- present the corrected implementation\n- add tests that prove the fix\n- list verification commands\n- explain why naive fixes are insufficient when relevant\n\nRepository sketch:\nrepo/\n scripts/\n run.sh\n deploy.sh\n tests/\n smoke.sh\n\nFocus: Focus on strong structured logic with edge cases, data validation, and concurrency safety.\n\nassistant: Diagnosis:\n- Root cause: the failure around rate-limit bypass is caused by missing validation, weak edge-case handling, or unsafe lifecycle behavior in the current implementation.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```bash\n#!/usr/bin/env bash\nset -euo pipefail\n\ninput=\"${1:-}\"\nif [[ -z \"$input\" ]]; then\n echo \"missing input\" >&2\n exit 1\nfi\n\nprintf '%s\n' \"$input\" | tr -d '\r'\n```\n\nTests:\n```bash\noutput=\"$(bash scripts/run.sh \"abc\")\"\ntest \"$output\" = \"abc\"\n```\n\nVerification:\n- `bash tests/smoke.sh`\n- `shellcheck scripts/*.sh`\n\nEngineering notes:\n- Language: Bash\n- Framework/tooling: GNU coreutils\n- Stack context: ASP.NET Core, SQL Server, EF Core, xUnit, Docker\n- Domain: model serving gateway\n- Task type: parser_validation_logic\n- Difficulty: hard\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "Fix the bug and add pytest tests.\n\n```python\ndef f06716(n: int) -> int:\n # sum 1..n inclusive\n if n < 0: raise ValueError\n total = 0\n for k in range(n): # BUG\n total += k\n return total\n```\nReturn unified diffs for `m72388.py` and `test_m72388.py`.\n\n*** Begin Patch\n*** Update File: m72388.py\n@@\n def f06716(n: int) -> int:\n@@\n- for k in range(n): # BUG\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_m72388.py\n+import pytest\n+from m72388 import f06716\n+\n+def test_small():\n+ assert f06716(7) == 28\n+\n+def test_zero():\n+ assert f06716(0) == 0\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ f06716(-1)\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Refactor an existing codebase in gaming to support search + pagination cleanly.\nTarget platform: infra (Terraform).\nRequirements: propose new modules/layers, dependency boundaries, and migration plan.\nConstraints: must be observable (logs/metrics/traces), must avoid global state, must include type hints where applicable, must be easy to extend.\nDifficulty: hard. Assume strict latency budget (p95 < 200ms).\n\nOutput: engineering-grade answer with edge cases covered.\nDeliverable: refactor plan + module boundaries.\n\n**Proposed modules**\n- `domain/` pure business logic (no I/O)\n- `adapters/` DB, cache, external APIs\n- `api/` request/response validation and routing\n- `observability/` logging/metrics/tracing\n- `tests/` unit + integration suites\n\n**Migration plan**\n1. Introduce new interfaces + adapters behind feature flags.\n2. Dual-write or read-compat layer if schema changes.\n3. Incremental cutover; deprecate legacy module.\n\nKey rule: dependencies flow inward; domain has no framework imports.\n\n\nHard-mode checks: concurrency safety, idempotency, and rollback validated; add chaos tests where feasible.", "source": "WithinUsAI/GOD_Coder_100k"} {"text": "Task type: tla_state_machine\nScenario: streaming ETL\nDomain focus: constraint solving\nPrimary language: tla+\nDifficulty: expert+\nScale/SLO: 10k RPS peak\nComponent: component_emyleloj\nConstraints: include security threat model (defensive only), include backward compatibility and migration plan, assume adversarial inputs; validate everything, include test vectors and fuzz strategy, include verification strategy, explicit contracts and invariants, include deterministic replay plan\nAssume tight memory budget and cold-start constraints.\nDeliverable: Provide a TLA+-style state machine (pseudo), safety/liveness properties, and a model-checking strategy. Include an implementation sketch and test vectors.\n\nOutput: elite engineering answer optimized for correctness, performance, and operability.\n**Contract**\n- Inputs validated at the boundary; explicit error taxonomy.\n- Idempotency for side effects via request_id; deterministic replay.\n- Backward compatibility: additive changes by default; versioned breaking changes.\n**Invariants**\n- Safety: state transitions preserve invariants; no partial commit leaks.\n- Liveness: under bounded faults and stable network, progress occurs.\n- Determinism: replay of the same event log yields identical outputs.\n**Failure modes & recovery**\n- Network partition: minority cannot commit; clients receive retriable errors.\n- Crash during commit: WAL replay completes or transaction aborts; no torn writes.\n- Data corruption: checksums + scrubber; quarantine and rebuild from replicas/snapshots.\n**Security posture (defensive)**\n- Threat model: auth/authz, injection, replay/abuse, supply chain.\n- Least privilege; secrets in managed store; audit logs for sensitive ops.\n- Input normalization, parameterized queries, path traversal protections.\n**Verification strategy**\n- Canary + shadow traffic; invariants checked in production via assertions/metrics.\n- Property tests against a pure reference model (state machine).\n- Deterministic simulation with fault injection (crash/partition/latency).\n\n**Snippet**\n```tla\nVARIABLES state, log, seen\n\nInit == state = [k \\in Keys |-> <<0, NULL>>] /\\ log = << >> /\\ seen = [r \\in ReqIds |-> NULL]\n\nPut(req, k, v) ==\n IF seen[req] # NULL THEN UNCHANGED <>\n ELSE\n LET ver == state[k][1] + 1 IN\n /\\ state' = [state EXCEPT ![k] = <>]\n /\\ log' = Append(log, <>)\n /\\ seen' = [seen EXCEPT ![req] = <<\"ok\", ver>>]\n\nSafety == \\A k \\in Keys: state[k][1] >= 0\n```\n\nExpert+ checks: mechanized invariants (or exhaustive model checking), adversarial fuzzing, and multi-region failure drills.", "source": "WithinUsAI/Omega_Genesis_Coder_100k"} {"text": "Task type: lockfree_primitive\nScenario: job scheduler\nDomain focus: edge robotics (safe)\nPrimary language: rust\nDifficulty: expert+\nScale/SLO: 10k RPS peak\nComponent: component_spcstukm\nConstraints: explicit contracts and invariants, avoid data races and undefined behavior, include test vectors and fuzz strategy, include deterministic replay plan, include failure modes and recovery, include performance model and limits, include security threat model (defensive only)\nAssume partial data corruption; include scrubbing strategy.\nDeliverable: Design a lock-free primitive with memory ordering reasoning and stress tests (no UB).\n\nOutput: rigorous design + invariants + verification plan + implementation sketch.\n**Contract**\n- Inputs validated at the boundary; explicit error taxonomy.\n- Idempotency for side effects via request_id; deterministic replay.\n- Backward compatibility: additive changes by default; versioned breaking changes.\n**Invariants**\n- Isolation: tenant boundary enforced; no cross-tenant reads/writes.\n- Safety: state transitions preserve invariants; no partial commit leaks.\n- Determinism: replay of the same event log yields identical outputs.\n**Failure modes & recovery**\n- Crash during commit: WAL replay completes or transaction aborts; no torn writes.\n- Network partition: minority cannot commit; clients receive retriable errors.\n- Data corruption: checksums + scrubber; quarantine and rebuild from replicas/snapshots.\n**Security posture (defensive)**\n- Threat model: auth/authz, injection, replay/abuse, supply chain.\n- Least privilege; secrets in managed store; audit logs for sensitive ops.\n- Input normalization, parameterized queries, path traversal protections.\n**Verification strategy**\n- Property tests against a pure reference model (state machine).\n- Fuzzing of parsers/framers/validators with corpus seeds.\n- Canary + shadow traffic; invariants checked in production via assertions/metrics.\n\n**Snippet**\n```rust\n// Skeleton: SPSC ring buffer with acquire/release (outline)\nuse std::sync::atomic::{AtomicUsize, Ordering};\n\npub struct Ring {\n buf: Vec>,\n head: AtomicUsize,\n tail: AtomicUsize,\n cap: usize,\n}\n\n// Correctness sketch: producer uses Release on tail store, consumer uses Acquire on tail load.\n```\n\nExpert+ checks: mechanized invariants (or exhaustive model checking), adversarial fuzzing, and multi-region failure drills.", "source": "WithinUsAI/Omega_Genesis_Coder_100k"} {"text": "Build an elite-grade solution in the domain of networking for scenario: payment processing.\nPrimary language: go.\nDifficulty: medium.\nConstraints: assume untrusted inputs; validate and sanitize, include tests or verification strategy, design for backward compatibility and migrations.\nComponent: component_cinyped.\nAssume cold-start and memory limits are tight.\nTask: Implement a concurrency primitive or subsystem (lock-free queue, thread pool, async runtime component). Explain memory ordering and correctness arguments; include stress tests.\n\nOutput: rigorous solution with invariants, failure modes, and performance notes.\nOutput: correctness-focused concurrency primitive + stress tests.\n\n**Primitive**\n- Bounded MPMC queue with backpressure (blocking push/pop) OR lock-free SPSC ring buffer.\n\n**Correctness notes**\n- For lock-free: use acquire/release semantics on head/tail indices.\n- Avoid ABA by monotonic counters; ring index = counter % capacity.\n\n**Stress tests**\n- Multi-thread producers/consumers; assert item multiset preserved.\n- Use time-bounded randomized schedules; detect deadlocks.\n\n\nChecks: boundary validation and deterministic behavior verified.", "source": "WithinUsAI/Elite_GOD_Coder_100k"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: Project stack: Rust, Axum, SQLx, Redis, Tokio, Docker\nLanguage: Bash\nDependency challenge: gRPC retry storm\nTask type: migration_patch\nDifficulty: hard\n\nFix this as a senior engineer.\nRequired:\n- identify the version or compatibility failure mode\n- produce the corrected config/code/build patch\n- explain rollback-safe migration notes\n- add regression tests or reproducibility checks\n- include concrete verification commands\n\nRepository sketch:\nrepo/\n scripts/\n run.sh\n deploy.sh\n tests/\n smoke.sh\n\nFocus: Focus on versioning, migrations, lockfiles, runtime compatibility, and secure dependency handling.\n\nassistant: Diagnosis:\n- Root cause: the issue around gRPC retry storm is a dependency, migration, or runtime-compatibility mismatch that needs a rollback-safe patch.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```bash\n#!/usr/bin/env bash\nset -euo pipefail\n\ninput=\"${1:-}\"\nif [[ -z \"$input\" ]]; then\n echo \"missing input\" >&2\n exit 1\nfi\n\nprintf '%s\n' \"$input\" | tr -d '\r'\n```\n\nTests:\n```bash\noutput=\"$(bash scripts/run.sh \"abc\")\"\ntest \"$output\" = \"abc\"\n```\n\nVerification:\n- `bash tests/smoke.sh`\n- `shellcheck scripts/*.sh`\n\nEngineering notes:\n- Language: Bash\n- Framework/tooling: jq\n- Stack context: Rust, Axum, SQLx, Redis, Tokio, Docker\n- Domain: artifact registry\n- Task type: migration_patch\n- Difficulty: hard\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Fix a bug and add tests.\n\nFile: b2h53tpd.py\n```python\ndef mpd7ql8kagi(n: int) -> int:\n \"\"\"Sum 1..n inclusive.\"\"\"\n if n < 0:\n raise ValueError(\"n must be non-negative\")\n total = 0\n for k in range(n): # BUG: should include n\n total += k\n return total\n```\n\nReturn unified diffs for b2h53tpd.py and test_b2h53tpd.py (pytest).\n\n*** Begin Patch\n*** Update File: b2h53tpd.py\n@@\n def mpd7ql8kagi(n: int) -> int:\n@@\n total = 0\n- for k in range(n): # BUG: should include n\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_b2h53tpd.py\n+import pytest\n+from b2h53tpd import mpd7ql8kagi\n+\n+def test_zero():\n+ assert mpd7ql8kagi(0) == 0\n+\n+def test_one():\n+ assert mpd7ql8kagi(1) == 1\n+\n+def test_small():\n+ assert mpd7ql8kagi(7) == 28\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ mpd7ql8kagi(-1)\n+\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Refactor to modern typed Python with immutability and tests.\n\nFile: w9l4iafd.py\n```python\nclass MlGq6Jrg:\n def __init__(self, name, values):\n self.name = name\n self.values = list(values)\n def add(self, v):\n self.values.append(v)\n def mean(self):\n s = 0\n for x in self.values:\n s += x\n return s / len(self.values)\n```\n\nReturn full new w9l4iafd.py and test_w9l4iafd.py.\n\n# w9l4iafd.py\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom typing import Iterable, Tuple\n\n@dataclass(frozen=True)\nclass MlGq6Jrg:\n name: str\n values: Tuple[float, ...]\n\n @staticmethod\n def create(name: str, values: Iterable[float]) -> \"MlGq6Jrg\":\n vals = tuple(float(v) for v in values)\n if not vals:\n raise ValueError(\"values must be non-empty\")\n return MlGq6Jrg(name=name, values=vals)\n\n def add(self, v: float) -> \"MlGq6Jrg\":\n return MlGq6Jrg(name=self.name, values=self.values + (float(v),))\n\n def mean(self) -> float:\n return sum(self.values) / len(self.values)\n\n# test_w9l4iafd.py\nimport pytest\nfrom w9l4iafd import MlGq6Jrg\n\ndef test_mean_and_add():\n c = MlGq6Jrg.create(\"a\", [1, 2, 3])\n assert c.mean() == 2.0\n assert c.add(5).mean() == (1 + 2 + 3 + 5) / 4\n\ndef test_empty_raises():\n with pytest.raises(ValueError):\n MlGq6Jrg.create(\"x\", [])", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Task type: storage_engine\nScenario: time-series metrics store\nDomain focus: cryptography engineering (defensive)\nPrimary language: sql\nDifficulty: expert+\nScale/SLO: p99 < 150ms\nComponent: component_ssfcjsbd\nConstraints: include deterministic replay plan, avoid data races and undefined behavior, assume adversarial inputs; validate everything, include test vectors and fuzz strategy, include failure modes and recovery, include backward compatibility and migration plan\nAssume schema changes every sprint; must be backward compatible.\nDeliverable: Design a storage engine subsystem (WAL, snapshots, compaction). Include crash recovery invariants and a benchmark plan.\n\nOutput: contract-first solution with failure modes, security posture, and test/verification strategy.\n**Contract**\n- Inputs validated at the boundary; explicit error taxonomy.\n- Idempotency for side effects via request_id; deterministic replay.\n- Backward compatibility: additive changes by default; versioned breaking changes.\n**Invariants**\n- Safety: state transitions preserve invariants; no partial commit leaks.\n- Isolation: tenant boundary enforced; no cross-tenant reads/writes.\n- Liveness: under bounded faults and stable network, progress occurs.\n**Failure modes & recovery**\n- Data corruption: checksums + scrubber; quarantine and rebuild from replicas/snapshots.\n- Duplicate requests: de-duplicate by (tenant, request_id) returning cached response.\n- Crash during commit: WAL replay completes or transaction aborts; no torn writes.\n**Security posture (defensive)**\n- Threat model: auth/authz, injection, replay/abuse, supply chain.\n- Least privilege; secrets in managed store; audit logs for sensitive ops.\n- Input normalization, parameterized queries, path traversal protections.\n**Verification strategy**\n- Deterministic simulation with fault injection (crash/partition/latency).\n- Property tests against a pure reference model (state machine).\n- Fuzzing of parsers/framers/validators with corpus seeds.\n\n**Snippet**\n```text\nImplementation sketch: factor pure state-machine core; adapters for I/O; add deterministic replay log.\n```\nExpert+ checks: mechanized invariants (or exhaustive model checking), adversarial fuzzing, and multi-region failure drills.", "source": "WithinUsAI/Omega_Genesis_Coder_100k"} {"text": "Task type: distributed_algorithm\nScenario: graph query service\nDomain focus: data lineage & governance\nPrimary language: sql\nDifficulty: expert+\nScale/SLO: 10k RPS peak\nComponent: component_iilcmvqo\nConstraints: include failure modes and recovery, include security threat model (defensive only), include test vectors and fuzz strategy, include backward compatibility and migration plan, avoid data races and undefined behavior\nAssume weekly network partitions.\nDeliverable: Design an algorithm with message flows and correctness arguments (safety + liveness). Include failure handling and a minimal reference implementation skeleton.\n\nOutput: rigorous design + invariants + verification plan + implementation sketch.\n**Contract**\n- Inputs validated at the boundary; explicit error taxonomy.\n- Idempotency for side effects via request_id; deterministic replay.\n- Backward compatibility: additive changes by default; versioned breaking changes.\n**Invariants**\n- Determinism: replay of the same event log yields identical outputs.\n- Isolation: tenant boundary enforced; no cross-tenant reads/writes.\n- Safety: state transitions preserve invariants; no partial commit leaks.\n**Failure modes & recovery**\n- Crash during commit: WAL replay completes or transaction aborts; no torn writes.\n- Network partition: minority cannot commit; clients receive retriable errors.\n- Data corruption: checksums + scrubber; quarantine and rebuild from replicas/snapshots.\n**Security posture (defensive)**\n- Threat model: auth/authz, injection, replay/abuse, supply chain.\n- Least privilege; secrets in managed store; audit logs for sensitive ops.\n- Input normalization, parameterized queries, path traversal protections.\n**Verification strategy**\n- Property tests against a pure reference model (state machine).\n- Canary + shadow traffic; invariants checked in production via assertions/metrics.\n- Fuzzing of parsers/framers/validators with corpus seeds.\n\n**Snippet**\n```text\nImplementation sketch: factor pure state-machine core; adapters for I/O; add deterministic replay log.\n```\nExpert+ checks: mechanized invariants (or exhaustive model checking), adversarial fuzzing, and multi-region failure drills.", "source": "WithinUsAI/Omega_Genesis_Coder_100k"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: Language: Go\nFramework/tooling: Fiber\nDomain: developer platform\nLogic challenge: path traversal on downloads\nTask type: monorepo_toolchain_recovery\nDifficulty: expert\n\nReturn a rigorous engineering answer:\n- identify the hidden root cause or logical failure\n- present the corrected implementation\n- add tests that prove the fix\n- list verification commands\n- explain why naive fixes are insufficient when relevant\n\nRepository sketch:\nrepo/\n cmd/server/main.go\n internal/service/service.go\n internal/store/store.go\n internal/api/api.go\n service_test.go\n go.mod\n\nFocus: Focus on staff-level problem solving with multi-file patches, rollout implications, performance and security tradeoffs.\n\nassistant: Diagnosis:\n- Staff-level diagnosis: path traversal on downloads impacts correctness, operability, and future maintenance, so the fix must be minimal where possible but complete where necessary.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```go\npackage service\n\nimport \"fmt\"\n\nfunc NormalizePayload(payload map[string]any) map[string]any {\n\tout := make(map[string]any)\n\tfor k, v := range payload {\n\t\tif v == nil {\n\t\t\tcontinue\n\t\t}\n\t\tout[k] = v\n\t}\n\treturn out\n}\n\nfunc Handle(payload map[string]any) (map[string]any, error) {\n\tclean := NormalizePayload(payload)\n\tif _, ok := clean[\"id\"]; !ok {\n\t\treturn nil, fmt.Errorf(\"missing id\")\n\t}\n\treturn map[string]any{\"ok\": true, \"data\": clean}, nil\n}\n```\n\nTests:\n```go\npackage service\n\nimport \"testing\"\n\nfunc TestHandle(t *testing.T) {\n\tgot, err := Handle(map[string]any{\"id\": 7, \"name\": \"ok\", \"unused\": nil})\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tif got[\"ok\"] != true {\n\t\tt.Fatalf(\"expected ok=true\")\n\t}\n\tif _, err := Handle(map[string]any{\"name\": \"x\"}); err == nil {\n\t\tt.Fatalf(\"expected missing id error\")\n\t}\n}\n```\n\nVerification:\n- `go test ./...`\n- `go vet ./...`\n\nEngineering notes:\n- Language: Go\n- Framework/tooling: Fiber\n- Stack context: Airflow, dbt, DuckDB, MinIO, pytest\n- Domain: developer platform\n- Task type: monorepo_toolchain_recovery\n- Difficulty: expert\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Fix a bug and add tests.\n\nFile: js906z8v8r4.py\n```python\ndef dg4pj4diob(n: int) -> int:\n \"\"\"Sum 1..n inclusive.\"\"\"\n if n < 0:\n raise ValueError(\"n must be non-negative\")\n total = 0\n for k in range(n): # BUG: should include n\n total += k\n return total\n```\n\nReturn unified diffs for js906z8v8r4.py and test_js906z8v8r4.py (pytest).\n\n*** Begin Patch\n*** Update File: js906z8v8r4.py\n@@\n def dg4pj4diob(n: int) -> int:\n@@\n total = 0\n- for k in range(n): # BUG: should include n\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_js906z8v8r4.py\n+import pytest\n+from js906z8v8r4 import dg4pj4diob\n+\n+def test_zero():\n+ assert dg4pj4diob(0) == 0\n+\n+def test_one():\n+ assert dg4pj4diob(1) == 1\n+\n+def test_small():\n+ assert dg4pj4diob(7) == 28\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ dg4pj4diob(-1)\n+\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Refactor to modern typed Python with immutability and tests.\n\nFile: m7qw6is8l.py\n```python\nclass A61Ynmpt7Rnh:\n def __init__(self, name, values):\n self.name = name\n self.values = list(values)\n def add(self, v):\n self.values.append(v)\n def mean(self):\n s = 0\n for x in self.values:\n s += x\n return s / len(self.values)\n```\n\nReturn full new m7qw6is8l.py and test_m7qw6is8l.py.\n\n# m7qw6is8l.py\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom typing import Iterable, Tuple\n\n@dataclass(frozen=True)\nclass A61Ynmpt7Rnh:\n name: str\n values: Tuple[float, ...]\n\n @staticmethod\n def create(name: str, values: Iterable[float]) -> \"A61Ynmpt7Rnh\":\n vals = tuple(float(v) for v in values)\n if not vals:\n raise ValueError(\"values must be non-empty\")\n return A61Ynmpt7Rnh(name=name, values=vals)\n\n def add(self, v: float) -> \"A61Ynmpt7Rnh\":\n return A61Ynmpt7Rnh(name=self.name, values=self.values + (float(v),))\n\n def mean(self) -> float:\n return sum(self.values) / len(self.values)\n\n# test_m7qw6is8l.py\nimport pytest\nfrom m7qw6is8l import A61Ynmpt7Rnh\n\ndef test_mean_and_add():\n c = A61Ynmpt7Rnh.create(\"a\", [1, 2, 3])\n assert c.mean() == 2.0\n assert c.add(5).mean() == (1 + 2 + 3 + 5) / 4\n\ndef test_empty_raises():\n with pytest.raises(ValueError):\n A61Ynmpt7Rnh.create(\"x\", [])", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Produce an offline-first self-evolving code assistant architecture named `a_n8i74`.\nMust include: module layout, patch-safety policy, evaluation gates (tests/lint/types), versioned memory index.\n\nArchitecture: `a_n8i74` (offline-first, self-evolving)\n\nModules\n- core/loop.py: evolve → validate → accept/reject (bounded iterations)\n- patching/: diff builder, safe apply, atomic writes, rollback points\n- policy/: allowlist paths, deny globs (.git/, __pycache__/, binaries), patch size caps\n- signals/: parse pytest/ruff/mypy into normalized findings\n- memory/index.jsonl: append-only snapshots (hashes, metrics, rationale)\n\nSafety gates\n- refuse path traversal/symlink escapes; never edit binaries\n- accept only if tests/lint/types stay green or improve", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: Language: SQL\nFramework/tooling: SQLite\nDomain: search service\nLogic challenge: transaction boundary bug\nTask type: cross_stack_outage_fix\nDifficulty: expert\n\nReturn a rigorous engineering answer:\n- identify the hidden root cause or logical failure\n- present the corrected implementation\n- add tests that prove the fix\n- list verification commands\n- explain why naive fixes are insufficient when relevant\n\nRepository sketch:\nrepo/\n migrations/\n 001_init.sql\n 002_add_index.sql\n queries/\n report.sql\n tests/\n report_cases.md\n\nFocus: Focus on staff-level problem solving with multi-file patches, rollout implications, performance and security tradeoffs.\n\nassistant: Diagnosis:\n- Staff-level diagnosis: transaction boundary bug impacts correctness, operability, and future maintenance, so the fix must be minimal where possible but complete where necessary.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```sql\nWITH ranked AS (\n SELECT\n user_id,\n created_at,\n amount,\n ROW_NUMBER() OVER (PARTITION BY user_id ORDER BY created_at DESC, id DESC) AS rn\n FROM orders\n)\nSELECT user_id, created_at, amount\nFROM ranked\nWHERE rn = 1;\n```\n\nTests:\n```sql\n-- Correctness checks:\n-- 1) multiple rows per user\n-- 2) identical timestamps require deterministic tie-breaker\n-- 3) null values handled by business rules\n```\n\nVerification:\n- `run migration checks`\n- `run query correctness cases`\n\nEngineering notes:\n- Language: SQL\n- Framework/tooling: SQLite\n- Stack context: GitHub Actions, Docker Compose, Kubernetes, Terraform\n- Domain: search service\n- Task type: cross_stack_outage_fix\n- Difficulty: expert\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Fix a bug and add tests.\n\nFile: oauuaoafltxj.py\n```python\ndef r334okno(n: int) -> int:\n \"\"\"Sum 1..n inclusive.\"\"\"\n if n < 0:\n raise ValueError(\"n must be non-negative\")\n total = 0\n for k in range(n): # BUG: should include n\n total += k\n return total\n```\n\nReturn unified diffs for oauuaoafltxj.py and test_oauuaoafltxj.py (pytest).\n\n*** Begin Patch\n*** Update File: oauuaoafltxj.py\n@@\n def r334okno(n: int) -> int:\n@@\n total = 0\n- for k in range(n): # BUG: should include n\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_oauuaoafltxj.py\n+import pytest\n+from oauuaoafltxj import r334okno\n+\n+def test_zero():\n+ assert r334okno(0) == 0\n+\n+def test_one():\n+ assert r334okno(1) == 1\n+\n+def test_small():\n+ assert r334okno(7) == 28\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ r334okno(-1)\n+\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Fix a bug and add tests.\n\nFile: q5bz1z9aa_ff.py\n```python\ndef koka7l(n: int) -> int:\n \"\"\"Sum 1..n inclusive.\"\"\"\n if n < 0:\n raise ValueError(\"n must be non-negative\")\n total = 0\n for k in range(n): # BUG: should include n\n total += k\n return total\n```\n\nReturn unified diffs for q5bz1z9aa_ff.py and test_q5bz1z9aa_ff.py (pytest).\n\n*** Begin Patch\n*** Update File: q5bz1z9aa_ff.py\n@@\n def koka7l(n: int) -> int:\n@@\n total = 0\n- for k in range(n): # BUG: should include n\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_q5bz1z9aa_ff.py\n+import pytest\n+from q5bz1z9aa_ff import koka7l\n+\n+def test_zero():\n+ assert koka7l(0) == 0\n+\n+def test_one():\n+ assert koka7l(1) == 1\n+\n+def test_small():\n+ assert koka7l(7) == 28\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ koka7l(-1)\n+\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Build an elite-grade solution in the domain of gpu compute for scenario: analytics pipeline.\nPrimary language: python.\nDifficulty: medium.\nConstraints: assume untrusted inputs; validate and sanitize, avoid undefined behavior and data races, design for backward compatibility and migrations, make the interface contract explicit, include tests or verification strategy.\nComponent: component_jghcnal.\nAssume partial network partitions occur weekly.\nTask: Define an API and evolving schema strategy (versioning, migrations, compatibility rules). Provide example schemas and validation tests.\n\nOutput: rigorous solution with invariants, failure modes, and performance notes.\nOutput: GPU pipeline design for throughput and tail-latency.\n\n**Pipeline**\n- Request batching with max batch size + max wait (e.g., 5ms) to control p99.\n- Separate CPU pre/post-processing threads; pin memory for transfers if available.\n- Model warmup; cache weights in VRAM; use concurrency limits.\n\n**Monitoring**\n- GPU utilization, queue wait time, batch size distribution, OOM events.\n\n**Fallback**\n- Graceful degradation to smaller batch size; circuit breaker on repeated OOM.\n\n\nChecks: boundary validation and deterministic behavior verified.", "source": "WithinUsAI/Elite_GOD_Coder_100k"} {"text": "Fix a subtle bug in a Python module used for configuration loading.\nRequirements: explain root cause briefly, provide corrected code, and add regression tests.\nConstraints: must handle Windows paths safely, must be memory-efficient, must avoid global state, must include docstrings.\nDifficulty: medium. Guarantee deterministic output ordering.\n\nDeliverable: production-ready reference solution.\n```python\nfrom __future__ import annotations\n\nfrom dataclasses import dataclass\nfrom pathlib import Path\nfrom typing import Iterable\nimport json\n\n\nclass ValidationError(ValueError):\n \"\"\"Raised when input validation fails.\"\"\"\n\n\ndef safe_join(base: Path, *parts: str) -> Path:\n \"\"\"Join paths while preventing traversal outside base.\"\"\"\n b = base.resolve()\n p = (b / Path(*parts)).resolve()\n if p != b and b not in p.parents:\n raise ValidationError(f\"unsafe path: {p}\")\n return p\n\n\n@dataclass(frozen=True, slots=True)\nclass Record:\n key: str\n value: int\n\n\ndef parse_jsonl(lines: Iterable[str]) -> list[Record]:\n out: list[Record] = []\n for idx, line in enumerate(lines, 1):\n s = line.strip()\n if not s:\n continue\n try:\n obj = json.loads(s)\n except json.JSONDecodeError as e:\n raise ValidationError(f\"line {idx}: invalid json\") from e\n if not isinstance(obj, dict):\n raise ValidationError(f\"line {idx}: expected object\")\n key = obj.get(\"key\")\n val = obj.get(\"value\")\n if not isinstance(key, str) or not key:\n raise ValidationError(f\"line {idx}: key must be non-empty str\")\n if not isinstance(val, int):\n raise ValidationError(f\"line {idx}: value must be int\")\n out.append(Record(key, val))\n return out\n\n\ndef write_jsonl(base: Path, rel: str, records: Iterable[Record]) -> Path:\n base.mkdir(parents=True, exist_ok=True)\n dst = safe_join(base, rel)\n dst.parent.mkdir(parents=True, exist_ok=True)\n with dst.open(\"w\", encoding=\"utf-8\", newline=\"\\n\") as f:\n for r in records:\n f.write(json.dumps({\"key\": r.key, \"value\": r.value}, ensure_ascii=False) + \"\\n\")\n return dst\n```\n\n```python\n# tests (pytest-style)\nimport json\nfrom pathlib import Path\nimport pytest\nfrom module_under_test import ValidationError, Record, parse_jsonl, write_jsonl\n\ndef test_parse_ok():\n lines = [json.dumps({\"key\":\"a\",\"value\":1}), json.dumps({\"key\":\"b\",\"value\":2})]\n assert parse_jsonl(lines) == [Record(\"a\",1), Record(\"b\",2)]\n\ndef test_parse_rejects_bad_json():\n with pytest.raises(ValidationError):\n parse_jsonl([\"{not json}\"])\n\ndef test_safe_join_blocks_traversal(tmp_path: Path):\n with pytest.raises(ValidationError):\n write_jsonl(tmp_path, \"../x.jsonl\", [Record(\"a\",1)])\n```", "source": "WithinUsAI/python_GOD_coder_100k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Refactor to modern typed Python with immutability and tests.\n\nFile: qcd0v44.py\n```python\nclass Gmhkja:\n def __init__(self, name, values):\n self.name = name\n self.values = list(values)\n def add(self, v):\n self.values.append(v)\n def mean(self):\n s = 0\n for x in self.values:\n s += x\n return s / len(self.values)\n```\n\nReturn full new qcd0v44.py and test_qcd0v44.py.\n\n# qcd0v44.py\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom typing import Iterable, Tuple\n\n@dataclass(frozen=True)\nclass Gmhkja:\n name: str\n values: Tuple[float, ...]\n\n @staticmethod\n def create(name: str, values: Iterable[float]) -> \"Gmhkja\":\n vals = tuple(float(v) for v in values)\n if not vals:\n raise ValueError(\"values must be non-empty\")\n return Gmhkja(name=name, values=vals)\n\n def add(self, v: float) -> \"Gmhkja\":\n return Gmhkja(name=self.name, values=self.values + (float(v),))\n\n def mean(self) -> float:\n return sum(self.values) / len(self.values)\n\n# test_qcd0v44.py\nimport pytest\nfrom qcd0v44 import Gmhkja\n\ndef test_mean_and_add():\n c = Gmhkja.create(\"a\", [1, 2, 3])\n assert c.mean() == 2.0\n assert c.add(5).mean() == (1 + 2 + 3 + 5) / 4\n\ndef test_empty_raises():\n with pytest.raises(ValueError):\n Gmhkja.create(\"x\", [])", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Perform a code review for a fintech PR implementing search + pagination.\nTarget platform: infra (Terraform).\nRequirements: list critical issues, improvements, and provide an improved patch excerpt.\nConstraints: must include tests, must include documentation/comments, must be observable (logs/metrics/traces).\nDifficulty: medium. Include rollback strategy.\n\nOutput: design + implementation guidance suitable for shipping.\nDeliverable: code review findings + improved patch excerpt.\n\n**Critical issues**\n1. Missing input validation at boundary; potential unexpected exceptions.\n2. No idempotency / retry safety for side-effecting endpoint.\n3. No tests for edge cases (empty input, duplicates, timeouts).\n4. Observability gaps: no request_id correlation, no metrics.\n\n**Improvements**\n- Add strict validation and explicit error responses.\n- Add idempotency key support for create endpoints.\n- Add unit + integration tests with CI gating.\n- Add structured logs and basic metrics.\n\nPatch excerpt (illustrative):\n```python\nif not idem_key:\n raise HTTPException(400, \"Missing Idempotency-Key\")\n```\n\n\nChecks: input validation, tests, and safe defaults included.", "source": "WithinUsAI/GOD_Coder_100k"} {"text": "Build an elite-grade solution in the domain of databases for scenario: job scheduler.\nPrimary language: rust.\nDifficulty: expert.\nConstraints: include invariants and failure modes, make the interface contract explicit, design for backward compatibility and migrations, avoid undefined behavior and data races, document performance characteristics.\nComponent: component_sfrsbaf.\nAssume crash-only design; recovery must be deterministic.\nTask: Define a small DSL, implement tokenizer/parser, IR, and a codegen or interpreter. Include tests and complexity notes.\n\nOutput: elite-grade engineering answer with contracts, edge cases, and verification.\nOutput: DSL + parser + IR + interpreter/codegen + tests.\n\n**DSL**\n- Expressions: integers, identifiers, `+ - * /`, let-binding: `let x = expr in expr`\n- Example: `let x = 2+3 in x*10`\n\n**Pipeline**\n1. Tokenize\n2. Parse into AST\n3. Lower into IR (stack ops) or interpret AST directly\n\n**Reference (Rust-style outline)**\n- `enum Expr { Int(i64), Var(String), Bin(Op, Box, Box), Let(String, Box, Box) }`\n- Parser: Pratt or recursive descent.\n\n**Tests**\n- Golden tests for parse trees.\n- Property: pretty-print(parse(x)) round-trips for a corpus.\n- Eval tests for precedence and scoping.\n\n\nExpert checks: state-machine reasoning, concurrency stress, and upgrade/rollback validated.", "source": "WithinUsAI/Elite_GOD_Coder_100k"} {"text": "Refactor to typed, mostly-immutable Python and add minimal tests.\n\n```python\nclass C92520:\n def __init__(self, values): self.values=list(values)\n def mean(self): return sum(self.values)/len(self.values)\n```\nReturn `m84040.py` and `test_m84040.py`.\n\n```python\n# m84040.py\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom typing import Iterable, Tuple\n\n@dataclass(frozen=True)\nclass C92520:\n values: Tuple[float, ...]\n\n @staticmethod\n def create(values: Iterable[float]) -> \"C92520\":\n vals = tuple(float(v) for v in values)\n if not vals: raise ValueError(\"empty\")\n return C92520(vals)\n\n def mean(self) -> float:\n return sum(self.values)/len(self.values)\n```\n\n```python\n# test_m84040.py\nimport pytest\nfrom m84040 import C92520\n\ndef test_mean():\n assert C92520.create([1,2,3]).mean() == 2.0\ndef test_empty():\n with pytest.raises(ValueError):\n C92520.create([])\n```", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Optimize while preserving behavior.\n\nFile: jn_2uhq.py\n```python\ndef qggtbu_u(xs):\n out = []\n for x in xs:\n if x not in out:\n out.append(x)\n return out\n```\n\nRequirements: preserve first-seen order; O(n) average; add types + docstring.\n\n# jn_2uhq.py\nfrom __future__ import annotations\nfrom typing import Iterable, List, Set, TypeVar\n\nT = TypeVar(\"T\")\n\ndef qggtbu_u(xs: Iterable[T]) -> List[T]:\n \"\"\"Return unique items preserving first-seen order.\"\"\"\n seen: Set[T] = set()\n out: List[T] = []\n for x in xs:\n if x in seen:\n continue\n seen.add(x)\n out.append(x)\n return out", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Fix the bug and add pytest tests.\n\n```python\ndef f12693(n: int) -> int:\n # sum 1..n inclusive\n if n < 0: raise ValueError\n total = 0\n for k in range(n): # BUG\n total += k\n return total\n```\nReturn unified diffs for `m16099.py` and `test_m16099.py`.\n\n*** Begin Patch\n*** Update File: m16099.py\n@@\n def f12693(n: int) -> int:\n@@\n- for k in range(n): # BUG\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_m16099.py\n+import pytest\n+from m16099 import f12693\n+\n+def test_small():\n+ assert f12693(7) == 28\n+\n+def test_zero():\n+ assert f12693(0) == 0\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ f12693(-1)\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Task type: query_optimizer\nScenario: streaming ETL\nDomain focus: large-scale ML systems\nPrimary language: sql\nDifficulty: expert\nScale/SLO: 1M msgs/min\nComponent: component_ojvvndim\nConstraints: include performance model and limits, include verification strategy, include test vectors and fuzz strategy, assume adversarial inputs; validate everything, include backward compatibility and migration plan, include security threat model (defensive only)\nAssume strict auditability and replayable history.\nDeliverable: Design a cost-based optimizer slice: logical rules, physical operators, and cost model. Include regression tests and query-plan explain examples.\n\nOutput: elite engineering answer optimized for correctness, performance, and operability.\n**Contract**\n- Inputs validated at the boundary; explicit error taxonomy.\n- Idempotency for side effects via request_id; deterministic replay.\n- Backward compatibility: additive changes by default; versioned breaking changes.\n**Invariants**\n- Liveness: under bounded faults and stable network, progress occurs.\n- Determinism: replay of the same event log yields identical outputs.\n- Isolation: tenant boundary enforced; no cross-tenant reads/writes.\n**Failure modes & recovery**\n- Network partition: minority cannot commit; clients receive retriable errors.\n- Data corruption: checksums + scrubber; quarantine and rebuild from replicas/snapshots.\n- Crash during commit: WAL replay completes or transaction aborts; no torn writes.\n**Security posture (defensive)**\n- Threat model: auth/authz, injection, replay/abuse, supply chain.\n- Least privilege; secrets in managed store; audit logs for sensitive ops.\n- Input normalization, parameterized queries, path traversal protections.\n**Verification strategy**\n- Property tests against a pure reference model (state machine).\n- Deterministic simulation with fault injection (crash/partition/latency).\n- Fuzzing of parsers/framers/validators with corpus seeds.\n\n**Snippet**\n```python\n# Minimal cost model skeleton\nfrom dataclasses import dataclass\n\n@dataclass(frozen=True)\nclass Plan:\n op: str\n cost: float\n children: tuple[\"Plan\", ...] = ()\n\ndef choose_best(plans: list[Plan]) -> Plan:\n return min(plans, key=lambda p: p.cost)\n```\n\nExpert checks: state-machine proof sketch + model checking; upgrade/rollback rehearsed.", "source": "WithinUsAI/Omega_Genesis_Coder_100k"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: Language: Bash\nFramework/tooling: curl\nDomain: developer platform\nLogic challenge: N+1 query explosion\nTask type: edge_case_hardening\nDifficulty: hard\n\nReturn a rigorous engineering answer:\n- identify the hidden root cause or logical failure\n- present the corrected implementation\n- add tests that prove the fix\n- list verification commands\n- explain why naive fixes are insufficient when relevant\n\nRepository sketch:\nrepo/\n scripts/\n run.sh\n deploy.sh\n tests/\n smoke.sh\n\nFocus: Focus on strong structured logic with edge cases, data validation, and concurrency safety.\n\nassistant: Diagnosis:\n- Root cause: the failure around N+1 query explosion is caused by missing validation, weak edge-case handling, or unsafe lifecycle behavior in the current implementation.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```bash\n#!/usr/bin/env bash\nset -euo pipefail\n\ninput=\"${1:-}\"\nif [[ -z \"$input\" ]]; then\n echo \"missing input\" >&2\n exit 1\nfi\n\nprintf '%s\n' \"$input\" | tr -d '\r'\n```\n\nTests:\n```bash\noutput=\"$(bash scripts/run.sh \"abc\")\"\ntest \"$output\" = \"abc\"\n```\n\nVerification:\n- `bash tests/smoke.sh`\n- `shellcheck scripts/*.sh`\n\nEngineering notes:\n- Language: Bash\n- Framework/tooling: curl\n- Stack context: Go, Gin, PostgreSQL, gRPC, Prometheus, Docker\n- Domain: developer platform\n- Task type: edge_case_hardening\n- Difficulty: hard\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: Language: C++\nFramework/tooling: CMake\nDomain: auth service\nLogic challenge: transaction boundary bug\nTask type: parser_validation_logic\nDifficulty: hard\n\nReturn a rigorous engineering answer:\n- identify the hidden root cause or logical failure\n- present the corrected implementation\n- add tests that prove the fix\n- list verification commands\n- explain why naive fixes are insufficient when relevant\n\nRepository sketch:\nrepo/\n src/main.cpp\n src/service.cpp\n include/service.h\n tests/test_service.cpp\n CMakeLists.txt\n\nFocus: Focus on strong structured logic with edge cases, data validation, and concurrency safety.\n\nassistant: Diagnosis:\n- Root cause: the failure around transaction boundary bug is caused by missing validation, weak edge-case handling, or unsafe lifecycle behavior in the current implementation.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```cpp\n#include \n#include \n\nusing Payload = std::unordered_map;\n\nPayload normalize_payload(const Payload& in) {\n Payload out;\n for (const auto& [k, v] : in) {\n if (!v.empty()) out[k] = v;\n }\n return out;\n}\n```\n\nTests:\n```cpp\nTEST_CASE(\"normalize_payload filters empty values\") {\n Payload in{{\"id\",\"7\"},{\"name\",\"\"}};\n auto out = normalize_payload(in);\n REQUIRE(out.count(\"id\") == 1);\n REQUIRE(out.count(\"name\") == 0);\n}\n```\n\nVerification:\n- `cmake --build build`\n- `ctest --test-dir build`\n\nEngineering notes:\n- Language: C++\n- Framework/tooling: CMake\n- Stack context: Go, Gin, PostgreSQL, gRPC, Prometheus, Docker\n- Domain: auth service\n- Task type: parser_validation_logic\n- Difficulty: hard\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Fix a bug and add tests.\n\nFile: yzkojv.py\n```python\ndef i8ma9jom09l(n: int) -> int:\n \"\"\"Sum 1..n inclusive.\"\"\"\n if n < 0:\n raise ValueError(\"n must be non-negative\")\n total = 0\n for k in range(n): # BUG: should include n\n total += k\n return total\n```\n\nReturn unified diffs for yzkojv.py and test_yzkojv.py (pytest).\n\n*** Begin Patch\n*** Update File: yzkojv.py\n@@\n def i8ma9jom09l(n: int) -> int:\n@@\n total = 0\n- for k in range(n): # BUG: should include n\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_yzkojv.py\n+import pytest\n+from yzkojv import i8ma9jom09l\n+\n+def test_zero():\n+ assert i8ma9jom09l(0) == 0\n+\n+def test_one():\n+ assert i8ma9jom09l(1) == 1\n+\n+def test_small():\n+ assert i8ma9jom09l(7) == 28\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ i8ma9jom09l(-1)\n+\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: Repository domain: developer platform\nPrimary language: SQL\nFramework/tooling: SQLite\nReported problem: broken pagination cursor\nTask type: api_endpoint_work\nDifficulty: hard\n\nProduce a complete professional engineering response:\n1. Diagnose the root cause.\n2. Provide the corrected implementation or patch.\n3. Add tests.\n4. Add verification commands.\n5. Note edge cases and any migration or rollback risk.\n\nRepository sketch:\nrepo/\n migrations/\n 001_init.sql\n 002_add_index.sql\n queries/\n report.sql\n tests/\n report_cases.md\n\nQuality target:\n- Minimal diff unless redesign is clearly required\n- Production-ready code\n- No placeholders\n- Secure defaults\n- Clear acceptance of failure cases\n\nFocus: Focus on complete implementation quality, patch correctness, tests, and production readiness.\n\nassistant: Diagnosis:\n- Root cause: the failure around broken pagination cursor is caused by missing validation, weak edge-case handling, or unsafe lifecycle behavior in the current implementation.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```sql\nWITH ranked AS (\n SELECT\n user_id,\n created_at,\n amount,\n ROW_NUMBER() OVER (PARTITION BY user_id ORDER BY created_at DESC, id DESC) AS rn\n FROM orders\n)\nSELECT user_id, created_at, amount\nFROM ranked\nWHERE rn = 1;\n```\n\nTests:\n```sql\n-- Correctness checks:\n-- 1) multiple rows per user\n-- 2) identical timestamps require deterministic tie-breaker\n-- 3) null values handled by business rules\n```\n\nVerification:\n- `run migration checks`\n- `run query correctness cases`\n\nEngineering notes:\n- Language: SQL\n- Framework/tooling: SQLite\n- Stack context: ASP.NET Core, SQL Server, EF Core, xUnit, Docker\n- Domain: developer platform\n- Task type: api_endpoint_work\n- Difficulty: hard\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Fix a bug and add tests.\n\nFile: csje26d9tebv.py\n```python\ndef ce294im59wb(n: int) -> int:\n \"\"\"Sum 1..n inclusive.\"\"\"\n if n < 0:\n raise ValueError(\"n must be non-negative\")\n total = 0\n for k in range(n): # BUG: should include n\n total += k\n return total\n```\n\nReturn unified diffs for csje26d9tebv.py and test_csje26d9tebv.py (pytest).\n\n*** Begin Patch\n*** Update File: csje26d9tebv.py\n@@\n def ce294im59wb(n: int) -> int:\n@@\n total = 0\n- for k in range(n): # BUG: should include n\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_csje26d9tebv.py\n+import pytest\n+from csje26d9tebv import ce294im59wb\n+\n+def test_zero():\n+ assert ce294im59wb(0) == 0\n+\n+def test_one():\n+ assert ce294im59wb(1) == 1\n+\n+def test_small():\n+ assert ce294im59wb(7) == 28\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ ce294im59wb(-1)\n+\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Fix the bug and add pytest tests.\n\n```python\ndef f01620(n: int) -> int:\n # sum 1..n inclusive\n if n < 0: raise ValueError\n total = 0\n for k in range(n): # BUG\n total += k\n return total\n```\nReturn unified diffs for `m71660.py` and `test_m71660.py`.\n\n*** Begin Patch\n*** Update File: m71660.py\n@@\n def f01620(n: int) -> int:\n@@\n- for k in range(n): # BUG\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_m71660.py\n+import pytest\n+from m71660 import f01620\n+\n+def test_small():\n+ assert f01620(7) == 28\n+\n+def test_zero():\n+ assert f01620(0) == 0\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ f01620(-1)\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Design CI/CD for a healthtech service delivering event-driven workflows.\nTarget platform: ML (PyTorch + serving).\nRequirements: pipelines, checks, artifact strategy, deployments, and rollbacks.\nConstraints: must be secure-by-default, must be performant under load, must include clear error handling, must include documentation/comments.\nDifficulty: medium. Assume strict latency budget (p95 < 200ms).\n\nOutput: design + implementation guidance suitable for shipping.\nDeliverable: CI/CD pipeline (GitHub Actions) with quality gates.\n\n```yaml\nname: ci\non:\n pull_request:\n push:\n branches: [main]\n\njobs:\n test:\n runs-on: ubuntu-latest\n steps:\n - uses: actions/checkout@v4\n - uses: actions/setup-python@v5\n with:\n python-version: \"3.11\"\n - run: python -m pip install -U pip\n - run: pip install -r requirements.txt\n - run: pip install -r requirements-dev.txt\n - run: ruff check .\n - run: mypy .\n - run: pytest -q --maxfail=1 --disable-warnings\n\n docker:\n needs: test\n runs-on: ubuntu-latest\n steps:\n - uses: actions/checkout@v4\n - uses: docker/setup-buildx-action@v3\n - run: docker build -t app:${{ github.sha }} .\n```\n\nDeployment strategy:\n- main → build → deploy to staging → smoke tests → canary to prod.\n- Rollback: redeploy previous image + DB migration rollback plan.\n\n\nChecks: input validation, tests, and safe defaults included.", "source": "WithinUsAI/GOD_Coder_100k"} {"text": "Build an elite-grade solution in the domain of databases for scenario: rate limiting gateway.\nPrimary language: rust.\nDifficulty: expert.\nConstraints: make the interface contract explicit, include invariants and failure modes, document performance characteristics, design for backward compatibility and migrations.\nComponent: component_utzrxyr.\nAssume crash-only design; recovery must be deterministic.\nTask: Define a small DSL, implement tokenizer/parser, IR, and a codegen or interpreter. Include tests and complexity notes.\n\nOutput: rigorous solution with invariants, failure modes, and performance notes.\nOutput: DSL + parser + IR + interpreter/codegen + tests.\n\n**DSL**\n- Expressions: integers, identifiers, `+ - * /`, let-binding: `let x = expr in expr`\n- Example: `let x = 2+3 in x*10`\n\n**Pipeline**\n1. Tokenize\n2. Parse into AST\n3. Lower into IR (stack ops) or interpret AST directly\n\n**Reference (Rust-style outline)**\n- `enum Expr { Int(i64), Var(String), Bin(Op, Box, Box), Let(String, Box, Box) }`\n- Parser: Pratt or recursive descent.\n\n**Tests**\n- Golden tests for parse trees.\n- Property: pretty-print(parse(x)) round-trips for a corpus.\n- Eval tests for precedence and scoping.\n\n\nExpert checks: state-machine reasoning, concurrency stress, and upgrade/rollback validated.", "source": "WithinUsAI/Elite_GOD_Coder_100k"} {"text": "Fix a subtle bug in a Python module used for ETL pipelines.\nRequirements: explain root cause briefly, provide corrected code, and add regression tests.\nConstraints: must include type hints, must be memory-efficient.\nDifficulty: medium. Provide helpful exceptions with actionable messages.\n\nDeliverable: production-ready reference solution.\n```python\nfrom __future__ import annotations\n\nfrom dataclasses import dataclass\nfrom pathlib import Path\nfrom typing import Iterable\nimport json\n\n\nclass ValidationError(ValueError):\n \"\"\"Raised when input validation fails.\"\"\"\n\n\ndef safe_join(base: Path, *parts: str) -> Path:\n \"\"\"Join paths while preventing traversal outside base.\"\"\"\n b = base.resolve()\n p = (b / Path(*parts)).resolve()\n if p != b and b not in p.parents:\n raise ValidationError(f\"unsafe path: {p}\")\n return p\n\n\n@dataclass(frozen=True, slots=True)\nclass Record:\n key: str\n value: int\n\n\ndef parse_jsonl(lines: Iterable[str]) -> list[Record]:\n out: list[Record] = []\n for idx, line in enumerate(lines, 1):\n s = line.strip()\n if not s:\n continue\n try:\n obj = json.loads(s)\n except json.JSONDecodeError as e:\n raise ValidationError(f\"line {idx}: invalid json\") from e\n if not isinstance(obj, dict):\n raise ValidationError(f\"line {idx}: expected object\")\n key = obj.get(\"key\")\n val = obj.get(\"value\")\n if not isinstance(key, str) or not key:\n raise ValidationError(f\"line {idx}: key must be non-empty str\")\n if not isinstance(val, int):\n raise ValidationError(f\"line {idx}: value must be int\")\n out.append(Record(key, val))\n return out\n\n\ndef write_jsonl(base: Path, rel: str, records: Iterable[Record]) -> Path:\n base.mkdir(parents=True, exist_ok=True)\n dst = safe_join(base, rel)\n dst.parent.mkdir(parents=True, exist_ok=True)\n with dst.open(\"w\", encoding=\"utf-8\", newline=\"\\n\") as f:\n for r in records:\n f.write(json.dumps({\"key\": r.key, \"value\": r.value}, ensure_ascii=False) + \"\\n\")\n return dst\n```\n\n```python\n# tests (pytest-style)\nimport json\nfrom pathlib import Path\nimport pytest\nfrom module_under_test import ValidationError, Record, parse_jsonl, write_jsonl\n\ndef test_parse_ok():\n lines = [json.dumps({\"key\":\"a\",\"value\":1}), json.dumps({\"key\":\"b\",\"value\":2})]\n assert parse_jsonl(lines) == [Record(\"a\",1), Record(\"b\",2)]\n\ndef test_parse_rejects_bad_json():\n with pytest.raises(ValidationError):\n parse_jsonl([\"{not json}\"])\n\ndef test_safe_join_blocks_traversal(tmp_path: Path):\n with pytest.raises(ValidationError):\n write_jsonl(tmp_path, \"../x.jsonl\", [Record(\"a\",1)])\n```", "source": "WithinUsAI/python_GOD_coder_100k"} {"text": "Build an elite-grade solution in the domain of ml systems for scenario: payment processing.\nPrimary language: go.\nDifficulty: hard.\nConstraints: include invariants and failure modes, document performance characteristics, include tests or verification strategy, provide rollout and rollback guidance.\nComponent: component_qvsuqvu.\nAssume compliance requires data deletion with proofs.\nTask: Design an application-level protocol (framing, retries, timeouts, backpressure). Provide client/server skeleton and test vectors.\n\nOutput: rigorous solution with invariants, failure modes, and performance notes.\nOutput: protocol framing + retry policy + client/server skeleton.\n\n**Framing**\n- Length-prefixed: uint32_be length + payload\n- Payload: msgpack/json; include request_id, type, and optional checksum\n\n**Reliability**\n- Retries only for idempotent ops; exponential backoff + jitter.\n- Timeouts: connect, read, overall; enforce max in-flight to provide backpressure.\n\n**Test vectors**\n- Corrupted length / truncated frame rejected\n- Duplicate request_id returns cached response\n- Slowloris protection by read deadlines\n\n\nHard checks: failure injection tests and performance regressions gated.", "source": "WithinUsAI/Elite_GOD_Coder_100k"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: Project domain: document processing API\nImplementation stack: Go, Gin, PostgreSQL, gRPC, Prometheus, Docker\nSoftware delivery problem: broken pagination cursor\nTask type: release_engineering_fix\nDifficulty: medium\n\nReturn a complete delivery-grade response with:\n- diagnosis or design reasoning\n- implementation\n- test plan or tests\n- rollout plan\n- rollback or compatibility note\n- verification commands\n\nRepository sketch:\nrepo/\n src/App/Program.cs\n src/App/Service.cs\n tests/App.Tests/ServiceTests.cs\n App.sln\n\nFocus: Focus on shipping production software with rollout safety, acceptance criteria, telemetry, and maintenance quality.\n\nassistant: Diagnosis:\n- Root cause or delivery blocker: broken pagination cursor needs both implementation work and a safe shipping plan.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```csharp\nusing System;\nusing System.Collections.Generic;\n\npublic static class RequestHandler\n{\n public static Dictionary HandleRequest(Dictionary payload)\n {\n var clean = new Dictionary();\n foreach (var entry in payload)\n {\n if (entry.Value != null)\n clean[entry.Key.Trim()] = entry.Value;\n }\n if (!clean.ContainsKey(\"id\"))\n throw new ArgumentException(\"missing id\");\n return new Dictionary\n {\n [\"ok\"] = true,\n [\"data\"] = clean\n };\n }\n}\n```\n\nTests:\n```csharp\nusing System;\nusing System.Collections.Generic;\nusing Xunit;\n\npublic class RequestHandlerTests\n{\n [Fact]\n public void RequiresId()\n {\n Assert.Throws(() => RequestHandler.HandleRequest(new Dictionary { [\"name\"] = \"x\" }));\n }\n}\n```\n\nVerification:\n- `dotnet test`\n- `dotnet build`\n\nEngineering notes:\n- Language: C#\n- Framework/tooling: EF Core\n- Stack context: Go, Gin, PostgreSQL, gRPC, Prometheus, Docker\n- Domain: document processing API\n- Task type: release_engineering_fix\n- Difficulty: medium\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "Task type: ml_system_design\nScenario: streaming ETL\nDomain focus: secure enclaves (defensive)\nPrimary language: sql\nDifficulty: expert\nScale/SLO: multi-region active-active\nComponent: component_mbhhxzxb\nConstraints: avoid data races and undefined behavior, include performance model and limits, include failure modes and recovery, include test vectors and fuzz strategy, include security threat model (defensive only)\nAssume weekly network partitions.\nDeliverable: Design end-to-end ML system: data contracts, training, evaluation, registry, serving, monitoring, and rollback.\n\nOutput: rigorous design + invariants + verification plan + implementation sketch.\n**Contract**\n- Inputs validated at the boundary; explicit error taxonomy.\n- Idempotency for side effects via request_id; deterministic replay.\n- Backward compatibility: additive changes by default; versioned breaking changes.\n**Invariants**\n- Liveness: under bounded faults and stable network, progress occurs.\n- Safety: state transitions preserve invariants; no partial commit leaks.\n- Determinism: replay of the same event log yields identical outputs.\n**Failure modes & recovery**\n- Duplicate requests: de-duplicate by (tenant, request_id) returning cached response.\n- Network partition: minority cannot commit; clients receive retriable errors.\n- Crash during commit: WAL replay completes or transaction aborts; no torn writes.\n**Security posture (defensive)**\n- Threat model: auth/authz, injection, replay/abuse, supply chain.\n- Least privilege; secrets in managed store; audit logs for sensitive ops.\n- Input normalization, parameterized queries, path traversal protections.\n**Verification strategy**\n- Property tests against a pure reference model (state machine).\n- Canary + shadow traffic; invariants checked in production via assertions/metrics.\n- Fuzzing of parsers/framers/validators with corpus seeds.\n\n**Snippet**\n```text\nImplementation sketch: factor pure state-machine core; adapters for I/O; add deterministic replay log.\n```\nExpert checks: state-machine proof sketch + model checking; upgrade/rollback rehearsed.", "source": "WithinUsAI/Omega_Genesis_Coder_100k"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: Language: Python\nFramework/tooling: FastAPI\nDomain: notification service\nLogic challenge: slow cold start\nTask type: multi_file_migration_repair\nDifficulty: expert\n\nReturn a rigorous engineering answer:\n- identify the hidden root cause or logical failure\n- present the corrected implementation\n- add tests that prove the fix\n- list verification commands\n- explain why naive fixes are insufficient when relevant\n\nRepository sketch:\nrepo/\n app/\n api.py\n service.py\n models.py\n tests/\n test_api.py\n pyproject.toml\n\nFocus: Focus on staff-level problem solving with multi-file patches, rollout implications, performance and security tradeoffs.\n\nassistant: Diagnosis:\n- Staff-level diagnosis: slow cold start impacts correctness, operability, and future maintenance, so the fix must be minimal where possible but complete where necessary.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```python\nfrom __future__ import annotations\n\nfrom dataclasses import dataclass\nfrom typing import Any\n\n@dataclass\nclass ServiceResult:\n ok: bool\n data: dict[str, Any]\n error: str | None = None\n\ndef normalize_payload(payload: dict[str, Any]) -> dict[str, Any]:\n if not isinstance(payload, dict):\n raise TypeError(\"payload must be a dict\")\n clean: dict[str, Any] = {}\n for key, value in payload.items():\n if value is None:\n continue\n clean[str(key).strip()] = value\n return clean\n\ndef handle_slow_cold_start(payload: dict[str, Any]) -> ServiceResult:\n clean = normalize_payload(payload)\n if \"id\" not in clean:\n return ServiceResult(ok=False, data={}, error=\"missing id\")\n return ServiceResult(ok=True, data=clean)\n```\n\nTests:\n```python\nimport pytest\nfrom app.service import handle_jwt_refresh_token_rotation as handler\n\ndef test_handler_accepts_valid_payload():\n result = handler({\"id\": 7, \"name\": \"ok\", \"unused\": None})\n assert result.ok is True\n assert result.data == {\"id\": 7, \"name\": \"ok\"}\n\ndef test_handler_rejects_missing_id():\n result = handler({\"name\": \"x\"})\n assert result.ok is False\n assert result.error == \"missing id\"\n```\n\nVerification:\n- `pytest -q`\n- `ruff check .`\n- `python -m compileall .`\n\nEngineering notes:\n- Language: Python\n- Framework/tooling: FastAPI\n- Stack context: FastAPI, PostgreSQL, Redis, Celery, pytest, Docker\n- Domain: notification service\n- Task type: multi_file_migration_repair\n- Difficulty: expert\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "Build an elite-grade solution in the domain of stream processing for scenario: payment processing.\nPrimary language: python.\nDifficulty: hard.\nConstraints: avoid undefined behavior and data races, design for backward compatibility and migrations, provide rollout and rollback guidance, include invariants and failure modes.\nComponent: component_kpelgnq.\nAssume cold-start and memory limits are tight.\nTask: Define a small DSL, implement tokenizer/parser, IR, and a codegen or interpreter. Include tests and complexity notes.\n\nOutput: rigorous solution with invariants, failure modes, and performance notes.\nOutput: DSL + parser + IR + interpreter/codegen + tests.\n\n**DSL**\n- Expressions: integers, identifiers, `+ - * /`, let-binding: `let x = expr in expr`\n- Example: `let x = 2+3 in x*10`\n\n**Pipeline**\n1. Tokenize\n2. Parse into AST\n3. Lower into IR (stack ops) or interpret AST directly\n\n**Reference (Rust-style outline)**\n- `enum Expr { Int(i64), Var(String), Bin(Op, Box, Box), Let(String, Box, Box) }`\n- Parser: Pratt or recursive descent.\n\n**Tests**\n- Golden tests for parse trees.\n- Property: pretty-print(parse(x)) round-trips for a corpus.\n- Eval tests for precedence and scoping.\n\n\nHard checks: failure injection tests and performance regressions gated.", "source": "WithinUsAI/Elite_GOD_Coder_100k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Fix a bug and add tests.\n\nFile: yit4ngh51f7.py\n```python\ndef jpecqyb5v1(n: int) -> int:\n \"\"\"Sum 1..n inclusive.\"\"\"\n if n < 0:\n raise ValueError(\"n must be non-negative\")\n total = 0\n for k in range(n): # BUG: should include n\n total += k\n return total\n```\n\nReturn unified diffs for yit4ngh51f7.py and test_yit4ngh51f7.py (pytest).\n\n*** Begin Patch\n*** Update File: yit4ngh51f7.py\n@@\n def jpecqyb5v1(n: int) -> int:\n@@\n total = 0\n- for k in range(n): # BUG: should include n\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_yit4ngh51f7.py\n+import pytest\n+from yit4ngh51f7 import jpecqyb5v1\n+\n+def test_zero():\n+ assert jpecqyb5v1(0) == 0\n+\n+def test_one():\n+ assert jpecqyb5v1(1) == 1\n+\n+def test_small():\n+ assert jpecqyb5v1(7) == 28\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ jpecqyb5v1(-1)\n+\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Produce an offline-first self-evolving code assistant architecture named `xwqa68wog`.\nMust include: module layout, patch-safety policy, evaluation gates (tests/lint/types), versioned memory index.\n\nArchitecture: `xwqa68wog` (offline-first, self-evolving)\n\nModules\n- core/loop.py: evolve → validate → accept/reject (bounded iterations)\n- patching/: diff builder, safe apply, atomic writes, rollback points\n- policy/: allowlist paths, deny globs (.git/, __pycache__/, binaries), patch size caps\n- signals/: parse pytest/ruff/mypy into normalized findings\n- memory/index.jsonl: append-only snapshots (hashes, metrics, rationale)\n\nSafety gates\n- refuse path traversal/symlink escapes; never edit binaries\n- accept only if tests/lint/types stay green or improve", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: Project domain: team dashboard\nImplementation stack: ASP.NET Core, SQL Server, EF Core, xUnit, Docker\nSoftware delivery problem: optimistic locking conflict\nTask type: architecture_patch\nDifficulty: medium\n\nReturn a complete delivery-grade response with:\n- diagnosis or design reasoning\n- implementation\n- test plan or tests\n- rollout plan\n- rollback or compatibility note\n- verification commands\n\nRepository sketch:\nrepo/\n src/main.cpp\n src/service.cpp\n include/service.h\n tests/test_service.cpp\n CMakeLists.txt\n\nFocus: Focus on shipping production software with rollout safety, acceptance criteria, telemetry, and maintenance quality.\n\nassistant: Diagnosis:\n- Root cause or delivery blocker: optimistic locking conflict needs both implementation work and a safe shipping plan.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```cpp\n#include \n#include \n\nusing Payload = std::unordered_map;\n\nPayload normalize_payload(const Payload& in) {\n Payload out;\n for (const auto& [k, v] : in) {\n if (!v.empty()) out[k] = v;\n }\n return out;\n}\n```\n\nTests:\n```cpp\nTEST_CASE(\"normalize_payload filters empty values\") {\n Payload in{{\"id\",\"7\"},{\"name\",\"\"}};\n auto out = normalize_payload(in);\n REQUIRE(out.count(\"id\") == 1);\n REQUIRE(out.count(\"name\") == 0);\n}\n```\n\nVerification:\n- `cmake --build build`\n- `ctest --test-dir build`\n\nEngineering notes:\n- Language: C++\n- Framework/tooling: CMake\n- Stack context: ASP.NET Core, SQL Server, EF Core, xUnit, Docker\n- Domain: team dashboard\n- Task type: architecture_patch\n- Difficulty: medium\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "Implement a web feature for calendar/scheduling: rate limiting.\nTarget platform: web (React + TypeScript).\nRequirements: accessible UI, API integration, and tests.\nConstraints: must include tests, must include type hints where applicable, must include documentation/comments.\nDifficulty: easy. Assume untrusted input; validate everything.\n\nOutput: production-oriented blueprint with code where appropriate.\nDeliverable: accessible React + TypeScript feature skeleton with tests.\n\n```tsx\n// Feature.tsx\nimport React, { useEffect, useMemo, useState } from \"react\";\n\ntype Item = { id: string; label: string };\n\nexport function Feature({ fetchItems }: { fetchItems: () => Promise }) {\n const [items, setItems] = useState([]);\n const [q, setQ] = useState(\"\");\n const filtered = useMemo(\n () => items.filter(i => i.label.toLowerCase().includes(q.toLowerCase())),\n [items, q]\n );\n\n useEffect(() => {\n let cancelled = false;\n fetchItems().then(xs => { if (!cancelled) setItems(xs); });\n return () => { cancelled = true; };\n }, [fetchItems]);\n\n return (\n
\n \n
    \n {filtered.map(i =>
  • {i.label}
  • )}\n
\n
\n );\n}\n```\n\n```tsx\n// Feature.test.tsx (vitest + testing-library)\nimport { render, screen } from \"@testing-library/react\";\nimport userEvent from \"@testing-library/user-event\";\nimport { Feature } from \"./Feature\";\n\ntest(\"filters items\", async () => {\n const fetchItems = async () => [{ id:\"1\", label:\"Alpha\" }, { id:\"2\", label:\"Beta\" }];\n render();\n expect(await screen.findByText(\"Alpha\")).toBeInTheDocument();\n await userEvent.type(screen.getByLabelText(\"Search\"), \"be\");\n expect(screen.queryByText(\"Alpha\")).toBeNull();\n expect(screen.getByText(\"Beta\")).toBeInTheDocument();\n});\n```\n\n\nChecks: input validation, tests, and safe defaults included.", "source": "WithinUsAI/GOD_Coder_100k"} {"text": "Implement background jobs for a logistics product.\nTarget platform: ML (PyTorch + serving).\nRequirements: provide production-ready code, configuration, and tests.\nConstraints: must avoid global state, must be secure-by-default, must be observable (logs/metrics/traces).\nDifficulty: expert. Assume mobile clients are occasionally offline.\n\nOutput: production-oriented blueprint with code where appropriate.\nDeliverable: production-grade reference implementation (FastAPI) + tests.\n\n```python\n# app.py\nfrom __future__ import annotations\n\nimport hashlib\nimport json\nfrom dataclasses import dataclass\nfrom datetime import datetime, timezone\nfrom typing import Any, Optional\n\nfrom fastapi import FastAPI, Header, HTTPException\nfrom pydantic import BaseModel, Field\n\napp = FastAPI(title=\"Idempotent API\")\n\nclass CreateReq(BaseModel):\n tenant_id: str = Field(min_length=1)\n amount_cents: int = Field(ge=0)\n currency: str = Field(min_length=3, max_length=3)\n\nclass CreateResp(BaseModel):\n id: str\n created_at: str\n echo: CreateReq\n\n@dataclass\nclass _IdempoEntry:\n request_hash: str\n response_json: str\n\n# In production: Postgres table with UNIQUE(tenant_id, key)\n_IDEMPO: dict[tuple[str, str], _IdempoEntry] = {}\n\ndef _hash_req(req: CreateReq) -> str:\n raw = req.model_dump_json()\n return hashlib.sha256(raw.encode(\"utf-8\")).hexdigest()\n\n@app.post(\"/v1/payments\", response_model=CreateResp)\ndef create_payment(\n req: CreateReq,\n idempotency_key: Optional[str] = Header(default=None, alias=\"Idempotency-Key\"),\n) -> Any:\n if not idempotency_key:\n raise HTTPException(status_code=400, detail=\"Missing Idempotency-Key\")\n if len(idempotency_key) > 128:\n raise HTTPException(status_code=400, detail=\"Idempotency-Key too long\")\n\n key = (req.tenant_id, idempotency_key)\n rh = _hash_req(req)\n\n existing = _IDEMPO.get(key)\n if existing:\n if existing.request_hash != rh:\n raise HTTPException(status_code=409, detail=\"Idempotency-Key reuse with different payload\")\n return json.loads(existing.response_json)\n\n # Create new payment (stubbed)\n pid = hashlib.md5(f\"{req.tenant_id}:{idempotency_key}\".encode()).hexdigest()\n resp = CreateResp(\n id=pid,\n created_at=datetime.now(timezone.utc).isoformat(),\n echo=req,\n )\n _IDEMPO[key] = _IdempoEntry(request_hash=rh, response_json=resp.model_dump_json())\n return resp\n```\n\n```python\n# test_app.py (pytest)\nfrom fastapi.testclient import TestClient\nfrom app import app\n\nclient = TestClient(app)\n\ndef test_idempotent_replay():\n headers = {\"Idempotency-Key\": \"abc\"}\n body = {\"tenant_id\":\"t1\",\"amount_cents\":100,\"currency\":\"USD\"}\n r1 = client.post(\"/v1/payments\", json=body, headers=headers)\n r2 = client.post(\"/v1/payments\", json=body, headers=headers)\n assert r1.status_code == 200 and r2.status_code == 200\n assert r1.json() == r2.json()\n\ndef test_payload_conflict():\n headers = {\"Idempotency-Key\": \"abc\"}\n b1 = {\"tenant_id\":\"t1\",\"amount_cents\":100,\"currency\":\"USD\"}\n b2 = {\"tenant_id\":\"t1\",\"amount_cents\":200,\"currency\":\"USD\"}\n assert client.post(\"/v1/payments\", json=b1, headers=headers).status_code == 200\n assert client.post(\"/v1/payments\", json=b2, headers=headers).status_code == 409\n```\n\nNotes:\n- Replace in-memory store with a DB table and transaction.\n- Store response + request hash to detect key reuse with different payload.\n\n\nHard-mode checks: concurrency safety, idempotency, and rollback validated; add chaos tests where feasible.", "source": "WithinUsAI/GOD_Coder_100k"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: Language: Rust\nFramework/tooling: SQLx\nDomain: developer platform\nLogic challenge: S3-compatible upload inconsistency\nTask type: concurrency_fix\nDifficulty: medium\n\nReturn a rigorous engineering answer:\n- identify the hidden root cause or logical failure\n- present the corrected implementation\n- add tests that prove the fix\n- list verification commands\n- explain why naive fixes are insufficient when relevant\n\nRepository sketch:\nrepo/\n src/main.rs\n src/lib.rs\n src/service.rs\n src/store.rs\n tests/integration.rs\n Cargo.toml\n\nFocus: Focus on strong structured logic with edge cases, data validation, and concurrency safety.\n\nassistant: Diagnosis:\n- Root cause: the failure around S3-compatible upload inconsistency is caused by missing validation, weak edge-case handling, or unsafe lifecycle behavior in the current implementation.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```rust\nuse std::collections::HashMap;\n\npub fn normalize_payload(payload: HashMap) -> HashMap {\n payload\n .into_iter()\n .filter(|(_, v)| !v.trim().is_empty())\n .collect()\n}\n```\n\nTests:\n```rust\n#[test]\nfn normalize_payload_filters_empty_values() {\n use std::collections::HashMap;\n let mut payload = HashMap::new();\n payload.insert(\"id\".to_string(), \"7\".to_string());\n payload.insert(\"name\".to_string(), \"\".to_string());\n let out = normalize_payload(payload);\n assert!(out.contains_key(\"id\"));\n assert!(!out.contains_key(\"name\"));\n}\n```\n\nVerification:\n- `cargo test`\n- `cargo clippy -- -D warnings`\n\nEngineering notes:\n- Language: Rust\n- Framework/tooling: SQLx\n- Stack context: Next.js, Node.js, Prisma, PostgreSQL, Playwright, Docker\n- Domain: developer platform\n- Task type: concurrency_fix\n- Difficulty: medium\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: Project domain: document processing API\nImplementation stack: FastAPI, PostgreSQL, Redis, Celery, pytest, Docker\nSoftware delivery problem: rate-limit bypass\nTask type: release_engineering_fix\nDifficulty: hard\n\nReturn a complete delivery-grade response with:\n- diagnosis or design reasoning\n- implementation\n- test plan or tests\n- rollout plan\n- rollback or compatibility note\n- verification commands\n\nRepository sketch:\nrepo/\n src/main.rs\n src/lib.rs\n src/service.rs\n src/store.rs\n tests/integration.rs\n Cargo.toml\n\nFocus: Focus on shipping production software with rollout safety, acceptance criteria, telemetry, and maintenance quality.\n\nassistant: Diagnosis:\n- Root cause or delivery blocker: rate-limit bypass needs both implementation work and a safe shipping plan.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```rust\nuse std::collections::HashMap;\n\npub fn normalize_payload(payload: HashMap) -> HashMap {\n payload\n .into_iter()\n .filter(|(_, v)| !v.trim().is_empty())\n .collect()\n}\n```\n\nTests:\n```rust\n#[test]\nfn normalize_payload_filters_empty_values() {\n use std::collections::HashMap;\n let mut payload = HashMap::new();\n payload.insert(\"id\".to_string(), \"7\".to_string());\n payload.insert(\"name\".to_string(), \"\".to_string());\n let out = normalize_payload(payload);\n assert!(out.contains_key(\"id\"));\n assert!(!out.contains_key(\"name\"));\n}\n```\n\nVerification:\n- `cargo test`\n- `cargo clippy -- -D warnings`\n\nEngineering notes:\n- Language: Rust\n- Framework/tooling: Tokio\n- Stack context: FastAPI, PostgreSQL, Redis, Celery, pytest, Docker\n- Domain: document processing API\n- Task type: release_engineering_fix\n- Difficulty: hard\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Fix a bug and add tests.\n\nFile: h6zcmg.py\n```python\ndef mfmumna(n: int) -> int:\n \"\"\"Sum 1..n inclusive.\"\"\"\n if n < 0:\n raise ValueError(\"n must be non-negative\")\n total = 0\n for k in range(n): # BUG: should include n\n total += k\n return total\n```\n\nReturn unified diffs for h6zcmg.py and test_h6zcmg.py (pytest).\n\n*** Begin Patch\n*** Update File: h6zcmg.py\n@@\n def mfmumna(n: int) -> int:\n@@\n total = 0\n- for k in range(n): # BUG: should include n\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_h6zcmg.py\n+import pytest\n+from h6zcmg import mfmumna\n+\n+def test_zero():\n+ assert mfmumna(0) == 0\n+\n+def test_one():\n+ assert mfmumna(1) == 1\n+\n+def test_small():\n+ assert mfmumna(7) == 28\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ mfmumna(-1)\n+\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: Project domain: model serving gateway\nImplementation stack: ASP.NET Core, SQL Server, EF Core, xUnit, Docker\nSoftware delivery problem: broken pagination cursor\nTask type: incident_to_remediation\nDifficulty: medium\n\nReturn a complete delivery-grade response with:\n- diagnosis or design reasoning\n- implementation\n- test plan or tests\n- rollout plan\n- rollback or compatibility note\n- verification commands\n\nRepository sketch:\nrepo/\n src/\n api.ts\n service.ts\n schema.ts\n tests/\n api.test.ts\n package.json\n\nFocus: Focus on shipping production software with rollout safety, acceptance criteria, telemetry, and maintenance quality.\n\nassistant: Diagnosis:\n- Root cause or delivery blocker: broken pagination cursor needs both implementation work and a safe shipping plan.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```ts\ntype Payload = Record;\n\nexport function normalizePayload(payload: Payload): Payload {\n if (!payload || typeof payload !== \"object\" || Array.isArray(payload)) {\n throw new TypeError(\"payload must be a plain object\");\n }\n return Object.fromEntries(\n Object.entries(payload)\n .filter(([, value]) => value !== null && value !== undefined)\n .map(([key, value]) => [String(key).trim(), value])\n );\n}\n\nexport function handleBrokenPaginationCursor(payload: Payload) {\n const clean = normalizePayload(payload);\n if (!(\"id\" in clean)) {\n return { ok: false, data: {}, error: \"missing id\" };\n }\n return { ok: true, data: clean, error: null };\n}\n```\n\nTests:\n```ts\nimport { describe, it, expect } from \"vitest\";\nimport { handleBrokenPaginationCursor } from \"../src/service\";\n\ndescribe(\"handler\", () => {\n it(\"accepts valid input\", () => {\n expect(handleBrokenPaginationCursor({ id: 7, name: \"ok\", unused: null })).toEqual({\n ok: true,\n data: { id: 7, name: \"ok\" },\n error: null\n });\n });\n\n it(\"rejects missing id\", () => {\n expect(handleBrokenPaginationCursor({ name: \"x\" }).error).toMatch(/missing id/);\n });\n});\n```\n\nVerification:\n- `npm test`\n- `npm run typecheck`\n- `npm run lint`\n\nEngineering notes:\n- Language: TypeScript\n- Framework/tooling: Vitest\n- Stack context: ASP.NET Core, SQL Server, EF Core, xUnit, Docker\n- Domain: model serving gateway\n- Task type: incident_to_remediation\n- Difficulty: medium\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: Project domain: job scheduler\nImplementation stack: Next.js, Node.js, Prisma, PostgreSQL, Playwright, Docker\nSoftware delivery problem: invalid rollback sequence\nTask type: incident_to_remediation\nDifficulty: hard\n\nReturn a complete delivery-grade response with:\n- diagnosis or design reasoning\n- implementation\n- test plan or tests\n- rollout plan\n- rollback or compatibility note\n- verification commands\n\nRepository sketch:\nrepo/\n src/main/java/com/acme/App.java\n src/main/java/com/acme/Service.java\n src/test/java/com/acme/AppTest.java\n pom.xml\n\nFocus: Focus on shipping production software with rollout safety, acceptance criteria, telemetry, and maintenance quality.\n\nassistant: Diagnosis:\n- Root cause or delivery blocker: invalid rollback sequence needs both implementation work and a safe shipping plan.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```java\nimport java.util.HashMap;\nimport java.util.Map;\n\npublic final class RequestHandler {\n public static Map handleRequest(Map payload) {\n Map clean = new HashMap<>();\n for (Map.Entry entry : payload.entrySet()) {\n if (entry.getValue() != null) clean.put(entry.getKey().trim(), entry.getValue());\n }\n if (!clean.containsKey(\"id\")) throw new IllegalArgumentException(\"missing id\");\n return Map.of(\"ok\", true, \"data\", clean);\n }\n}\n```\n\nTests:\n```java\nimport static org.junit.jupiter.api.Assertions.*;\nimport java.util.Map;\nimport org.junit.jupiter.api.Test;\n\nclass RequestHandlerTest {\n @Test\n void requiresId() {\n assertThrows(IllegalArgumentException.class, () -> RequestHandler.handleRequest(Map.of(\"name\", \"x\")));\n }\n}\n```\n\nVerification:\n- `./gradlew test`\n- `mvn test`\n\nEngineering notes:\n- Language: Java\n- Framework/tooling: Gradle\n- Stack context: Next.js, Node.js, Prisma, PostgreSQL, Playwright, Docker\n- Domain: job scheduler\n- Task type: incident_to_remediation\n- Difficulty: hard\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "Write pytest tests for `f41184`.\n\n```python\ndef f41184(a: int, b: int) -> int:\n return a*a + b*b\n```\nInclude edge cases and a property-style check.\n\n```python\nimport random\nfrom m77312 import f41184\n\ndef test_known():\n assert f41184(3,4) == 25\n\ndef test_zero():\n assert f41184(0,0) == 0\n\ndef test_property_nonnegative():\n for _ in range(200):\n a=random.randint(-50,50)\n b=random.randint(-50,50)\n assert f41184(a,b) >= 0\n```", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Create a small, production-ready Python package for CLI tooling.\nRequirements: include module code, CLI entrypoint, logging, and a minimal pyproject.toml.\nConstraints: must include docstrings, must include tests.\nDifficulty: hard. Avoid quadratic behavior on large inputs.\n\nDeliverable: API + reference implementation + tests.\nPackage layout:\n- mypkg/core.py\n- mypkg/cli.py\n- pyproject.toml\n\n```python\n# mypkg/core.py\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom typing import Iterable\nimport logging\n\nlog = logging.getLogger(__name__)\n\n@dataclass(frozen=True, slots=True)\nclass Result:\n total: int\n count: int\n\ndef aggregate(values: Iterable[int]) -> Result:\n total = 0\n count = 0\n for v in values:\n if not isinstance(v, int):\n raise TypeError(\"values must be ints\")\n total += v\n count += 1\n log.debug(\"aggregate count=%s total=%s\", count, total)\n return Result(total, count)\n```\n\n```python\n# mypkg/cli.py\nfrom __future__ import annotations\nimport argparse\nimport logging\nimport sys\nfrom .core import aggregate\n\ndef main(argv: list[str] | None = None) -> int:\n p = argparse.ArgumentParser(prog=\"mypkg\")\n p.add_argument(\"--log-level\", default=\"WARNING\")\n args = p.parse_args(argv)\n logging.basicConfig(level=getattr(logging, args.log_level.upper(), logging.WARNING))\n data: list[int] = []\n for line in sys.stdin:\n line = line.strip()\n if line:\n data.append(int(line))\n r = aggregate(data)\n print(f\"count={r.count} total={r.total}\")\n return 0\n```\n\n```toml\n# pyproject.toml\n[project]\nname = \"mypkg\"\nversion = \"0.1.0\"\nrequires-python = \">=3.10\"\n\n[project.scripts]\nmypkg = \"mypkg.cli:main\"\n```", "source": "WithinUsAI/python_GOD_coder_100k"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: System domain: model serving gateway\nStack: Go, Gin, PostgreSQL, gRPC, Prometheus, Docker\nCross-layer incident: JWT refresh token rotation\nTask type: deploy_runtime_patch\nDifficulty: hard\n\nSolve this as a complete-project engineer.\nOutput must include:\n- root cause across layers\n- final implementation patch\n- tests touching at least two layers\n- deployment or observability note\n- verification commands\n\nRepository sketch:\nrepo/\n .github/workflows/ci.yml\n docker-compose.yml\n deploy/\n app.yaml\n\nFocus: Focus on multi-layer debugging across frontend, backend, database, CI, caching, and deployment.\n\nassistant: Diagnosis:\n- Root cause: JWT refresh token rotation crosses service boundaries, so the fix must align code, contracts, tests, and deployment behavior.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```yaml\nname: ci\non: [push, pull_request]\njobs:\n test:\n runs-on: ubuntu-latest\n steps:\n - uses: actions/checkout@v4\n - name: Validate\n run: echo \"validated\"\n```\n\nTests:\n```yaml\n# Verification:\n# - validate syntax\n# - run smoke workflow\n# - fail fast on broken config\n```\n\nVerification:\n- `validate workflow syntax`\n- `run CI smoke job`\n\nEngineering notes:\n- Language: YAML\n- Framework/tooling: Terraform\n- Stack context: Go, Gin, PostgreSQL, gRPC, Prometheus, Docker\n- Domain: model serving gateway\n- Task type: deploy_runtime_patch\n- Difficulty: hard\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "Build an elite-grade solution in the domain of stream processing for scenario: edge sync.\nPrimary language: typescript.\nDifficulty: hard.\nConstraints: include tests or verification strategy, design for backward compatibility and migrations, assume untrusted inputs; validate and sanitize.\nComponent: component_vdercbm.\nAssume compliance requires data deletion with proofs.\nTask: Provide SLOs, alerting, dashboards, runbooks, and incident playbook. Include chaos testing and safe rollout strategy.\n\nOutput: production blueprint plus correctness arguments and test strategy.\nOutput: SLOs + alerts + runbooks + chaos strategy.\n\n**SLOs**\n- Availability: 99.9% monthly\n- Latency: p95 < 200ms, p99 < 400ms\n- Error rate: < 0.1%\n\n**Alerts**\n- Burn-rate alerts for SLOs (fast/slow windows)\n- Saturation: CPU, memory, queue depth, DB connections\n- Dependency health: cache hit rate drop, downstream timeouts\n\n**Runbooks**\n- Triage: identify blast radius, feature-flag rollback, capacity mitigation\n- Post-incident: timeline, contributing factors, action items\n\n**Chaos**\n- Inject latency, partial outages, and restarts in staging; verify steady-state SLOs.\n\n\nHard checks: failure injection tests and performance regressions gated.", "source": "WithinUsAI/Elite_GOD_Coder_100k"} {"text": "Fix a subtle bug in a Python module used for event dispatching.\nRequirements: explain root cause briefly, provide corrected code, and add regression tests.\nConstraints: must include type hints, must include docstrings, must avoid global state.\nDifficulty: medium. Avoid quadratic behavior on large inputs.\n\nDeliverable: production-ready reference solution.\n```python\nfrom __future__ import annotations\n\nfrom dataclasses import dataclass\nfrom pathlib import Path\nfrom typing import Iterable\nimport json\n\n\nclass ValidationError(ValueError):\n \"\"\"Raised when input validation fails.\"\"\"\n\n\ndef safe_join(base: Path, *parts: str) -> Path:\n \"\"\"Join paths while preventing traversal outside base.\"\"\"\n b = base.resolve()\n p = (b / Path(*parts)).resolve()\n if p != b and b not in p.parents:\n raise ValidationError(f\"unsafe path: {p}\")\n return p\n\n\n@dataclass(frozen=True, slots=True)\nclass Record:\n key: str\n value: int\n\n\ndef parse_jsonl(lines: Iterable[str]) -> list[Record]:\n out: list[Record] = []\n for idx, line in enumerate(lines, 1):\n s = line.strip()\n if not s:\n continue\n try:\n obj = json.loads(s)\n except json.JSONDecodeError as e:\n raise ValidationError(f\"line {idx}: invalid json\") from e\n if not isinstance(obj, dict):\n raise ValidationError(f\"line {idx}: expected object\")\n key = obj.get(\"key\")\n val = obj.get(\"value\")\n if not isinstance(key, str) or not key:\n raise ValidationError(f\"line {idx}: key must be non-empty str\")\n if not isinstance(val, int):\n raise ValidationError(f\"line {idx}: value must be int\")\n out.append(Record(key, val))\n return out\n\n\ndef write_jsonl(base: Path, rel: str, records: Iterable[Record]) -> Path:\n base.mkdir(parents=True, exist_ok=True)\n dst = safe_join(base, rel)\n dst.parent.mkdir(parents=True, exist_ok=True)\n with dst.open(\"w\", encoding=\"utf-8\", newline=\"\\n\") as f:\n for r in records:\n f.write(json.dumps({\"key\": r.key, \"value\": r.value}, ensure_ascii=False) + \"\\n\")\n return dst\n```\n\n```python\n# tests (pytest-style)\nimport json\nfrom pathlib import Path\nimport pytest\nfrom module_under_test import ValidationError, Record, parse_jsonl, write_jsonl\n\ndef test_parse_ok():\n lines = [json.dumps({\"key\":\"a\",\"value\":1}), json.dumps({\"key\":\"b\",\"value\":2})]\n assert parse_jsonl(lines) == [Record(\"a\",1), Record(\"b\",2)]\n\ndef test_parse_rejects_bad_json():\n with pytest.raises(ValidationError):\n parse_jsonl([\"{not json}\"])\n\ndef test_safe_join_blocks_traversal(tmp_path: Path):\n with pytest.raises(ValidationError):\n write_jsonl(tmp_path, \"../x.jsonl\", [Record(\"a\",1)])\n```", "source": "WithinUsAI/python_GOD_coder_100k"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: Language: TypeScript\nFramework/tooling: Node.js\nDomain: document processing API\nLogic challenge: async cancellation bug\nTask type: multi_service_security_patch\nDifficulty: hard\n\nReturn a rigorous engineering answer:\n- identify the hidden root cause or logical failure\n- present the corrected implementation\n- add tests that prove the fix\n- list verification commands\n- explain why naive fixes are insufficient when relevant\n\nRepository sketch:\nrepo/\n src/\n api.ts\n service.ts\n schema.ts\n tests/\n api.test.ts\n package.json\n\nFocus: Focus on staff-level problem solving with multi-file patches, rollout implications, performance and security tradeoffs.\n\nassistant: Diagnosis:\n- Staff-level diagnosis: async cancellation bug impacts correctness, operability, and future maintenance, so the fix must be minimal where possible but complete where necessary.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```ts\ntype Payload = Record;\n\nexport function normalizePayload(payload: Payload): Payload {\n if (!payload || typeof payload !== \"object\" || Array.isArray(payload)) {\n throw new TypeError(\"payload must be a plain object\");\n }\n return Object.fromEntries(\n Object.entries(payload)\n .filter(([, value]) => value !== null && value !== undefined)\n .map(([key, value]) => [String(key).trim(), value])\n );\n}\n\nexport function handleAsyncCancellationBug(payload: Payload) {\n const clean = normalizePayload(payload);\n if (!(\"id\" in clean)) {\n return { ok: false, data: {}, error: \"missing id\" };\n }\n return { ok: true, data: clean, error: null };\n}\n```\n\nTests:\n```ts\nimport { describe, it, expect } from \"vitest\";\nimport { handleAsyncCancellationBug } from \"../src/service\";\n\ndescribe(\"handler\", () => {\n it(\"accepts valid input\", () => {\n expect(handleAsyncCancellationBug({ id: 7, name: \"ok\", unused: null })).toEqual({\n ok: true,\n data: { id: 7, name: \"ok\" },\n error: null\n });\n });\n\n it(\"rejects missing id\", () => {\n expect(handleAsyncCancellationBug({ name: \"x\" }).error).toMatch(/missing id/);\n });\n});\n```\n\nVerification:\n- `npm test`\n- `npm run typecheck`\n- `npm run lint`\n\nEngineering notes:\n- Language: TypeScript\n- Framework/tooling: Node.js\n- Stack context: Airflow, dbt, DuckDB, MinIO, pytest\n- Domain: document processing API\n- Task type: multi_service_security_patch\n- Difficulty: hard\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Refactor to modern typed Python with immutability and tests.\n\nFile: lao9w_6dj.py\n```python\nclass J61Inzf8Ik:\n def __init__(self, name, values):\n self.name = name\n self.values = list(values)\n def add(self, v):\n self.values.append(v)\n def mean(self):\n s = 0\n for x in self.values:\n s += x\n return s / len(self.values)\n```\n\nReturn full new lao9w_6dj.py and test_lao9w_6dj.py.\n\n# lao9w_6dj.py\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom typing import Iterable, Tuple\n\n@dataclass(frozen=True)\nclass J61Inzf8Ik:\n name: str\n values: Tuple[float, ...]\n\n @staticmethod\n def create(name: str, values: Iterable[float]) -> \"J61Inzf8Ik\":\n vals = tuple(float(v) for v in values)\n if not vals:\n raise ValueError(\"values must be non-empty\")\n return J61Inzf8Ik(name=name, values=vals)\n\n def add(self, v: float) -> \"J61Inzf8Ik\":\n return J61Inzf8Ik(name=self.name, values=self.values + (float(v),))\n\n def mean(self) -> float:\n return sum(self.values) / len(self.values)\n\n# test_lao9w_6dj.py\nimport pytest\nfrom lao9w_6dj import J61Inzf8Ik\n\ndef test_mean_and_add():\n c = J61Inzf8Ik.create(\"a\", [1, 2, 3])\n assert c.mean() == 2.0\n assert c.add(5).mean() == (1 + 2 + 3 + 5) / 4\n\ndef test_empty_raises():\n with pytest.raises(ValueError):\n J61Inzf8Ik.create(\"x\", [])", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Provision infrastructure for a e-commerce workload providing background jobs.\nTarget platform: ML (scikit + batch).\nRequirements: IaC (Terraform or Kubernetes YAML), networking, secrets, autoscaling.\nConstraints: must be observable (logs/metrics/traces), must include type hints where applicable, must avoid global state.\nDifficulty: easy. Assume strict latency budget (p95 < 200ms).\n\nOutput: engineering-grade answer with edge cases covered.\nDeliverable: Kubernetes deployment + basic security posture.\n\n```yaml\napiVersion: apps/v1\nkind: Deployment\nmetadata:\n name: app\nspec:\n replicas: 3\n selector:\n matchLabels: { app: app }\n template:\n metadata:\n labels: { app: app }\n spec:\n containers:\n - name: app\n image: app:latest\n ports: [{ containerPort: 8080 }]\n readinessProbe:\n httpGet: { path: /healthz, port: 8080 }\n resources:\n requests: { cpu: \"200m\", memory: \"256Mi\" }\n limits: { cpu: \"1\", memory: \"1Gi\" }\n```\n\nAdditions:\n- NetworkPolicy to restrict egress/ingress.\n- Secrets via external secret store; rotate regularly.\n- HPA for autoscaling; PodDisruptionBudget for availability.\n\n\nChecks: input validation, tests, and safe defaults included.", "source": "WithinUsAI/GOD_Coder_100k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Fix a bug and add tests.\n\nFile: nzieffdv6.py\n```python\ndef zxsbi0_ojev5(n: int) -> int:\n \"\"\"Sum 1..n inclusive.\"\"\"\n if n < 0:\n raise ValueError(\"n must be non-negative\")\n total = 0\n for k in range(n): # BUG: should include n\n total += k\n return total\n```\n\nReturn unified diffs for nzieffdv6.py and test_nzieffdv6.py (pytest).\n\n*** Begin Patch\n*** Update File: nzieffdv6.py\n@@\n def zxsbi0_ojev5(n: int) -> int:\n@@\n total = 0\n- for k in range(n): # BUG: should include n\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_nzieffdv6.py\n+import pytest\n+from nzieffdv6 import zxsbi0_ojev5\n+\n+def test_zero():\n+ assert zxsbi0_ojev5(0) == 0\n+\n+def test_one():\n+ assert zxsbi0_ojev5(1) == 1\n+\n+def test_small():\n+ assert zxsbi0_ojev5(7) == 28\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ zxsbi0_ojev5(-1)\n+\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Task type: compiler_backend_ir\nScenario: payment ledger\nDomain focus: data lineage & governance\nPrimary language: cpp\nDifficulty: hard\nScale/SLO: p99 < 50ms\nComponent: component_crrnojrx\nConstraints: include security threat model (defensive only), include verification strategy, include failure modes and recovery, assume adversarial inputs; validate everything, include backward compatibility and migration plan, include test vectors and fuzz strategy\nAssume crash-only processes; recovery must be deterministic.\nDeliverable: Design an IR and lowering pipeline; include an optimization pass and correctness checks. Provide minimal code skeleton and tests.\n\nOutput: elite engineering answer optimized for correctness, performance, and operability.\n**Contract**\n- Inputs validated at the boundary; explicit error taxonomy.\n- Idempotency for side effects via request_id; deterministic replay.\n- Backward compatibility: additive changes by default; versioned breaking changes.\n**Invariants**\n- Liveness: under bounded faults and stable network, progress occurs.\n- Isolation: tenant boundary enforced; no cross-tenant reads/writes.\n- Safety: state transitions preserve invariants; no partial commit leaks.\n**Failure modes & recovery**\n- Crash during commit: WAL replay completes or transaction aborts; no torn writes.\n- Network partition: minority cannot commit; clients receive retriable errors.\n- Duplicate requests: de-duplicate by (tenant, request_id) returning cached response.\n**Security posture (defensive)**\n- Threat model: auth/authz, injection, replay/abuse, supply chain.\n- Least privilege; secrets in managed store; audit logs for sensitive ops.\n- Input normalization, parameterized queries, path traversal protections.\n**Verification strategy**\n- Deterministic simulation with fault injection (crash/partition/latency).\n- Fuzzing of parsers/framers/validators with corpus seeds.\n- Property tests against a pure reference model (state machine).\n\n**Snippet**\n```text\nImplementation sketch: factor pure state-machine core; adapters for I/O; add deterministic replay log.\n```\nHard checks: fault injection tests gate merges; perf thresholds enforced in CI.", "source": "WithinUsAI/Omega_Genesis_Coder_100k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Produce an offline-first self-evolving code assistant architecture named `iuqh3a8hm_g`.\nMust include: module layout, patch-safety policy, evaluation gates (tests/lint/types), versioned memory index.\n\nArchitecture: `iuqh3a8hm_g` (offline-first, self-evolving)\n\nModules\n- core/loop.py: evolve → validate → accept/reject (bounded iterations)\n- patching/: diff builder, safe apply, atomic writes, rollback points\n- policy/: allowlist paths, deny globs (.git/, __pycache__/, binaries), patch size caps\n- signals/: parse pytest/ruff/mypy into normalized findings\n- memory/index.jsonl: append-only snapshots (hashes, metrics, rationale)\n\nSafety gates\n- refuse path traversal/symlink escapes; never edit binaries\n- accept only if tests/lint/types stay green or improve", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Write pytest tests for `f92131`.\n\n```python\ndef f92131(a: int, b: int) -> int:\n return a*a + b*b\n```\nInclude edge cases and a property-style check.\n\n```python\nimport random\nfrom m41733 import f92131\n\ndef test_known():\n assert f92131(3,4) == 25\n\ndef test_zero():\n assert f92131(0,0) == 0\n\ndef test_property_nonnegative():\n for _ in range(200):\n a=random.randint(-50,50)\n b=random.randint(-50,50)\n assert f92131(a,b) >= 0\n```", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: Project domain: data pipeline\nImplementation stack: GitHub Actions, Docker Compose, Kubernetes, Terraform\nSoftware delivery problem: log redaction failure\nTask type: rollback_safe_migration\nDifficulty: hard\n\nReturn a complete delivery-grade response with:\n- diagnosis or design reasoning\n- implementation\n- test plan or tests\n- rollout plan\n- rollback or compatibility note\n- verification commands\n\nRepository sketch:\nrepo/\n migrations/\n 001_init.sql\n 002_add_index.sql\n queries/\n report.sql\n tests/\n report_cases.md\n\nFocus: Focus on shipping production software with rollout safety, acceptance criteria, telemetry, and maintenance quality.\n\nassistant: Diagnosis:\n- Root cause or delivery blocker: log redaction failure needs both implementation work and a safe shipping plan.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```sql\nWITH ranked AS (\n SELECT\n user_id,\n created_at,\n amount,\n ROW_NUMBER() OVER (PARTITION BY user_id ORDER BY created_at DESC, id DESC) AS rn\n FROM orders\n)\nSELECT user_id, created_at, amount\nFROM ranked\nWHERE rn = 1;\n```\n\nTests:\n```sql\n-- Correctness checks:\n-- 1) multiple rows per user\n-- 2) identical timestamps require deterministic tie-breaker\n-- 3) null values handled by business rules\n```\n\nVerification:\n- `run migration checks`\n- `run query correctness cases`\n\nEngineering notes:\n- Language: SQL\n- Framework/tooling: MySQL\n- Stack context: GitHub Actions, Docker Compose, Kubernetes, Terraform\n- Domain: data pipeline\n- Task type: rollback_safe_migration\n- Difficulty: hard\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "Fix the bug and add pytest tests.\n\n```python\ndef f31699(n: int) -> int:\n # sum 1..n inclusive\n if n < 0: raise ValueError\n total = 0\n for k in range(n): # BUG\n total += k\n return total\n```\nReturn unified diffs for `m75957.py` and `test_m75957.py`.\n\n*** Begin Patch\n*** Update File: m75957.py\n@@\n def f31699(n: int) -> int:\n@@\n- for k in range(n): # BUG\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_m75957.py\n+import pytest\n+from m75957 import f31699\n+\n+def test_small():\n+ assert f31699(7) == 28\n+\n+def test_zero():\n+ assert f31699(0) == 0\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ f31699(-1)\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Fix the bug and add pytest tests.\n\n```python\ndef f87098(n: int) -> int:\n # sum 1..n inclusive\n if n < 0: raise ValueError\n total = 0\n for k in range(n): # BUG\n total += k\n return total\n```\nReturn unified diffs for `m41014.py` and `test_m41014.py`.\n\n*** Begin Patch\n*** Update File: m41014.py\n@@\n def f87098(n: int) -> int:\n@@\n- for k in range(n): # BUG\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_m41014.py\n+import pytest\n+from m41014 import f87098\n+\n+def test_small():\n+ assert f87098(7) == 28\n+\n+def test_zero():\n+ assert f87098(0) == 0\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ f87098(-1)\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Refactor to modern typed Python with immutability and tests.\n\nFile: w1vw30.py\n```python\nclass Dravp12Sp:\n def __init__(self, name, values):\n self.name = name\n self.values = list(values)\n def add(self, v):\n self.values.append(v)\n def mean(self):\n s = 0\n for x in self.values:\n s += x\n return s / len(self.values)\n```\n\nReturn full new w1vw30.py and test_w1vw30.py.\n\n# w1vw30.py\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom typing import Iterable, Tuple\n\n@dataclass(frozen=True)\nclass Dravp12Sp:\n name: str\n values: Tuple[float, ...]\n\n @staticmethod\n def create(name: str, values: Iterable[float]) -> \"Dravp12Sp\":\n vals = tuple(float(v) for v in values)\n if not vals:\n raise ValueError(\"values must be non-empty\")\n return Dravp12Sp(name=name, values=vals)\n\n def add(self, v: float) -> \"Dravp12Sp\":\n return Dravp12Sp(name=self.name, values=self.values + (float(v),))\n\n def mean(self) -> float:\n return sum(self.values) / len(self.values)\n\n# test_w1vw30.py\nimport pytest\nfrom w1vw30 import Dravp12Sp\n\ndef test_mean_and_add():\n c = Dravp12Sp.create(\"a\", [1, 2, 3])\n assert c.mean() == 2.0\n assert c.add(5).mean() == (1 + 2 + 3 + 5) / 4\n\ndef test_empty_raises():\n with pytest.raises(ValueError):\n Dravp12Sp.create(\"x\", [])", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Build an elite-grade solution in the domain of networking for scenario: analytics pipeline.\nPrimary language: python.\nDifficulty: medium.\nConstraints: make the interface contract explicit, assume untrusted inputs; validate and sanitize, include tests or verification strategy.\nComponent: component_jgpahcg.\nAssume cold-start and memory limits are tight.\nTask: Define a small DSL, implement tokenizer/parser, IR, and a codegen or interpreter. Include tests and complexity notes.\n\nOutput: production blueprint plus correctness arguments and test strategy.\nOutput: DSL + parser + IR + interpreter/codegen + tests.\n\n**DSL**\n- Expressions: integers, identifiers, `+ - * /`, let-binding: `let x = expr in expr`\n- Example: `let x = 2+3 in x*10`\n\n**Pipeline**\n1. Tokenize\n2. Parse into AST\n3. Lower into IR (stack ops) or interpret AST directly\n\n**Reference (Rust-style outline)**\n- `enum Expr { Int(i64), Var(String), Bin(Op, Box, Box), Let(String, Box, Box) }`\n- Parser: Pratt or recursive descent.\n\n**Tests**\n- Golden tests for parse trees.\n- Property: pretty-print(parse(x)) round-trips for a corpus.\n- Eval tests for precedence and scoping.\n\n\nChecks: boundary validation and deterministic behavior verified.", "source": "WithinUsAI/Elite_GOD_Coder_100k"} {"text": "Implement a concurrent Python solution for event dispatching.\nRequirements: choose appropriate concurrency model, handle cancellation/timeouts, include tests.\nConstraints: must include tests, stdlib-only, must be memory-efficient.\nDifficulty: easy. Avoid quadratic behavior on large inputs.\n\nDeliverable: implementation + tests.\n```python\nfrom __future__ import annotations\nimport asyncio\nfrom dataclasses import dataclass\nfrom typing import Awaitable, Callable, Iterable, Optional\n\n@dataclass(frozen=True, slots=True)\nclass JobResult:\n ok: bool\n value: Optional[int]\n error: Optional[str]\n\nasync def run_bounded(\n factories: Iterable[Callable[[], Awaitable[int]]],\n *,\n limit: int = 10,\n timeout_s: float = 5.0,\n) -> list[JobResult]:\n if limit <= 0:\n raise ValueError(\"limit must be > 0\")\n sem = asyncio.Semaphore(limit)\n results: list[JobResult] = []\n\n async def one(factory: Callable[[], Awaitable[int]]) -> None:\n async with sem:\n try:\n v = await asyncio.wait_for(factory(), timeout=timeout_s)\n results.append(JobResult(True, v, None))\n except Exception as e:\n results.append(JobResult(False, None, str(e)))\n\n tasks = [asyncio.create_task(one(f)) for f in factories]\n try:\n await asyncio.gather(*tasks)\n finally:\n for t in tasks:\n if not t.done():\n t.cancel()\n return results\n```\n\n```python\nimport asyncio\nimport pytest\nfrom module_under_test import run_bounded\n\n@pytest.mark.asyncio\nasync def test_run_bounded_collects():\n async def work(x: int) -> int:\n await asyncio.sleep(0.01)\n return x\n fs = [(lambda i=i: work(i)) for i in range(30)]\n out = await run_bounded(fs, limit=5, timeout_s=1.0)\n assert len(out) == 30\n assert all(r.ok for r in out)\n```", "source": "WithinUsAI/python_GOD_coder_100k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Optimize while preserving behavior.\n\nFile: ks_iuxonnen6.py\n```python\ndef v5ktejcediw(xs):\n out = []\n for x in xs:\n if x not in out:\n out.append(x)\n return out\n```\n\nRequirements: preserve first-seen order; O(n) average; add types + docstring.\n\n# ks_iuxonnen6.py\nfrom __future__ import annotations\nfrom typing import Iterable, List, Set, TypeVar\n\nT = TypeVar(\"T\")\n\ndef v5ktejcediw(xs: Iterable[T]) -> List[T]:\n \"\"\"Return unique items preserving first-seen order.\"\"\"\n seen: Set[T] = set()\n out: List[T] = []\n for x in xs:\n if x in seen:\n continue\n seen.add(x)\n out.append(x)\n return out", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Optimize while preserving behavior and order.\n\n```python\ndef f96158(xs):\n out=[]\n for x in xs:\n if x not in out: out.append(x)\n return out\n```\nReturn `m56594.py` with types and O(n) average.\n\n```python\n# m56594.py\nfrom __future__ import annotations\nfrom typing import Iterable, List, Set, TypeVar\nT=TypeVar(\"T\")\n\ndef f96158(xs: Iterable[T]) -> List[T]:\n \"\"\"Unique items preserving first-seen order.\"\"\"\n seen: Set[T]=set()\n out: List[T]=[]\n for x in xs:\n if x in seen: continue\n seen.add(x); out.append(x)\n return out\n```", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Task type: static_analyzer\nScenario: rate limit gateway\nDomain focus: observability platforms\nPrimary language: sql\nDifficulty: expert+\nScale/SLO: p99 < 50ms\nComponent: component_pmlmfpib\nConstraints: include test vectors and fuzz strategy, explicit contracts and invariants, include verification strategy, include failure modes and recovery, include deterministic replay plan, include backward compatibility and migration plan, include security threat model (defensive only)\nAssume schema changes every sprint; must be backward compatible.\nDeliverable: Design a static analyzer for a safety property (e.g., taint/SQLi prevention); include rule set, false-positive strategy, and tests.\n\nOutput: elite engineering answer optimized for correctness, performance, and operability.\n**Contract**\n- Inputs validated at the boundary; explicit error taxonomy.\n- Idempotency for side effects via request_id; deterministic replay.\n- Backward compatibility: additive changes by default; versioned breaking changes.\n**Invariants**\n- Safety: state transitions preserve invariants; no partial commit leaks.\n- Isolation: tenant boundary enforced; no cross-tenant reads/writes.\n- Determinism: replay of the same event log yields identical outputs.\n**Failure modes & recovery**\n- Duplicate requests: de-duplicate by (tenant, request_id) returning cached response.\n- Crash during commit: WAL replay completes or transaction aborts; no torn writes.\n- Network partition: minority cannot commit; clients receive retriable errors.\n**Security posture (defensive)**\n- Threat model: auth/authz, injection, replay/abuse, supply chain.\n- Least privilege; secrets in managed store; audit logs for sensitive ops.\n- Input normalization, parameterized queries, path traversal protections.\n**Verification strategy**\n- Deterministic simulation with fault injection (crash/partition/latency).\n- Canary + shadow traffic; invariants checked in production via assertions/metrics.\n- Property tests against a pure reference model (state machine).\n\n**Snippet**\n```text\nImplementation sketch: factor pure state-machine core; adapters for I/O; add deterministic replay log.\n```\nExpert+ checks: mechanized invariants (or exhaustive model checking), adversarial fuzzing, and multi-region failure drills.", "source": "WithinUsAI/Omega_Genesis_Coder_100k"} {"text": "Design a small, production-grade Python API for report generation.\nRequirements: define data models and interfaces, implement reference version, include tests.\nConstraints: must be easy to extend, stdlib-only, must include tests, must be memory-efficient.\nDifficulty: expert. Support both Windows and POSIX paths correctly.\n\nDeliverable: production-ready reference solution.\nArchitecture:\n- Public facade class coordinating concerns (parsing, validation, persistence)\n- Small pure functions for testability\n- No global state; dependency injection for filesystem I/O\n\n```python\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom pathlib import Path\nfrom typing import Protocol, Iterable\nimport json\n\nclass Store(Protocol):\n def write_text(self, path: Path, data: str) -> None: ...\n\nclass FSStore:\n def write_text(self, path: Path, data: str) -> None:\n path.parent.mkdir(parents=True, exist_ok=True)\n path.write_text(data, encoding=\"utf-8\")\n\n@dataclass(frozen=True, slots=True)\nclass Item:\n name: str\n qty: int\n\ndef parse_items(lines: Iterable[str]) -> list[Item]:\n out: list[Item] = []\n for i, line in enumerate(lines, 1):\n s = line.strip()\n if not s:\n continue\n obj = json.loads(s)\n if not isinstance(obj, dict):\n raise ValueError(f\"line {i}: expected object\")\n name = obj.get(\"name\")\n qty = obj.get(\"qty\")\n if not isinstance(name, str) or not name:\n raise ValueError(f\"line {i}: name must be str\")\n if not isinstance(qty, int) or qty < 0:\n raise ValueError(f\"line {i}: qty must be non-negative int\")\n out.append(Item(name, qty))\n return out\n\nclass InventoryWriter:\n def __init__(self, base_dir: Path, store: Store | None = None) -> None:\n self._base = base_dir\n self._store: Store = store or FSStore()\n\n def write(self, rel_path: str, items: list[Item]) -> Path:\n dst = (self._base / rel_path).resolve()\n base = self._base.resolve()\n if dst != base and base not in dst.parents:\n raise ValueError(\"unsafe path traversal\")\n payload = json.dumps([item.__dict__ for item in items], ensure_ascii=False)\n self._store.write_text(dst, payload)\n return dst\n```\n\n```python\nimport json\nfrom pathlib import Path\nimport pytest\nfrom module_under_test import InventoryWriter, parse_items\n\ndef test_parse_items_valid():\n lines = [json.dumps({\"name\":\"x\",\"qty\":1})]\n assert parse_items(lines)[0].name == \"x\"\n\ndef test_writer_blocks_traversal(tmp_path: Path):\n w = InventoryWriter(tmp_path)\n with pytest.raises(ValueError):\n w.write(\"../evil.json\", [])\n```", "source": "WithinUsAI/python_GOD_coder_100k"} {"text": "Secure-by-default implementation for idempotent payments in a developer tooling product.\nTarget platform: backend (Python FastAPI).\nRequirements: threat model, input validation, authz/authn guidance, safe storage, tests.\nConstraints: must include type hints where applicable, must be secure-by-default, must avoid global state, must be performant under load.\nDifficulty: hard. Assume schema evolves frequently; design for migrations.\n\nOutput: actionable implementation and verification artifacts.\nDeliverable: threat model + secure patterns (no offensive content).\n\n**Threat model**\n- Input: untrusted clients → validation required\n- Auth: token theft / privilege escalation → short-lived tokens + RBAC checks\n- Data: PII exposure → encryption at rest + access logging + least privilege\n- Webhooks/callbacks: SSRF → allowlist destinations + timeouts + egress controls\n\n**Secure implementation patterns**\n- Validate and normalize inputs at boundaries (API/CLI/file).\n- Use parameterized SQL; never string interpolate.\n- Prevent path traversal when writing files (resolve + base containment).\n- Use idempotency keys for side-effecting endpoints; safe retries.\n- Centralize authorization checks in one layer; test them.\n\n**Test checklist**\n- Invalid inputs rejected with clear error messages.\n- AuthZ tests for tenant boundary violations.\n- Replay/idempotency conflict test.\n\n\nHard-mode checks: concurrency safety, idempotency, and rollback validated; add chaos tests where feasible.", "source": "WithinUsAI/GOD_Coder_100k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Optimize while preserving behavior.\n\nFile: ji1j3xx.py\n```python\ndef qt4h559yj(xs):\n out = []\n for x in xs:\n if x not in out:\n out.append(x)\n return out\n```\n\nRequirements: preserve first-seen order; O(n) average; add types + docstring.\n\n# ji1j3xx.py\nfrom __future__ import annotations\nfrom typing import Iterable, List, Set, TypeVar\n\nT = TypeVar(\"T\")\n\ndef qt4h559yj(xs: Iterable[T]) -> List[T]:\n \"\"\"Return unique items preserving first-seen order.\"\"\"\n seen: Set[T] = set()\n out: List[T] = []\n for x in xs:\n if x in seen:\n continue\n seen.add(x)\n out.append(x)\n return out", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Design a production system for gaming supporting webhooks.\nTarget platform: CI (GitHub Actions).\nRequirements: APIs, data model, scaling strategy, failure modes, and security.\nConstraints: must be easy to extend, must be performant under load, must be observable (logs/metrics/traces), must include type hints where applicable, must include clear error handling.\nDifficulty: expert. Assume strict latency budget (p95 < 200ms).\n\nOutput: production-oriented blueprint with code where appropriate.\nDeliverable: system design with APIs, data model, and operational plan.\n\n**High-level architecture**\n- Edge: API Gateway + WAF\n- Core service: stateless app pods behind L7 LB\n- Data: Postgres (primary), Redis (cache + rate limit tokens), Object storage (uploads if needed)\n- Async: message queue (e.g., SQS/Rabbit) + worker pool for background jobs\n- Observability: structured logs + metrics + tracing\n\n**APIs (example)**\n- `POST /v1/{resource}` create (idempotent via `Idempotency-Key`)\n- `GET /v1/{resource}/{id}` read\n- `POST /v1/{resource}/{id}:action` command endpoint when side effects exist\n\n**Data model (Postgres)**\n- `resources(id UUID PK, tenant_id UUID, status TEXT, payload JSONB, created_at, updated_at)`\n- Unique constraint for idempotency: `(tenant_id, idempotency_key)` in a separate table:\n - `idempotency(tenant_id, key TEXT, request_hash TEXT, response JSONB, created_at, PRIMARY KEY(tenant_id,key))`\n\n**Scaling**\n- App layer scales horizontally; keep sessions out of process.\n- Cache reads in Redis; write-through invalidation on mutations.\n- Use connection pooling; consider read replicas for heavy reads.\n\n**Failure modes**\n- Retries: only for safe/ idempotent operations; exponential backoff + jitter.\n- Partial failures: background jobs must be idempotent; use a de-dup key.\n\n**Security**\n- AuthN: JWT/OIDC; AuthZ: RBAC/ABAC with tenant isolation\n- Validate all inputs; enforce per-tenant quotas/rate limits.\n\n**Rollout**\n- Dark launch + feature flags; canary; rapid rollback by toggling flags.\n\n\nHard-mode checks: concurrency safety, idempotency, and rollback validated; add chaos tests where feasible.", "source": "WithinUsAI/GOD_Coder_100k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Refactor to modern typed Python with immutability and tests.\n\nFile: j12r2d8.py\n```python\nclass Y2Osgirak:\n def __init__(self, name, values):\n self.name = name\n self.values = list(values)\n def add(self, v):\n self.values.append(v)\n def mean(self):\n s = 0\n for x in self.values:\n s += x\n return s / len(self.values)\n```\n\nReturn full new j12r2d8.py and test_j12r2d8.py.\n\n# j12r2d8.py\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom typing import Iterable, Tuple\n\n@dataclass(frozen=True)\nclass Y2Osgirak:\n name: str\n values: Tuple[float, ...]\n\n @staticmethod\n def create(name: str, values: Iterable[float]) -> \"Y2Osgirak\":\n vals = tuple(float(v) for v in values)\n if not vals:\n raise ValueError(\"values must be non-empty\")\n return Y2Osgirak(name=name, values=vals)\n\n def add(self, v: float) -> \"Y2Osgirak\":\n return Y2Osgirak(name=self.name, values=self.values + (float(v),))\n\n def mean(self) -> float:\n return sum(self.values) / len(self.values)\n\n# test_j12r2d8.py\nimport pytest\nfrom j12r2d8 import Y2Osgirak\n\ndef test_mean_and_add():\n c = Y2Osgirak.create(\"a\", [1, 2, 3])\n assert c.mean() == 2.0\n assert c.add(5).mean() == (1 + 2 + 3 + 5) / 4\n\ndef test_empty_raises():\n with pytest.raises(ValueError):\n Y2Osgirak.create(\"x\", [])", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Refactor to modern typed Python with immutability and tests.\n\nFile: opl900kiyo9r.py\n```python\nclass PhxpqU:\n def __init__(self, name, values):\n self.name = name\n self.values = list(values)\n def add(self, v):\n self.values.append(v)\n def mean(self):\n s = 0\n for x in self.values:\n s += x\n return s / len(self.values)\n```\n\nReturn full new opl900kiyo9r.py and test_opl900kiyo9r.py.\n\n# opl900kiyo9r.py\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom typing import Iterable, Tuple\n\n@dataclass(frozen=True)\nclass PhxpqU:\n name: str\n values: Tuple[float, ...]\n\n @staticmethod\n def create(name: str, values: Iterable[float]) -> \"PhxpqU\":\n vals = tuple(float(v) for v in values)\n if not vals:\n raise ValueError(\"values must be non-empty\")\n return PhxpqU(name=name, values=vals)\n\n def add(self, v: float) -> \"PhxpqU\":\n return PhxpqU(name=self.name, values=self.values + (float(v),))\n\n def mean(self) -> float:\n return sum(self.values) / len(self.values)\n\n# test_opl900kiyo9r.py\nimport pytest\nfrom opl900kiyo9r import PhxpqU\n\ndef test_mean_and_add():\n c = PhxpqU.create(\"a\", [1, 2, 3])\n assert c.mean() == 2.0\n assert c.add(5).mean() == (1 + 2 + 3 + 5) / 4\n\ndef test_empty_raises():\n with pytest.raises(ValueError):\n PhxpqU.create(\"x\", [])", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Optimize while preserving behavior.\n\nFile: l_thghtyk3h.py\n```python\ndef rma8o_(xs):\n out = []\n for x in xs:\n if x not in out:\n out.append(x)\n return out\n```\n\nRequirements: preserve first-seen order; O(n) average; add types + docstring.\n\n# l_thghtyk3h.py\nfrom __future__ import annotations\nfrom typing import Iterable, List, Set, TypeVar\n\nT = TypeVar(\"T\")\n\ndef rma8o_(xs: Iterable[T]) -> List[T]:\n \"\"\"Return unique items preserving first-seen order.\"\"\"\n seen: Set[T] = set()\n out: List[T] = []\n for x in xs:\n if x in seen:\n continue\n seen.add(x)\n out.append(x)\n return out", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Create a comprehensive test plan and automated tests for offline-first sync in a customer support product.\nTarget platform: backend (Node.js).\nRequirements: unit/integration tests, edge cases, load tests strategy, and CI gates.\nConstraints: must be easy to extend, must be production-ready, must include clear error handling.\nDifficulty: hard. Assume 10k RPS peak traffic.\n\nOutput: production-oriented blueprint with code where appropriate.\nDeliverable: test plan + automation guidance.\n\n**Unit tests**\n- Validation: malformed payloads rejected with correct codes.\n- AuthZ: tenant boundary enforced.\n- Idempotency: replay returns same response; conflicting reuse yields 409.\n\n**Integration tests**\n- DB transaction behavior; unique constraints.\n- Cache behavior: correctness under concurrent requests.\n\n**Load tests**\n- 10k RPS target: measure p95 latency, error rate, saturation.\n\n**CI gates**\n- Lint + typecheck + unit tests required.\n- Coverage threshold for critical modules.\n- Block merge on flaky test detection.\n\n\nHard-mode checks: concurrency safety, idempotency, and rollback validated; add chaos tests where feasible.", "source": "WithinUsAI/GOD_Coder_100k"} {"text": "Build an elite-grade solution in the domain of gpu compute for scenario: time-series metrics.\nPrimary language: go.\nDifficulty: hard.\nConstraints: design for backward compatibility and migrations, include tests or verification strategy, avoid undefined behavior and data races, include invariants and failure modes, provide rollout and rollback guidance.\nComponent: component_ekwlpzk.\nAssume cold-start and memory limits are tight.\nTask: Write a precise interface contract, list invariants, and provide a lightweight formal/spec-style description (pseudo-TLA+/state machine) plus reference implementation skeleton and tests.\n\nOutput: production blueprint plus correctness arguments and test strategy.\nOutput: contract + invariants + spec + reference skeleton.\n\n**Interface contract**\n- Commands: `Put(key, value, expected_version?)`, `Get(key)`, `Delete(key, expected_version?)`\n- Responses: `Ok(version, value?)`, `NotFound`, `Conflict(current_version)`, `InvalidInput`\n- Idempotency: client supplies `request_id`; server must de-duplicate per (tenant_id, request_id).\n\n**Invariants**\n1. Monotonic version per key (strictly increases on successful writes).\n2. Reads return latest committed value for a given consistency level.\n3. Exactly-once effect for a given `request_id` (at-most-once execution + replay response).\n4. Tenant isolation: keys are scoped by tenant_id.\n\n**State machine (pseudo)**\nState:\n- store: map[(tenant,key)] -> (version:int, value:bytes|tombstone)\n- seen: map[(tenant,request_id)] -> response\nTransition Put:\n- if request_id in seen: return seen[...]\n- validate input; if expected_version set and != current version -> Conflict\n- version' = version + 1; store[...] := (version', value); seen[...] := Ok(version', value)\n\n**Reference skeleton (Python)**\n```python\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom typing import Dict, Optional, Tuple\n\nclass Conflict(Exception): pass\nclass InvalidInput(ValueError): pass\n\n@dataclass(frozen=True, slots=True)\nclass Value:\n version: int\n data: Optional[bytes] # None == tombstone\n\n@dataclass(frozen=True, slots=True)\nclass Reply:\n kind: str\n version: Optional[int] = None\n data: Optional[bytes] = None\n\nclass KV:\n def __init__(self) -> None:\n self._store: Dict[Tuple[str,str], Value] = {}\n self._seen: Dict[Tuple[str,str], Reply] = {}\n\n def put(self, tenant: str, request_id: str, key: str, data: bytes, expected_version: Optional[int]=None) -> Reply:\n if not tenant or not request_id or not key:\n raise InvalidInput(\"tenant/request_id/key required\")\n de = self._seen.get((tenant, request_id))\n if de: \n return de\n cur = self._store.get((tenant, key), Value(0, None))\n if expected_version is not None and expected_version != cur.version:\n r = Reply(\"conflict\", version=cur.version)\n self._seen[(tenant, request_id)] = r\n return r\n nxt = Value(cur.version + 1, data)\n self._store[(tenant, key)] = nxt\n r = Reply(\"ok\", version=nxt.version)\n self._seen[(tenant, request_id)] = r\n return r\n```\n\n**Tests**\n- Determinism: same request_id → same reply.\n- Conflict detection and version monotonicity.\n\n\nHard checks: failure injection tests and performance regressions gated.", "source": "WithinUsAI/Elite_GOD_Coder_100k"} {"text": "Refactor a Python module used for time series into a clean, extensible design.\nRequirements: outline the new architecture briefly, then provide the refactored code and tests.\nConstraints: must provide clear error messages, must be memory-efficient, must include tests.\nDifficulty: hard. Guarantee deterministic output ordering.\n\nDeliverable: corrected code and verification tests.\nArchitecture:\n- Public facade class coordinating concerns (parsing, validation, persistence)\n- Small pure functions for testability\n- No global state; dependency injection for filesystem I/O\n\n```python\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom pathlib import Path\nfrom typing import Protocol, Iterable\nimport json\n\nclass Store(Protocol):\n def write_text(self, path: Path, data: str) -> None: ...\n\nclass FSStore:\n def write_text(self, path: Path, data: str) -> None:\n path.parent.mkdir(parents=True, exist_ok=True)\n path.write_text(data, encoding=\"utf-8\")\n\n@dataclass(frozen=True, slots=True)\nclass Item:\n name: str\n qty: int\n\ndef parse_items(lines: Iterable[str]) -> list[Item]:\n out: list[Item] = []\n for i, line in enumerate(lines, 1):\n s = line.strip()\n if not s:\n continue\n obj = json.loads(s)\n if not isinstance(obj, dict):\n raise ValueError(f\"line {i}: expected object\")\n name = obj.get(\"name\")\n qty = obj.get(\"qty\")\n if not isinstance(name, str) or not name:\n raise ValueError(f\"line {i}: name must be str\")\n if not isinstance(qty, int) or qty < 0:\n raise ValueError(f\"line {i}: qty must be non-negative int\")\n out.append(Item(name, qty))\n return out\n\nclass InventoryWriter:\n def __init__(self, base_dir: Path, store: Store | None = None) -> None:\n self._base = base_dir\n self._store: Store = store or FSStore()\n\n def write(self, rel_path: str, items: list[Item]) -> Path:\n dst = (self._base / rel_path).resolve()\n base = self._base.resolve()\n if dst != base and base not in dst.parents:\n raise ValueError(\"unsafe path traversal\")\n payload = json.dumps([item.__dict__ for item in items], ensure_ascii=False)\n self._store.write_text(dst, payload)\n return dst\n```\n\n```python\nimport json\nfrom pathlib import Path\nimport pytest\nfrom module_under_test import InventoryWriter, parse_items\n\ndef test_parse_items_valid():\n lines = [json.dumps({\"name\":\"x\",\"qty\":1})]\n assert parse_items(lines)[0].name == \"x\"\n\ndef test_writer_blocks_traversal(tmp_path: Path):\n w = InventoryWriter(tmp_path)\n with pytest.raises(ValueError):\n w.write(\"../evil.json\", [])\n```", "source": "WithinUsAI/python_GOD_coder_100k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Fix a bug and add tests.\n\nFile: nidpghynhpa.py\n```python\ndef s91_s9k(n: int) -> int:\n \"\"\"Sum 1..n inclusive.\"\"\"\n if n < 0:\n raise ValueError(\"n must be non-negative\")\n total = 0\n for k in range(n): # BUG: should include n\n total += k\n return total\n```\n\nReturn unified diffs for nidpghynhpa.py and test_nidpghynhpa.py (pytest).\n\n*** Begin Patch\n*** Update File: nidpghynhpa.py\n@@\n def s91_s9k(n: int) -> int:\n@@\n total = 0\n- for k in range(n): # BUG: should include n\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_nidpghynhpa.py\n+import pytest\n+from nidpghynhpa import s91_s9k\n+\n+def test_zero():\n+ assert s91_s9k(0) == 0\n+\n+def test_one():\n+ assert s91_s9k(1) == 1\n+\n+def test_small():\n+ assert s91_s9k(7) == 28\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ s91_s9k(-1)\n+\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Task type: compiler_backend_ir\nScenario: identity and access\nDomain focus: network protocols\nPrimary language: rust\nDifficulty: expert\nScale/SLO: multi-region active-active\nComponent: component_zgufmjko\nConstraints: include security threat model (defensive only), include performance model and limits, include verification strategy, assume adversarial inputs; validate everything, explicit contracts and invariants, include backward compatibility and migration plan, include failure modes and recovery\nAssume partial data corruption; include scrubbing strategy.\nDeliverable: Design an IR and lowering pipeline; include an optimization pass and correctness checks. Provide minimal code skeleton and tests.\n\nOutput: contract-first solution with failure modes, security posture, and test/verification strategy.\n**Contract**\n- Inputs validated at the boundary; explicit error taxonomy.\n- Idempotency for side effects via request_id; deterministic replay.\n- Backward compatibility: additive changes by default; versioned breaking changes.\n**Invariants**\n- Liveness: under bounded faults and stable network, progress occurs.\n- Safety: state transitions preserve invariants; no partial commit leaks.\n- Determinism: replay of the same event log yields identical outputs.\n**Failure modes & recovery**\n- Crash during commit: WAL replay completes or transaction aborts; no torn writes.\n- Data corruption: checksums + scrubber; quarantine and rebuild from replicas/snapshots.\n- Duplicate requests: de-duplicate by (tenant, request_id) returning cached response.\n**Security posture (defensive)**\n- Threat model: auth/authz, injection, replay/abuse, supply chain.\n- Least privilege; secrets in managed store; audit logs for sensitive ops.\n- Input normalization, parameterized queries, path traversal protections.\n**Verification strategy**\n- Canary + shadow traffic; invariants checked in production via assertions/metrics.\n- Deterministic simulation with fault injection (crash/partition/latency).\n- Property tests against a pure reference model (state machine).\n\n**Snippet**\n```text\nImplementation sketch: factor pure state-machine core; adapters for I/O; add deterministic replay log.\n```\nExpert checks: state-machine proof sketch + model checking; upgrade/rollback rehearsed.", "source": "WithinUsAI/Omega_Genesis_Coder_100k"} {"text": "Task type: mechanized_spec\nScenario: identity and access\nDomain focus: distributed storage\nPrimary language: lean\nDifficulty: expert+\nScale/SLO: 100k RPS peak\nComponent: component_qyvufvhe\nConstraints: include performance model and limits, include backward compatibility and migration plan, include deterministic replay plan, include failure modes and recovery, assume adversarial inputs; validate everything, avoid data races and undefined behavior\nAssume weekly network partitions.\nDeliverable: Provide a mechanized-style spec outline (Lean-like), key definitions, and a proof plan. Include executable reference code skeleton and tests.\n\nOutput: rigorous design + invariants + verification plan + implementation sketch.\n**Contract**\n- Inputs validated at the boundary; explicit error taxonomy.\n- Idempotency for side effects via request_id; deterministic replay.\n- Backward compatibility: additive changes by default; versioned breaking changes.\n**Invariants**\n- Isolation: tenant boundary enforced; no cross-tenant reads/writes.\n- Determinism: replay of the same event log yields identical outputs.\n- Safety: state transitions preserve invariants; no partial commit leaks.\n**Failure modes & recovery**\n- Duplicate requests: de-duplicate by (tenant, request_id) returning cached response.\n- Crash during commit: WAL replay completes or transaction aborts; no torn writes.\n- Data corruption: checksums + scrubber; quarantine and rebuild from replicas/snapshots.\n**Security posture (defensive)**\n- Threat model: auth/authz, injection, replay/abuse, supply chain.\n- Least privilege; secrets in managed store; audit logs for sensitive ops.\n- Input normalization, parameterized queries, path traversal protections.\n**Verification strategy**\n- Deterministic simulation with fault injection (crash/partition/latency).\n- Canary + shadow traffic; invariants checked in production via assertions/metrics.\n- Fuzzing of parsers/framers/validators with corpus seeds.\n\n**Snippet**\n```lean\n-- Pseudo-Lean outline\nstructure State where\n ver : Nat\n val : Option ByteArray\n\ndef invariant (s : State) : Prop := True\n\ntheorem step_preserves_invariant :\n ∀ s, invariant s → ∀ s', Step s s' → invariant s' := by\n intro s hs s' hstep\n -- proof plan: case analysis on transition; trivial here\n trivial\n```\n\nExpert+ checks: mechanized invariants (or exhaustive model checking), adversarial fuzzing, and multi-region failure drills.", "source": "WithinUsAI/Omega_Genesis_Coder_100k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Fix a bug and add tests.\n\nFile: omssndo.py\n```python\ndef guiizh19_w(n: int) -> int:\n \"\"\"Sum 1..n inclusive.\"\"\"\n if n < 0:\n raise ValueError(\"n must be non-negative\")\n total = 0\n for k in range(n): # BUG: should include n\n total += k\n return total\n```\n\nReturn unified diffs for omssndo.py and test_omssndo.py (pytest).\n\n*** Begin Patch\n*** Update File: omssndo.py\n@@\n def guiizh19_w(n: int) -> int:\n@@\n total = 0\n- for k in range(n): # BUG: should include n\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_omssndo.py\n+import pytest\n+from omssndo import guiizh19_w\n+\n+def test_zero():\n+ assert guiizh19_w(0) == 0\n+\n+def test_one():\n+ assert guiizh19_w(1) == 1\n+\n+def test_small():\n+ assert guiizh19_w(7) == 28\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ guiizh19_w(-1)\n+\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Task type: robust_e2e_testing\nScenario: time-series metrics store\nDomain focus: observability platforms\nPrimary language: sql\nDifficulty: expert+\nScale/SLO: 10k RPS peak\nComponent: component_tweynxpo\nConstraints: include backward compatibility and migration plan, include performance model and limits, include deterministic replay plan, include failure modes and recovery, include test vectors and fuzz strategy, include verification strategy\nAssume weekly network partitions.\nDeliverable: Design an E2E testing strategy with determinism, fuzzing, chaos, and CI gating.\n\nOutput: elite engineering answer optimized for correctness, performance, and operability.\n**Contract**\n- Inputs validated at the boundary; explicit error taxonomy.\n- Idempotency for side effects via request_id; deterministic replay.\n- Backward compatibility: additive changes by default; versioned breaking changes.\n**Invariants**\n- Isolation: tenant boundary enforced; no cross-tenant reads/writes.\n- Safety: state transitions preserve invariants; no partial commit leaks.\n- Liveness: under bounded faults and stable network, progress occurs.\n**Failure modes & recovery**\n- Data corruption: checksums + scrubber; quarantine and rebuild from replicas/snapshots.\n- Crash during commit: WAL replay completes or transaction aborts; no torn writes.\n- Network partition: minority cannot commit; clients receive retriable errors.\n**Security posture (defensive)**\n- Threat model: auth/authz, injection, replay/abuse, supply chain.\n- Least privilege; secrets in managed store; audit logs for sensitive ops.\n- Input normalization, parameterized queries, path traversal protections.\n**Verification strategy**\n- Canary + shadow traffic; invariants checked in production via assertions/metrics.\n- Fuzzing of parsers/framers/validators with corpus seeds.\n- Deterministic simulation with fault injection (crash/partition/latency).\n\n**Snippet**\n```text\nImplementation sketch: factor pure state-machine core; adapters for I/O; add deterministic replay log.\n```\nExpert+ checks: mechanized invariants (or exhaustive model checking), adversarial fuzzing, and multi-region failure drills.", "source": "WithinUsAI/Omega_Genesis_Coder_100k"} {"text": "Fix the bug and add pytest tests.\n\n```python\ndef f91535(n: int) -> int:\n # sum 1..n inclusive\n if n < 0: raise ValueError\n total = 0\n for k in range(n): # BUG\n total += k\n return total\n```\nReturn unified diffs for `m84505.py` and `test_m84505.py`.\n\n*** Begin Patch\n*** Update File: m84505.py\n@@\n def f91535(n: int) -> int:\n@@\n- for k in range(n): # BUG\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_m84505.py\n+import pytest\n+from m84505 import f91535\n+\n+def test_small():\n+ assert f91535(7) == 28\n+\n+def test_zero():\n+ assert f91535(0) == 0\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ f91535(-1)\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Optimize while preserving behavior and order.\n\n```python\ndef f17867(xs):\n out=[]\n for x in xs:\n if x not in out: out.append(x)\n return out\n```\nReturn `m73981.py` with types and O(n) average.\n\n```python\n# m73981.py\nfrom __future__ import annotations\nfrom typing import Iterable, List, Set, TypeVar\nT=TypeVar(\"T\")\n\ndef f17867(xs: Iterable[T]) -> List[T]:\n \"\"\"Unique items preserving first-seen order.\"\"\"\n seen: Set[T]=set()\n out: List[T]=[]\n for x in xs:\n if x in seen: continue\n seen.add(x); out.append(x)\n return out\n```", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Fix the bug and add pytest tests.\n\n```python\ndef f87767(n: int) -> int:\n # sum 1..n inclusive\n if n < 0: raise ValueError\n total = 0\n for k in range(n): # BUG\n total += k\n return total\n```\nReturn unified diffs for `m69681.py` and `test_m69681.py`.\n\n*** Begin Patch\n*** Update File: m69681.py\n@@\n def f87767(n: int) -> int:\n@@\n- for k in range(n): # BUG\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_m69681.py\n+import pytest\n+from m69681 import f87767\n+\n+def test_small():\n+ assert f87767(7) == 28\n+\n+def test_zero():\n+ assert f87767(0) == 0\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ f87767(-1)\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Fix a bug and add tests.\n\nFile: tjs1j3d.py\n```python\ndef ibzp0i_1z(n: int) -> int:\n \"\"\"Sum 1..n inclusive.\"\"\"\n if n < 0:\n raise ValueError(\"n must be non-negative\")\n total = 0\n for k in range(n): # BUG: should include n\n total += k\n return total\n```\n\nReturn unified diffs for tjs1j3d.py and test_tjs1j3d.py (pytest).\n\n*** Begin Patch\n*** Update File: tjs1j3d.py\n@@\n def ibzp0i_1z(n: int) -> int:\n@@\n total = 0\n- for k in range(n): # BUG: should include n\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_tjs1j3d.py\n+import pytest\n+from tjs1j3d import ibzp0i_1z\n+\n+def test_zero():\n+ assert ibzp0i_1z(0) == 0\n+\n+def test_one():\n+ assert ibzp0i_1z(1) == 1\n+\n+def test_small():\n+ assert ibzp0i_1z(7) == 28\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ ibzp0i_1z(-1)\n+\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Optimize while preserving behavior and order.\n\n```python\ndef f57501(xs):\n out=[]\n for x in xs:\n if x not in out: out.append(x)\n return out\n```\nReturn `m79643.py` with types and O(n) average.\n\n```python\n# m79643.py\nfrom __future__ import annotations\nfrom typing import Iterable, List, Set, TypeVar\nT=TypeVar(\"T\")\n\ndef f57501(xs: Iterable[T]) -> List[T]:\n \"\"\"Unique items preserving first-seen order.\"\"\"\n seen: Set[T]=set()\n out: List[T]=[]\n for x in xs:\n if x in seen: continue\n seen.add(x); out.append(x)\n return out\n```", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Write pytest tests for `f93890`.\n\n```python\ndef f93890(a: int, b: int) -> int:\n return a*a + b*b\n```\nInclude edge cases and a property-style check.\n\n```python\nimport random\nfrom m56270 import f93890\n\ndef test_known():\n assert f93890(3,4) == 25\n\ndef test_zero():\n assert f93890(0,0) == 0\n\ndef test_property_nonnegative():\n for _ in range(200):\n a=random.randint(-50,50)\n b=random.randint(-50,50)\n assert f93890(a,b) >= 0\n```", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Build an elite-grade solution in the domain of networking for scenario: analytics pipeline.\nPrimary language: python.\nDifficulty: medium.\nConstraints: avoid undefined behavior and data races, include invariants and failure modes, make the interface contract explicit, assume untrusted inputs; validate and sanitize, design for backward compatibility and migrations.\nComponent: component_vuwxfmg.\nAssume cold-start and memory limits are tight.\nTask: Design an application-level protocol (framing, retries, timeouts, backpressure). Provide client/server skeleton and test vectors.\n\nOutput: rigorous solution with invariants, failure modes, and performance notes.\nOutput: protocol framing + retry policy + client/server skeleton.\n\n**Framing**\n- Length-prefixed: uint32_be length + payload\n- Payload: msgpack/json; include request_id, type, and optional checksum\n\n**Reliability**\n- Retries only for idempotent ops; exponential backoff + jitter.\n- Timeouts: connect, read, overall; enforce max in-flight to provide backpressure.\n\n**Test vectors**\n- Corrupted length / truncated frame rejected\n- Duplicate request_id returns cached response\n- Slowloris protection by read deadlines\n\n\nChecks: boundary validation and deterministic behavior verified.", "source": "WithinUsAI/Elite_GOD_Coder_100k"} {"text": "Build an elite-grade solution in the domain of security engineering (defensive) for scenario: rate limiting gateway.\nPrimary language: go.\nDifficulty: expert.\nConstraints: include tests or verification strategy, avoid undefined behavior and data races, assume untrusted inputs; validate and sanitize, make the interface contract explicit, design for backward compatibility and migrations.\nComponent: component_otlmkxz.\nAssume 50k RPS and p99 < 250ms.\nTask: Write a precise interface contract, list invariants, and provide a lightweight formal/spec-style description (pseudo-TLA+/state machine) plus reference implementation skeleton and tests.\n\nOutput: rigorous solution with invariants, failure modes, and performance notes.\nOutput: contract + invariants + spec + reference skeleton.\n\n**Interface contract**\n- Commands: `Put(key, value, expected_version?)`, `Get(key)`, `Delete(key, expected_version?)`\n- Responses: `Ok(version, value?)`, `NotFound`, `Conflict(current_version)`, `InvalidInput`\n- Idempotency: client supplies `request_id`; server must de-duplicate per (tenant_id, request_id).\n\n**Invariants**\n1. Monotonic version per key (strictly increases on successful writes).\n2. Reads return latest committed value for a given consistency level.\n3. Exactly-once effect for a given `request_id` (at-most-once execution + replay response).\n4. Tenant isolation: keys are scoped by tenant_id.\n\n**State machine (pseudo)**\nState:\n- store: map[(tenant,key)] -> (version:int, value:bytes|tombstone)\n- seen: map[(tenant,request_id)] -> response\nTransition Put:\n- if request_id in seen: return seen[...]\n- validate input; if expected_version set and != current version -> Conflict\n- version' = version + 1; store[...] := (version', value); seen[...] := Ok(version', value)\n\n**Reference skeleton (Python)**\n```python\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom typing import Dict, Optional, Tuple\n\nclass Conflict(Exception): pass\nclass InvalidInput(ValueError): pass\n\n@dataclass(frozen=True, slots=True)\nclass Value:\n version: int\n data: Optional[bytes] # None == tombstone\n\n@dataclass(frozen=True, slots=True)\nclass Reply:\n kind: str\n version: Optional[int] = None\n data: Optional[bytes] = None\n\nclass KV:\n def __init__(self) -> None:\n self._store: Dict[Tuple[str,str], Value] = {}\n self._seen: Dict[Tuple[str,str], Reply] = {}\n\n def put(self, tenant: str, request_id: str, key: str, data: bytes, expected_version: Optional[int]=None) -> Reply:\n if not tenant or not request_id or not key:\n raise InvalidInput(\"tenant/request_id/key required\")\n de = self._seen.get((tenant, request_id))\n if de: \n return de\n cur = self._store.get((tenant, key), Value(0, None))\n if expected_version is not None and expected_version != cur.version:\n r = Reply(\"conflict\", version=cur.version)\n self._seen[(tenant, request_id)] = r\n return r\n nxt = Value(cur.version + 1, data)\n self._store[(tenant, key)] = nxt\n r = Reply(\"ok\", version=nxt.version)\n self._seen[(tenant, request_id)] = r\n return r\n```\n\n**Tests**\n- Determinism: same request_id → same reply.\n- Conflict detection and version monotonicity.\n\n\nExpert checks: state-machine reasoning, concurrency stress, and upgrade/rollback validated.", "source": "WithinUsAI/Elite_GOD_Coder_100k"} {"text": "Optimize a Python workflow for validation.\nRequirements: provide an optimized implementation and a small benchmark harness.\nConstraints: must be memory-efficient, must provide clear error messages, must handle Windows paths safely.\nDifficulty: expert. Support both Windows and POSIX paths correctly.\n\nDeliverable: corrected code and verification tests.\nStrategy:\n- Avoid repeated parsing; precompile regex if needed; use local variables; stream processing.\n\n```python\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom typing import Iterable\nimport time\n\n@dataclass(frozen=True, slots=True)\nclass Stats:\n count: int\n total: int\n\ndef compute_stats_stream(values: Iterable[int]) -> Stats:\n c = 0\n t = 0\n for v in values:\n c += 1\n t += v\n return Stats(c, t)\n\ndef bench(n: int = 1_000_00) -> float:\n data = range(n)\n t0 = time.perf_counter()\n _ = compute_stats_stream(data)\n return time.perf_counter() - t0\n```\n\n```python\nfrom module_under_test import bench\ndef test_bench_runs_fast_enough():\n # Sanity: should run quickly on typical machines; adjust threshold for CI.\n assert bench(50_000) < 0.5\n```", "source": "WithinUsAI/python_GOD_coder_100k"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: Repository domain: benchmark harness\nPrimary language: YAML\nFramework/tooling: GitHub Actions\nReported problem: memory leak in AST cache\nTask type: repo_issue_patch\nDifficulty: hard\n\nProduce a complete professional engineering response:\n1. Diagnose the root cause.\n2. Provide the corrected implementation or patch.\n3. Add tests.\n4. Add verification commands.\n5. Note edge cases and any migration or rollback risk.\n\nRepository sketch:\nrepo/\n .github/workflows/ci.yml\n docker-compose.yml\n deploy/\n app.yaml\n\nQuality target:\n- Minimal diff unless redesign is clearly required\n- Production-ready code\n- No placeholders\n- Secure defaults\n- Clear acceptance of failure cases\n\nFocus: Focus on complete implementation quality, patch correctness, tests, and production readiness.\n\nassistant: Diagnosis:\n- Root cause: the failure around memory leak in AST cache is caused by missing validation, weak edge-case handling, or unsafe lifecycle behavior in the current implementation.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```yaml\nname: ci\non: [push, pull_request]\njobs:\n test:\n runs-on: ubuntu-latest\n steps:\n - uses: actions/checkout@v4\n - name: Validate\n run: echo \"validated\"\n```\n\nTests:\n```yaml\n# Verification:\n# - validate syntax\n# - run smoke workflow\n# - fail fast on broken config\n```\n\nVerification:\n- `validate workflow syntax`\n- `run CI smoke job`\n\nEngineering notes:\n- Language: YAML\n- Framework/tooling: GitHub Actions\n- Stack context: GitHub Actions, Docker Compose, Kubernetes, Terraform\n- Domain: benchmark harness\n- Task type: repo_issue_patch\n- Difficulty: hard\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Optimize while preserving behavior.\n\nFile: v76z5us.py\n```python\ndef fbn595utly8(xs):\n out = []\n for x in xs:\n if x not in out:\n out.append(x)\n return out\n```\n\nRequirements: preserve first-seen order; O(n) average; add types + docstring.\n\n# v76z5us.py\nfrom __future__ import annotations\nfrom typing import Iterable, List, Set, TypeVar\n\nT = TypeVar(\"T\")\n\ndef fbn595utly8(xs: Iterable[T]) -> List[T]:\n \"\"\"Return unique items preserving first-seen order.\"\"\"\n seen: Set[T] = set()\n out: List[T] = []\n for x in xs:\n if x in seen:\n continue\n seen.add(x)\n out.append(x)\n return out", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Optimize while preserving behavior.\n\nFile: jn6r4h03tdoo.py\n```python\ndef pi0bbjipz(xs):\n out = []\n for x in xs:\n if x not in out:\n out.append(x)\n return out\n```\n\nRequirements: preserve first-seen order; O(n) average; add types + docstring.\n\n# jn6r4h03tdoo.py\nfrom __future__ import annotations\nfrom typing import Iterable, List, Set, TypeVar\n\nT = TypeVar(\"T\")\n\ndef pi0bbjipz(xs: Iterable[T]) -> List[T]:\n \"\"\"Return unique items preserving first-seen order.\"\"\"\n seen: Set[T] = set()\n out: List[T] = []\n for x in xs:\n if x in seen:\n continue\n seen.add(x)\n out.append(x)\n return out", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Task type: compiler_frontend\nScenario: multi-tenant event ingestion\nDomain focus: consensus & replication\nPrimary language: sql\nDifficulty: expert\nScale/SLO: p99 < 150ms\nComponent: component_vojwrmlz\nConstraints: include deterministic replay plan, include verification strategy, include failure modes and recovery, include backward compatibility and migration plan, assume adversarial inputs; validate everything, avoid data races and undefined behavior\nAssume partial data corruption; include scrubbing strategy.\nDeliverable: Design a DSL language frontend: lexer/parser, AST, type checking, error reporting, and tests.\n\nOutput: contract-first solution with failure modes, security posture, and test/verification strategy.\n**Contract**\n- Inputs validated at the boundary; explicit error taxonomy.\n- Idempotency for side effects via request_id; deterministic replay.\n- Backward compatibility: additive changes by default; versioned breaking changes.\n**Invariants**\n- Liveness: under bounded faults and stable network, progress occurs.\n- Isolation: tenant boundary enforced; no cross-tenant reads/writes.\n- Determinism: replay of the same event log yields identical outputs.\n**Failure modes & recovery**\n- Duplicate requests: de-duplicate by (tenant, request_id) returning cached response.\n- Data corruption: checksums + scrubber; quarantine and rebuild from replicas/snapshots.\n- Crash during commit: WAL replay completes or transaction aborts; no torn writes.\n**Security posture (defensive)**\n- Threat model: auth/authz, injection, replay/abuse, supply chain.\n- Least privilege; secrets in managed store; audit logs for sensitive ops.\n- Input normalization, parameterized queries, path traversal protections.\n**Verification strategy**\n- Fuzzing of parsers/framers/validators with corpus seeds.\n- Deterministic simulation with fault injection (crash/partition/latency).\n- Canary + shadow traffic; invariants checked in production via assertions/metrics.\n\n**Snippet**\n```text\nImplementation sketch: factor pure state-machine core; adapters for I/O; add deterministic replay log.\n```\nExpert checks: state-machine proof sketch + model checking; upgrade/rollback rehearsed.", "source": "WithinUsAI/Omega_Genesis_Coder_100k"} {"text": "Fix the bug and add pytest tests.\n\n```python\ndef f30675(n: int) -> int:\n # sum 1..n inclusive\n if n < 0: raise ValueError\n total = 0\n for k in range(n): # BUG\n total += k\n return total\n```\nReturn unified diffs for `m61525.py` and `test_m61525.py`.\n\n*** Begin Patch\n*** Update File: m61525.py\n@@\n def f30675(n: int) -> int:\n@@\n- for k in range(n): # BUG\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_m61525.py\n+import pytest\n+from m61525 import f30675\n+\n+def test_small():\n+ assert f30675(7) == 28\n+\n+def test_zero():\n+ assert f30675(0) == 0\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ f30675(-1)\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Perform a code review for a enterprise SaaS PR implementing A/B experimentation.\nTarget platform: data (SQL + Python).\nRequirements: list critical issues, improvements, and provide an improved patch excerpt.\nConstraints: must be production-ready, must be easy to extend, must include clear error handling, must include tests, must avoid global state.\nDifficulty: medium. Assume PII must be protected.\n\nOutput: engineering-grade answer with edge cases covered.\nDeliverable: code review findings + improved patch excerpt.\n\n**Critical issues**\n1. Missing input validation at boundary; potential unexpected exceptions.\n2. No idempotency / retry safety for side-effecting endpoint.\n3. No tests for edge cases (empty input, duplicates, timeouts).\n4. Observability gaps: no request_id correlation, no metrics.\n\n**Improvements**\n- Add strict validation and explicit error responses.\n- Add idempotency key support for create endpoints.\n- Add unit + integration tests with CI gating.\n- Add structured logs and basic metrics.\n\nPatch excerpt (illustrative):\n```python\nif not idem_key:\n raise HTTPException(400, \"Missing Idempotency-Key\")\n```\n\n\nChecks: input validation, tests, and safe defaults included.", "source": "WithinUsAI/GOD_Coder_100k"} {"text": "Debug and fix a subtle production bug related to idempotent payments in a logistics service.\nTarget platform: data (SQL + Python).\nRequirements: identify root cause, provide patch, and add regression tests.\nConstraints: must include clear error handling, must include tests, must be easy to extend, must include type hints where applicable, must include documentation/comments.\nDifficulty: easy. Assume untrusted input; validate everything.\n\nOutput: production-oriented blueprint with code where appropriate.\nDeliverable: production-grade reference implementation (FastAPI) + tests.\n\n```python\n# app.py\nfrom __future__ import annotations\n\nimport hashlib\nimport json\nfrom dataclasses import dataclass\nfrom datetime import datetime, timezone\nfrom typing import Any, Optional\n\nfrom fastapi import FastAPI, Header, HTTPException\nfrom pydantic import BaseModel, Field\n\napp = FastAPI(title=\"Idempotent API\")\n\nclass CreateReq(BaseModel):\n tenant_id: str = Field(min_length=1)\n amount_cents: int = Field(ge=0)\n currency: str = Field(min_length=3, max_length=3)\n\nclass CreateResp(BaseModel):\n id: str\n created_at: str\n echo: CreateReq\n\n@dataclass\nclass _IdempoEntry:\n request_hash: str\n response_json: str\n\n# In production: Postgres table with UNIQUE(tenant_id, key)\n_IDEMPO: dict[tuple[str, str], _IdempoEntry] = {}\n\ndef _hash_req(req: CreateReq) -> str:\n raw = req.model_dump_json()\n return hashlib.sha256(raw.encode(\"utf-8\")).hexdigest()\n\n@app.post(\"/v1/payments\", response_model=CreateResp)\ndef create_payment(\n req: CreateReq,\n idempotency_key: Optional[str] = Header(default=None, alias=\"Idempotency-Key\"),\n) -> Any:\n if not idempotency_key:\n raise HTTPException(status_code=400, detail=\"Missing Idempotency-Key\")\n if len(idempotency_key) > 128:\n raise HTTPException(status_code=400, detail=\"Idempotency-Key too long\")\n\n key = (req.tenant_id, idempotency_key)\n rh = _hash_req(req)\n\n existing = _IDEMPO.get(key)\n if existing:\n if existing.request_hash != rh:\n raise HTTPException(status_code=409, detail=\"Idempotency-Key reuse with different payload\")\n return json.loads(existing.response_json)\n\n # Create new payment (stubbed)\n pid = hashlib.md5(f\"{req.tenant_id}:{idempotency_key}\".encode()).hexdigest()\n resp = CreateResp(\n id=pid,\n created_at=datetime.now(timezone.utc).isoformat(),\n echo=req,\n )\n _IDEMPO[key] = _IdempoEntry(request_hash=rh, response_json=resp.model_dump_json())\n return resp\n```\n\n```python\n# test_app.py (pytest)\nfrom fastapi.testclient import TestClient\nfrom app import app\n\nclient = TestClient(app)\n\ndef test_idempotent_replay():\n headers = {\"Idempotency-Key\": \"abc\"}\n body = {\"tenant_id\":\"t1\",\"amount_cents\":100,\"currency\":\"USD\"}\n r1 = client.post(\"/v1/payments\", json=body, headers=headers)\n r2 = client.post(\"/v1/payments\", json=body, headers=headers)\n assert r1.status_code == 200 and r2.status_code == 200\n assert r1.json() == r2.json()\n\ndef test_payload_conflict():\n headers = {\"Idempotency-Key\": \"abc\"}\n b1 = {\"tenant_id\":\"t1\",\"amount_cents\":100,\"currency\":\"USD\"}\n b2 = {\"tenant_id\":\"t1\",\"amount_cents\":200,\"currency\":\"USD\"}\n assert client.post(\"/v1/payments\", json=b1, headers=headers).status_code == 200\n assert client.post(\"/v1/payments\", json=b2, headers=headers).status_code == 409\n```\n\nNotes:\n- Replace in-memory store with a DB table and transaction.\n- Store response + request hash to detect key reuse with different payload.\n\n\nChecks: input validation, tests, and safe defaults included.", "source": "WithinUsAI/GOD_Coder_100k"} {"text": "Refactor an existing codebase in enterprise SaaS to support file uploads cleanly.\nTarget platform: mobile (iOS Swift).\nRequirements: propose new modules/layers, dependency boundaries, and migration plan.\nConstraints: must include type hints where applicable, must include documentation/comments, must be observable (logs/metrics/traces), must be easy to extend, must include clear error handling.\nDifficulty: medium. Assume untrusted input; validate everything.\n\nOutput: production-oriented blueprint with code where appropriate.\nDeliverable: refactor plan + module boundaries.\n\n**Proposed modules**\n- `domain/` pure business logic (no I/O)\n- `adapters/` DB, cache, external APIs\n- `api/` request/response validation and routing\n- `observability/` logging/metrics/tracing\n- `tests/` unit + integration suites\n\n**Migration plan**\n1. Introduce new interfaces + adapters behind feature flags.\n2. Dual-write or read-compat layer if schema changes.\n3. Incremental cutover; deprecate legacy module.\n\nKey rule: dependencies flow inward; domain has no framework imports.\n\n\nChecks: input validation, tests, and safe defaults included.", "source": "WithinUsAI/GOD_Coder_100k"} {"text": "Build an elite-grade solution in the domain of networking for scenario: event ingestion.\nPrimary language: typescript.\nDifficulty: expert.\nConstraints: avoid undefined behavior and data races, make the interface contract explicit, include invariants and failure modes, design for backward compatibility and migrations, document performance characteristics.\nComponent: component_jwufvym.\nAssume schema changes every sprint; must be backward compatible.\nTask: Provide threat model, secure-by-default design, and defensive implementation patterns. No offensive/exploit content; focus on prevention and detection.\n\nOutput: elite-grade engineering answer with contracts, edge cases, and verification.\nOutput: threat model + defensive design + detection.\n\n**Threat model**\n- Auth: token theft → short-lived tokens, rotation, audience checks\n- AuthZ: privilege escalation → centralized policy checks, tenant isolation tests\n- Input: injection → strict validation, parameterized queries, output encoding\n- Supply chain: dependencies → lockfiles, signature verification, SBOM\n\n**Defensive patterns**\n- Idempotency keys for side effects; replay-safe handlers\n- Secrets in managed store; never logs\n- Audit logging for sensitive ops; tamper-evident storage\n\n**Detection**\n- Alert on unusual auth failures, access pattern anomalies, and data exfil signals.\n\n\nExpert checks: state-machine reasoning, concurrency stress, and upgrade/rollback validated.", "source": "WithinUsAI/Elite_GOD_Coder_100k"} {"text": "Fix the bug and add pytest tests.\n\n```python\ndef f57875(n: int) -> int:\n # sum 1..n inclusive\n if n < 0: raise ValueError\n total = 0\n for k in range(n): # BUG\n total += k\n return total\n```\nReturn unified diffs for `m51125.py` and `test_m51125.py`.\n\n*** Begin Patch\n*** Update File: m51125.py\n@@\n def f57875(n: int) -> int:\n@@\n- for k in range(n): # BUG\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_m51125.py\n+import pytest\n+from m51125 import f57875\n+\n+def test_small():\n+ assert f57875(7) == 28\n+\n+def test_zero():\n+ assert f57875(0) == 0\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ f57875(-1)\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Fix the bug and add pytest tests.\n\n```python\ndef f57329(n: int) -> int:\n # sum 1..n inclusive\n if n < 0: raise ValueError\n total = 0\n for k in range(n): # BUG\n total += k\n return total\n```\nReturn unified diffs for `m51047.py` and `test_m51047.py`.\n\n*** Begin Patch\n*** Update File: m51047.py\n@@\n def f57329(n: int) -> int:\n@@\n- for k in range(n): # BUG\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_m51047.py\n+import pytest\n+from m51047 import f57329\n+\n+def test_small():\n+ assert f57329(7) == 28\n+\n+def test_zero():\n+ assert f57329(0) == 0\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ f57329(-1)\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Build an elite-grade solution in the domain of operating systems for scenario: document indexing.\nPrimary language: python.\nDifficulty: hard.\nConstraints: design for backward compatibility and migrations, avoid undefined behavior and data races, provide rollout and rollback guidance, document performance characteristics.\nComponent: component_owxxhfb.\nAssume crash-only design; recovery must be deterministic.\nTask: Implement or outline a storage/indexing subsystem (LSM/B-Tree, WAL, snapshots). Include transaction/consistency considerations and benchmark plan.\n\nOutput: elite-grade engineering answer with contracts, edge cases, and verification.\nOutput: storage design + WAL + compaction + benchmarks.\n\n**Design**\n- WAL (append-only) for durability; fsync policy configurable.\n- Memtable (in-memory) → flush to immutable SSTables.\n- LSM compaction tiers; bloom filters per SSTable for point-lookups.\n- Manifest tracks SSTable set; atomic pointer swap on updates.\n\n**Correctness**\n- Crash recovery: replay WAL to rebuild memtable; manifest ensures last consistent set.\n- Reads: merge memtable + SSTables newest→oldest; tombstones override older values.\n\n**Bench plan**\n- Workloads: write-heavy, read-heavy, mixed; measure p50/p95 latency and write amplification.\n- Track compaction debt and space amplification.\n\n**Test plan**\n- Fuzz crash points: kill after WAL append / after manifest update; verify invariants on restart.\n\n\nHard checks: failure injection tests and performance regressions gated.", "source": "WithinUsAI/Elite_GOD_Coder_100k"} {"text": "Refactor a Python module used for event dispatching into a clean, extensible design.\nRequirements: outline the new architecture briefly, then provide the refactored code and tests.\nConstraints: must handle Windows paths safely, must avoid global state, must include type hints.\nDifficulty: medium. Include a small CLI example if relevant.\n\nDeliverable: implementation + tests.\nArchitecture:\n- Public facade class coordinating concerns (parsing, validation, persistence)\n- Small pure functions for testability\n- No global state; dependency injection for filesystem I/O\n\n```python\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom pathlib import Path\nfrom typing import Protocol, Iterable\nimport json\n\nclass Store(Protocol):\n def write_text(self, path: Path, data: str) -> None: ...\n\nclass FSStore:\n def write_text(self, path: Path, data: str) -> None:\n path.parent.mkdir(parents=True, exist_ok=True)\n path.write_text(data, encoding=\"utf-8\")\n\n@dataclass(frozen=True, slots=True)\nclass Item:\n name: str\n qty: int\n\ndef parse_items(lines: Iterable[str]) -> list[Item]:\n out: list[Item] = []\n for i, line in enumerate(lines, 1):\n s = line.strip()\n if not s:\n continue\n obj = json.loads(s)\n if not isinstance(obj, dict):\n raise ValueError(f\"line {i}: expected object\")\n name = obj.get(\"name\")\n qty = obj.get(\"qty\")\n if not isinstance(name, str) or not name:\n raise ValueError(f\"line {i}: name must be str\")\n if not isinstance(qty, int) or qty < 0:\n raise ValueError(f\"line {i}: qty must be non-negative int\")\n out.append(Item(name, qty))\n return out\n\nclass InventoryWriter:\n def __init__(self, base_dir: Path, store: Store | None = None) -> None:\n self._base = base_dir\n self._store: Store = store or FSStore()\n\n def write(self, rel_path: str, items: list[Item]) -> Path:\n dst = (self._base / rel_path).resolve()\n base = self._base.resolve()\n if dst != base and base not in dst.parents:\n raise ValueError(\"unsafe path traversal\")\n payload = json.dumps([item.__dict__ for item in items], ensure_ascii=False)\n self._store.write_text(dst, payload)\n return dst\n```\n\n```python\nimport json\nfrom pathlib import Path\nimport pytest\nfrom module_under_test import InventoryWriter, parse_items\n\ndef test_parse_items_valid():\n lines = [json.dumps({\"name\":\"x\",\"qty\":1})]\n assert parse_items(lines)[0].name == \"x\"\n\ndef test_writer_blocks_traversal(tmp_path: Path):\n w = InventoryWriter(tmp_path)\n with pytest.raises(ValueError):\n w.write(\"../evil.json\", [])\n```", "source": "WithinUsAI/python_GOD_coder_100k"} {"text": "Perform a code review for a gaming PR implementing offline-first sync.\nTarget platform: ML (PyTorch + serving).\nRequirements: list critical issues, improvements, and provide an improved patch excerpt.\nConstraints: must be performant under load, must be production-ready, must include type hints where applicable.\nDifficulty: easy. Assume GDPR-style deletion requests must be supported.\n\nOutput: actionable implementation and verification artifacts.\nDeliverable: code review findings + improved patch excerpt.\n\n**Critical issues**\n1. Missing input validation at boundary; potential unexpected exceptions.\n2. No idempotency / retry safety for side-effecting endpoint.\n3. No tests for edge cases (empty input, duplicates, timeouts).\n4. Observability gaps: no request_id correlation, no metrics.\n\n**Improvements**\n- Add strict validation and explicit error responses.\n- Add idempotency key support for create endpoints.\n- Add unit + integration tests with CI gating.\n- Add structured logs and basic metrics.\n\nPatch excerpt (illustrative):\n```python\nif not idem_key:\n raise HTTPException(400, \"Missing Idempotency-Key\")\n```\n\n\nChecks: input validation, tests, and safe defaults included.", "source": "WithinUsAI/GOD_Coder_100k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Produce an offline-first self-evolving code assistant architecture named `ztzlr23e68z`.\nMust include: module layout, patch-safety policy, evaluation gates (tests/lint/types), versioned memory index.\n\nArchitecture: `ztzlr23e68z` (offline-first, self-evolving)\n\nModules\n- core/loop.py: evolve → validate → accept/reject (bounded iterations)\n- patching/: diff builder, safe apply, atomic writes, rollback points\n- policy/: allowlist paths, deny globs (.git/, __pycache__/, binaries), patch size caps\n- signals/: parse pytest/ruff/mypy into normalized findings\n- memory/index.jsonl: append-only snapshots (hashes, metrics, rationale)\n\nSafety gates\n- refuse path traversal/symlink escapes; never edit binaries\n- accept only if tests/lint/types stay green or improve", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Fix a bug and add tests.\n\nFile: dpdf3_m3jvb.py\n```python\ndef uyo2bikxv(n: int) -> int:\n \"\"\"Sum 1..n inclusive.\"\"\"\n if n < 0:\n raise ValueError(\"n must be non-negative\")\n total = 0\n for k in range(n): # BUG: should include n\n total += k\n return total\n```\n\nReturn unified diffs for dpdf3_m3jvb.py and test_dpdf3_m3jvb.py (pytest).\n\n*** Begin Patch\n*** Update File: dpdf3_m3jvb.py\n@@\n def uyo2bikxv(n: int) -> int:\n@@\n total = 0\n- for k in range(n): # BUG: should include n\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_dpdf3_m3jvb.py\n+import pytest\n+from dpdf3_m3jvb import uyo2bikxv\n+\n+def test_zero():\n+ assert uyo2bikxv(0) == 0\n+\n+def test_one():\n+ assert uyo2bikxv(1) == 1\n+\n+def test_small():\n+ assert uyo2bikxv(7) == 28\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ uyo2bikxv(-1)\n+\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Refactor to typed, mostly-immutable Python and add minimal tests.\n\n```python\nclass C92024:\n def __init__(self, values): self.values=list(values)\n def mean(self): return sum(self.values)/len(self.values)\n```\nReturn `m37848.py` and `test_m37848.py`.\n\n```python\n# m37848.py\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom typing import Iterable, Tuple\n\n@dataclass(frozen=True)\nclass C92024:\n values: Tuple[float, ...]\n\n @staticmethod\n def create(values: Iterable[float]) -> \"C92024\":\n vals = tuple(float(v) for v in values)\n if not vals: raise ValueError(\"empty\")\n return C92024(vals)\n\n def mean(self) -> float:\n return sum(self.values)/len(self.values)\n```\n\n```python\n# test_m37848.py\nimport pytest\nfrom m37848 import C92024\n\ndef test_mean():\n assert C92024.create([1,2,3]).mean() == 2.0\ndef test_empty():\n with pytest.raises(ValueError):\n C92024.create([])\n```", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Add a clear docstring and type hints to this function:\n\n```python\ndef f90668(s):\n return ''.join(x for x in s if x.isalnum()).lower()\n```\n\n```python\nfrom __future__ import annotations\n\ndef f90668(s: str) -> str:\n \"\"\"Normalize a string: keep only alphanumerics and lowercase the result.\"\"\"\n return \"\".join(ch for ch in s if ch.isalnum()).lower()\n```", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: Language: C++\nFramework/tooling: STL\nDomain: data pipeline\nLogic challenge: JWT refresh token rotation\nTask type: cross_stack_outage_fix\nDifficulty: expert\n\nReturn a rigorous engineering answer:\n- identify the hidden root cause or logical failure\n- present the corrected implementation\n- add tests that prove the fix\n- list verification commands\n- explain why naive fixes are insufficient when relevant\n\nRepository sketch:\nrepo/\n src/main.cpp\n src/service.cpp\n include/service.h\n tests/test_service.cpp\n CMakeLists.txt\n\nFocus: Focus on staff-level problem solving with multi-file patches, rollout implications, performance and security tradeoffs.\n\nassistant: Diagnosis:\n- Staff-level diagnosis: JWT refresh token rotation impacts correctness, operability, and future maintenance, so the fix must be minimal where possible but complete where necessary.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```cpp\n#include \n#include \n\nusing Payload = std::unordered_map;\n\nPayload normalize_payload(const Payload& in) {\n Payload out;\n for (const auto& [k, v] : in) {\n if (!v.empty()) out[k] = v;\n }\n return out;\n}\n```\n\nTests:\n```cpp\nTEST_CASE(\"normalize_payload filters empty values\") {\n Payload in{{\"id\",\"7\"},{\"name\",\"\"}};\n auto out = normalize_payload(in);\n REQUIRE(out.count(\"id\") == 1);\n REQUIRE(out.count(\"name\") == 0);\n}\n```\n\nVerification:\n- `cmake --build build`\n- `ctest --test-dir build`\n\nEngineering notes:\n- Language: C++\n- Framework/tooling: STL\n- Stack context: ASP.NET Core, SQL Server, EF Core, xUnit, Docker\n- Domain: data pipeline\n- Task type: cross_stack_outage_fix\n- Difficulty: expert\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "Write a thorough test suite for a Python component used for report generation.\nRequirements: cover edge cases, invalid inputs, and behavior invariants.\nConstraints: must be memory-efficient, must be streaming-friendly, must include type hints, must be easy to extend.\nDifficulty: expert. Avoid quadratic behavior on large inputs.\n\nDeliverable: production-ready reference solution.\n```python\n# tests (pytest-style) for a module providing: normalize(), parse_lines(), compute_stats()\nimport math\nimport pytest\n\ndef test_normalize_idempotent(module_under_test):\n x = \" A\\tB \"\n assert module_under_test.normalize(module_under_test.normalize(x)) == module_under_test.normalize(x)\n\ndef test_parse_lines_rejects_invalid(module_under_test):\n with pytest.raises(ValueError):\n module_under_test.parse_lines([\"\", \"???\", None]) # type: ignore[arg-type]\n\ndef test_compute_stats_basic(module_under_test):\n data = [1, 2, 3, 4]\n s = module_under_test.compute_stats(data)\n assert s.count == 4\n assert s.total == 10\n assert math.isclose(s.mean, 2.5)\n```", "source": "WithinUsAI/python_GOD_coder_100k"} {"text": "Refactor a Python module used for data modeling into a clean, extensible design.\nRequirements: outline the new architecture briefly, then provide the refactored code and tests.\nConstraints: must be memory-efficient, must include docstrings.\nDifficulty: expert. Provide helpful exceptions with actionable messages.\n\nDeliverable: corrected code and verification tests.\nArchitecture:\n- Public facade class coordinating concerns (parsing, validation, persistence)\n- Small pure functions for testability\n- No global state; dependency injection for filesystem I/O\n\n```python\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom pathlib import Path\nfrom typing import Protocol, Iterable\nimport json\n\nclass Store(Protocol):\n def write_text(self, path: Path, data: str) -> None: ...\n\nclass FSStore:\n def write_text(self, path: Path, data: str) -> None:\n path.parent.mkdir(parents=True, exist_ok=True)\n path.write_text(data, encoding=\"utf-8\")\n\n@dataclass(frozen=True, slots=True)\nclass Item:\n name: str\n qty: int\n\ndef parse_items(lines: Iterable[str]) -> list[Item]:\n out: list[Item] = []\n for i, line in enumerate(lines, 1):\n s = line.strip()\n if not s:\n continue\n obj = json.loads(s)\n if not isinstance(obj, dict):\n raise ValueError(f\"line {i}: expected object\")\n name = obj.get(\"name\")\n qty = obj.get(\"qty\")\n if not isinstance(name, str) or not name:\n raise ValueError(f\"line {i}: name must be str\")\n if not isinstance(qty, int) or qty < 0:\n raise ValueError(f\"line {i}: qty must be non-negative int\")\n out.append(Item(name, qty))\n return out\n\nclass InventoryWriter:\n def __init__(self, base_dir: Path, store: Store | None = None) -> None:\n self._base = base_dir\n self._store: Store = store or FSStore()\n\n def write(self, rel_path: str, items: list[Item]) -> Path:\n dst = (self._base / rel_path).resolve()\n base = self._base.resolve()\n if dst != base and base not in dst.parents:\n raise ValueError(\"unsafe path traversal\")\n payload = json.dumps([item.__dict__ for item in items], ensure_ascii=False)\n self._store.write_text(dst, payload)\n return dst\n```\n\n```python\nimport json\nfrom pathlib import Path\nimport pytest\nfrom module_under_test import InventoryWriter, parse_items\n\ndef test_parse_items_valid():\n lines = [json.dumps({\"name\":\"x\",\"qty\":1})]\n assert parse_items(lines)[0].name == \"x\"\n\ndef test_writer_blocks_traversal(tmp_path: Path):\n w = InventoryWriter(tmp_path)\n with pytest.raises(ValueError):\n w.write(\"../evil.json\", [])\n```", "source": "WithinUsAI/python_GOD_coder_100k"} {"text": "Optimize a Python workflow for telemetry ingestion.\nRequirements: provide an optimized implementation and a small benchmark harness.\nConstraints: must handle Windows paths safely, must be memory-efficient, must include docstrings.\nDifficulty: medium. Avoid quadratic behavior on large inputs.\n\nDeliverable: implementation + tests.\nStrategy:\n- Avoid repeated parsing; precompile regex if needed; use local variables; stream processing.\n\n```python\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom typing import Iterable\nimport time\n\n@dataclass(frozen=True, slots=True)\nclass Stats:\n count: int\n total: int\n\ndef compute_stats_stream(values: Iterable[int]) -> Stats:\n c = 0\n t = 0\n for v in values:\n c += 1\n t += v\n return Stats(c, t)\n\ndef bench(n: int = 1_000_00) -> float:\n data = range(n)\n t0 = time.perf_counter()\n _ = compute_stats_stream(data)\n return time.perf_counter() - t0\n```\n\n```python\nfrom module_under_test import bench\ndef test_bench_runs_fast_enough():\n # Sanity: should run quickly on typical machines; adjust threshold for CI.\n assert bench(50_000) < 0.5\n```", "source": "WithinUsAI/python_GOD_coder_100k"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: Project domain: payments platform\nImplementation stack: ASP.NET Core, SQL Server, EF Core, xUnit, Docker\nSoftware delivery problem: transaction boundary bug\nTask type: test_strategy_implementation\nDifficulty: medium\n\nReturn a complete delivery-grade response with:\n- diagnosis or design reasoning\n- implementation\n- test plan or tests\n- rollout plan\n- rollback or compatibility note\n- verification commands\n\nRepository sketch:\nrepo/\n src/main.cpp\n src/service.cpp\n include/service.h\n tests/test_service.cpp\n CMakeLists.txt\n\nFocus: Focus on shipping production software with rollout safety, acceptance criteria, telemetry, and maintenance quality.\n\nassistant: Diagnosis:\n- Root cause or delivery blocker: transaction boundary bug needs both implementation work and a safe shipping plan.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```cpp\n#include \n#include \n\nusing Payload = std::unordered_map;\n\nPayload normalize_payload(const Payload& in) {\n Payload out;\n for (const auto& [k, v] : in) {\n if (!v.empty()) out[k] = v;\n }\n return out;\n}\n```\n\nTests:\n```cpp\nTEST_CASE(\"normalize_payload filters empty values\") {\n Payload in{{\"id\",\"7\"},{\"name\",\"\"}};\n auto out = normalize_payload(in);\n REQUIRE(out.count(\"id\") == 1);\n REQUIRE(out.count(\"name\") == 0);\n}\n```\n\nVerification:\n- `cmake --build build`\n- `ctest --test-dir build`\n\nEngineering notes:\n- Language: C++\n- Framework/tooling: CMake\n- Stack context: ASP.NET Core, SQL Server, EF Core, xUnit, Docker\n- Domain: payments platform\n- Task type: test_strategy_implementation\n- Difficulty: medium\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Refactor to modern typed Python with immutability and tests.\n\nFile: l18z_x5q2p.py\n```python\nclass Bxr5Iz:\n def __init__(self, name, values):\n self.name = name\n self.values = list(values)\n def add(self, v):\n self.values.append(v)\n def mean(self):\n s = 0\n for x in self.values:\n s += x\n return s / len(self.values)\n```\n\nReturn full new l18z_x5q2p.py and test_l18z_x5q2p.py.\n\n# l18z_x5q2p.py\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom typing import Iterable, Tuple\n\n@dataclass(frozen=True)\nclass Bxr5Iz:\n name: str\n values: Tuple[float, ...]\n\n @staticmethod\n def create(name: str, values: Iterable[float]) -> \"Bxr5Iz\":\n vals = tuple(float(v) for v in values)\n if not vals:\n raise ValueError(\"values must be non-empty\")\n return Bxr5Iz(name=name, values=vals)\n\n def add(self, v: float) -> \"Bxr5Iz\":\n return Bxr5Iz(name=self.name, values=self.values + (float(v),))\n\n def mean(self) -> float:\n return sum(self.values) / len(self.values)\n\n# test_l18z_x5q2p.py\nimport pytest\nfrom l18z_x5q2p import Bxr5Iz\n\ndef test_mean_and_add():\n c = Bxr5Iz.create(\"a\", [1, 2, 3])\n assert c.mean() == 2.0\n assert c.add(5).mean() == (1 + 2 + 3 + 5) / 4\n\ndef test_empty_raises():\n with pytest.raises(ValueError):\n Bxr5Iz.create(\"x\", [])", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: Language: Go\nFramework/tooling: Fiber\nDomain: developer platform\nLogic challenge: path traversal on downloads\nTask type: multi_service_security_patch\nDifficulty: expert\n\nReturn a rigorous engineering answer:\n- identify the hidden root cause or logical failure\n- present the corrected implementation\n- add tests that prove the fix\n- list verification commands\n- explain why naive fixes are insufficient when relevant\n\nRepository sketch:\nrepo/\n cmd/server/main.go\n internal/service/service.go\n internal/store/store.go\n internal/api/api.go\n service_test.go\n go.mod\n\nFocus: Focus on staff-level problem solving with multi-file patches, rollout implications, performance and security tradeoffs.\n\nassistant: Diagnosis:\n- Staff-level diagnosis: path traversal on downloads impacts correctness, operability, and future maintenance, so the fix must be minimal where possible but complete where necessary.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```go\npackage service\n\nimport \"fmt\"\n\nfunc NormalizePayload(payload map[string]any) map[string]any {\n\tout := make(map[string]any)\n\tfor k, v := range payload {\n\t\tif v == nil {\n\t\t\tcontinue\n\t\t}\n\t\tout[k] = v\n\t}\n\treturn out\n}\n\nfunc Handle(payload map[string]any) (map[string]any, error) {\n\tclean := NormalizePayload(payload)\n\tif _, ok := clean[\"id\"]; !ok {\n\t\treturn nil, fmt.Errorf(\"missing id\")\n\t}\n\treturn map[string]any{\"ok\": true, \"data\": clean}, nil\n}\n```\n\nTests:\n```go\npackage service\n\nimport \"testing\"\n\nfunc TestHandle(t *testing.T) {\n\tgot, err := Handle(map[string]any{\"id\": 7, \"name\": \"ok\", \"unused\": nil})\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tif got[\"ok\"] != true {\n\t\tt.Fatalf(\"expected ok=true\")\n\t}\n\tif _, err := Handle(map[string]any{\"name\": \"x\"}); err == nil {\n\t\tt.Fatalf(\"expected missing id error\")\n\t}\n}\n```\n\nVerification:\n- `go test ./...`\n- `go vet ./...`\n\nEngineering notes:\n- Language: Go\n- Framework/tooling: Fiber\n- Stack context: GitHub Actions, Docker Compose, Kubernetes, Terraform\n- Domain: developer platform\n- Task type: multi_service_security_patch\n- Difficulty: expert\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Produce an offline-first self-evolving code assistant architecture named `u7ctpq6ttop3`.\nMust include: module layout, patch-safety policy, evaluation gates (tests/lint/types), versioned memory index.\n\nArchitecture: `u7ctpq6ttop3` (offline-first, self-evolving)\n\nModules\n- core/loop.py: evolve → validate → accept/reject (bounded iterations)\n- patching/: diff builder, safe apply, atomic writes, rollback points\n- policy/: allowlist paths, deny globs (.git/, __pycache__/, binaries), patch size caps\n- signals/: parse pytest/ruff/mypy into normalized findings\n- memory/index.jsonl: append-only snapshots (hashes, metrics, rationale)\n\nSafety gates\n- refuse path traversal/symlink escapes; never edit binaries\n- accept only if tests/lint/types stay green or improve", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Optimize while preserving behavior.\n\nFile: kupsik.py\n```python\ndef smty2f_6pnj(xs):\n out = []\n for x in xs:\n if x not in out:\n out.append(x)\n return out\n```\n\nRequirements: preserve first-seen order; O(n) average; add types + docstring.\n\n# kupsik.py\nfrom __future__ import annotations\nfrom typing import Iterable, List, Set, TypeVar\n\nT = TypeVar(\"T\")\n\ndef smty2f_6pnj(xs: Iterable[T]) -> List[T]:\n \"\"\"Return unique items preserving first-seen order.\"\"\"\n seen: Set[T] = set()\n out: List[T] = []\n for x in xs:\n if x in seen:\n continue\n seen.add(x)\n out.append(x)\n return out", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Task type: network_protocol\nScenario: time-series metrics store\nDomain focus: kernel primitives\nPrimary language: sql\nDifficulty: expert\nScale/SLO: 10k RPS peak\nComponent: component_xppepurk\nConstraints: include failure modes and recovery, include backward compatibility and migration plan, explicit contracts and invariants, include deterministic replay plan, include verification strategy\nAssume schema changes every sprint; must be backward compatible.\nDeliverable: Design an application protocol: framing, retries, backpressure, timeouts; include client/server skeleton and test vectors.\n\nOutput: contract-first solution with failure modes, security posture, and test/verification strategy.\n**Contract**\n- Inputs validated at the boundary; explicit error taxonomy.\n- Idempotency for side effects via request_id; deterministic replay.\n- Backward compatibility: additive changes by default; versioned breaking changes.\n**Invariants**\n- Isolation: tenant boundary enforced; no cross-tenant reads/writes.\n- Liveness: under bounded faults and stable network, progress occurs.\n- Determinism: replay of the same event log yields identical outputs.\n**Failure modes & recovery**\n- Crash during commit: WAL replay completes or transaction aborts; no torn writes.\n- Network partition: minority cannot commit; clients receive retriable errors.\n- Duplicate requests: de-duplicate by (tenant, request_id) returning cached response.\n**Security posture (defensive)**\n- Threat model: auth/authz, injection, replay/abuse, supply chain.\n- Least privilege; secrets in managed store; audit logs for sensitive ops.\n- Input normalization, parameterized queries, path traversal protections.\n**Verification strategy**\n- Deterministic simulation with fault injection (crash/partition/latency).\n- Fuzzing of parsers/framers/validators with corpus seeds.\n- Property tests against a pure reference model (state machine).\n\n**Snippet**\n```text\nImplementation sketch: factor pure state-machine core; adapters for I/O; add deterministic replay log.\n```\nExpert checks: state-machine proof sketch + model checking; upgrade/rollback rehearsed.", "source": "WithinUsAI/Omega_Genesis_Coder_100k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Produce an offline-first self-evolving code assistant architecture named `w0hpdsc`.\nMust include: module layout, patch-safety policy, evaluation gates (tests/lint/types), versioned memory index.\n\nArchitecture: `w0hpdsc` (offline-first, self-evolving)\n\nModules\n- core/loop.py: evolve → validate → accept/reject (bounded iterations)\n- patching/: diff builder, safe apply, atomic writes, rollback points\n- policy/: allowlist paths, deny globs (.git/, __pycache__/, binaries), patch size caps\n- signals/: parse pytest/ruff/mypy into normalized findings\n- memory/index.jsonl: append-only snapshots (hashes, metrics, rationale)\n\nSafety gates\n- refuse path traversal/symlink escapes; never edit binaries\n- accept only if tests/lint/types stay green or improve", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Fix a bug and add tests.\n\nFile: xwd46yc.py\n```python\ndef n5f3bwwb(n: int) -> int:\n \"\"\"Sum 1..n inclusive.\"\"\"\n if n < 0:\n raise ValueError(\"n must be non-negative\")\n total = 0\n for k in range(n): # BUG: should include n\n total += k\n return total\n```\n\nReturn unified diffs for xwd46yc.py and test_xwd46yc.py (pytest).\n\n*** Begin Patch\n*** Update File: xwd46yc.py\n@@\n def n5f3bwwb(n: int) -> int:\n@@\n total = 0\n- for k in range(n): # BUG: should include n\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_xwd46yc.py\n+import pytest\n+from xwd46yc import n5f3bwwb\n+\n+def test_zero():\n+ assert n5f3bwwb(0) == 0\n+\n+def test_one():\n+ assert n5f3bwwb(1) == 1\n+\n+def test_small():\n+ assert n5f3bwwb(7) == 28\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ n5f3bwwb(-1)\n+\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Refactor a Python module used for rate limiting into a clean, extensible design.\nRequirements: outline the new architecture briefly, then provide the refactored code and tests.\nConstraints: must include tests, must provide clear error messages.\nDifficulty: easy. Include a small CLI example if relevant.\n\nDeliverable: corrected code and verification tests.\nArchitecture:\n- Public facade class coordinating concerns (parsing, validation, persistence)\n- Small pure functions for testability\n- No global state; dependency injection for filesystem I/O\n\n```python\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom pathlib import Path\nfrom typing import Protocol, Iterable\nimport json\n\nclass Store(Protocol):\n def write_text(self, path: Path, data: str) -> None: ...\n\nclass FSStore:\n def write_text(self, path: Path, data: str) -> None:\n path.parent.mkdir(parents=True, exist_ok=True)\n path.write_text(data, encoding=\"utf-8\")\n\n@dataclass(frozen=True, slots=True)\nclass Item:\n name: str\n qty: int\n\ndef parse_items(lines: Iterable[str]) -> list[Item]:\n out: list[Item] = []\n for i, line in enumerate(lines, 1):\n s = line.strip()\n if not s:\n continue\n obj = json.loads(s)\n if not isinstance(obj, dict):\n raise ValueError(f\"line {i}: expected object\")\n name = obj.get(\"name\")\n qty = obj.get(\"qty\")\n if not isinstance(name, str) or not name:\n raise ValueError(f\"line {i}: name must be str\")\n if not isinstance(qty, int) or qty < 0:\n raise ValueError(f\"line {i}: qty must be non-negative int\")\n out.append(Item(name, qty))\n return out\n\nclass InventoryWriter:\n def __init__(self, base_dir: Path, store: Store | None = None) -> None:\n self._base = base_dir\n self._store: Store = store or FSStore()\n\n def write(self, rel_path: str, items: list[Item]) -> Path:\n dst = (self._base / rel_path).resolve()\n base = self._base.resolve()\n if dst != base and base not in dst.parents:\n raise ValueError(\"unsafe path traversal\")\n payload = json.dumps([item.__dict__ for item in items], ensure_ascii=False)\n self._store.write_text(dst, payload)\n return dst\n```\n\n```python\nimport json\nfrom pathlib import Path\nimport pytest\nfrom module_under_test import InventoryWriter, parse_items\n\ndef test_parse_items_valid():\n lines = [json.dumps({\"name\":\"x\",\"qty\":1})]\n assert parse_items(lines)[0].name == \"x\"\n\ndef test_writer_blocks_traversal(tmp_path: Path):\n w = InventoryWriter(tmp_path)\n with pytest.raises(ValueError):\n w.write(\"../evil.json\", [])\n```", "source": "WithinUsAI/python_GOD_coder_100k"} {"text": "Improve typing and robustness of a Python module used for validation.\nRequirements: provide type-safe APIs (generics/protocols where appropriate) and include tests.\nConstraints: must include type hints, must include docstrings.\nDifficulty: easy. Provide helpful exceptions with actionable messages.\n\nDeliverable: corrected code and verification tests.\n```python\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom typing import Callable, Generic, Iterable, Protocol, TypeVar\n\nT = TypeVar(\"T\")\nR = TypeVar(\"R\")\n\nclass Mapper(Protocol[T, R]):\n def __call__(self, x: T) -> R: ...\n\n@dataclass(frozen=True, slots=True)\nclass Batch(Generic[T]):\n items: tuple[T, ...]\n\ndef map_batch(batch: Batch[T], fn: Mapper[T, R]) -> Batch[R]:\n return Batch(items=tuple(fn(x) for x in batch.items))\n\ndef chunked(xs: Iterable[T], size: int) -> Iterable[Batch[T]]:\n if size <= 0:\n raise ValueError(\"size must be > 0\")\n buf: list[T] = []\n for x in xs:\n buf.append(x)\n if len(buf) == size:\n yield Batch(items=tuple(buf))\n buf.clear()\n if buf:\n yield Batch(items=tuple(buf))\n```\n\n```python\nimport pytest\nfrom module_under_test import Batch, map_batch, chunked\n\ndef test_map_batch():\n b = Batch(items=(1,2,3))\n assert map_batch(b, lambda x: x*2).items == (2,4,6)\n\ndef test_chunked():\n out = list(chunked([1,2,3,4,5], 2))\n assert [b.items for b in out] == [(1,2),(3,4),(5,)]\n```", "source": "WithinUsAI/python_GOD_coder_100k"} {"text": "Build an elite-grade solution in the domain of ml systems for scenario: multi-tenant SaaS.\nPrimary language: python.\nDifficulty: medium.\nConstraints: include tests or verification strategy, include invariants and failure modes, design for backward compatibility and migrations, document performance characteristics.\nComponent: component_oobocxw.\nAssume schema changes every sprint; must be backward compatible.\nTask: Provide SLOs, alerting, dashboards, runbooks, and incident playbook. Include chaos testing and safe rollout strategy.\n\nOutput: elite-grade engineering answer with contracts, edge cases, and verification.\nOutput: SLOs + alerts + runbooks + chaos strategy.\n\n**SLOs**\n- Availability: 99.9% monthly\n- Latency: p95 < 200ms, p99 < 400ms\n- Error rate: < 0.1%\n\n**Alerts**\n- Burn-rate alerts for SLOs (fast/slow windows)\n- Saturation: CPU, memory, queue depth, DB connections\n- Dependency health: cache hit rate drop, downstream timeouts\n\n**Runbooks**\n- Triage: identify blast radius, feature-flag rollback, capacity mitigation\n- Post-incident: timeline, contributing factors, action items\n\n**Chaos**\n- Inject latency, partial outages, and restarts in staging; verify steady-state SLOs.\n\n\nChecks: boundary validation and deterministic behavior verified.", "source": "WithinUsAI/Elite_GOD_Coder_100k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Fix a bug and add tests.\n\nFile: c_wu_n92.py\n```python\ndef ota7mxg3f(n: int) -> int:\n \"\"\"Sum 1..n inclusive.\"\"\"\n if n < 0:\n raise ValueError(\"n must be non-negative\")\n total = 0\n for k in range(n): # BUG: should include n\n total += k\n return total\n```\n\nReturn unified diffs for c_wu_n92.py and test_c_wu_n92.py (pytest).\n\n*** Begin Patch\n*** Update File: c_wu_n92.py\n@@\n def ota7mxg3f(n: int) -> int:\n@@\n total = 0\n- for k in range(n): # BUG: should include n\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_c_wu_n92.py\n+import pytest\n+from c_wu_n92 import ota7mxg3f\n+\n+def test_zero():\n+ assert ota7mxg3f(0) == 0\n+\n+def test_one():\n+ assert ota7mxg3f(1) == 1\n+\n+def test_small():\n+ assert ota7mxg3f(7) == 28\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ ota7mxg3f(-1)\n+\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Implement a concurrent Python solution for CLI tooling.\nRequirements: choose appropriate concurrency model, handle cancellation/timeouts, include tests.\nConstraints: must include tests, must provide clear error messages, must include type hints, stdlib-only.\nDifficulty: easy. Avoid quadratic behavior on large inputs.\n\nDeliverable: API + reference implementation + tests.\n```python\nfrom __future__ import annotations\nimport asyncio\nfrom dataclasses import dataclass\nfrom typing import Awaitable, Callable, Iterable, Optional\n\n@dataclass(frozen=True, slots=True)\nclass JobResult:\n ok: bool\n value: Optional[int]\n error: Optional[str]\n\nasync def run_bounded(\n factories: Iterable[Callable[[], Awaitable[int]]],\n *,\n limit: int = 10,\n timeout_s: float = 5.0,\n) -> list[JobResult]:\n if limit <= 0:\n raise ValueError(\"limit must be > 0\")\n sem = asyncio.Semaphore(limit)\n results: list[JobResult] = []\n\n async def one(factory: Callable[[], Awaitable[int]]) -> None:\n async with sem:\n try:\n v = await asyncio.wait_for(factory(), timeout=timeout_s)\n results.append(JobResult(True, v, None))\n except Exception as e:\n results.append(JobResult(False, None, str(e)))\n\n tasks = [asyncio.create_task(one(f)) for f in factories]\n try:\n await asyncio.gather(*tasks)\n finally:\n for t in tasks:\n if not t.done():\n t.cancel()\n return results\n```\n\n```python\nimport asyncio\nimport pytest\nfrom module_under_test import run_bounded\n\n@pytest.mark.asyncio\nasync def test_run_bounded_collects():\n async def work(x: int) -> int:\n await asyncio.sleep(0.01)\n return x\n fs = [(lambda i=i: work(i)) for i in range(30)]\n out = await run_bounded(fs, limit=5, timeout_s=1.0)\n assert len(out) == 30\n assert all(r.ok for r in out)\n```", "source": "WithinUsAI/python_GOD_coder_100k"} {"text": "Task type: query_optimizer\nScenario: identity and access\nDomain focus: fault injection & chaos engineering\nPrimary language: sql\nDifficulty: expert\nScale/SLO: 50 TB/day ingestion\nComponent: component_fzylzqju\nConstraints: explicit contracts and invariants, assume adversarial inputs; validate everything, include test vectors and fuzz strategy, include security threat model (defensive only), include verification strategy, include failure modes and recovery, include backward compatibility and migration plan\nAssume tight memory budget and cold-start constraints.\nDeliverable: Design a cost-based optimizer slice: logical rules, physical operators, and cost model. Include regression tests and query-plan explain examples.\n\nOutput: contract-first solution with failure modes, security posture, and test/verification strategy.\n**Contract**\n- Inputs validated at the boundary; explicit error taxonomy.\n- Idempotency for side effects via request_id; deterministic replay.\n- Backward compatibility: additive changes by default; versioned breaking changes.\n**Invariants**\n- Liveness: under bounded faults and stable network, progress occurs.\n- Determinism: replay of the same event log yields identical outputs.\n- Safety: state transitions preserve invariants; no partial commit leaks.\n**Failure modes & recovery**\n- Network partition: minority cannot commit; clients receive retriable errors.\n- Duplicate requests: de-duplicate by (tenant, request_id) returning cached response.\n- Crash during commit: WAL replay completes or transaction aborts; no torn writes.\n**Security posture (defensive)**\n- Threat model: auth/authz, injection, replay/abuse, supply chain.\n- Least privilege; secrets in managed store; audit logs for sensitive ops.\n- Input normalization, parameterized queries, path traversal protections.\n**Verification strategy**\n- Fuzzing of parsers/framers/validators with corpus seeds.\n- Canary + shadow traffic; invariants checked in production via assertions/metrics.\n- Deterministic simulation with fault injection (crash/partition/latency).\n\n**Snippet**\n```python\n# Minimal cost model skeleton\nfrom dataclasses import dataclass\n\n@dataclass(frozen=True)\nclass Plan:\n op: str\n cost: float\n children: tuple[\"Plan\", ...] = ()\n\ndef choose_best(plans: list[Plan]) -> Plan:\n return min(plans, key=lambda p: p.cost)\n```\n\nExpert checks: state-machine proof sketch + model checking; upgrade/rollback rehearsed.", "source": "WithinUsAI/Omega_Genesis_Coder_100k"} {"text": "Refactor to typed, mostly-immutable Python and add minimal tests.\n\n```python\nclass C94790:\n def __init__(self, values): self.values=list(values)\n def mean(self): return sum(self.values)/len(self.values)\n```\nReturn `m68830.py` and `test_m68830.py`.\n\n```python\n# m68830.py\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom typing import Iterable, Tuple\n\n@dataclass(frozen=True)\nclass C94790:\n values: Tuple[float, ...]\n\n @staticmethod\n def create(values: Iterable[float]) -> \"C94790\":\n vals = tuple(float(v) for v in values)\n if not vals: raise ValueError(\"empty\")\n return C94790(vals)\n\n def mean(self) -> float:\n return sum(self.values)/len(self.values)\n```\n\n```python\n# test_m68830.py\nimport pytest\nfrom m68830 import C94790\n\ndef test_mean():\n assert C94790.create([1,2,3]).mean() == 2.0\ndef test_empty():\n with pytest.raises(ValueError):\n C94790.create([])\n```", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Task type: supply_chain_security\nScenario: real-time notification hub\nDomain focus: model checking\nPrimary language: sql\nDifficulty: hard\nScale/SLO: 99.99% availability\nComponent: component_gqclbbea\nConstraints: include security threat model (defensive only), include performance model and limits, include failure modes and recovery, assume adversarial inputs; validate everything, include backward compatibility and migration plan\nAssume weekly network partitions.\nDeliverable: Design a supply-chain security plan: SBOM, signing, provenance, dependency policy, and CI gates.\n\nOutput: contract-first solution with failure modes, security posture, and test/verification strategy.\n**Contract**\n- Inputs validated at the boundary; explicit error taxonomy.\n- Idempotency for side effects via request_id; deterministic replay.\n- Backward compatibility: additive changes by default; versioned breaking changes.\n**Invariants**\n- Safety: state transitions preserve invariants; no partial commit leaks.\n- Determinism: replay of the same event log yields identical outputs.\n- Liveness: under bounded faults and stable network, progress occurs.\n**Failure modes & recovery**\n- Duplicate requests: de-duplicate by (tenant, request_id) returning cached response.\n- Crash during commit: WAL replay completes or transaction aborts; no torn writes.\n- Data corruption: checksums + scrubber; quarantine and rebuild from replicas/snapshots.\n**Security posture (defensive)**\n- Threat model: auth/authz, injection, replay/abuse, supply chain.\n- Least privilege; secrets in managed store; audit logs for sensitive ops.\n- Input normalization, parameterized queries, path traversal protections.\n**Verification strategy**\n- Property tests against a pure reference model (state machine).\n- Fuzzing of parsers/framers/validators with corpus seeds.\n- Deterministic simulation with fault injection (crash/partition/latency).\n\n**Snippet**\n```text\nImplementation sketch: factor pure state-machine core; adapters for I/O; add deterministic replay log.\n```\nHard checks: fault injection tests gate merges; perf thresholds enforced in CI.", "source": "WithinUsAI/Omega_Genesis_Coder_100k"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: Language: JavaScript\nFramework/tooling: Playwright\nDomain: model serving gateway\nLogic challenge: dead-letter queue replay\nTask type: backwards_compatible_redesign\nDifficulty: expert\n\nReturn a rigorous engineering answer:\n- identify the hidden root cause or logical failure\n- present the corrected implementation\n- add tests that prove the fix\n- list verification commands\n- explain why naive fixes are insufficient when relevant\n\nRepository sketch:\nrepo/\n src/\n api.js\n service.js\n utils.js\n tests/\n api.test.js\n package.json\n\nFocus: Focus on staff-level problem solving with multi-file patches, rollout implications, performance and security tradeoffs.\n\nassistant: Diagnosis:\n- Staff-level diagnosis: dead-letter queue replay impacts correctness, operability, and future maintenance, so the fix must be minimal where possible but complete where necessary.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```javascript\ntype Payload = Record;\n\nexport function normalizePayload(payload: Payload): Payload {\n if (!payload || typeof payload !== \"object\" || Array.isArray(payload)) {\n throw new TypeError(\"payload must be a plain object\");\n }\n return Object.fromEntries(\n Object.entries(payload)\n .filter(([, value]) => value !== null && value !== undefined)\n .map(([key, value]) => [String(key).trim(), value])\n );\n}\n\nexport function handleDeadLetterQueueReplay(payload: Payload) {\n const clean = normalizePayload(payload);\n if (!(\"id\" in clean)) {\n return { ok: false, data: {}, error: \"missing id\" };\n }\n return { ok: true, data: clean, error: null };\n}\n```\n\nTests:\n```javascript\nimport { describe, it, expect } from \"vitest\";\nimport { handleDeadLetterQueueReplay } from \"../src/service\";\n\ndescribe(\"handler\", () => {\n it(\"accepts valid input\", () => {\n expect(handleDeadLetterQueueReplay({ id: 7, name: \"ok\", unused: null })).toEqual({\n ok: true,\n data: { id: 7, name: \"ok\" },\n error: null\n });\n });\n\n it(\"rejects missing id\", () => {\n expect(handleDeadLetterQueueReplay({ name: \"x\" }).error).toMatch(/missing id/);\n });\n});\n```\n\nVerification:\n- `npm test`\n- `npm run lint`\n\nEngineering notes:\n- Language: JavaScript\n- Framework/tooling: Playwright\n- Stack context: Go, Gin, PostgreSQL, gRPC, Prometheus, Docker\n- Domain: model serving gateway\n- Task type: backwards_compatible_redesign\n- Difficulty: expert\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Produce an offline-first self-evolving code assistant architecture named `cvqo5avk8`.\nMust include: module layout, patch-safety policy, evaluation gates (tests/lint/types), versioned memory index.\n\nArchitecture: `cvqo5avk8` (offline-first, self-evolving)\n\nModules\n- core/loop.py: evolve → validate → accept/reject (bounded iterations)\n- patching/: diff builder, safe apply, atomic writes, rollback points\n- policy/: allowlist paths, deny globs (.git/, __pycache__/, binaries), patch size caps\n- signals/: parse pytest/ruff/mypy into normalized findings\n- memory/index.jsonl: append-only snapshots (hashes, metrics, rationale)\n\nSafety gates\n- refuse path traversal/symlink escapes; never edit binaries\n- accept only if tests/lint/types stay green or improve", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Optimize while preserving behavior and order.\n\n```python\ndef f35565(xs):\n out=[]\n for x in xs:\n if x not in out: out.append(x)\n return out\n```\nReturn `m90795.py` with types and O(n) average.\n\n```python\n# m90795.py\nfrom __future__ import annotations\nfrom typing import Iterable, List, Set, TypeVar\nT=TypeVar(\"T\")\n\ndef f35565(xs: Iterable[T]) -> List[T]:\n \"\"\"Unique items preserving first-seen order.\"\"\"\n seen: Set[T]=set()\n out: List[T]=[]\n for x in xs:\n if x in seen: continue\n seen.add(x); out.append(x)\n return out\n```", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Optimize while preserving behavior.\n\nFile: k7t3j3q4.py\n```python\ndef p2iygy(xs):\n out = []\n for x in xs:\n if x not in out:\n out.append(x)\n return out\n```\n\nRequirements: preserve first-seen order; O(n) average; add types + docstring.\n\n# k7t3j3q4.py\nfrom __future__ import annotations\nfrom typing import Iterable, List, Set, TypeVar\n\nT = TypeVar(\"T\")\n\ndef p2iygy(xs: Iterable[T]) -> List[T]:\n \"\"\"Return unique items preserving first-seen order.\"\"\"\n seen: Set[T] = set()\n out: List[T] = []\n for x in xs:\n if x in seen:\n continue\n seen.add(x)\n out.append(x)\n return out", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Implement an ML engineering workflow for document processing focusing on background jobs.\nTarget platform: ML (training + serving).\nRequirements: data contract, training loop, evaluation, model registry, serving API, monitoring.\nConstraints: must be observable (logs/metrics/traces), must include type hints where applicable, must be performant under load, must be easy to extend.\nDifficulty: expert. Assume 10k RPS peak traffic.\n\nOutput: production-oriented blueprint with code where appropriate.\nDeliverable: ML engineering blueprint (training + serving + monitoring), safe and production-oriented.\n\n**Data contract**\n- Define feature schema + ranges; validate at training and serving.\n\n**Training**\n- Deterministic split; baseline model; track metrics (AUC/F1/latency).\n- Store artifacts: model, config, feature stats.\n\n**Registry**\n- Promote models via approval gates; record lineage.\n\n**Serving**\n- Separate inference service with `/predict`.\n- Input validation + default handling; timeouts.\n\n**Monitoring**\n- Data drift: feature distribution checks.\n- Performance: online metrics + periodic labels; alert on regression.\n\nMinimal serving skeleton (FastAPI-ish):\n```python\n# validate input -> vectorize -> model.predict_proba -> return\n```\n\n\nHard-mode checks: concurrency safety, idempotency, and rollback validated; add chaos tests where feasible.", "source": "WithinUsAI/GOD_Coder_100k"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: Project domain: team dashboard\nImplementation stack: FastAPI, PostgreSQL, Redis, Celery, pytest, Docker\nSoftware delivery problem: multi-tenant access leak\nTask type: prd_to_patch\nDifficulty: hard\n\nReturn a complete delivery-grade response with:\n- diagnosis or design reasoning\n- implementation\n- test plan or tests\n- rollout plan\n- rollback or compatibility note\n- verification commands\n\nRepository sketch:\nrepo/\n src/\n api.js\n service.js\n utils.js\n tests/\n api.test.js\n package.json\n\nFocus: Focus on shipping production software with rollout safety, acceptance criteria, telemetry, and maintenance quality.\n\nassistant: Diagnosis:\n- Root cause or delivery blocker: multi-tenant access leak needs both implementation work and a safe shipping plan.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```javascript\ntype Payload = Record;\n\nexport function normalizePayload(payload: Payload): Payload {\n if (!payload || typeof payload !== \"object\" || Array.isArray(payload)) {\n throw new TypeError(\"payload must be a plain object\");\n }\n return Object.fromEntries(\n Object.entries(payload)\n .filter(([, value]) => value !== null && value !== undefined)\n .map(([key, value]) => [String(key).trim(), value])\n );\n}\n\nexport function handleMultiTenantAccessLeak(payload: Payload) {\n const clean = normalizePayload(payload);\n if (!(\"id\" in clean)) {\n return { ok: false, data: {}, error: \"missing id\" };\n }\n return { ok: true, data: clean, error: null };\n}\n```\n\nTests:\n```javascript\nimport { describe, it, expect } from \"vitest\";\nimport { handleMultiTenantAccessLeak } from \"../src/service\";\n\ndescribe(\"handler\", () => {\n it(\"accepts valid input\", () => {\n expect(handleMultiTenantAccessLeak({ id: 7, name: \"ok\", unused: null })).toEqual({\n ok: true,\n data: { id: 7, name: \"ok\" },\n error: null\n });\n });\n\n it(\"rejects missing id\", () => {\n expect(handleMultiTenantAccessLeak({ name: \"x\" }).error).toMatch(/missing id/);\n });\n});\n```\n\nVerification:\n- `npm test`\n- `npm run lint`\n\nEngineering notes:\n- Language: JavaScript\n- Framework/tooling: Node.js\n- Stack context: FastAPI, PostgreSQL, Redis, Celery, pytest, Docker\n- Domain: team dashboard\n- Task type: prd_to_patch\n- Difficulty: hard\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Optimize while preserving behavior.\n\nFile: a48hvnhvp.py\n```python\ndef cv1l_zj(xs):\n out = []\n for x in xs:\n if x not in out:\n out.append(x)\n return out\n```\n\nRequirements: preserve first-seen order; O(n) average; add types + docstring.\n\n# a48hvnhvp.py\nfrom __future__ import annotations\nfrom typing import Iterable, List, Set, TypeVar\n\nT = TypeVar(\"T\")\n\ndef cv1l_zj(xs: Iterable[T]) -> List[T]:\n \"\"\"Return unique items preserving first-seen order.\"\"\"\n seen: Set[T] = set()\n out: List[T] = []\n for x in xs:\n if x in seen:\n continue\n seen.add(x)\n out.append(x)\n return out", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Task type: compiler_frontend\nScenario: job scheduler\nDomain focus: network protocols\nPrimary language: sql\nDifficulty: expert\nScale/SLO: 100k RPS peak\nComponent: component_rmnmrsbm\nConstraints: include security threat model (defensive only), avoid data races and undefined behavior, include deterministic replay plan, include verification strategy, assume adversarial inputs; validate everything\nAssume partial data corruption; include scrubbing strategy.\nDeliverable: Design a DSL language frontend: lexer/parser, AST, type checking, error reporting, and tests.\n\nOutput: rigorous design + invariants + verification plan + implementation sketch.\n**Contract**\n- Inputs validated at the boundary; explicit error taxonomy.\n- Idempotency for side effects via request_id; deterministic replay.\n- Backward compatibility: additive changes by default; versioned breaking changes.\n**Invariants**\n- Isolation: tenant boundary enforced; no cross-tenant reads/writes.\n- Liveness: under bounded faults and stable network, progress occurs.\n- Determinism: replay of the same event log yields identical outputs.\n**Failure modes & recovery**\n- Duplicate requests: de-duplicate by (tenant, request_id) returning cached response.\n- Network partition: minority cannot commit; clients receive retriable errors.\n- Data corruption: checksums + scrubber; quarantine and rebuild from replicas/snapshots.\n**Security posture (defensive)**\n- Threat model: auth/authz, injection, replay/abuse, supply chain.\n- Least privilege; secrets in managed store; audit logs for sensitive ops.\n- Input normalization, parameterized queries, path traversal protections.\n**Verification strategy**\n- Canary + shadow traffic; invariants checked in production via assertions/metrics.\n- Fuzzing of parsers/framers/validators with corpus seeds.\n- Property tests against a pure reference model (state machine).\n\n**Snippet**\n```text\nImplementation sketch: factor pure state-machine core; adapters for I/O; add deterministic replay log.\n```\nExpert checks: state-machine proof sketch + model checking; upgrade/rollback rehearsed.", "source": "WithinUsAI/Omega_Genesis_Coder_100k"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: Language: SQL\nFramework/tooling: PostgreSQL\nDomain: artifact registry\nLogic challenge: CI failures after dependency upgrade\nTask type: backwards_compatible_redesign\nDifficulty: expert\n\nReturn a rigorous engineering answer:\n- identify the hidden root cause or logical failure\n- present the corrected implementation\n- add tests that prove the fix\n- list verification commands\n- explain why naive fixes are insufficient when relevant\n\nRepository sketch:\nrepo/\n migrations/\n 001_init.sql\n 002_add_index.sql\n queries/\n report.sql\n tests/\n report_cases.md\n\nFocus: Focus on staff-level problem solving with multi-file patches, rollout implications, performance and security tradeoffs.\n\nassistant: Diagnosis:\n- Staff-level diagnosis: CI failures after dependency upgrade impacts correctness, operability, and future maintenance, so the fix must be minimal where possible but complete where necessary.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```sql\nWITH ranked AS (\n SELECT\n user_id,\n created_at,\n amount,\n ROW_NUMBER() OVER (PARTITION BY user_id ORDER BY created_at DESC, id DESC) AS rn\n FROM orders\n)\nSELECT user_id, created_at, amount\nFROM ranked\nWHERE rn = 1;\n```\n\nTests:\n```sql\n-- Correctness checks:\n-- 1) multiple rows per user\n-- 2) identical timestamps require deterministic tie-breaker\n-- 3) null values handled by business rules\n```\n\nVerification:\n- `run migration checks`\n- `run query correctness cases`\n\nEngineering notes:\n- Language: SQL\n- Framework/tooling: PostgreSQL\n- Stack context: ASP.NET Core, SQL Server, EF Core, xUnit, Docker\n- Domain: artifact registry\n- Task type: backwards_compatible_redesign\n- Difficulty: expert\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "Design and implement an algorithm for parsing.\nRequirements: define inputs/outputs, implement solution with complexity analysis, and include tests.\nConstraints: must include tests, must handle Windows paths safely, must provide clear error messages, must be easy to extend.\nDifficulty: hard. Ensure the API is testable via dependency injection.\n\nDeliverable: corrected code and verification tests.\nProblem: compute rolling sums over events (ts:int,value:int) with window W seconds. Events may be out-of-order.\n\nComplexity: sorting O(n log n); window maintenance O(n); memory O(k).\n\n```python\nfrom __future__ import annotations\nfrom collections import deque\nfrom dataclasses import dataclass\nfrom typing import Iterable, List, Tuple\n\n@dataclass(frozen=True, slots=True)\nclass Event:\n ts: int\n value: int\n\ndef rolling_sum(events: Iterable[Event], window_s: int) -> List[Tuple[int,int]]:\n if window_s < 0:\n raise ValueError(\"window_s must be >= 0\")\n evs = sorted(events, key=lambda e: e.ts)\n q: deque[Event] = deque()\n s = 0\n out: List[Tuple[int,int]] = []\n for e in evs:\n q.append(e)\n s += e.value\n cutoff = e.ts - window_s\n while q and q[0].ts < cutoff:\n old = q.popleft()\n s -= old.value\n out.append((e.ts, s))\n return out\n```\n\n```python\nimport pytest\nfrom module_under_test import Event, rolling_sum\n\ndef test_rolling_sum():\n ev = [Event(10,1), Event(11,2), Event(20,5)]\n assert rolling_sum(ev, 5) == [(10,1),(11,3),(20,5)]\n```", "source": "WithinUsAI/python_GOD_coder_100k"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: Language: Rust\nFramework/tooling: Axum\nDomain: team dashboard\nLogic challenge: broken pagination cursor\nTask type: concurrency_fix\nDifficulty: hard\n\nReturn a rigorous engineering answer:\n- identify the hidden root cause or logical failure\n- present the corrected implementation\n- add tests that prove the fix\n- list verification commands\n- explain why naive fixes are insufficient when relevant\n\nRepository sketch:\nrepo/\n src/main.rs\n src/lib.rs\n src/service.rs\n src/store.rs\n tests/integration.rs\n Cargo.toml\n\nFocus: Focus on strong structured logic with edge cases, data validation, and concurrency safety.\n\nassistant: Diagnosis:\n- Root cause: the failure around broken pagination cursor is caused by missing validation, weak edge-case handling, or unsafe lifecycle behavior in the current implementation.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```rust\nuse std::collections::HashMap;\n\npub fn normalize_payload(payload: HashMap) -> HashMap {\n payload\n .into_iter()\n .filter(|(_, v)| !v.trim().is_empty())\n .collect()\n}\n```\n\nTests:\n```rust\n#[test]\nfn normalize_payload_filters_empty_values() {\n use std::collections::HashMap;\n let mut payload = HashMap::new();\n payload.insert(\"id\".to_string(), \"7\".to_string());\n payload.insert(\"name\".to_string(), \"\".to_string());\n let out = normalize_payload(payload);\n assert!(out.contains_key(\"id\"));\n assert!(!out.contains_key(\"name\"));\n}\n```\n\nVerification:\n- `cargo test`\n- `cargo clippy -- -D warnings`\n\nEngineering notes:\n- Language: Rust\n- Framework/tooling: Axum\n- Stack context: Go, Gin, PostgreSQL, gRPC, Prometheus, Docker\n- Domain: team dashboard\n- Task type: concurrency_fix\n- Difficulty: hard\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "Provision infrastructure for a enterprise SaaS workload providing role-based access control.\nTarget platform: ML (PyTorch + serving).\nRequirements: IaC (Terraform or Kubernetes YAML), networking, secrets, autoscaling.\nConstraints: must include type hints where applicable, must be secure-by-default, must be performant under load, must include clear error handling.\nDifficulty: easy. Include rollback strategy.\n\nOutput: production-oriented blueprint with code where appropriate.\nDeliverable: Kubernetes deployment + basic security posture.\n\n```yaml\napiVersion: apps/v1\nkind: Deployment\nmetadata:\n name: app\nspec:\n replicas: 3\n selector:\n matchLabels: { app: app }\n template:\n metadata:\n labels: { app: app }\n spec:\n containers:\n - name: app\n image: app:latest\n ports: [{ containerPort: 8080 }]\n readinessProbe:\n httpGet: { path: /healthz, port: 8080 }\n resources:\n requests: { cpu: \"200m\", memory: \"256Mi\" }\n limits: { cpu: \"1\", memory: \"1Gi\" }\n```\n\nAdditions:\n- NetworkPolicy to restrict egress/ingress.\n- Secrets via external secret store; rotate regularly.\n- HPA for autoscaling; PodDisruptionBudget for availability.\n\n\nChecks: input validation, tests, and safe defaults included.", "source": "WithinUsAI/GOD_Coder_100k"} {"text": "Refactor to typed, mostly-immutable Python and add minimal tests.\n\n```python\nclass C37352:\n def __init__(self, values): self.values=list(values)\n def mean(self): return sum(self.values)/len(self.values)\n```\nReturn `m72104.py` and `test_m72104.py`.\n\n```python\n# m72104.py\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom typing import Iterable, Tuple\n\n@dataclass(frozen=True)\nclass C37352:\n values: Tuple[float, ...]\n\n @staticmethod\n def create(values: Iterable[float]) -> \"C37352\":\n vals = tuple(float(v) for v in values)\n if not vals: raise ValueError(\"empty\")\n return C37352(vals)\n\n def mean(self) -> float:\n return sum(self.values)/len(self.values)\n```\n\n```python\n# test_m72104.py\nimport pytest\nfrom m72104 import C37352\n\ndef test_mean():\n assert C37352.create([1,2,3]).mean() == 2.0\ndef test_empty():\n with pytest.raises(ValueError):\n C37352.create([])\n```", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: System domain: search service\nStack: GitHub Actions, Docker Compose, Kubernetes, Terraform\nCross-layer incident: async cancellation bug\nTask type: cache_consistency_patch\nDifficulty: hard\n\nSolve this as a complete-project engineer.\nOutput must include:\n- root cause across layers\n- final implementation patch\n- tests touching at least two layers\n- deployment or observability note\n- verification commands\n\nRepository sketch:\nrepo/\n src/main.cpp\n src/service.cpp\n include/service.h\n tests/test_service.cpp\n CMakeLists.txt\n\nFocus: Focus on multi-layer debugging across frontend, backend, database, CI, caching, and deployment.\n\nassistant: Diagnosis:\n- Root cause: async cancellation bug crosses service boundaries, so the fix must align code, contracts, tests, and deployment behavior.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```cpp\n#include \n#include \n\nusing Payload = std::unordered_map;\n\nPayload normalize_payload(const Payload& in) {\n Payload out;\n for (const auto& [k, v] : in) {\n if (!v.empty()) out[k] = v;\n }\n return out;\n}\n```\n\nTests:\n```cpp\nTEST_CASE(\"normalize_payload filters empty values\") {\n Payload in{{\"id\",\"7\"},{\"name\",\"\"}};\n auto out = normalize_payload(in);\n REQUIRE(out.count(\"id\") == 1);\n REQUIRE(out.count(\"name\") == 0);\n}\n```\n\nVerification:\n- `cmake --build build`\n- `ctest --test-dir build`\n\nEngineering notes:\n- Language: C++\n- Framework/tooling: Boost\n- Stack context: GitHub Actions, Docker Compose, Kubernetes, Terraform\n- Domain: search service\n- Task type: cache_consistency_patch\n- Difficulty: hard\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Produce an offline-first self-evolving code assistant architecture named `uns1przy3`.\nMust include: module layout, patch-safety policy, evaluation gates (tests/lint/types), versioned memory index.\n\nArchitecture: `uns1przy3` (offline-first, self-evolving)\n\nModules\n- core/loop.py: evolve → validate → accept/reject (bounded iterations)\n- patching/: diff builder, safe apply, atomic writes, rollback points\n- policy/: allowlist paths, deny globs (.git/, __pycache__/, binaries), patch size caps\n- signals/: parse pytest/ruff/mypy into normalized findings\n- memory/index.jsonl: append-only snapshots (hashes, metrics, rationale)\n\nSafety gates\n- refuse path traversal/symlink escapes; never edit binaries\n- accept only if tests/lint/types stay green or improve", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Refactor to modern typed Python with immutability and tests.\n\nFile: pbtxrcg.py\n```python\nclass Weoapioe6X:\n def __init__(self, name, values):\n self.name = name\n self.values = list(values)\n def add(self, v):\n self.values.append(v)\n def mean(self):\n s = 0\n for x in self.values:\n s += x\n return s / len(self.values)\n```\n\nReturn full new pbtxrcg.py and test_pbtxrcg.py.\n\n# pbtxrcg.py\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom typing import Iterable, Tuple\n\n@dataclass(frozen=True)\nclass Weoapioe6X:\n name: str\n values: Tuple[float, ...]\n\n @staticmethod\n def create(name: str, values: Iterable[float]) -> \"Weoapioe6X\":\n vals = tuple(float(v) for v in values)\n if not vals:\n raise ValueError(\"values must be non-empty\")\n return Weoapioe6X(name=name, values=vals)\n\n def add(self, v: float) -> \"Weoapioe6X\":\n return Weoapioe6X(name=self.name, values=self.values + (float(v),))\n\n def mean(self) -> float:\n return sum(self.values) / len(self.values)\n\n# test_pbtxrcg.py\nimport pytest\nfrom pbtxrcg import Weoapioe6X\n\ndef test_mean_and_add():\n c = Weoapioe6X.create(\"a\", [1, 2, 3])\n assert c.mean() == 2.0\n assert c.add(5).mean() == (1 + 2 + 3 + 5) / 4\n\ndef test_empty_raises():\n with pytest.raises(ValueError):\n Weoapioe6X.create(\"x\", [])", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Write pytest tests for `f41418`.\n\n```python\ndef f41418(a: int, b: int) -> int:\n return a*a + b*b\n```\nInclude edge cases and a property-style check.\n\n```python\nimport random\nfrom m48774 import f41418\n\ndef test_known():\n assert f41418(3,4) == 25\n\ndef test_zero():\n assert f41418(0,0) == 0\n\ndef test_property_nonnegative():\n for _ in range(200):\n a=random.randint(-50,50)\n b=random.randint(-50,50)\n assert f41418(a,b) >= 0\n```", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Build an elite-grade solution in the domain of realtime systems for scenario: time-series metrics.\nPrimary language: go.\nDifficulty: hard.\nConstraints: include invariants and failure modes, avoid undefined behavior and data races, include tests or verification strategy, design for backward compatibility and migrations.\nComponent: component_haorvfk.\nAssume partial network partitions occur weekly.\nTask: Design an application-level protocol (framing, retries, timeouts, backpressure). Provide client/server skeleton and test vectors.\n\nOutput: elite-grade engineering answer with contracts, edge cases, and verification.\nOutput: protocol framing + retry policy + client/server skeleton.\n\n**Framing**\n- Length-prefixed: uint32_be length + payload\n- Payload: msgpack/json; include request_id, type, and optional checksum\n\n**Reliability**\n- Retries only for idempotent ops; exponential backoff + jitter.\n- Timeouts: connect, read, overall; enforce max in-flight to provide backpressure.\n\n**Test vectors**\n- Corrupted length / truncated frame rejected\n- Duplicate request_id returns cached response\n- Slowloris protection by read deadlines\n\n\nHard checks: failure injection tests and performance regressions gated.", "source": "WithinUsAI/Elite_GOD_Coder_100k"} {"text": "Task type: smt_constraint_model\nScenario: rate limit gateway\nDomain focus: zero-downtime migrations\nPrimary language: python\nDifficulty: expert\nScale/SLO: 10k RPS peak\nComponent: component_hhkqgoco\nConstraints: explicit contracts and invariants, include verification strategy, include deterministic replay plan, include test vectors and fuzz strategy, include performance model and limits, include backward compatibility and migration plan\nAssume weekly network partitions.\nDeliverable: Provide an SMT constraint model (or Python-to-SMT) for correctness/optimization; include sample instances and how to validate solutions.\n\nOutput: contract-first solution with failure modes, security posture, and test/verification strategy.\n**Contract**\n- Inputs validated at the boundary; explicit error taxonomy.\n- Idempotency for side effects via request_id; deterministic replay.\n- Backward compatibility: additive changes by default; versioned breaking changes.\n**Invariants**\n- Safety: state transitions preserve invariants; no partial commit leaks.\n- Liveness: under bounded faults and stable network, progress occurs.\n- Determinism: replay of the same event log yields identical outputs.\n**Failure modes & recovery**\n- Network partition: minority cannot commit; clients receive retriable errors.\n- Duplicate requests: de-duplicate by (tenant, request_id) returning cached response.\n- Data corruption: checksums + scrubber; quarantine and rebuild from replicas/snapshots.\n**Security posture (defensive)**\n- Threat model: auth/authz, injection, replay/abuse, supply chain.\n- Least privilege; secrets in managed store; audit logs for sensitive ops.\n- Input normalization, parameterized queries, path traversal protections.\n**Verification strategy**\n- Deterministic simulation with fault injection (crash/partition/latency).\n- Canary + shadow traffic; invariants checked in production via assertions/metrics.\n- Property tests against a pure reference model (state machine).\n\n**Snippet**\n```smtlib\n; Find an assignment minimizing cost while satisfying constraints\n(declare-const x Int)\n(declare-const y Int)\n(assert (and (>= x 0) (>= y 0) (<= (+ x y) 10)))\n(minimize (+ (* 3 x) (* 2 y)))\n(check-sat)\n(get-model)\n```\n\nExpert checks: state-machine proof sketch + model checking; upgrade/rollback rehearsed.", "source": "WithinUsAI/Omega_Genesis_Coder_100k"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: Language: JavaScript\nFramework/tooling: Node.js\nDomain: job scheduler\nLogic challenge: timezone bug in reporting\nTask type: performance_bottleneck_patch\nDifficulty: hard\n\nReturn a rigorous engineering answer:\n- identify the hidden root cause or logical failure\n- present the corrected implementation\n- add tests that prove the fix\n- list verification commands\n- explain why naive fixes are insufficient when relevant\n\nRepository sketch:\nrepo/\n src/\n api.js\n service.js\n utils.js\n tests/\n api.test.js\n package.json\n\nFocus: Focus on ambiguity, misleading symptoms, hidden root causes, and high-stakes debugging.\n\nassistant: Diagnosis:\n- Hidden root cause: timezone bug in reporting presents misleading symptoms, so the patch must target the actual logic boundary rather than the first visible failure.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```javascript\ntype Payload = Record;\n\nexport function normalizePayload(payload: Payload): Payload {\n if (!payload || typeof payload !== \"object\" || Array.isArray(payload)) {\n throw new TypeError(\"payload must be a plain object\");\n }\n return Object.fromEntries(\n Object.entries(payload)\n .filter(([, value]) => value !== null && value !== undefined)\n .map(([key, value]) => [String(key).trim(), value])\n );\n}\n\nexport function handleTimezoneBugInReporting(payload: Payload) {\n const clean = normalizePayload(payload);\n if (!(\"id\" in clean)) {\n return { ok: false, data: {}, error: \"missing id\" };\n }\n return { ok: true, data: clean, error: null };\n}\n```\n\nTests:\n```javascript\nimport { describe, it, expect } from \"vitest\";\nimport { handleTimezoneBugInReporting } from \"../src/service\";\n\ndescribe(\"handler\", () => {\n it(\"accepts valid input\", () => {\n expect(handleTimezoneBugInReporting({ id: 7, name: \"ok\", unused: null })).toEqual({\n ok: true,\n data: { id: 7, name: \"ok\" },\n error: null\n });\n });\n\n it(\"rejects missing id\", () => {\n expect(handleTimezoneBugInReporting({ name: \"x\" }).error).toMatch(/missing id/);\n });\n});\n```\n\nVerification:\n- `npm test`\n- `npm run lint`\n\nEngineering notes:\n- Language: JavaScript\n- Framework/tooling: Node.js\n- Stack context: GitHub Actions, Docker Compose, Kubernetes, Terraform\n- Domain: job scheduler\n- Task type: performance_bottleneck_patch\n- Difficulty: hard\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "Fix a subtle bug in a Python module used for task scheduling.\nRequirements: explain root cause briefly, provide corrected code, and add regression tests.\nConstraints: must avoid global state, must include tests, must be streaming-friendly.\nDifficulty: easy. Handle empty inputs and malformed records gracefully.\n\nDeliverable: corrected code and verification tests.\n```python\nfrom __future__ import annotations\n\nfrom dataclasses import dataclass\nfrom pathlib import Path\nfrom typing import Iterable\nimport json\n\n\nclass ValidationError(ValueError):\n \"\"\"Raised when input validation fails.\"\"\"\n\n\ndef safe_join(base: Path, *parts: str) -> Path:\n \"\"\"Join paths while preventing traversal outside base.\"\"\"\n b = base.resolve()\n p = (b / Path(*parts)).resolve()\n if p != b and b not in p.parents:\n raise ValidationError(f\"unsafe path: {p}\")\n return p\n\n\n@dataclass(frozen=True, slots=True)\nclass Record:\n key: str\n value: int\n\n\ndef parse_jsonl(lines: Iterable[str]) -> list[Record]:\n out: list[Record] = []\n for idx, line in enumerate(lines, 1):\n s = line.strip()\n if not s:\n continue\n try:\n obj = json.loads(s)\n except json.JSONDecodeError as e:\n raise ValidationError(f\"line {idx}: invalid json\") from e\n if not isinstance(obj, dict):\n raise ValidationError(f\"line {idx}: expected object\")\n key = obj.get(\"key\")\n val = obj.get(\"value\")\n if not isinstance(key, str) or not key:\n raise ValidationError(f\"line {idx}: key must be non-empty str\")\n if not isinstance(val, int):\n raise ValidationError(f\"line {idx}: value must be int\")\n out.append(Record(key, val))\n return out\n\n\ndef write_jsonl(base: Path, rel: str, records: Iterable[Record]) -> Path:\n base.mkdir(parents=True, exist_ok=True)\n dst = safe_join(base, rel)\n dst.parent.mkdir(parents=True, exist_ok=True)\n with dst.open(\"w\", encoding=\"utf-8\", newline=\"\\n\") as f:\n for r in records:\n f.write(json.dumps({\"key\": r.key, \"value\": r.value}, ensure_ascii=False) + \"\\n\")\n return dst\n```\n\n```python\n# tests (pytest-style)\nimport json\nfrom pathlib import Path\nimport pytest\nfrom module_under_test import ValidationError, Record, parse_jsonl, write_jsonl\n\ndef test_parse_ok():\n lines = [json.dumps({\"key\":\"a\",\"value\":1}), json.dumps({\"key\":\"b\",\"value\":2})]\n assert parse_jsonl(lines) == [Record(\"a\",1), Record(\"b\",2)]\n\ndef test_parse_rejects_bad_json():\n with pytest.raises(ValidationError):\n parse_jsonl([\"{not json}\"])\n\ndef test_safe_join_blocks_traversal(tmp_path: Path):\n with pytest.raises(ValidationError):\n write_jsonl(tmp_path, \"../x.jsonl\", [Record(\"a\",1)])\n```", "source": "WithinUsAI/python_GOD_coder_100k"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: Repository domain: repo automation\nPrimary language: C#\nFramework/tooling: EF Core\nReported problem: invalid rollback sequence\nTask type: bug_fix\nDifficulty: medium\n\nProduce a complete professional engineering response:\n1. Diagnose the root cause.\n2. Provide the corrected implementation or patch.\n3. Add tests.\n4. Add verification commands.\n5. Note edge cases and any migration or rollback risk.\n\nRepository sketch:\nrepo/\n src/App/Program.cs\n src/App/Service.cs\n tests/App.Tests/ServiceTests.cs\n App.sln\n\nQuality target:\n- Minimal diff unless redesign is clearly required\n- Production-ready code\n- No placeholders\n- Secure defaults\n- Clear acceptance of failure cases\n\nFocus: Focus on complete implementation quality, patch correctness, tests, and production readiness.\n\nassistant: Diagnosis:\n- Root cause: the failure around invalid rollback sequence is caused by missing validation, weak edge-case handling, or unsafe lifecycle behavior in the current implementation.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```csharp\nusing System;\nusing System.Collections.Generic;\n\npublic static class RequestHandler\n{\n public static Dictionary HandleRequest(Dictionary payload)\n {\n var clean = new Dictionary();\n foreach (var entry in payload)\n {\n if (entry.Value != null)\n clean[entry.Key.Trim()] = entry.Value;\n }\n if (!clean.ContainsKey(\"id\"))\n throw new ArgumentException(\"missing id\");\n return new Dictionary\n {\n [\"ok\"] = true,\n [\"data\"] = clean\n };\n }\n}\n```\n\nTests:\n```csharp\nusing System;\nusing System.Collections.Generic;\nusing Xunit;\n\npublic class RequestHandlerTests\n{\n [Fact]\n public void RequiresId()\n {\n Assert.Throws(() => RequestHandler.HandleRequest(new Dictionary { [\"name\"] = \"x\" }));\n }\n}\n```\n\nVerification:\n- `dotnet test`\n- `dotnet build`\n\nEngineering notes:\n- Language: C#\n- Framework/tooling: EF Core\n- Stack context: Go, Gin, PostgreSQL, gRPC, Prometheus, Docker\n- Domain: repo automation\n- Task type: bug_fix\n- Difficulty: medium\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Optimize while preserving behavior.\n\nFile: nv34rqw65.py\n```python\ndef posfdg3(xs):\n out = []\n for x in xs:\n if x not in out:\n out.append(x)\n return out\n```\n\nRequirements: preserve first-seen order; O(n) average; add types + docstring.\n\n# nv34rqw65.py\nfrom __future__ import annotations\nfrom typing import Iterable, List, Set, TypeVar\n\nT = TypeVar(\"T\")\n\ndef posfdg3(xs: Iterable[T]) -> List[T]:\n \"\"\"Return unique items preserving first-seen order.\"\"\"\n seen: Set[T] = set()\n out: List[T] = []\n for x in xs:\n if x in seen:\n continue\n seen.add(x)\n out.append(x)\n return out", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: Language: Rust\nFramework/tooling: Tokio\nDomain: payments platform\nLogic challenge: path traversal on downloads\nTask type: backwards_compatible_redesign\nDifficulty: expert\n\nReturn a rigorous engineering answer:\n- identify the hidden root cause or logical failure\n- present the corrected implementation\n- add tests that prove the fix\n- list verification commands\n- explain why naive fixes are insufficient when relevant\n\nRepository sketch:\nrepo/\n src/main.rs\n src/lib.rs\n src/service.rs\n src/store.rs\n tests/integration.rs\n Cargo.toml\n\nFocus: Focus on staff-level problem solving with multi-file patches, rollout implications, performance and security tradeoffs.\n\nassistant: Diagnosis:\n- Staff-level diagnosis: path traversal on downloads impacts correctness, operability, and future maintenance, so the fix must be minimal where possible but complete where necessary.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```rust\nuse std::collections::HashMap;\n\npub fn normalize_payload(payload: HashMap) -> HashMap {\n payload\n .into_iter()\n .filter(|(_, v)| !v.trim().is_empty())\n .collect()\n}\n```\n\nTests:\n```rust\n#[test]\nfn normalize_payload_filters_empty_values() {\n use std::collections::HashMap;\n let mut payload = HashMap::new();\n payload.insert(\"id\".to_string(), \"7\".to_string());\n payload.insert(\"name\".to_string(), \"\".to_string());\n let out = normalize_payload(payload);\n assert!(out.contains_key(\"id\"));\n assert!(!out.contains_key(\"name\"));\n}\n```\n\nVerification:\n- `cargo test`\n- `cargo clippy -- -D warnings`\n\nEngineering notes:\n- Language: Rust\n- Framework/tooling: Tokio\n- Stack context: Airflow, dbt, DuckDB, MinIO, pytest\n- Domain: payments platform\n- Task type: backwards_compatible_redesign\n- Difficulty: expert\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: Project domain: search service\nImplementation stack: Airflow, dbt, DuckDB, MinIO, pytest\nSoftware delivery problem: dead-letter queue replay\nTask type: architecture_patch\nDifficulty: hard\n\nReturn a complete delivery-grade response with:\n- diagnosis or design reasoning\n- implementation\n- test plan or tests\n- rollout plan\n- rollback or compatibility note\n- verification commands\n\nRepository sketch:\nrepo/\n migrations/\n 001_init.sql\n 002_add_index.sql\n queries/\n report.sql\n tests/\n report_cases.md\n\nFocus: Focus on shipping production software with rollout safety, acceptance criteria, telemetry, and maintenance quality.\n\nassistant: Diagnosis:\n- Root cause or delivery blocker: dead-letter queue replay needs both implementation work and a safe shipping plan.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```sql\nWITH ranked AS (\n SELECT\n user_id,\n created_at,\n amount,\n ROW_NUMBER() OVER (PARTITION BY user_id ORDER BY created_at DESC, id DESC) AS rn\n FROM orders\n)\nSELECT user_id, created_at, amount\nFROM ranked\nWHERE rn = 1;\n```\n\nTests:\n```sql\n-- Correctness checks:\n-- 1) multiple rows per user\n-- 2) identical timestamps require deterministic tie-breaker\n-- 3) null values handled by business rules\n```\n\nVerification:\n- `run migration checks`\n- `run query correctness cases`\n\nEngineering notes:\n- Language: SQL\n- Framework/tooling: PostgreSQL\n- Stack context: Airflow, dbt, DuckDB, MinIO, pytest\n- Domain: search service\n- Task type: architecture_patch\n- Difficulty: hard\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: Repository domain: model serving gateway\nPrimary language: SQL\nFramework/tooling: PostgreSQL\nReported problem: optimistic locking conflict\nTask type: feature_delivery\nDifficulty: hard\n\nProduce a complete professional engineering response:\n1. Diagnose the root cause.\n2. Provide the corrected implementation or patch.\n3. Add tests.\n4. Add verification commands.\n5. Note edge cases and any migration or rollback risk.\n\nRepository sketch:\nrepo/\n migrations/\n 001_init.sql\n 002_add_index.sql\n queries/\n report.sql\n tests/\n report_cases.md\n\nQuality target:\n- Minimal diff unless redesign is clearly required\n- Production-ready code\n- No placeholders\n- Secure defaults\n- Clear acceptance of failure cases\n\nFocus: Focus on complete implementation quality, patch correctness, tests, and production readiness.\n\nassistant: Diagnosis:\n- Root cause: the failure around optimistic locking conflict is caused by missing validation, weak edge-case handling, or unsafe lifecycle behavior in the current implementation.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```sql\nWITH ranked AS (\n SELECT\n user_id,\n created_at,\n amount,\n ROW_NUMBER() OVER (PARTITION BY user_id ORDER BY created_at DESC, id DESC) AS rn\n FROM orders\n)\nSELECT user_id, created_at, amount\nFROM ranked\nWHERE rn = 1;\n```\n\nTests:\n```sql\n-- Correctness checks:\n-- 1) multiple rows per user\n-- 2) identical timestamps require deterministic tie-breaker\n-- 3) null values handled by business rules\n```\n\nVerification:\n- `run migration checks`\n- `run query correctness cases`\n\nEngineering notes:\n- Language: SQL\n- Framework/tooling: PostgreSQL\n- Stack context: Airflow, dbt, DuckDB, MinIO, pytest\n- Domain: model serving gateway\n- Task type: feature_delivery\n- Difficulty: hard\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "Optimize a Python workflow for report generation.\nRequirements: provide an optimized implementation and a small benchmark harness.\nConstraints: must include tests, stdlib-only, must be easy to extend, must handle Windows paths safely.\nDifficulty: hard. Provide helpful exceptions with actionable messages.\n\nDeliverable: implementation + tests.\nStrategy:\n- Avoid repeated parsing; precompile regex if needed; use local variables; stream processing.\n\n```python\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom typing import Iterable\nimport time\n\n@dataclass(frozen=True, slots=True)\nclass Stats:\n count: int\n total: int\n\ndef compute_stats_stream(values: Iterable[int]) -> Stats:\n c = 0\n t = 0\n for v in values:\n c += 1\n t += v\n return Stats(c, t)\n\ndef bench(n: int = 1_000_00) -> float:\n data = range(n)\n t0 = time.perf_counter()\n _ = compute_stats_stream(data)\n return time.perf_counter() - t0\n```\n\n```python\nfrom module_under_test import bench\ndef test_bench_runs_fast_enough():\n # Sanity: should run quickly on typical machines; adjust threshold for CI.\n assert bench(50_000) < 0.5\n```", "source": "WithinUsAI/python_GOD_coder_100k"} {"text": "Task type: query_optimizer\nScenario: job scheduler\nDomain focus: kernel primitives\nPrimary language: bash\nDifficulty: expert+\nScale/SLO: 1M msgs/min\nComponent: component_ctppcgzi\nConstraints: include verification strategy, assume adversarial inputs; validate everything, include performance model and limits, avoid data races and undefined behavior, include deterministic replay plan\nAssume weekly network partitions.\nDeliverable: Design a cost-based optimizer slice: logical rules, physical operators, and cost model. Include regression tests and query-plan explain examples.\n\nOutput: rigorous design + invariants + verification plan + implementation sketch.\n**Contract**\n- Inputs validated at the boundary; explicit error taxonomy.\n- Idempotency for side effects via request_id; deterministic replay.\n- Backward compatibility: additive changes by default; versioned breaking changes.\n**Invariants**\n- Determinism: replay of the same event log yields identical outputs.\n- Safety: state transitions preserve invariants; no partial commit leaks.\n- Liveness: under bounded faults and stable network, progress occurs.\n**Failure modes & recovery**\n- Crash during commit: WAL replay completes or transaction aborts; no torn writes.\n- Network partition: minority cannot commit; clients receive retriable errors.\n- Data corruption: checksums + scrubber; quarantine and rebuild from replicas/snapshots.\n**Security posture (defensive)**\n- Threat model: auth/authz, injection, replay/abuse, supply chain.\n- Least privilege; secrets in managed store; audit logs for sensitive ops.\n- Input normalization, parameterized queries, path traversal protections.\n**Verification strategy**\n- Property tests against a pure reference model (state machine).\n- Fuzzing of parsers/framers/validators with corpus seeds.\n- Canary + shadow traffic; invariants checked in production via assertions/metrics.\n\n**Snippet**\n```python\n# Minimal cost model skeleton\nfrom dataclasses import dataclass\n\n@dataclass(frozen=True)\nclass Plan:\n op: str\n cost: float\n children: tuple[\"Plan\", ...] = ()\n\ndef choose_best(plans: list[Plan]) -> Plan:\n return min(plans, key=lambda p: p.cost)\n```\n\nExpert+ checks: mechanized invariants (or exhaustive model checking), adversarial fuzzing, and multi-region failure drills.", "source": "WithinUsAI/Omega_Genesis_Coder_100k"} {"text": "Optimize while preserving behavior and order.\n\n```python\ndef f56498(xs):\n out=[]\n for x in xs:\n if x not in out: out.append(x)\n return out\n```\nReturn `m65214.py` with types and O(n) average.\n\n```python\n# m65214.py\nfrom __future__ import annotations\nfrom typing import Iterable, List, Set, TypeVar\nT=TypeVar(\"T\")\n\ndef f56498(xs: Iterable[T]) -> List[T]:\n \"\"\"Unique items preserving first-seen order.\"\"\"\n seen: Set[T]=set()\n out: List[T]=[]\n for x in xs:\n if x in seen: continue\n seen.add(x); out.append(x)\n return out\n```", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Fix a bug and add tests.\n\nFile: eyzofdngn5.py\n```python\ndef usatgoz6xj(n: int) -> int:\n \"\"\"Sum 1..n inclusive.\"\"\"\n if n < 0:\n raise ValueError(\"n must be non-negative\")\n total = 0\n for k in range(n): # BUG: should include n\n total += k\n return total\n```\n\nReturn unified diffs for eyzofdngn5.py and test_eyzofdngn5.py (pytest).\n\n*** Begin Patch\n*** Update File: eyzofdngn5.py\n@@\n def usatgoz6xj(n: int) -> int:\n@@\n total = 0\n- for k in range(n): # BUG: should include n\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_eyzofdngn5.py\n+import pytest\n+from eyzofdngn5 import usatgoz6xj\n+\n+def test_zero():\n+ assert usatgoz6xj(0) == 0\n+\n+def test_one():\n+ assert usatgoz6xj(1) == 1\n+\n+def test_small():\n+ assert usatgoz6xj(7) == 28\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ usatgoz6xj(-1)\n+\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Fix a subtle bug in a Python module used for event dispatching.\nRequirements: explain root cause briefly, provide corrected code, and add regression tests.\nConstraints: must include docstrings, must provide clear error messages.\nDifficulty: medium. Provide helpful exceptions with actionable messages.\n\nDeliverable: corrected code and verification tests.\n```python\nfrom __future__ import annotations\n\nfrom dataclasses import dataclass\nfrom pathlib import Path\nfrom typing import Iterable\nimport json\n\n\nclass ValidationError(ValueError):\n \"\"\"Raised when input validation fails.\"\"\"\n\n\ndef safe_join(base: Path, *parts: str) -> Path:\n \"\"\"Join paths while preventing traversal outside base.\"\"\"\n b = base.resolve()\n p = (b / Path(*parts)).resolve()\n if p != b and b not in p.parents:\n raise ValidationError(f\"unsafe path: {p}\")\n return p\n\n\n@dataclass(frozen=True, slots=True)\nclass Record:\n key: str\n value: int\n\n\ndef parse_jsonl(lines: Iterable[str]) -> list[Record]:\n out: list[Record] = []\n for idx, line in enumerate(lines, 1):\n s = line.strip()\n if not s:\n continue\n try:\n obj = json.loads(s)\n except json.JSONDecodeError as e:\n raise ValidationError(f\"line {idx}: invalid json\") from e\n if not isinstance(obj, dict):\n raise ValidationError(f\"line {idx}: expected object\")\n key = obj.get(\"key\")\n val = obj.get(\"value\")\n if not isinstance(key, str) or not key:\n raise ValidationError(f\"line {idx}: key must be non-empty str\")\n if not isinstance(val, int):\n raise ValidationError(f\"line {idx}: value must be int\")\n out.append(Record(key, val))\n return out\n\n\ndef write_jsonl(base: Path, rel: str, records: Iterable[Record]) -> Path:\n base.mkdir(parents=True, exist_ok=True)\n dst = safe_join(base, rel)\n dst.parent.mkdir(parents=True, exist_ok=True)\n with dst.open(\"w\", encoding=\"utf-8\", newline=\"\\n\") as f:\n for r in records:\n f.write(json.dumps({\"key\": r.key, \"value\": r.value}, ensure_ascii=False) + \"\\n\")\n return dst\n```\n\n```python\n# tests (pytest-style)\nimport json\nfrom pathlib import Path\nimport pytest\nfrom module_under_test import ValidationError, Record, parse_jsonl, write_jsonl\n\ndef test_parse_ok():\n lines = [json.dumps({\"key\":\"a\",\"value\":1}), json.dumps({\"key\":\"b\",\"value\":2})]\n assert parse_jsonl(lines) == [Record(\"a\",1), Record(\"b\",2)]\n\ndef test_parse_rejects_bad_json():\n with pytest.raises(ValidationError):\n parse_jsonl([\"{not json}\"])\n\ndef test_safe_join_blocks_traversal(tmp_path: Path):\n with pytest.raises(ValidationError):\n write_jsonl(tmp_path, \"../x.jsonl\", [Record(\"a\",1)])\n```", "source": "WithinUsAI/python_GOD_coder_100k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Fix a bug and add tests.\n\nFile: e5t0ltcps.py\n```python\ndef jvw4l3q_2vnz(n: int) -> int:\n \"\"\"Sum 1..n inclusive.\"\"\"\n if n < 0:\n raise ValueError(\"n must be non-negative\")\n total = 0\n for k in range(n): # BUG: should include n\n total += k\n return total\n```\n\nReturn unified diffs for e5t0ltcps.py and test_e5t0ltcps.py (pytest).\n\n*** Begin Patch\n*** Update File: e5t0ltcps.py\n@@\n def jvw4l3q_2vnz(n: int) -> int:\n@@\n total = 0\n- for k in range(n): # BUG: should include n\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_e5t0ltcps.py\n+import pytest\n+from e5t0ltcps import jvw4l3q_2vnz\n+\n+def test_zero():\n+ assert jvw4l3q_2vnz(0) == 0\n+\n+def test_one():\n+ assert jvw4l3q_2vnz(1) == 1\n+\n+def test_small():\n+ assert jvw4l3q_2vnz(7) == 28\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ jvw4l3q_2vnz(-1)\n+\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Build an elite-grade solution in the domain of edge/IoT for scenario: analytics pipeline.\nPrimary language: rust.\nDifficulty: expert.\nConstraints: include tests or verification strategy, include invariants and failure modes, make the interface contract explicit, provide rollout and rollback guidance, assume untrusted inputs; validate and sanitize.\nComponent: component_uyyqdgv.\nAssume crash-only design; recovery must be deterministic.\nTask: Define a small DSL, implement tokenizer/parser, IR, and a codegen or interpreter. Include tests and complexity notes.\n\nOutput: elite-grade engineering answer with contracts, edge cases, and verification.\nOutput: DSL + parser + IR + interpreter/codegen + tests.\n\n**DSL**\n- Expressions: integers, identifiers, `+ - * /`, let-binding: `let x = expr in expr`\n- Example: `let x = 2+3 in x*10`\n\n**Pipeline**\n1. Tokenize\n2. Parse into AST\n3. Lower into IR (stack ops) or interpret AST directly\n\n**Reference (Rust-style outline)**\n- `enum Expr { Int(i64), Var(String), Bin(Op, Box, Box), Let(String, Box, Box) }`\n- Parser: Pratt or recursive descent.\n\n**Tests**\n- Golden tests for parse trees.\n- Property: pretty-print(parse(x)) round-trips for a corpus.\n- Eval tests for precedence and scoping.\n\n\nExpert checks: state-machine reasoning, concurrency stress, and upgrade/rollback validated.", "source": "WithinUsAI/Elite_GOD_Coder_100k"} {"text": "Optimize a Python workflow for task scheduling.\nRequirements: provide an optimized implementation and a small benchmark harness.\nConstraints: must avoid global state, stdlib-only.\nDifficulty: medium. Provide helpful exceptions with actionable messages.\n\nDeliverable: production-ready reference solution.\nStrategy:\n- Avoid repeated parsing; precompile regex if needed; use local variables; stream processing.\n\n```python\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom typing import Iterable\nimport time\n\n@dataclass(frozen=True, slots=True)\nclass Stats:\n count: int\n total: int\n\ndef compute_stats_stream(values: Iterable[int]) -> Stats:\n c = 0\n t = 0\n for v in values:\n c += 1\n t += v\n return Stats(c, t)\n\ndef bench(n: int = 1_000_00) -> float:\n data = range(n)\n t0 = time.perf_counter()\n _ = compute_stats_stream(data)\n return time.perf_counter() - t0\n```\n\n```python\nfrom module_under_test import bench\ndef test_bench_runs_fast_enough():\n # Sanity: should run quickly on typical machines; adjust threshold for CI.\n assert bench(50_000) < 0.5\n```", "source": "WithinUsAI/python_GOD_coder_100k"} {"text": "Refactor a Python module used for ETL pipelines into a clean, extensible design.\nRequirements: outline the new architecture briefly, then provide the refactored code and tests.\nConstraints: must include docstrings, must include tests, must be streaming-friendly, must handle Windows paths safely.\nDifficulty: expert. Handle empty inputs and malformed records gracefully.\n\nDeliverable: implementation + tests.\nArchitecture:\n- Public facade class coordinating concerns (parsing, validation, persistence)\n- Small pure functions for testability\n- No global state; dependency injection for filesystem I/O\n\n```python\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom pathlib import Path\nfrom typing import Protocol, Iterable\nimport json\n\nclass Store(Protocol):\n def write_text(self, path: Path, data: str) -> None: ...\n\nclass FSStore:\n def write_text(self, path: Path, data: str) -> None:\n path.parent.mkdir(parents=True, exist_ok=True)\n path.write_text(data, encoding=\"utf-8\")\n\n@dataclass(frozen=True, slots=True)\nclass Item:\n name: str\n qty: int\n\ndef parse_items(lines: Iterable[str]) -> list[Item]:\n out: list[Item] = []\n for i, line in enumerate(lines, 1):\n s = line.strip()\n if not s:\n continue\n obj = json.loads(s)\n if not isinstance(obj, dict):\n raise ValueError(f\"line {i}: expected object\")\n name = obj.get(\"name\")\n qty = obj.get(\"qty\")\n if not isinstance(name, str) or not name:\n raise ValueError(f\"line {i}: name must be str\")\n if not isinstance(qty, int) or qty < 0:\n raise ValueError(f\"line {i}: qty must be non-negative int\")\n out.append(Item(name, qty))\n return out\n\nclass InventoryWriter:\n def __init__(self, base_dir: Path, store: Store | None = None) -> None:\n self._base = base_dir\n self._store: Store = store or FSStore()\n\n def write(self, rel_path: str, items: list[Item]) -> Path:\n dst = (self._base / rel_path).resolve()\n base = self._base.resolve()\n if dst != base and base not in dst.parents:\n raise ValueError(\"unsafe path traversal\")\n payload = json.dumps([item.__dict__ for item in items], ensure_ascii=False)\n self._store.write_text(dst, payload)\n return dst\n```\n\n```python\nimport json\nfrom pathlib import Path\nimport pytest\nfrom module_under_test import InventoryWriter, parse_items\n\ndef test_parse_items_valid():\n lines = [json.dumps({\"name\":\"x\",\"qty\":1})]\n assert parse_items(lines)[0].name == \"x\"\n\ndef test_writer_blocks_traversal(tmp_path: Path):\n w = InventoryWriter(tmp_path)\n with pytest.raises(ValueError):\n w.write(\"../evil.json\", [])\n```", "source": "WithinUsAI/python_GOD_coder_100k"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: Language: C++\nFramework/tooling: Catch2\nDomain: search service\nLogic challenge: broken pagination cursor\nTask type: performance_bottleneck_patch\nDifficulty: hard\n\nReturn a rigorous engineering answer:\n- identify the hidden root cause or logical failure\n- present the corrected implementation\n- add tests that prove the fix\n- list verification commands\n- explain why naive fixes are insufficient when relevant\n\nRepository sketch:\nrepo/\n src/main.cpp\n src/service.cpp\n include/service.h\n tests/test_service.cpp\n CMakeLists.txt\n\nFocus: Focus on ambiguity, misleading symptoms, hidden root causes, and high-stakes debugging.\n\nassistant: Diagnosis:\n- Hidden root cause: broken pagination cursor presents misleading symptoms, so the patch must target the actual logic boundary rather than the first visible failure.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```cpp\n#include \n#include \n\nusing Payload = std::unordered_map;\n\nPayload normalize_payload(const Payload& in) {\n Payload out;\n for (const auto& [k, v] : in) {\n if (!v.empty()) out[k] = v;\n }\n return out;\n}\n```\n\nTests:\n```cpp\nTEST_CASE(\"normalize_payload filters empty values\") {\n Payload in{{\"id\",\"7\"},{\"name\",\"\"}};\n auto out = normalize_payload(in);\n REQUIRE(out.count(\"id\") == 1);\n REQUIRE(out.count(\"name\") == 0);\n}\n```\n\nVerification:\n- `cmake --build build`\n- `ctest --test-dir build`\n\nEngineering notes:\n- Language: C++\n- Framework/tooling: Catch2\n- Stack context: ASP.NET Core, SQL Server, EF Core, xUnit, Docker\n- Domain: search service\n- Task type: performance_bottleneck_patch\n- Difficulty: hard\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "Build an elite-grade solution in the domain of sre/observability for scenario: event ingestion.\nPrimary language: sql.\nDifficulty: medium.\nConstraints: include tests or verification strategy, provide rollout and rollback guidance, assume untrusted inputs; validate and sanitize, document performance characteristics, include invariants and failure modes.\nComponent: component_gwxwwra.\nAssume cold-start and memory limits are tight.\nTask: Provide threat model, secure-by-default design, and defensive implementation patterns. No offensive/exploit content; focus on prevention and detection.\n\nOutput: rigorous solution with invariants, failure modes, and performance notes.\nOutput: threat model + defensive design + detection.\n\n**Threat model**\n- Auth: token theft → short-lived tokens, rotation, audience checks\n- AuthZ: privilege escalation → centralized policy checks, tenant isolation tests\n- Input: injection → strict validation, parameterized queries, output encoding\n- Supply chain: dependencies → lockfiles, signature verification, SBOM\n\n**Defensive patterns**\n- Idempotency keys for side effects; replay-safe handlers\n- Secrets in managed store; never logs\n- Audit logging for sensitive ops; tamper-evident storage\n\n**Detection**\n- Alert on unusual auth failures, access pattern anomalies, and data exfil signals.\n\n\nChecks: boundary validation and deterministic behavior verified.", "source": "WithinUsAI/Elite_GOD_Coder_100k"} {"text": "Fix the bug and add pytest tests.\n\n```python\ndef f52629(n: int) -> int:\n # sum 1..n inclusive\n if n < 0: raise ValueError\n total = 0\n for k in range(n): # BUG\n total += k\n return total\n```\nReturn unified diffs for `m78947.py` and `test_m78947.py`.\n\n*** Begin Patch\n*** Update File: m78947.py\n@@\n def f52629(n: int) -> int:\n@@\n- for k in range(n): # BUG\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_m78947.py\n+import pytest\n+from m78947 import f52629\n+\n+def test_small():\n+ assert f52629(7) == 28\n+\n+def test_zero():\n+ assert f52629(0) == 0\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ f52629(-1)\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: Project stack: ASP.NET Core, SQL Server, EF Core, xUnit, Docker\nLanguage: TypeScript\nDependency challenge: rate-limit bypass\nTask type: migration_patch\nDifficulty: medium\n\nFix this as a senior engineer.\nRequired:\n- identify the version or compatibility failure mode\n- produce the corrected config/code/build patch\n- explain rollback-safe migration notes\n- add regression tests or reproducibility checks\n- include concrete verification commands\n\nRepository sketch:\nrepo/\n src/\n api.ts\n service.ts\n schema.ts\n tests/\n api.test.ts\n package.json\n\nFocus: Focus on versioning, migrations, lockfiles, runtime compatibility, and secure dependency handling.\n\nassistant: Diagnosis:\n- Root cause: the issue around rate-limit bypass is a dependency, migration, or runtime-compatibility mismatch that needs a rollback-safe patch.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```ts\ntype Payload = Record;\n\nexport function normalizePayload(payload: Payload): Payload {\n if (!payload || typeof payload !== \"object\" || Array.isArray(payload)) {\n throw new TypeError(\"payload must be a plain object\");\n }\n return Object.fromEntries(\n Object.entries(payload)\n .filter(([, value]) => value !== null && value !== undefined)\n .map(([key, value]) => [String(key).trim(), value])\n );\n}\n\nexport function handleRateLimitBypass(payload: Payload) {\n const clean = normalizePayload(payload);\n if (!(\"id\" in clean)) {\n return { ok: false, data: {}, error: \"missing id\" };\n }\n return { ok: true, data: clean, error: null };\n}\n```\n\nTests:\n```ts\nimport { describe, it, expect } from \"vitest\";\nimport { handleRateLimitBypass } from \"../src/service\";\n\ndescribe(\"handler\", () => {\n it(\"accepts valid input\", () => {\n expect(handleRateLimitBypass({ id: 7, name: \"ok\", unused: null })).toEqual({\n ok: true,\n data: { id: 7, name: \"ok\" },\n error: null\n });\n });\n\n it(\"rejects missing id\", () => {\n expect(handleRateLimitBypass({ name: \"x\" }).error).toMatch(/missing id/);\n });\n});\n```\n\nVerification:\n- `npm test`\n- `npm run typecheck`\n- `npm run lint`\n\nEngineering notes:\n- Language: TypeScript\n- Framework/tooling: NestJS\n- Stack context: ASP.NET Core, SQL Server, EF Core, xUnit, Docker\n- Domain: observability collector\n- Task type: migration_patch\n- Difficulty: medium\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "Build an elite-grade solution in the domain of stream processing for scenario: time-series metrics.\nPrimary language: go.\nDifficulty: medium.\nConstraints: provide rollout and rollback guidance, include tests or verification strategy, include invariants and failure modes, document performance characteristics, design for backward compatibility and migrations.\nComponent: component_zvrcszy.\nAssume cold-start and memory limits are tight.\nTask: Write a precise interface contract, list invariants, and provide a lightweight formal/spec-style description (pseudo-TLA+/state machine) plus reference implementation skeleton and tests.\n\nOutput: production blueprint plus correctness arguments and test strategy.\nOutput: contract + invariants + spec + reference skeleton.\n\n**Interface contract**\n- Commands: `Put(key, value, expected_version?)`, `Get(key)`, `Delete(key, expected_version?)`\n- Responses: `Ok(version, value?)`, `NotFound`, `Conflict(current_version)`, `InvalidInput`\n- Idempotency: client supplies `request_id`; server must de-duplicate per (tenant_id, request_id).\n\n**Invariants**\n1. Monotonic version per key (strictly increases on successful writes).\n2. Reads return latest committed value for a given consistency level.\n3. Exactly-once effect for a given `request_id` (at-most-once execution + replay response).\n4. Tenant isolation: keys are scoped by tenant_id.\n\n**State machine (pseudo)**\nState:\n- store: map[(tenant,key)] -> (version:int, value:bytes|tombstone)\n- seen: map[(tenant,request_id)] -> response\nTransition Put:\n- if request_id in seen: return seen[...]\n- validate input; if expected_version set and != current version -> Conflict\n- version' = version + 1; store[...] := (version', value); seen[...] := Ok(version', value)\n\n**Reference skeleton (Python)**\n```python\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom typing import Dict, Optional, Tuple\n\nclass Conflict(Exception): pass\nclass InvalidInput(ValueError): pass\n\n@dataclass(frozen=True, slots=True)\nclass Value:\n version: int\n data: Optional[bytes] # None == tombstone\n\n@dataclass(frozen=True, slots=True)\nclass Reply:\n kind: str\n version: Optional[int] = None\n data: Optional[bytes] = None\n\nclass KV:\n def __init__(self) -> None:\n self._store: Dict[Tuple[str,str], Value] = {}\n self._seen: Dict[Tuple[str,str], Reply] = {}\n\n def put(self, tenant: str, request_id: str, key: str, data: bytes, expected_version: Optional[int]=None) -> Reply:\n if not tenant or not request_id or not key:\n raise InvalidInput(\"tenant/request_id/key required\")\n de = self._seen.get((tenant, request_id))\n if de: \n return de\n cur = self._store.get((tenant, key), Value(0, None))\n if expected_version is not None and expected_version != cur.version:\n r = Reply(\"conflict\", version=cur.version)\n self._seen[(tenant, request_id)] = r\n return r\n nxt = Value(cur.version + 1, data)\n self._store[(tenant, key)] = nxt\n r = Reply(\"ok\", version=nxt.version)\n self._seen[(tenant, request_id)] = r\n return r\n```\n\n**Tests**\n- Determinism: same request_id → same reply.\n- Conflict detection and version monotonicity.\n\n\nChecks: boundary validation and deterministic behavior verified.", "source": "WithinUsAI/Elite_GOD_Coder_100k"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: Project domain: auth service\nImplementation stack: Go, Gin, PostgreSQL, gRPC, Prometheus, Docker\nSoftware delivery problem: gRPC retry storm\nTask type: architecture_patch\nDifficulty: hard\n\nReturn a complete delivery-grade response with:\n- diagnosis or design reasoning\n- implementation\n- test plan or tests\n- rollout plan\n- rollback or compatibility note\n- verification commands\n\nRepository sketch:\nrepo/\n src/main/java/com/acme/App.java\n src/main/java/com/acme/Service.java\n src/test/java/com/acme/AppTest.java\n pom.xml\n\nFocus: Focus on shipping production software with rollout safety, acceptance criteria, telemetry, and maintenance quality.\n\nassistant: Diagnosis:\n- Root cause or delivery blocker: gRPC retry storm needs both implementation work and a safe shipping plan.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```java\nimport java.util.HashMap;\nimport java.util.Map;\n\npublic final class RequestHandler {\n public static Map handleRequest(Map payload) {\n Map clean = new HashMap<>();\n for (Map.Entry entry : payload.entrySet()) {\n if (entry.getValue() != null) clean.put(entry.getKey().trim(), entry.getValue());\n }\n if (!clean.containsKey(\"id\")) throw new IllegalArgumentException(\"missing id\");\n return Map.of(\"ok\", true, \"data\", clean);\n }\n}\n```\n\nTests:\n```java\nimport static org.junit.jupiter.api.Assertions.*;\nimport java.util.Map;\nimport org.junit.jupiter.api.Test;\n\nclass RequestHandlerTest {\n @Test\n void requiresId() {\n assertThrows(IllegalArgumentException.class, () -> RequestHandler.handleRequest(Map.of(\"name\", \"x\")));\n }\n}\n```\n\nVerification:\n- `./gradlew test`\n- `mvn test`\n\nEngineering notes:\n- Language: Java\n- Framework/tooling: Gradle\n- Stack context: Go, Gin, PostgreSQL, gRPC, Prometheus, Docker\n- Domain: auth service\n- Task type: architecture_patch\n- Difficulty: hard\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "Write a thorough test suite for a Python component used for report generation.\nRequirements: cover edge cases, invalid inputs, and behavior invariants.\nConstraints: must be streaming-friendly, must avoid global state.\nDifficulty: hard. Provide helpful exceptions with actionable messages.\n\nDeliverable: API + reference implementation + tests.\n```python\n# tests (pytest-style) for a module providing: normalize(), parse_lines(), compute_stats()\nimport math\nimport pytest\n\ndef test_normalize_idempotent(module_under_test):\n x = \" A\\tB \"\n assert module_under_test.normalize(module_under_test.normalize(x)) == module_under_test.normalize(x)\n\ndef test_parse_lines_rejects_invalid(module_under_test):\n with pytest.raises(ValueError):\n module_under_test.parse_lines([\"\", \"???\", None]) # type: ignore[arg-type]\n\ndef test_compute_stats_basic(module_under_test):\n data = [1, 2, 3, 4]\n s = module_under_test.compute_stats(data)\n assert s.count == 4\n assert s.total == 10\n assert math.isclose(s.mean, 2.5)\n```", "source": "WithinUsAI/python_GOD_coder_100k"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: Project stack: GitHub Actions, Docker Compose, Kubernetes, Terraform\nLanguage: C#\nDependency challenge: unsafe deserialization\nTask type: version_conflict_resolution\nDifficulty: medium\n\nFix this as a senior engineer.\nRequired:\n- identify the version or compatibility failure mode\n- produce the corrected config/code/build patch\n- explain rollback-safe migration notes\n- add regression tests or reproducibility checks\n- include concrete verification commands\n\nRepository sketch:\nrepo/\n src/App/Program.cs\n src/App/Service.cs\n tests/App.Tests/ServiceTests.cs\n App.sln\n\nFocus: Focus on versioning, migrations, lockfiles, runtime compatibility, and secure dependency handling.\n\nassistant: Diagnosis:\n- Root cause: the issue around unsafe deserialization is a dependency, migration, or runtime-compatibility mismatch that needs a rollback-safe patch.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```csharp\nusing System;\nusing System.Collections.Generic;\n\npublic static class RequestHandler\n{\n public static Dictionary HandleRequest(Dictionary payload)\n {\n var clean = new Dictionary();\n foreach (var entry in payload)\n {\n if (entry.Value != null)\n clean[entry.Key.Trim()] = entry.Value;\n }\n if (!clean.ContainsKey(\"id\"))\n throw new ArgumentException(\"missing id\");\n return new Dictionary\n {\n [\"ok\"] = true,\n [\"data\"] = clean\n };\n }\n}\n```\n\nTests:\n```csharp\nusing System;\nusing System.Collections.Generic;\nusing Xunit;\n\npublic class RequestHandlerTests\n{\n [Fact]\n public void RequiresId()\n {\n Assert.Throws(() => RequestHandler.HandleRequest(new Dictionary { [\"name\"] = \"x\" }));\n }\n}\n```\n\nVerification:\n- `dotnet test`\n- `dotnet build`\n\nEngineering notes:\n- Language: C#\n- Framework/tooling: ASP.NET Core\n- Stack context: GitHub Actions, Docker Compose, Kubernetes, Terraform\n- Domain: payments platform\n- Task type: version_conflict_resolution\n- Difficulty: medium\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "Add a clear docstring and type hints to this function:\n\n```python\ndef f03742(s):\n return ''.join(x for x in s if x.isalnum()).lower()\n```\n\n```python\nfrom __future__ import annotations\n\ndef f03742(s: str) -> str:\n \"\"\"Normalize a string: keep only alphanumerics and lowercase the result.\"\"\"\n return \"\".join(ch for ch in s if ch.isalnum()).lower()\n```", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Optimize a Python workflow for parsing.\nRequirements: provide an optimized implementation and a small benchmark harness.\nConstraints: must provide clear error messages, must be memory-efficient, must include tests.\nDifficulty: medium. Guarantee deterministic output ordering.\n\nDeliverable: corrected code and verification tests.\nStrategy:\n- Avoid repeated parsing; precompile regex if needed; use local variables; stream processing.\n\n```python\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom typing import Iterable\nimport time\n\n@dataclass(frozen=True, slots=True)\nclass Stats:\n count: int\n total: int\n\ndef compute_stats_stream(values: Iterable[int]) -> Stats:\n c = 0\n t = 0\n for v in values:\n c += 1\n t += v\n return Stats(c, t)\n\ndef bench(n: int = 1_000_00) -> float:\n data = range(n)\n t0 = time.perf_counter()\n _ = compute_stats_stream(data)\n return time.perf_counter() - t0\n```\n\n```python\nfrom module_under_test import bench\ndef test_bench_runs_fast_enough():\n # Sanity: should run quickly on typical machines; adjust threshold for CI.\n assert bench(50_000) < 0.5\n```", "source": "WithinUsAI/python_GOD_coder_100k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Optimize while preserving behavior.\n\nFile: k3p3fy_dec.py\n```python\ndef a7b2s0lch4_3(xs):\n out = []\n for x in xs:\n if x not in out:\n out.append(x)\n return out\n```\n\nRequirements: preserve first-seen order; O(n) average; add types + docstring.\n\n# k3p3fy_dec.py\nfrom __future__ import annotations\nfrom typing import Iterable, List, Set, TypeVar\n\nT = TypeVar(\"T\")\n\ndef a7b2s0lch4_3(xs: Iterable[T]) -> List[T]:\n \"\"\"Return unique items preserving first-seen order.\"\"\"\n seen: Set[T] = set()\n out: List[T] = []\n for x in xs:\n if x in seen:\n continue\n seen.add(x)\n out.append(x)\n return out", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Fix a subtle bug in a Python module used for data modeling.\nRequirements: explain root cause briefly, provide corrected code, and add regression tests.\nConstraints: must handle Windows paths safely, must avoid global state, must include type hints, must be memory-efficient.\nDifficulty: hard. Include a small CLI example if relevant.\n\nDeliverable: API + reference implementation + tests.\n```python\nfrom __future__ import annotations\n\nfrom dataclasses import dataclass\nfrom pathlib import Path\nfrom typing import Iterable\nimport json\n\n\nclass ValidationError(ValueError):\n \"\"\"Raised when input validation fails.\"\"\"\n\n\ndef safe_join(base: Path, *parts: str) -> Path:\n \"\"\"Join paths while preventing traversal outside base.\"\"\"\n b = base.resolve()\n p = (b / Path(*parts)).resolve()\n if p != b and b not in p.parents:\n raise ValidationError(f\"unsafe path: {p}\")\n return p\n\n\n@dataclass(frozen=True, slots=True)\nclass Record:\n key: str\n value: int\n\n\ndef parse_jsonl(lines: Iterable[str]) -> list[Record]:\n out: list[Record] = []\n for idx, line in enumerate(lines, 1):\n s = line.strip()\n if not s:\n continue\n try:\n obj = json.loads(s)\n except json.JSONDecodeError as e:\n raise ValidationError(f\"line {idx}: invalid json\") from e\n if not isinstance(obj, dict):\n raise ValidationError(f\"line {idx}: expected object\")\n key = obj.get(\"key\")\n val = obj.get(\"value\")\n if not isinstance(key, str) or not key:\n raise ValidationError(f\"line {idx}: key must be non-empty str\")\n if not isinstance(val, int):\n raise ValidationError(f\"line {idx}: value must be int\")\n out.append(Record(key, val))\n return out\n\n\ndef write_jsonl(base: Path, rel: str, records: Iterable[Record]) -> Path:\n base.mkdir(parents=True, exist_ok=True)\n dst = safe_join(base, rel)\n dst.parent.mkdir(parents=True, exist_ok=True)\n with dst.open(\"w\", encoding=\"utf-8\", newline=\"\\n\") as f:\n for r in records:\n f.write(json.dumps({\"key\": r.key, \"value\": r.value}, ensure_ascii=False) + \"\\n\")\n return dst\n```\n\n```python\n# tests (pytest-style)\nimport json\nfrom pathlib import Path\nimport pytest\nfrom module_under_test import ValidationError, Record, parse_jsonl, write_jsonl\n\ndef test_parse_ok():\n lines = [json.dumps({\"key\":\"a\",\"value\":1}), json.dumps({\"key\":\"b\",\"value\":2})]\n assert parse_jsonl(lines) == [Record(\"a\",1), Record(\"b\",2)]\n\ndef test_parse_rejects_bad_json():\n with pytest.raises(ValidationError):\n parse_jsonl([\"{not json}\"])\n\ndef test_safe_join_blocks_traversal(tmp_path: Path):\n with pytest.raises(ValidationError):\n write_jsonl(tmp_path, \"../x.jsonl\", [Record(\"a\",1)])\n```", "source": "WithinUsAI/python_GOD_coder_100k"} {"text": "Fix the bug and add pytest tests.\n\n```python\ndef f97019(n: int) -> int:\n # sum 1..n inclusive\n if n < 0: raise ValueError\n total = 0\n for k in range(n): # BUG\n total += k\n return total\n```\nReturn unified diffs for `m56717.py` and `test_m56717.py`.\n\n*** Begin Patch\n*** Update File: m56717.py\n@@\n def f97019(n: int) -> int:\n@@\n- for k in range(n): # BUG\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_m56717.py\n+import pytest\n+from m56717 import f97019\n+\n+def test_small():\n+ assert f97019(7) == 28\n+\n+def test_zero():\n+ assert f97019(0) == 0\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ f97019(-1)\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: Repository domain: data pipeline\nPrimary language: C++\nFramework/tooling: Boost\nReported problem: log redaction failure\nTask type: feature_delivery\nDifficulty: hard\n\nProduce a complete professional engineering response:\n1. Diagnose the root cause.\n2. Provide the corrected implementation or patch.\n3. Add tests.\n4. Add verification commands.\n5. Note edge cases and any migration or rollback risk.\n\nRepository sketch:\nrepo/\n src/main.cpp\n src/service.cpp\n include/service.h\n tests/test_service.cpp\n CMakeLists.txt\n\nQuality target:\n- Minimal diff unless redesign is clearly required\n- Production-ready code\n- No placeholders\n- Secure defaults\n- Clear acceptance of failure cases\n\nFocus: Focus on complete implementation quality, patch correctness, tests, and production readiness.\n\nassistant: Diagnosis:\n- Root cause: the failure around log redaction failure is caused by missing validation, weak edge-case handling, or unsafe lifecycle behavior in the current implementation.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```cpp\n#include \n#include \n\nusing Payload = std::unordered_map;\n\nPayload normalize_payload(const Payload& in) {\n Payload out;\n for (const auto& [k, v] : in) {\n if (!v.empty()) out[k] = v;\n }\n return out;\n}\n```\n\nTests:\n```cpp\nTEST_CASE(\"normalize_payload filters empty values\") {\n Payload in{{\"id\",\"7\"},{\"name\",\"\"}};\n auto out = normalize_payload(in);\n REQUIRE(out.count(\"id\") == 1);\n REQUIRE(out.count(\"name\") == 0);\n}\n```\n\nVerification:\n- `cmake --build build`\n- `ctest --test-dir build`\n\nEngineering notes:\n- Language: C++\n- Framework/tooling: Boost\n- Stack context: Rust, Axum, SQLx, Redis, Tokio, Docker\n- Domain: data pipeline\n- Task type: feature_delivery\n- Difficulty: hard\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "Write a thorough test suite for a Python component used for rate limiting.\nRequirements: cover edge cases, invalid inputs, and behavior invariants.\nConstraints: must be memory-efficient, stdlib-only, must include tests.\nDifficulty: medium. Include a small CLI example if relevant.\n\nDeliverable: production-ready reference solution.\n```python\n# tests (pytest-style) for a module providing: normalize(), parse_lines(), compute_stats()\nimport math\nimport pytest\n\ndef test_normalize_idempotent(module_under_test):\n x = \" A\\tB \"\n assert module_under_test.normalize(module_under_test.normalize(x)) == module_under_test.normalize(x)\n\ndef test_parse_lines_rejects_invalid(module_under_test):\n with pytest.raises(ValueError):\n module_under_test.parse_lines([\"\", \"???\", None]) # type: ignore[arg-type]\n\ndef test_compute_stats_basic(module_under_test):\n data = [1, 2, 3, 4]\n s = module_under_test.compute_stats(data)\n assert s.count == 4\n assert s.total == 10\n assert math.isclose(s.mean, 2.5)\n```", "source": "WithinUsAI/python_GOD_coder_100k"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: Project stack: Spring Boot, PostgreSQL, JUnit, Gradle, Docker, GitHub Actions\nLanguage: Rust\nDependency challenge: streaming timeout handling\nTask type: container_runtime_fix\nDifficulty: medium\n\nFix this as a senior engineer.\nRequired:\n- identify the version or compatibility failure mode\n- produce the corrected config/code/build patch\n- explain rollback-safe migration notes\n- add regression tests or reproducibility checks\n- include concrete verification commands\n\nRepository sketch:\nrepo/\n src/main.rs\n src/lib.rs\n src/service.rs\n src/store.rs\n tests/integration.rs\n Cargo.toml\n\nFocus: Focus on versioning, migrations, lockfiles, runtime compatibility, and secure dependency handling.\n\nassistant: Diagnosis:\n- Root cause: the issue around streaming timeout handling is a dependency, migration, or runtime-compatibility mismatch that needs a rollback-safe patch.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```rust\nuse std::collections::HashMap;\n\npub fn normalize_payload(payload: HashMap) -> HashMap {\n payload\n .into_iter()\n .filter(|(_, v)| !v.trim().is_empty())\n .collect()\n}\n```\n\nTests:\n```rust\n#[test]\nfn normalize_payload_filters_empty_values() {\n use std::collections::HashMap;\n let mut payload = HashMap::new();\n payload.insert(\"id\".to_string(), \"7\".to_string());\n payload.insert(\"name\".to_string(), \"\".to_string());\n let out = normalize_payload(payload);\n assert!(out.contains_key(\"id\"));\n assert!(!out.contains_key(\"name\"));\n}\n```\n\nVerification:\n- `cargo test`\n- `cargo clippy -- -D warnings`\n\nEngineering notes:\n- Language: Rust\n- Framework/tooling: Tokio\n- Stack context: Spring Boot, PostgreSQL, JUnit, Gradle, Docker, GitHub Actions\n- Domain: notification service\n- Task type: container_runtime_fix\n- Difficulty: medium\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: Language: Go\nFramework/tooling: Fiber\nDomain: model serving gateway\nLogic challenge: schema drift during deployment\nTask type: performance_bottleneck_patch\nDifficulty: hard\n\nReturn a rigorous engineering answer:\n- identify the hidden root cause or logical failure\n- present the corrected implementation\n- add tests that prove the fix\n- list verification commands\n- explain why naive fixes are insufficient when relevant\n\nRepository sketch:\nrepo/\n cmd/server/main.go\n internal/service/service.go\n internal/store/store.go\n internal/api/api.go\n service_test.go\n go.mod\n\nFocus: Focus on ambiguity, misleading symptoms, hidden root causes, and high-stakes debugging.\n\nassistant: Diagnosis:\n- Hidden root cause: schema drift during deployment presents misleading symptoms, so the patch must target the actual logic boundary rather than the first visible failure.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```go\npackage service\n\nimport \"fmt\"\n\nfunc NormalizePayload(payload map[string]any) map[string]any {\n\tout := make(map[string]any)\n\tfor k, v := range payload {\n\t\tif v == nil {\n\t\t\tcontinue\n\t\t}\n\t\tout[k] = v\n\t}\n\treturn out\n}\n\nfunc Handle(payload map[string]any) (map[string]any, error) {\n\tclean := NormalizePayload(payload)\n\tif _, ok := clean[\"id\"]; !ok {\n\t\treturn nil, fmt.Errorf(\"missing id\")\n\t}\n\treturn map[string]any{\"ok\": true, \"data\": clean}, nil\n}\n```\n\nTests:\n```go\npackage service\n\nimport \"testing\"\n\nfunc TestHandle(t *testing.T) {\n\tgot, err := Handle(map[string]any{\"id\": 7, \"name\": \"ok\", \"unused\": nil})\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tif got[\"ok\"] != true {\n\t\tt.Fatalf(\"expected ok=true\")\n\t}\n\tif _, err := Handle(map[string]any{\"name\": \"x\"}); err == nil {\n\t\tt.Fatalf(\"expected missing id error\")\n\t}\n}\n```\n\nVerification:\n- `go test ./...`\n- `go vet ./...`\n\nEngineering notes:\n- Language: Go\n- Framework/tooling: Fiber\n- Stack context: FastAPI, PostgreSQL, Redis, Celery, pytest, Docker\n- Domain: model serving gateway\n- Task type: performance_bottleneck_patch\n- Difficulty: hard\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Refactor to modern typed Python with immutability and tests.\n\nFile: x8w1qaqx1x.py\n```python\nclass Opiprozuvn:\n def __init__(self, name, values):\n self.name = name\n self.values = list(values)\n def add(self, v):\n self.values.append(v)\n def mean(self):\n s = 0\n for x in self.values:\n s += x\n return s / len(self.values)\n```\n\nReturn full new x8w1qaqx1x.py and test_x8w1qaqx1x.py.\n\n# x8w1qaqx1x.py\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom typing import Iterable, Tuple\n\n@dataclass(frozen=True)\nclass Opiprozuvn:\n name: str\n values: Tuple[float, ...]\n\n @staticmethod\n def create(name: str, values: Iterable[float]) -> \"Opiprozuvn\":\n vals = tuple(float(v) for v in values)\n if not vals:\n raise ValueError(\"values must be non-empty\")\n return Opiprozuvn(name=name, values=vals)\n\n def add(self, v: float) -> \"Opiprozuvn\":\n return Opiprozuvn(name=self.name, values=self.values + (float(v),))\n\n def mean(self) -> float:\n return sum(self.values) / len(self.values)\n\n# test_x8w1qaqx1x.py\nimport pytest\nfrom x8w1qaqx1x import Opiprozuvn\n\ndef test_mean_and_add():\n c = Opiprozuvn.create(\"a\", [1, 2, 3])\n assert c.mean() == 2.0\n assert c.add(5).mean() == (1 + 2 + 3 + 5) / 4\n\ndef test_empty_raises():\n with pytest.raises(ValueError):\n Opiprozuvn.create(\"x\", [])", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: Repository domain: model serving gateway\nPrimary language: C++\nFramework/tooling: Boost\nReported problem: log redaction failure\nTask type: test_repair\nDifficulty: medium\n\nProduce a complete professional engineering response:\n1. Diagnose the root cause.\n2. Provide the corrected implementation or patch.\n3. Add tests.\n4. Add verification commands.\n5. Note edge cases and any migration or rollback risk.\n\nRepository sketch:\nrepo/\n src/main.cpp\n src/service.cpp\n include/service.h\n tests/test_service.cpp\n CMakeLists.txt\n\nQuality target:\n- Minimal diff unless redesign is clearly required\n- Production-ready code\n- No placeholders\n- Secure defaults\n- Clear acceptance of failure cases\n\nFocus: Focus on complete implementation quality, patch correctness, tests, and production readiness.\n\nassistant: Diagnosis:\n- Root cause: the failure around log redaction failure is caused by missing validation, weak edge-case handling, or unsafe lifecycle behavior in the current implementation.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```cpp\n#include \n#include \n\nusing Payload = std::unordered_map;\n\nPayload normalize_payload(const Payload& in) {\n Payload out;\n for (const auto& [k, v] : in) {\n if (!v.empty()) out[k] = v;\n }\n return out;\n}\n```\n\nTests:\n```cpp\nTEST_CASE(\"normalize_payload filters empty values\") {\n Payload in{{\"id\",\"7\"},{\"name\",\"\"}};\n auto out = normalize_payload(in);\n REQUIRE(out.count(\"id\") == 1);\n REQUIRE(out.count(\"name\") == 0);\n}\n```\n\nVerification:\n- `cmake --build build`\n- `ctest --test-dir build`\n\nEngineering notes:\n- Language: C++\n- Framework/tooling: Boost\n- Stack context: FastAPI, PostgreSQL, Redis, Celery, pytest, Docker\n- Domain: model serving gateway\n- Task type: test_repair\n- Difficulty: medium\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Optimize while preserving behavior.\n\nFile: qvsxp8t4zeek.py\n```python\ndef bc7mey3(xs):\n out = []\n for x in xs:\n if x not in out:\n out.append(x)\n return out\n```\n\nRequirements: preserve first-seen order; O(n) average; add types + docstring.\n\n# qvsxp8t4zeek.py\nfrom __future__ import annotations\nfrom typing import Iterable, List, Set, TypeVar\n\nT = TypeVar(\"T\")\n\ndef bc7mey3(xs: Iterable[T]) -> List[T]:\n \"\"\"Return unique items preserving first-seen order.\"\"\"\n seen: Set[T] = set()\n out: List[T] = []\n for x in xs:\n if x in seen:\n continue\n seen.add(x)\n out.append(x)\n return out", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Task type: compiler_frontend\nScenario: streaming ETL\nDomain focus: secure enclaves (defensive)\nPrimary language: rust\nDifficulty: expert+\nScale/SLO: p99 < 50ms\nComponent: component_meyeidhz\nConstraints: include backward compatibility and migration plan, include failure modes and recovery, explicit contracts and invariants, avoid data races and undefined behavior, include verification strategy\nAssume tight memory budget and cold-start constraints.\nDeliverable: Design a DSL language frontend: lexer/parser, AST, type checking, error reporting, and tests.\n\nOutput: elite engineering answer optimized for correctness, performance, and operability.\n**Contract**\n- Inputs validated at the boundary; explicit error taxonomy.\n- Idempotency for side effects via request_id; deterministic replay.\n- Backward compatibility: additive changes by default; versioned breaking changes.\n**Invariants**\n- Determinism: replay of the same event log yields identical outputs.\n- Isolation: tenant boundary enforced; no cross-tenant reads/writes.\n- Safety: state transitions preserve invariants; no partial commit leaks.\n**Failure modes & recovery**\n- Data corruption: checksums + scrubber; quarantine and rebuild from replicas/snapshots.\n- Duplicate requests: de-duplicate by (tenant, request_id) returning cached response.\n- Crash during commit: WAL replay completes or transaction aborts; no torn writes.\n**Security posture (defensive)**\n- Threat model: auth/authz, injection, replay/abuse, supply chain.\n- Least privilege; secrets in managed store; audit logs for sensitive ops.\n- Input normalization, parameterized queries, path traversal protections.\n**Verification strategy**\n- Deterministic simulation with fault injection (crash/partition/latency).\n- Canary + shadow traffic; invariants checked in production via assertions/metrics.\n- Property tests against a pure reference model (state machine).\n\n**Snippet**\n```text\nImplementation sketch: factor pure state-machine core; adapters for I/O; add deterministic replay log.\n```\nExpert+ checks: mechanized invariants (or exhaustive model checking), adversarial fuzzing, and multi-region failure drills.", "source": "WithinUsAI/Omega_Genesis_Coder_100k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Fix a bug and add tests.\n\nFile: abcuvw7.py\n```python\ndef u105gm(n: int) -> int:\n \"\"\"Sum 1..n inclusive.\"\"\"\n if n < 0:\n raise ValueError(\"n must be non-negative\")\n total = 0\n for k in range(n): # BUG: should include n\n total += k\n return total\n```\n\nReturn unified diffs for abcuvw7.py and test_abcuvw7.py (pytest).\n\n*** Begin Patch\n*** Update File: abcuvw7.py\n@@\n def u105gm(n: int) -> int:\n@@\n total = 0\n- for k in range(n): # BUG: should include n\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_abcuvw7.py\n+import pytest\n+from abcuvw7 import u105gm\n+\n+def test_zero():\n+ assert u105gm(0) == 0\n+\n+def test_one():\n+ assert u105gm(1) == 1\n+\n+def test_small():\n+ assert u105gm(7) == 28\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ u105gm(-1)\n+\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Provision infrastructure for a e-commerce workload providing role-based access control.\nTarget platform: data (SQL + Python).\nRequirements: IaC (Terraform or Kubernetes YAML), networking, secrets, autoscaling.\nConstraints: must avoid global state, must be production-ready, must include type hints where applicable, must include documentation/comments.\nDifficulty: easy. Assume GDPR-style deletion requests must be supported.\n\nOutput: design + implementation guidance suitable for shipping.\nDeliverable: Kubernetes deployment + basic security posture.\n\n```yaml\napiVersion: apps/v1\nkind: Deployment\nmetadata:\n name: app\nspec:\n replicas: 3\n selector:\n matchLabels: { app: app }\n template:\n metadata:\n labels: { app: app }\n spec:\n containers:\n - name: app\n image: app:latest\n ports: [{ containerPort: 8080 }]\n readinessProbe:\n httpGet: { path: /healthz, port: 8080 }\n resources:\n requests: { cpu: \"200m\", memory: \"256Mi\" }\n limits: { cpu: \"1\", memory: \"1Gi\" }\n```\n\nAdditions:\n- NetworkPolicy to restrict egress/ingress.\n- Secrets via external secret store; rotate regularly.\n- HPA for autoscaling; PodDisruptionBudget for availability.\n\n\nChecks: input validation, tests, and safe defaults included.", "source": "WithinUsAI/GOD_Coder_100k"} {"text": "Task type: secure_architecture\nScenario: feature-flag evaluation\nDomain focus: real-time scheduling\nPrimary language: go\nDifficulty: hard\nScale/SLO: multi-region active-active\nComponent: component_oxdssega\nConstraints: include verification strategy, avoid data races and undefined behavior, include test vectors and fuzz strategy, include security threat model (defensive only), include failure modes and recovery, include performance model and limits\nAssume schema changes every sprint; must be backward compatible.\nDeliverable: Provide a defensive threat model and secure-by-default architecture; include monitoring/detection and tests (no offensive content).\n\nOutput: contract-first solution with failure modes, security posture, and test/verification strategy.\n**Contract**\n- Inputs validated at the boundary; explicit error taxonomy.\n- Idempotency for side effects via request_id; deterministic replay.\n- Backward compatibility: additive changes by default; versioned breaking changes.\n**Invariants**\n- Liveness: under bounded faults and stable network, progress occurs.\n- Safety: state transitions preserve invariants; no partial commit leaks.\n- Isolation: tenant boundary enforced; no cross-tenant reads/writes.\n**Failure modes & recovery**\n- Data corruption: checksums + scrubber; quarantine and rebuild from replicas/snapshots.\n- Crash during commit: WAL replay completes or transaction aborts; no torn writes.\n- Duplicate requests: de-duplicate by (tenant, request_id) returning cached response.\n**Security posture (defensive)**\n- Threat model: auth/authz, injection, replay/abuse, supply chain.\n- Least privilege; secrets in managed store; audit logs for sensitive ops.\n- Input normalization, parameterized queries, path traversal protections.\n**Verification strategy**\n- Fuzzing of parsers/framers/validators with corpus seeds.\n- Canary + shadow traffic; invariants checked in production via assertions/metrics.\n- Deterministic simulation with fault injection (crash/partition/latency).\n\n**Snippet**\n```text\nImplementation sketch: factor pure state-machine core; adapters for I/O; add deterministic replay log.\n```\nHard checks: fault injection tests gate merges; perf thresholds enforced in CI.", "source": "WithinUsAI/Omega_Genesis_Coder_100k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Refactor to modern typed Python with immutability and tests.\n\nFile: sssbrd3iealm.py\n```python\nclass W2Rdoq5T:\n def __init__(self, name, values):\n self.name = name\n self.values = list(values)\n def add(self, v):\n self.values.append(v)\n def mean(self):\n s = 0\n for x in self.values:\n s += x\n return s / len(self.values)\n```\n\nReturn full new sssbrd3iealm.py and test_sssbrd3iealm.py.\n\n# sssbrd3iealm.py\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom typing import Iterable, Tuple\n\n@dataclass(frozen=True)\nclass W2Rdoq5T:\n name: str\n values: Tuple[float, ...]\n\n @staticmethod\n def create(name: str, values: Iterable[float]) -> \"W2Rdoq5T\":\n vals = tuple(float(v) for v in values)\n if not vals:\n raise ValueError(\"values must be non-empty\")\n return W2Rdoq5T(name=name, values=vals)\n\n def add(self, v: float) -> \"W2Rdoq5T\":\n return W2Rdoq5T(name=self.name, values=self.values + (float(v),))\n\n def mean(self) -> float:\n return sum(self.values) / len(self.values)\n\n# test_sssbrd3iealm.py\nimport pytest\nfrom sssbrd3iealm import W2Rdoq5T\n\ndef test_mean_and_add():\n c = W2Rdoq5T.create(\"a\", [1, 2, 3])\n assert c.mean() == 2.0\n assert c.add(5).mean() == (1 + 2 + 3 + 5) / 4\n\ndef test_empty_raises():\n with pytest.raises(ValueError):\n W2Rdoq5T.create(\"x\", [])", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Task type: mechanized_spec\nScenario: identity and access\nDomain focus: observability platforms\nPrimary language: lean\nDifficulty: expert+\nScale/SLO: 1M msgs/min\nComponent: component_mpogmjwj\nConstraints: include verification strategy, include performance model and limits, include security threat model (defensive only), explicit contracts and invariants, include test vectors and fuzz strategy, include deterministic replay plan, include backward compatibility and migration plan\nAssume schema changes every sprint; must be backward compatible.\nDeliverable: Provide a mechanized-style spec outline (Lean-like), key definitions, and a proof plan. Include executable reference code skeleton and tests.\n\nOutput: elite engineering answer optimized for correctness, performance, and operability.\n**Contract**\n- Inputs validated at the boundary; explicit error taxonomy.\n- Idempotency for side effects via request_id; deterministic replay.\n- Backward compatibility: additive changes by default; versioned breaking changes.\n**Invariants**\n- Safety: state transitions preserve invariants; no partial commit leaks.\n- Determinism: replay of the same event log yields identical outputs.\n- Liveness: under bounded faults and stable network, progress occurs.\n**Failure modes & recovery**\n- Duplicate requests: de-duplicate by (tenant, request_id) returning cached response.\n- Crash during commit: WAL replay completes or transaction aborts; no torn writes.\n- Data corruption: checksums + scrubber; quarantine and rebuild from replicas/snapshots.\n**Security posture (defensive)**\n- Threat model: auth/authz, injection, replay/abuse, supply chain.\n- Least privilege; secrets in managed store; audit logs for sensitive ops.\n- Input normalization, parameterized queries, path traversal protections.\n**Verification strategy**\n- Fuzzing of parsers/framers/validators with corpus seeds.\n- Property tests against a pure reference model (state machine).\n- Canary + shadow traffic; invariants checked in production via assertions/metrics.\n\n**Snippet**\n```lean\n-- Pseudo-Lean outline\nstructure State where\n ver : Nat\n val : Option ByteArray\n\ndef invariant (s : State) : Prop := True\n\ntheorem step_preserves_invariant :\n ∀ s, invariant s → ∀ s', Step s s' → invariant s' := by\n intro s hs s' hstep\n -- proof plan: case analysis on transition; trivial here\n trivial\n```\n\nExpert+ checks: mechanized invariants (or exhaustive model checking), adversarial fuzzing, and multi-region failure drills.", "source": "WithinUsAI/Omega_Genesis_Coder_100k"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: Language: Java\nFramework/tooling: JUnit\nDomain: team dashboard\nLogic challenge: async cancellation bug\nTask type: performance_bottleneck_patch\nDifficulty: hard\n\nReturn a rigorous engineering answer:\n- identify the hidden root cause or logical failure\n- present the corrected implementation\n- add tests that prove the fix\n- list verification commands\n- explain why naive fixes are insufficient when relevant\n\nRepository sketch:\nrepo/\n src/main/java/com/acme/App.java\n src/main/java/com/acme/Service.java\n src/test/java/com/acme/AppTest.java\n pom.xml\n\nFocus: Focus on ambiguity, misleading symptoms, hidden root causes, and high-stakes debugging.\n\nassistant: Diagnosis:\n- Hidden root cause: async cancellation bug presents misleading symptoms, so the patch must target the actual logic boundary rather than the first visible failure.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```java\nimport java.util.HashMap;\nimport java.util.Map;\n\npublic final class RequestHandler {\n public static Map handleRequest(Map payload) {\n Map clean = new HashMap<>();\n for (Map.Entry entry : payload.entrySet()) {\n if (entry.getValue() != null) clean.put(entry.getKey().trim(), entry.getValue());\n }\n if (!clean.containsKey(\"id\")) throw new IllegalArgumentException(\"missing id\");\n return Map.of(\"ok\", true, \"data\", clean);\n }\n}\n```\n\nTests:\n```java\nimport static org.junit.jupiter.api.Assertions.*;\nimport java.util.Map;\nimport org.junit.jupiter.api.Test;\n\nclass RequestHandlerTest {\n @Test\n void requiresId() {\n assertThrows(IllegalArgumentException.class, () -> RequestHandler.handleRequest(Map.of(\"name\", \"x\")));\n }\n}\n```\n\nVerification:\n- `./gradlew test`\n- `mvn test`\n\nEngineering notes:\n- Language: Java\n- Framework/tooling: JUnit\n- Stack context: Spring Boot, PostgreSQL, JUnit, Gradle, Docker, GitHub Actions\n- Domain: team dashboard\n- Task type: performance_bottleneck_patch\n- Difficulty: hard\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "Optimize while preserving behavior and order.\n\n```python\ndef f58541(xs):\n out=[]\n for x in xs:\n if x not in out: out.append(x)\n return out\n```\nReturn `m08363.py` with types and O(n) average.\n\n```python\n# m08363.py\nfrom __future__ import annotations\nfrom typing import Iterable, List, Set, TypeVar\nT=TypeVar(\"T\")\n\ndef f58541(xs: Iterable[T]) -> List[T]:\n \"\"\"Unique items preserving first-seen order.\"\"\"\n seen: Set[T]=set()\n out: List[T]=[]\n for x in xs:\n if x in seen: continue\n seen.add(x); out.append(x)\n return out\n```", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Refactor to modern typed Python with immutability and tests.\n\nFile: bcmfonjtl3xr.py\n```python\nclass L7Y1Xb7I:\n def __init__(self, name, values):\n self.name = name\n self.values = list(values)\n def add(self, v):\n self.values.append(v)\n def mean(self):\n s = 0\n for x in self.values:\n s += x\n return s / len(self.values)\n```\n\nReturn full new bcmfonjtl3xr.py and test_bcmfonjtl3xr.py.\n\n# bcmfonjtl3xr.py\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom typing import Iterable, Tuple\n\n@dataclass(frozen=True)\nclass L7Y1Xb7I:\n name: str\n values: Tuple[float, ...]\n\n @staticmethod\n def create(name: str, values: Iterable[float]) -> \"L7Y1Xb7I\":\n vals = tuple(float(v) for v in values)\n if not vals:\n raise ValueError(\"values must be non-empty\")\n return L7Y1Xb7I(name=name, values=vals)\n\n def add(self, v: float) -> \"L7Y1Xb7I\":\n return L7Y1Xb7I(name=self.name, values=self.values + (float(v),))\n\n def mean(self) -> float:\n return sum(self.values) / len(self.values)\n\n# test_bcmfonjtl3xr.py\nimport pytest\nfrom bcmfonjtl3xr import L7Y1Xb7I\n\ndef test_mean_and_add():\n c = L7Y1Xb7I.create(\"a\", [1, 2, 3])\n assert c.mean() == 2.0\n assert c.add(5).mean() == (1 + 2 + 3 + 5) / 4\n\ndef test_empty_raises():\n with pytest.raises(ValueError):\n L7Y1Xb7I.create(\"x\", [])", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Design a production system for gaming supporting event-driven workflows.\nTarget platform: ML (PyTorch + serving).\nRequirements: APIs, data model, scaling strategy, failure modes, and security.\nConstraints: must be easy to extend, must avoid global state, must include type hints where applicable.\nDifficulty: expert. Assume untrusted input; validate everything.\n\nOutput: design + implementation guidance suitable for shipping.\nDeliverable: system design with APIs, data model, and operational plan.\n\n**High-level architecture**\n- Edge: API Gateway + WAF\n- Core service: stateless app pods behind L7 LB\n- Data: Postgres (primary), Redis (cache + rate limit tokens), Object storage (uploads if needed)\n- Async: message queue (e.g., SQS/Rabbit) + worker pool for background jobs\n- Observability: structured logs + metrics + tracing\n\n**APIs (example)**\n- `POST /v1/{resource}` create (idempotent via `Idempotency-Key`)\n- `GET /v1/{resource}/{id}` read\n- `POST /v1/{resource}/{id}:action` command endpoint when side effects exist\n\n**Data model (Postgres)**\n- `resources(id UUID PK, tenant_id UUID, status TEXT, payload JSONB, created_at, updated_at)`\n- Unique constraint for idempotency: `(tenant_id, idempotency_key)` in a separate table:\n - `idempotency(tenant_id, key TEXT, request_hash TEXT, response JSONB, created_at, PRIMARY KEY(tenant_id,key))`\n\n**Scaling**\n- App layer scales horizontally; keep sessions out of process.\n- Cache reads in Redis; write-through invalidation on mutations.\n- Use connection pooling; consider read replicas for heavy reads.\n\n**Failure modes**\n- Retries: only for safe/ idempotent operations; exponential backoff + jitter.\n- Partial failures: background jobs must be idempotent; use a de-dup key.\n\n**Security**\n- AuthN: JWT/OIDC; AuthZ: RBAC/ABAC with tenant isolation\n- Validate all inputs; enforce per-tenant quotas/rate limits.\n\n**Rollout**\n- Dark launch + feature flags; canary; rapid rollback by toggling flags.\n\n\nHard-mode checks: concurrency safety, idempotency, and rollback validated; add chaos tests where feasible.", "source": "WithinUsAI/GOD_Coder_100k"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: Language: SQL\nFramework/tooling: MySQL\nDomain: feature flag service\nLogic challenge: invalid rollback sequence\nTask type: multi_file_migration_repair\nDifficulty: expert\n\nReturn a rigorous engineering answer:\n- identify the hidden root cause or logical failure\n- present the corrected implementation\n- add tests that prove the fix\n- list verification commands\n- explain why naive fixes are insufficient when relevant\n\nRepository sketch:\nrepo/\n migrations/\n 001_init.sql\n 002_add_index.sql\n queries/\n report.sql\n tests/\n report_cases.md\n\nFocus: Focus on staff-level problem solving with multi-file patches, rollout implications, performance and security tradeoffs.\n\nassistant: Diagnosis:\n- Staff-level diagnosis: invalid rollback sequence impacts correctness, operability, and future maintenance, so the fix must be minimal where possible but complete where necessary.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```sql\nWITH ranked AS (\n SELECT\n user_id,\n created_at,\n amount,\n ROW_NUMBER() OVER (PARTITION BY user_id ORDER BY created_at DESC, id DESC) AS rn\n FROM orders\n)\nSELECT user_id, created_at, amount\nFROM ranked\nWHERE rn = 1;\n```\n\nTests:\n```sql\n-- Correctness checks:\n-- 1) multiple rows per user\n-- 2) identical timestamps require deterministic tie-breaker\n-- 3) null values handled by business rules\n```\n\nVerification:\n- `run migration checks`\n- `run query correctness cases`\n\nEngineering notes:\n- Language: SQL\n- Framework/tooling: MySQL\n- Stack context: Rust, Axum, SQLx, Redis, Tokio, Docker\n- Domain: feature flag service\n- Task type: multi_file_migration_repair\n- Difficulty: expert\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: Language: C++\nFramework/tooling: Boost\nDomain: feature flag service\nLogic challenge: memory leak in AST cache\nTask type: backwards_compatible_redesign\nDifficulty: hard\n\nReturn a rigorous engineering answer:\n- identify the hidden root cause or logical failure\n- present the corrected implementation\n- add tests that prove the fix\n- list verification commands\n- explain why naive fixes are insufficient when relevant\n\nRepository sketch:\nrepo/\n src/main.cpp\n src/service.cpp\n include/service.h\n tests/test_service.cpp\n CMakeLists.txt\n\nFocus: Focus on staff-level problem solving with multi-file patches, rollout implications, performance and security tradeoffs.\n\nassistant: Diagnosis:\n- Staff-level diagnosis: memory leak in AST cache impacts correctness, operability, and future maintenance, so the fix must be minimal where possible but complete where necessary.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```cpp\n#include \n#include \n\nusing Payload = std::unordered_map;\n\nPayload normalize_payload(const Payload& in) {\n Payload out;\n for (const auto& [k, v] : in) {\n if (!v.empty()) out[k] = v;\n }\n return out;\n}\n```\n\nTests:\n```cpp\nTEST_CASE(\"normalize_payload filters empty values\") {\n Payload in{{\"id\",\"7\"},{\"name\",\"\"}};\n auto out = normalize_payload(in);\n REQUIRE(out.count(\"id\") == 1);\n REQUIRE(out.count(\"name\") == 0);\n}\n```\n\nVerification:\n- `cmake --build build`\n- `ctest --test-dir build`\n\nEngineering notes:\n- Language: C++\n- Framework/tooling: Boost\n- Stack context: Next.js, Node.js, Prisma, PostgreSQL, Playwright, Docker\n- Domain: feature flag service\n- Task type: backwards_compatible_redesign\n- Difficulty: hard\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "Fix the bug and add pytest tests.\n\n```python\ndef f56442(n: int) -> int:\n # sum 1..n inclusive\n if n < 0: raise ValueError\n total = 0\n for k in range(n): # BUG\n total += k\n return total\n```\nReturn unified diffs for `m65206.py` and `test_m65206.py`.\n\n*** Begin Patch\n*** Update File: m65206.py\n@@\n def f56442(n: int) -> int:\n@@\n- for k in range(n): # BUG\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_m65206.py\n+import pytest\n+from m65206 import f56442\n+\n+def test_small():\n+ assert f56442(7) == 28\n+\n+def test_zero():\n+ assert f56442(0) == 0\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ f56442(-1)\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Task type: supply_chain_security\nScenario: document indexing pipeline\nDomain focus: formal verification\nPrimary language: go\nDifficulty: expert\nScale/SLO: 100k RPS peak\nComponent: component_saiahtnx\nConstraints: include failure modes and recovery, explicit contracts and invariants, include test vectors and fuzz strategy, avoid data races and undefined behavior, include deterministic replay plan\nAssume crash-only processes; recovery must be deterministic.\nDeliverable: Design a supply-chain security plan: SBOM, signing, provenance, dependency policy, and CI gates.\n\nOutput: elite engineering answer optimized for correctness, performance, and operability.\n**Contract**\n- Inputs validated at the boundary; explicit error taxonomy.\n- Idempotency for side effects via request_id; deterministic replay.\n- Backward compatibility: additive changes by default; versioned breaking changes.\n**Invariants**\n- Isolation: tenant boundary enforced; no cross-tenant reads/writes.\n- Liveness: under bounded faults and stable network, progress occurs.\n- Determinism: replay of the same event log yields identical outputs.\n**Failure modes & recovery**\n- Crash during commit: WAL replay completes or transaction aborts; no torn writes.\n- Data corruption: checksums + scrubber; quarantine and rebuild from replicas/snapshots.\n- Duplicate requests: de-duplicate by (tenant, request_id) returning cached response.\n**Security posture (defensive)**\n- Threat model: auth/authz, injection, replay/abuse, supply chain.\n- Least privilege; secrets in managed store; audit logs for sensitive ops.\n- Input normalization, parameterized queries, path traversal protections.\n**Verification strategy**\n- Fuzzing of parsers/framers/validators with corpus seeds.\n- Canary + shadow traffic; invariants checked in production via assertions/metrics.\n- Deterministic simulation with fault injection (crash/partition/latency).\n\n**Snippet**\n```text\nImplementation sketch: factor pure state-machine core; adapters for I/O; add deterministic replay log.\n```\nExpert checks: state-machine proof sketch + model checking; upgrade/rollback rehearsed.", "source": "WithinUsAI/Omega_Genesis_Coder_100k"} {"text": "Write a thorough test suite for a Python component used for time series.\nRequirements: cover edge cases, invalid inputs, and behavior invariants.\nConstraints: must be streaming-friendly, must handle Windows paths safely, must provide clear error messages, must include tests.\nDifficulty: expert. Avoid quadratic behavior on large inputs.\n\nDeliverable: corrected code and verification tests.\n```python\n# tests (pytest-style) for a module providing: normalize(), parse_lines(), compute_stats()\nimport math\nimport pytest\n\ndef test_normalize_idempotent(module_under_test):\n x = \" A\\tB \"\n assert module_under_test.normalize(module_under_test.normalize(x)) == module_under_test.normalize(x)\n\ndef test_parse_lines_rejects_invalid(module_under_test):\n with pytest.raises(ValueError):\n module_under_test.parse_lines([\"\", \"???\", None]) # type: ignore[arg-type]\n\ndef test_compute_stats_basic(module_under_test):\n data = [1, 2, 3, 4]\n s = module_under_test.compute_stats(data)\n assert s.count == 4\n assert s.total == 10\n assert math.isclose(s.mean, 2.5)\n```", "source": "WithinUsAI/python_GOD_coder_100k"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: Project domain: feature flag service\nImplementation stack: Go, Gin, PostgreSQL, gRPC, Prometheus, Docker\nSoftware delivery problem: CI failures after dependency upgrade\nTask type: prd_to_patch\nDifficulty: hard\n\nReturn a complete delivery-grade response with:\n- diagnosis or design reasoning\n- implementation\n- test plan or tests\n- rollout plan\n- rollback or compatibility note\n- verification commands\n\nRepository sketch:\nrepo/\n src/\n api.js\n service.js\n utils.js\n tests/\n api.test.js\n package.json\n\nFocus: Focus on shipping production software with rollout safety, acceptance criteria, telemetry, and maintenance quality.\n\nassistant: Diagnosis:\n- Root cause or delivery blocker: CI failures after dependency upgrade needs both implementation work and a safe shipping plan.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```javascript\ntype Payload = Record;\n\nexport function normalizePayload(payload: Payload): Payload {\n if (!payload || typeof payload !== \"object\" || Array.isArray(payload)) {\n throw new TypeError(\"payload must be a plain object\");\n }\n return Object.fromEntries(\n Object.entries(payload)\n .filter(([, value]) => value !== null && value !== undefined)\n .map(([key, value]) => [String(key).trim(), value])\n );\n}\n\nexport function handleCiFailuresAfterDependencyUpgrade(payload: Payload) {\n const clean = normalizePayload(payload);\n if (!(\"id\" in clean)) {\n return { ok: false, data: {}, error: \"missing id\" };\n }\n return { ok: true, data: clean, error: null };\n}\n```\n\nTests:\n```javascript\nimport { describe, it, expect } from \"vitest\";\nimport { handleCiFailuresAfterDependencyUpgrade } from \"../src/service\";\n\ndescribe(\"handler\", () => {\n it(\"accepts valid input\", () => {\n expect(handleCiFailuresAfterDependencyUpgrade({ id: 7, name: \"ok\", unused: null })).toEqual({\n ok: true,\n data: { id: 7, name: \"ok\" },\n error: null\n });\n });\n\n it(\"rejects missing id\", () => {\n expect(handleCiFailuresAfterDependencyUpgrade({ name: \"x\" }).error).toMatch(/missing id/);\n });\n});\n```\n\nVerification:\n- `npm test`\n- `npm run lint`\n\nEngineering notes:\n- Language: JavaScript\n- Framework/tooling: Vite\n- Stack context: Go, Gin, PostgreSQL, gRPC, Prometheus, Docker\n- Domain: feature flag service\n- Task type: prd_to_patch\n- Difficulty: hard\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: Language: TypeScript\nFramework/tooling: React\nDomain: artifact registry\nLogic challenge: build reproducibility failure\nTask type: algorithmic_correctness\nDifficulty: medium\n\nReturn a rigorous engineering answer:\n- identify the hidden root cause or logical failure\n- present the corrected implementation\n- add tests that prove the fix\n- list verification commands\n- explain why naive fixes are insufficient when relevant\n\nRepository sketch:\nrepo/\n src/\n api.ts\n service.ts\n schema.ts\n tests/\n api.test.ts\n package.json\n\nFocus: Focus on strong structured logic with edge cases, data validation, and concurrency safety.\n\nassistant: Diagnosis:\n- Root cause: the failure around build reproducibility failure is caused by missing validation, weak edge-case handling, or unsafe lifecycle behavior in the current implementation.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```ts\ntype Payload = Record;\n\nexport function normalizePayload(payload: Payload): Payload {\n if (!payload || typeof payload !== \"object\" || Array.isArray(payload)) {\n throw new TypeError(\"payload must be a plain object\");\n }\n return Object.fromEntries(\n Object.entries(payload)\n .filter(([, value]) => value !== null && value !== undefined)\n .map(([key, value]) => [String(key).trim(), value])\n );\n}\n\nexport function handleBuildReproducibilityFailure(payload: Payload) {\n const clean = normalizePayload(payload);\n if (!(\"id\" in clean)) {\n return { ok: false, data: {}, error: \"missing id\" };\n }\n return { ok: true, data: clean, error: null };\n}\n```\n\nTests:\n```ts\nimport { describe, it, expect } from \"vitest\";\nimport { handleBuildReproducibilityFailure } from \"../src/service\";\n\ndescribe(\"handler\", () => {\n it(\"accepts valid input\", () => {\n expect(handleBuildReproducibilityFailure({ id: 7, name: \"ok\", unused: null })).toEqual({\n ok: true,\n data: { id: 7, name: \"ok\" },\n error: null\n });\n });\n\n it(\"rejects missing id\", () => {\n expect(handleBuildReproducibilityFailure({ name: \"x\" }).error).toMatch(/missing id/);\n });\n});\n```\n\nVerification:\n- `npm test`\n- `npm run typecheck`\n- `npm run lint`\n\nEngineering notes:\n- Language: TypeScript\n- Framework/tooling: React\n- Stack context: GitHub Actions, Docker Compose, Kubernetes, Terraform\n- Domain: artifact registry\n- Task type: algorithmic_correctness\n- Difficulty: medium\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Fix a bug and add tests.\n\nFile: s1gee1qf.py\n```python\ndef glpbah(n: int) -> int:\n \"\"\"Sum 1..n inclusive.\"\"\"\n if n < 0:\n raise ValueError(\"n must be non-negative\")\n total = 0\n for k in range(n): # BUG: should include n\n total += k\n return total\n```\n\nReturn unified diffs for s1gee1qf.py and test_s1gee1qf.py (pytest).\n\n*** Begin Patch\n*** Update File: s1gee1qf.py\n@@\n def glpbah(n: int) -> int:\n@@\n total = 0\n- for k in range(n): # BUG: should include n\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_s1gee1qf.py\n+import pytest\n+from s1gee1qf import glpbah\n+\n+def test_zero():\n+ assert glpbah(0) == 0\n+\n+def test_one():\n+ assert glpbah(1) == 1\n+\n+def test_small():\n+ assert glpbah(7) == 28\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ glpbah(-1)\n+\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: Project domain: artifact registry\nImplementation stack: GitHub Actions, Docker Compose, Kubernetes, Terraform\nSoftware delivery problem: async cancellation bug\nTask type: release_engineering_fix\nDifficulty: hard\n\nReturn a complete delivery-grade response with:\n- diagnosis or design reasoning\n- implementation\n- test plan or tests\n- rollout plan\n- rollback or compatibility note\n- verification commands\n\nRepository sketch:\nrepo/\n migrations/\n 001_init.sql\n 002_add_index.sql\n queries/\n report.sql\n tests/\n report_cases.md\n\nFocus: Focus on shipping production software with rollout safety, acceptance criteria, telemetry, and maintenance quality.\n\nassistant: Diagnosis:\n- Root cause or delivery blocker: async cancellation bug needs both implementation work and a safe shipping plan.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```sql\nWITH ranked AS (\n SELECT\n user_id,\n created_at,\n amount,\n ROW_NUMBER() OVER (PARTITION BY user_id ORDER BY created_at DESC, id DESC) AS rn\n FROM orders\n)\nSELECT user_id, created_at, amount\nFROM ranked\nWHERE rn = 1;\n```\n\nTests:\n```sql\n-- Correctness checks:\n-- 1) multiple rows per user\n-- 2) identical timestamps require deterministic tie-breaker\n-- 3) null values handled by business rules\n```\n\nVerification:\n- `run migration checks`\n- `run query correctness cases`\n\nEngineering notes:\n- Language: SQL\n- Framework/tooling: PostgreSQL\n- Stack context: GitHub Actions, Docker Compose, Kubernetes, Terraform\n- Domain: artifact registry\n- Task type: release_engineering_fix\n- Difficulty: hard\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "Task type: distributed_algorithm\nScenario: graph query service\nDomain focus: static analysis\nPrimary language: sql\nDifficulty: expert\nScale/SLO: 10k RPS peak\nComponent: component_tmkigiro\nConstraints: include verification strategy, include deterministic replay plan, include backward compatibility and migration plan, avoid data races and undefined behavior, include test vectors and fuzz strategy\nAssume hostile inputs and targeted abuse patterns.\nDeliverable: Design an algorithm with message flows and correctness arguments (safety + liveness). Include failure handling and a minimal reference implementation skeleton.\n\nOutput: elite engineering answer optimized for correctness, performance, and operability.\n**Contract**\n- Inputs validated at the boundary; explicit error taxonomy.\n- Idempotency for side effects via request_id; deterministic replay.\n- Backward compatibility: additive changes by default; versioned breaking changes.\n**Invariants**\n- Determinism: replay of the same event log yields identical outputs.\n- Safety: state transitions preserve invariants; no partial commit leaks.\n- Liveness: under bounded faults and stable network, progress occurs.\n**Failure modes & recovery**\n- Data corruption: checksums + scrubber; quarantine and rebuild from replicas/snapshots.\n- Network partition: minority cannot commit; clients receive retriable errors.\n- Duplicate requests: de-duplicate by (tenant, request_id) returning cached response.\n**Security posture (defensive)**\n- Threat model: auth/authz, injection, replay/abuse, supply chain.\n- Least privilege; secrets in managed store; audit logs for sensitive ops.\n- Input normalization, parameterized queries, path traversal protections.\n**Verification strategy**\n- Property tests against a pure reference model (state machine).\n- Deterministic simulation with fault injection (crash/partition/latency).\n- Canary + shadow traffic; invariants checked in production via assertions/metrics.\n\n**Snippet**\n```text\nImplementation sketch: factor pure state-machine core; adapters for I/O; add deterministic replay log.\n```\nExpert checks: state-machine proof sketch + model checking; upgrade/rollback rehearsed.", "source": "WithinUsAI/Omega_Genesis_Coder_100k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Refactor to modern typed Python with immutability and tests.\n\nFile: nawhwluwm_l.py\n```python\nclass I8Kg064Zvnxx:\n def __init__(self, name, values):\n self.name = name\n self.values = list(values)\n def add(self, v):\n self.values.append(v)\n def mean(self):\n s = 0\n for x in self.values:\n s += x\n return s / len(self.values)\n```\n\nReturn full new nawhwluwm_l.py and test_nawhwluwm_l.py.\n\n# nawhwluwm_l.py\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom typing import Iterable, Tuple\n\n@dataclass(frozen=True)\nclass I8Kg064Zvnxx:\n name: str\n values: Tuple[float, ...]\n\n @staticmethod\n def create(name: str, values: Iterable[float]) -> \"I8Kg064Zvnxx\":\n vals = tuple(float(v) for v in values)\n if not vals:\n raise ValueError(\"values must be non-empty\")\n return I8Kg064Zvnxx(name=name, values=vals)\n\n def add(self, v: float) -> \"I8Kg064Zvnxx\":\n return I8Kg064Zvnxx(name=self.name, values=self.values + (float(v),))\n\n def mean(self) -> float:\n return sum(self.values) / len(self.values)\n\n# test_nawhwluwm_l.py\nimport pytest\nfrom nawhwluwm_l import I8Kg064Zvnxx\n\ndef test_mean_and_add():\n c = I8Kg064Zvnxx.create(\"a\", [1, 2, 3])\n assert c.mean() == 2.0\n assert c.add(5).mean() == (1 + 2 + 3 + 5) / 4\n\ndef test_empty_raises():\n with pytest.raises(ValueError):\n I8Kg064Zvnxx.create(\"x\", [])", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Optimize while preserving behavior and order.\n\n```python\ndef f57417(xs):\n out=[]\n for x in xs:\n if x not in out: out.append(x)\n return out\n```\nReturn `m79631.py` with types and O(n) average.\n\n```python\n# m79631.py\nfrom __future__ import annotations\nfrom typing import Iterable, List, Set, TypeVar\nT=TypeVar(\"T\")\n\ndef f57417(xs: Iterable[T]) -> List[T]:\n \"\"\"Unique items preserving first-seen order.\"\"\"\n seen: Set[T]=set()\n out: List[T]=[]\n for x in xs:\n if x in seen: continue\n seen.add(x); out.append(x)\n return out\n```", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Design a small, production-grade Python API for time series.\nRequirements: define data models and interfaces, implement reference version, include tests.\nConstraints: must include type hints, must provide clear error messages, must be memory-efficient.\nDifficulty: medium. Guarantee deterministic output ordering.\n\nDeliverable: API + reference implementation + tests.\nArchitecture:\n- Public facade class coordinating concerns (parsing, validation, persistence)\n- Small pure functions for testability\n- No global state; dependency injection for filesystem I/O\n\n```python\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom pathlib import Path\nfrom typing import Protocol, Iterable\nimport json\n\nclass Store(Protocol):\n def write_text(self, path: Path, data: str) -> None: ...\n\nclass FSStore:\n def write_text(self, path: Path, data: str) -> None:\n path.parent.mkdir(parents=True, exist_ok=True)\n path.write_text(data, encoding=\"utf-8\")\n\n@dataclass(frozen=True, slots=True)\nclass Item:\n name: str\n qty: int\n\ndef parse_items(lines: Iterable[str]) -> list[Item]:\n out: list[Item] = []\n for i, line in enumerate(lines, 1):\n s = line.strip()\n if not s:\n continue\n obj = json.loads(s)\n if not isinstance(obj, dict):\n raise ValueError(f\"line {i}: expected object\")\n name = obj.get(\"name\")\n qty = obj.get(\"qty\")\n if not isinstance(name, str) or not name:\n raise ValueError(f\"line {i}: name must be str\")\n if not isinstance(qty, int) or qty < 0:\n raise ValueError(f\"line {i}: qty must be non-negative int\")\n out.append(Item(name, qty))\n return out\n\nclass InventoryWriter:\n def __init__(self, base_dir: Path, store: Store | None = None) -> None:\n self._base = base_dir\n self._store: Store = store or FSStore()\n\n def write(self, rel_path: str, items: list[Item]) -> Path:\n dst = (self._base / rel_path).resolve()\n base = self._base.resolve()\n if dst != base and base not in dst.parents:\n raise ValueError(\"unsafe path traversal\")\n payload = json.dumps([item.__dict__ for item in items], ensure_ascii=False)\n self._store.write_text(dst, payload)\n return dst\n```\n\n```python\nimport json\nfrom pathlib import Path\nimport pytest\nfrom module_under_test import InventoryWriter, parse_items\n\ndef test_parse_items_valid():\n lines = [json.dumps({\"name\":\"x\",\"qty\":1})]\n assert parse_items(lines)[0].name == \"x\"\n\ndef test_writer_blocks_traversal(tmp_path: Path):\n w = InventoryWriter(tmp_path)\n with pytest.raises(ValueError):\n w.write(\"../evil.json\", [])\n```", "source": "WithinUsAI/python_GOD_coder_100k"} {"text": "Task type: mechanized_spec\nScenario: graph query service\nDomain focus: edge robotics (safe)\nPrimary language: lean\nDifficulty: expert\nScale/SLO: 1M msgs/min\nComponent: component_pahcdzys\nConstraints: assume adversarial inputs; validate everything, include backward compatibility and migration plan, avoid data races and undefined behavior, include deterministic replay plan, include failure modes and recovery\nAssume weekly network partitions.\nDeliverable: Provide a mechanized-style spec outline (Lean-like), key definitions, and a proof plan. Include executable reference code skeleton and tests.\n\nOutput: contract-first solution with failure modes, security posture, and test/verification strategy.\n**Contract**\n- Inputs validated at the boundary; explicit error taxonomy.\n- Idempotency for side effects via request_id; deterministic replay.\n- Backward compatibility: additive changes by default; versioned breaking changes.\n**Invariants**\n- Determinism: replay of the same event log yields identical outputs.\n- Isolation: tenant boundary enforced; no cross-tenant reads/writes.\n- Safety: state transitions preserve invariants; no partial commit leaks.\n**Failure modes & recovery**\n- Crash during commit: WAL replay completes or transaction aborts; no torn writes.\n- Data corruption: checksums + scrubber; quarantine and rebuild from replicas/snapshots.\n- Duplicate requests: de-duplicate by (tenant, request_id) returning cached response.\n**Security posture (defensive)**\n- Threat model: auth/authz, injection, replay/abuse, supply chain.\n- Least privilege; secrets in managed store; audit logs for sensitive ops.\n- Input normalization, parameterized queries, path traversal protections.\n**Verification strategy**\n- Deterministic simulation with fault injection (crash/partition/latency).\n- Property tests against a pure reference model (state machine).\n- Canary + shadow traffic; invariants checked in production via assertions/metrics.\n\n**Snippet**\n```lean\n-- Pseudo-Lean outline\nstructure State where\n ver : Nat\n val : Option ByteArray\n\ndef invariant (s : State) : Prop := True\n\ntheorem step_preserves_invariant :\n ∀ s, invariant s → ∀ s', Step s s' → invariant s' := by\n intro s hs s' hstep\n -- proof plan: case analysis on transition; trivial here\n trivial\n```\n\nExpert checks: state-machine proof sketch + model checking; upgrade/rollback rehearsed.", "source": "WithinUsAI/Omega_Genesis_Coder_100k"} {"text": "Create a comprehensive test plan and automated tests for idempotent payments in a document processing product.\nTarget platform: ML (scikit + batch).\nRequirements: unit/integration tests, edge cases, load tests strategy, and CI gates.\nConstraints: must include tests, must avoid global state, must include type hints where applicable.\nDifficulty: easy. Assume schema evolves frequently; design for migrations.\n\nOutput: design + implementation guidance suitable for shipping.\nDeliverable: test plan + automation guidance.\n\n**Unit tests**\n- Validation: malformed payloads rejected with correct codes.\n- AuthZ: tenant boundary enforced.\n- Idempotency: replay returns same response; conflicting reuse yields 409.\n\n**Integration tests**\n- DB transaction behavior; unique constraints.\n- Cache behavior: correctness under concurrent requests.\n\n**Load tests**\n- 10k RPS target: measure p95 latency, error rate, saturation.\n\n**CI gates**\n- Lint + typecheck + unit tests required.\n- Coverage threshold for critical modules.\n- Block merge on flaky test detection.\n\n\nChecks: input validation, tests, and safe defaults included.", "source": "WithinUsAI/GOD_Coder_100k"} {"text": "Task type: distributed_algorithm\nScenario: job scheduler\nDomain focus: high-frequency trading systems (safe engineering)\nPrimary language: sql\nDifficulty: expert\nScale/SLO: multi-region active-active\nComponent: component_uajsfnoy\nConstraints: explicit contracts and invariants, include test vectors and fuzz strategy, include performance model and limits, include backward compatibility and migration plan, avoid data races and undefined behavior, include verification strategy\nAssume schema changes every sprint; must be backward compatible.\nDeliverable: Design an algorithm with message flows and correctness arguments (safety + liveness). Include failure handling and a minimal reference implementation skeleton.\n\nOutput: contract-first solution with failure modes, security posture, and test/verification strategy.\n**Contract**\n- Inputs validated at the boundary; explicit error taxonomy.\n- Idempotency for side effects via request_id; deterministic replay.\n- Backward compatibility: additive changes by default; versioned breaking changes.\n**Invariants**\n- Isolation: tenant boundary enforced; no cross-tenant reads/writes.\n- Safety: state transitions preserve invariants; no partial commit leaks.\n- Liveness: under bounded faults and stable network, progress occurs.\n**Failure modes & recovery**\n- Data corruption: checksums + scrubber; quarantine and rebuild from replicas/snapshots.\n- Network partition: minority cannot commit; clients receive retriable errors.\n- Crash during commit: WAL replay completes or transaction aborts; no torn writes.\n**Security posture (defensive)**\n- Threat model: auth/authz, injection, replay/abuse, supply chain.\n- Least privilege; secrets in managed store; audit logs for sensitive ops.\n- Input normalization, parameterized queries, path traversal protections.\n**Verification strategy**\n- Property tests against a pure reference model (state machine).\n- Fuzzing of parsers/framers/validators with corpus seeds.\n- Deterministic simulation with fault injection (crash/partition/latency).\n\n**Snippet**\n```text\nImplementation sketch: factor pure state-machine core; adapters for I/O; add deterministic replay log.\n```\nExpert checks: state-machine proof sketch + model checking; upgrade/rollback rehearsed.", "source": "WithinUsAI/Omega_Genesis_Coder_100k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Fix a bug and add tests.\n\nFile: bgqdaiq0bp_c.py\n```python\ndef d5avog(n: int) -> int:\n \"\"\"Sum 1..n inclusive.\"\"\"\n if n < 0:\n raise ValueError(\"n must be non-negative\")\n total = 0\n for k in range(n): # BUG: should include n\n total += k\n return total\n```\n\nReturn unified diffs for bgqdaiq0bp_c.py and test_bgqdaiq0bp_c.py (pytest).\n\n*** Begin Patch\n*** Update File: bgqdaiq0bp_c.py\n@@\n def d5avog(n: int) -> int:\n@@\n total = 0\n- for k in range(n): # BUG: should include n\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_bgqdaiq0bp_c.py\n+import pytest\n+from bgqdaiq0bp_c import d5avog\n+\n+def test_zero():\n+ assert d5avog(0) == 0\n+\n+def test_one():\n+ assert d5avog(1) == 1\n+\n+def test_small():\n+ assert d5avog(7) == 28\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ d5avog(-1)\n+\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: System domain: model serving gateway\nStack: Airflow, dbt, DuckDB, MinIO, pytest\nCross-layer incident: monorepo toolchain skew\nTask type: cache_consistency_patch\nDifficulty: hard\n\nSolve this as a complete-project engineer.\nOutput must include:\n- root cause across layers\n- final implementation patch\n- tests touching at least two layers\n- deployment or observability note\n- verification commands\n\nRepository sketch:\nrepo/\n src/\n api.js\n service.js\n utils.js\n tests/\n api.test.js\n package.json\n\nFocus: Focus on multi-layer debugging across frontend, backend, database, CI, caching, and deployment.\n\nassistant: Diagnosis:\n- Root cause: monorepo toolchain skew crosses service boundaries, so the fix must align code, contracts, tests, and deployment behavior.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```javascript\ntype Payload = Record;\n\nexport function normalizePayload(payload: Payload): Payload {\n if (!payload || typeof payload !== \"object\" || Array.isArray(payload)) {\n throw new TypeError(\"payload must be a plain object\");\n }\n return Object.fromEntries(\n Object.entries(payload)\n .filter(([, value]) => value !== null && value !== undefined)\n .map(([key, value]) => [String(key).trim(), value])\n );\n}\n\nexport function handleMonorepoToolchainSkew(payload: Payload) {\n const clean = normalizePayload(payload);\n if (!(\"id\" in clean)) {\n return { ok: false, data: {}, error: \"missing id\" };\n }\n return { ok: true, data: clean, error: null };\n}\n```\n\nTests:\n```javascript\nimport { describe, it, expect } from \"vitest\";\nimport { handleMonorepoToolchainSkew } from \"../src/service\";\n\ndescribe(\"handler\", () => {\n it(\"accepts valid input\", () => {\n expect(handleMonorepoToolchainSkew({ id: 7, name: \"ok\", unused: null })).toEqual({\n ok: true,\n data: { id: 7, name: \"ok\" },\n error: null\n });\n });\n\n it(\"rejects missing id\", () => {\n expect(handleMonorepoToolchainSkew({ name: \"x\" }).error).toMatch(/missing id/);\n });\n});\n```\n\nVerification:\n- `npm test`\n- `npm run lint`\n\nEngineering notes:\n- Language: JavaScript\n- Framework/tooling: Express\n- Stack context: Airflow, dbt, DuckDB, MinIO, pytest\n- Domain: model serving gateway\n- Task type: cache_consistency_patch\n- Difficulty: hard\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "Task type: mechanized_spec\nScenario: document indexing pipeline\nDomain focus: data lineage & governance\nPrimary language: lean\nDifficulty: hard\nScale/SLO: 10k RPS peak\nComponent: component_ecjoxhzc\nConstraints: include test vectors and fuzz strategy, include backward compatibility and migration plan, include security threat model (defensive only), explicit contracts and invariants, include failure modes and recovery\nAssume weekly network partitions.\nDeliverable: Provide a mechanized-style spec outline (Lean-like), key definitions, and a proof plan. Include executable reference code skeleton and tests.\n\nOutput: rigorous design + invariants + verification plan + implementation sketch.\n**Contract**\n- Inputs validated at the boundary; explicit error taxonomy.\n- Idempotency for side effects via request_id; deterministic replay.\n- Backward compatibility: additive changes by default; versioned breaking changes.\n**Invariants**\n- Safety: state transitions preserve invariants; no partial commit leaks.\n- Determinism: replay of the same event log yields identical outputs.\n- Isolation: tenant boundary enforced; no cross-tenant reads/writes.\n**Failure modes & recovery**\n- Network partition: minority cannot commit; clients receive retriable errors.\n- Data corruption: checksums + scrubber; quarantine and rebuild from replicas/snapshots.\n- Crash during commit: WAL replay completes or transaction aborts; no torn writes.\n**Security posture (defensive)**\n- Threat model: auth/authz, injection, replay/abuse, supply chain.\n- Least privilege; secrets in managed store; audit logs for sensitive ops.\n- Input normalization, parameterized queries, path traversal protections.\n**Verification strategy**\n- Deterministic simulation with fault injection (crash/partition/latency).\n- Canary + shadow traffic; invariants checked in production via assertions/metrics.\n- Property tests against a pure reference model (state machine).\n\n**Snippet**\n```lean\n-- Pseudo-Lean outline\nstructure State where\n ver : Nat\n val : Option ByteArray\n\ndef invariant (s : State) : Prop := True\n\ntheorem step_preserves_invariant :\n ∀ s, invariant s → ∀ s', Step s s' → invariant s' := by\n intro s hs s' hstep\n -- proof plan: case analysis on transition; trivial here\n trivial\n```\n\nHard checks: fault injection tests gate merges; perf thresholds enforced in CI.", "source": "WithinUsAI/Omega_Genesis_Coder_100k"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: Repository domain: data pipeline\nPrimary language: Bash\nFramework/tooling: curl\nReported problem: memory leak in AST cache\nTask type: security_patch\nDifficulty: medium\n\nProduce a complete professional engineering response:\n1. Diagnose the root cause.\n2. Provide the corrected implementation or patch.\n3. Add tests.\n4. Add verification commands.\n5. Note edge cases and any migration or rollback risk.\n\nRepository sketch:\nrepo/\n scripts/\n run.sh\n deploy.sh\n tests/\n smoke.sh\n\nQuality target:\n- Minimal diff unless redesign is clearly required\n- Production-ready code\n- No placeholders\n- Secure defaults\n- Clear acceptance of failure cases\n\nFocus: Focus on complete implementation quality, patch correctness, tests, and production readiness.\n\nassistant: Diagnosis:\n- Root cause: the failure around memory leak in AST cache is caused by missing validation, weak edge-case handling, or unsafe lifecycle behavior in the current implementation.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```bash\n#!/usr/bin/env bash\nset -euo pipefail\n\ninput=\"${1:-}\"\nif [[ -z \"$input\" ]]; then\n echo \"missing input\" >&2\n exit 1\nfi\n\nprintf '%s\n' \"$input\" | tr -d '\r'\n```\n\nTests:\n```bash\noutput=\"$(bash scripts/run.sh \"abc\")\"\ntest \"$output\" = \"abc\"\n```\n\nVerification:\n- `bash tests/smoke.sh`\n- `shellcheck scripts/*.sh`\n\nEngineering notes:\n- Language: Bash\n- Framework/tooling: curl\n- Stack context: Next.js, Node.js, Prisma, PostgreSQL, Playwright, Docker\n- Domain: data pipeline\n- Task type: security_patch\n- Difficulty: medium\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "Write pytest tests for `f76290`.\n\n```python\ndef f76290(a: int, b: int) -> int:\n return a*a + b*b\n```\nInclude edge cases and a property-style check.\n\n```python\nimport random\nfrom m39470 import f76290\n\ndef test_known():\n assert f76290(3,4) == 25\n\ndef test_zero():\n assert f76290(0,0) == 0\n\ndef test_property_nonnegative():\n for _ in range(200):\n a=random.randint(-50,50)\n b=random.randint(-50,50)\n assert f76290(a,b) >= 0\n```", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Optimize while preserving behavior.\n\nFile: xmonr312.py\n```python\ndef e52mwo2(xs):\n out = []\n for x in xs:\n if x not in out:\n out.append(x)\n return out\n```\n\nRequirements: preserve first-seen order; O(n) average; add types + docstring.\n\n# xmonr312.py\nfrom __future__ import annotations\nfrom typing import Iterable, List, Set, TypeVar\n\nT = TypeVar(\"T\")\n\ndef e52mwo2(xs: Iterable[T]) -> List[T]:\n \"\"\"Return unique items preserving first-seen order.\"\"\"\n seen: Set[T] = set()\n out: List[T] = []\n for x in xs:\n if x in seen:\n continue\n seen.add(x)\n out.append(x)\n return out", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Create a comprehensive test plan and automated tests for search + pagination in a document processing product.\nTarget platform: ML (scikit + batch).\nRequirements: unit/integration tests, edge cases, load tests strategy, and CI gates.\nConstraints: must include tests, must be observable (logs/metrics/traces), must include documentation/comments, must be secure-by-default, must be production-ready.\nDifficulty: hard. Assume mobile clients are occasionally offline.\n\nOutput: design + implementation guidance suitable for shipping.\nDeliverable: test plan + automation guidance.\n\n**Unit tests**\n- Validation: malformed payloads rejected with correct codes.\n- AuthZ: tenant boundary enforced.\n- Idempotency: replay returns same response; conflicting reuse yields 409.\n\n**Integration tests**\n- DB transaction behavior; unique constraints.\n- Cache behavior: correctness under concurrent requests.\n\n**Load tests**\n- 10k RPS target: measure p95 latency, error rate, saturation.\n\n**CI gates**\n- Lint + typecheck + unit tests required.\n- Coverage threshold for critical modules.\n- Block merge on flaky test detection.\n\n\nHard-mode checks: concurrency safety, idempotency, and rollback validated; add chaos tests where feasible.", "source": "WithinUsAI/GOD_Coder_100k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Optimize while preserving behavior.\n\nFile: yxza1z.py\n```python\ndef t5w1mejfcttg(xs):\n out = []\n for x in xs:\n if x not in out:\n out.append(x)\n return out\n```\n\nRequirements: preserve first-seen order; O(n) average; add types + docstring.\n\n# yxza1z.py\nfrom __future__ import annotations\nfrom typing import Iterable, List, Set, TypeVar\n\nT = TypeVar(\"T\")\n\ndef t5w1mejfcttg(xs: Iterable[T]) -> List[T]:\n \"\"\"Return unique items preserving first-seen order.\"\"\"\n seen: Set[T] = set()\n out: List[T] = []\n for x in xs:\n if x in seen:\n continue\n seen.add(x)\n out.append(x)\n return out", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Write secure, defensive Python code for validation.\nRequirements: input validation, safe file handling, prevent path traversal, include tests.\nConstraints: must be streaming-friendly, must be easy to extend, must include tests, must include type hints.\nDifficulty: expert. Avoid quadratic behavior on large inputs.\n\nDeliverable: corrected code and verification tests.\n```python\nfrom __future__ import annotations\n\nfrom dataclasses import dataclass\nfrom pathlib import Path\nfrom typing import Iterable\nimport json\n\n\nclass ValidationError(ValueError):\n \"\"\"Raised when input validation fails.\"\"\"\n\n\ndef safe_join(base: Path, *parts: str) -> Path:\n \"\"\"Join paths while preventing traversal outside base.\"\"\"\n b = base.resolve()\n p = (b / Path(*parts)).resolve()\n if p != b and b not in p.parents:\n raise ValidationError(f\"unsafe path: {p}\")\n return p\n\n\n@dataclass(frozen=True, slots=True)\nclass Record:\n key: str\n value: int\n\n\ndef parse_jsonl(lines: Iterable[str]) -> list[Record]:\n out: list[Record] = []\n for idx, line in enumerate(lines, 1):\n s = line.strip()\n if not s:\n continue\n try:\n obj = json.loads(s)\n except json.JSONDecodeError as e:\n raise ValidationError(f\"line {idx}: invalid json\") from e\n if not isinstance(obj, dict):\n raise ValidationError(f\"line {idx}: expected object\")\n key = obj.get(\"key\")\n val = obj.get(\"value\")\n if not isinstance(key, str) or not key:\n raise ValidationError(f\"line {idx}: key must be non-empty str\")\n if not isinstance(val, int):\n raise ValidationError(f\"line {idx}: value must be int\")\n out.append(Record(key, val))\n return out\n\n\ndef write_jsonl(base: Path, rel: str, records: Iterable[Record]) -> Path:\n base.mkdir(parents=True, exist_ok=True)\n dst = safe_join(base, rel)\n dst.parent.mkdir(parents=True, exist_ok=True)\n with dst.open(\"w\", encoding=\"utf-8\", newline=\"\\n\") as f:\n for r in records:\n f.write(json.dumps({\"key\": r.key, \"value\": r.value}, ensure_ascii=False) + \"\\n\")\n return dst\n```\n\n```python\n# tests (pytest-style)\nimport json\nfrom pathlib import Path\nimport pytest\nfrom module_under_test import ValidationError, Record, parse_jsonl, write_jsonl\n\ndef test_parse_ok():\n lines = [json.dumps({\"key\":\"a\",\"value\":1}), json.dumps({\"key\":\"b\",\"value\":2})]\n assert parse_jsonl(lines) == [Record(\"a\",1), Record(\"b\",2)]\n\ndef test_parse_rejects_bad_json():\n with pytest.raises(ValidationError):\n parse_jsonl([\"{not json}\"])\n\ndef test_safe_join_blocks_traversal(tmp_path: Path):\n with pytest.raises(ValidationError):\n write_jsonl(tmp_path, \"../x.jsonl\", [Record(\"a\",1)])\n```", "source": "WithinUsAI/python_GOD_coder_100k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Refactor to modern typed Python with immutability and tests.\n\nFile: b1sb56zet.py\n```python\nclass U9Rav9Hyi9:\n def __init__(self, name, values):\n self.name = name\n self.values = list(values)\n def add(self, v):\n self.values.append(v)\n def mean(self):\n s = 0\n for x in self.values:\n s += x\n return s / len(self.values)\n```\n\nReturn full new b1sb56zet.py and test_b1sb56zet.py.\n\n# b1sb56zet.py\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom typing import Iterable, Tuple\n\n@dataclass(frozen=True)\nclass U9Rav9Hyi9:\n name: str\n values: Tuple[float, ...]\n\n @staticmethod\n def create(name: str, values: Iterable[float]) -> \"U9Rav9Hyi9\":\n vals = tuple(float(v) for v in values)\n if not vals:\n raise ValueError(\"values must be non-empty\")\n return U9Rav9Hyi9(name=name, values=vals)\n\n def add(self, v: float) -> \"U9Rav9Hyi9\":\n return U9Rav9Hyi9(name=self.name, values=self.values + (float(v),))\n\n def mean(self) -> float:\n return sum(self.values) / len(self.values)\n\n# test_b1sb56zet.py\nimport pytest\nfrom b1sb56zet import U9Rav9Hyi9\n\ndef test_mean_and_add():\n c = U9Rav9Hyi9.create(\"a\", [1, 2, 3])\n assert c.mean() == 2.0\n assert c.add(5).mean() == (1 + 2 + 3 + 5) / 4\n\ndef test_empty_raises():\n with pytest.raises(ValueError):\n U9Rav9Hyi9.create(\"x\", [])", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Design CI/CD for a document processing service delivering real-time notifications.\nTarget platform: infra (Docker + Kubernetes).\nRequirements: pipelines, checks, artifact strategy, deployments, and rollbacks.\nConstraints: must be easy to extend, must be performant under load, must avoid global state.\nDifficulty: expert. Assume 10k RPS peak traffic.\n\nOutput: production-oriented blueprint with code where appropriate.\nDeliverable: CI/CD pipeline (GitHub Actions) with quality gates.\n\n```yaml\nname: ci\non:\n pull_request:\n push:\n branches: [main]\n\njobs:\n test:\n runs-on: ubuntu-latest\n steps:\n - uses: actions/checkout@v4\n - uses: actions/setup-python@v5\n with:\n python-version: \"3.11\"\n - run: python -m pip install -U pip\n - run: pip install -r requirements.txt\n - run: pip install -r requirements-dev.txt\n - run: ruff check .\n - run: mypy .\n - run: pytest -q --maxfail=1 --disable-warnings\n\n docker:\n needs: test\n runs-on: ubuntu-latest\n steps:\n - uses: actions/checkout@v4\n - uses: docker/setup-buildx-action@v3\n - run: docker build -t app:${{ github.sha }} .\n```\n\nDeployment strategy:\n- main → build → deploy to staging → smoke tests → canary to prod.\n- Rollback: redeploy previous image + DB migration rollback plan.\n\n\nHard-mode checks: concurrency safety, idempotency, and rollback validated; add chaos tests where feasible.", "source": "WithinUsAI/GOD_Coder_100k"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: Language: C#\nFramework/tooling: xUnit\nDomain: team dashboard\nLogic challenge: N+1 query explosion\nTask type: backwards_compatible_redesign\nDifficulty: expert\n\nReturn a rigorous engineering answer:\n- identify the hidden root cause or logical failure\n- present the corrected implementation\n- add tests that prove the fix\n- list verification commands\n- explain why naive fixes are insufficient when relevant\n\nRepository sketch:\nrepo/\n src/App/Program.cs\n src/App/Service.cs\n tests/App.Tests/ServiceTests.cs\n App.sln\n\nFocus: Focus on staff-level problem solving with multi-file patches, rollout implications, performance and security tradeoffs.\n\nassistant: Diagnosis:\n- Staff-level diagnosis: N+1 query explosion impacts correctness, operability, and future maintenance, so the fix must be minimal where possible but complete where necessary.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```csharp\nusing System;\nusing System.Collections.Generic;\n\npublic static class RequestHandler\n{\n public static Dictionary HandleRequest(Dictionary payload)\n {\n var clean = new Dictionary();\n foreach (var entry in payload)\n {\n if (entry.Value != null)\n clean[entry.Key.Trim()] = entry.Value;\n }\n if (!clean.ContainsKey(\"id\"))\n throw new ArgumentException(\"missing id\");\n return new Dictionary\n {\n [\"ok\"] = true,\n [\"data\"] = clean\n };\n }\n}\n```\n\nTests:\n```csharp\nusing System;\nusing System.Collections.Generic;\nusing Xunit;\n\npublic class RequestHandlerTests\n{\n [Fact]\n public void RequiresId()\n {\n Assert.Throws(() => RequestHandler.HandleRequest(new Dictionary { [\"name\"] = \"x\" }));\n }\n}\n```\n\nVerification:\n- `dotnet test`\n- `dotnet build`\n\nEngineering notes:\n- Language: C#\n- Framework/tooling: xUnit\n- Stack context: Airflow, dbt, DuckDB, MinIO, pytest\n- Domain: team dashboard\n- Task type: backwards_compatible_redesign\n- Difficulty: expert\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "Write pytest tests for `f59639`.\n\n```python\ndef f59639(a: int, b: int) -> int:\n return a*a + b*b\n```\nInclude edge cases and a property-style check.\n\n```python\nimport random\nfrom m51377 import f59639\n\ndef test_known():\n assert f59639(3,4) == 25\n\ndef test_zero():\n assert f59639(0,0) == 0\n\ndef test_property_nonnegative():\n for _ in range(200):\n a=random.randint(-50,50)\n b=random.randint(-50,50)\n assert f59639(a,b) >= 0\n```", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Task type: network_protocol\nScenario: identity and access\nDomain focus: runtime systems\nPrimary language: python\nDifficulty: expert+\nScale/SLO: p99 < 50ms\nComponent: component_laqhsopj\nConstraints: include backward compatibility and migration plan, avoid data races and undefined behavior, explicit contracts and invariants, include security threat model (defensive only), include performance model and limits\nAssume strict auditability and replayable history.\nDeliverable: Design an application protocol: framing, retries, backpressure, timeouts; include client/server skeleton and test vectors.\n\nOutput: elite engineering answer optimized for correctness, performance, and operability.\n**Contract**\n- Inputs validated at the boundary; explicit error taxonomy.\n- Idempotency for side effects via request_id; deterministic replay.\n- Backward compatibility: additive changes by default; versioned breaking changes.\n**Invariants**\n- Liveness: under bounded faults and stable network, progress occurs.\n- Determinism: replay of the same event log yields identical outputs.\n- Isolation: tenant boundary enforced; no cross-tenant reads/writes.\n**Failure modes & recovery**\n- Crash during commit: WAL replay completes or transaction aborts; no torn writes.\n- Duplicate requests: de-duplicate by (tenant, request_id) returning cached response.\n- Network partition: minority cannot commit; clients receive retriable errors.\n**Security posture (defensive)**\n- Threat model: auth/authz, injection, replay/abuse, supply chain.\n- Least privilege; secrets in managed store; audit logs for sensitive ops.\n- Input normalization, parameterized queries, path traversal protections.\n**Verification strategy**\n- Fuzzing of parsers/framers/validators with corpus seeds.\n- Property tests against a pure reference model (state machine).\n- Canary + shadow traffic; invariants checked in production via assertions/metrics.\n\n**Snippet**\n```text\nImplementation sketch: factor pure state-machine core; adapters for I/O; add deterministic replay log.\n```\nExpert+ checks: mechanized invariants (or exhaustive model checking), adversarial fuzzing, and multi-region failure drills.", "source": "WithinUsAI/Omega_Genesis_Coder_100k"} {"text": "Refactor to typed, mostly-immutable Python and add minimal tests.\n\n```python\nclass C99343:\n def __init__(self, values): self.values=list(values)\n def mean(self): return sum(self.values)/len(self.values)\n```\nReturn `m38411.py` and `test_m38411.py`.\n\n```python\n# m38411.py\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom typing import Iterable, Tuple\n\n@dataclass(frozen=True)\nclass C99343:\n values: Tuple[float, ...]\n\n @staticmethod\n def create(values: Iterable[float]) -> \"C99343\":\n vals = tuple(float(v) for v in values)\n if not vals: raise ValueError(\"empty\")\n return C99343(vals)\n\n def mean(self) -> float:\n return sum(self.values)/len(self.values)\n```\n\n```python\n# test_m38411.py\nimport pytest\nfrom m38411 import C99343\n\ndef test_mean():\n assert C99343.create([1,2,3]).mean() == 2.0\ndef test_empty():\n with pytest.raises(ValueError):\n C99343.create([])\n```", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Task type: static_analyzer\nScenario: streaming ETL\nDomain focus: model checking\nPrimary language: sql\nDifficulty: hard\nScale/SLO: 99.99% availability\nComponent: component_jphbtmmc\nConstraints: include verification strategy, include backward compatibility and migration plan, include test vectors and fuzz strategy, explicit contracts and invariants, avoid data races and undefined behavior, assume adversarial inputs; validate everything\nAssume partial data corruption; include scrubbing strategy.\nDeliverable: Design a static analyzer for a safety property (e.g., taint/SQLi prevention); include rule set, false-positive strategy, and tests.\n\nOutput: rigorous design + invariants + verification plan + implementation sketch.\n**Contract**\n- Inputs validated at the boundary; explicit error taxonomy.\n- Idempotency for side effects via request_id; deterministic replay.\n- Backward compatibility: additive changes by default; versioned breaking changes.\n**Invariants**\n- Determinism: replay of the same event log yields identical outputs.\n- Safety: state transitions preserve invariants; no partial commit leaks.\n- Liveness: under bounded faults and stable network, progress occurs.\n**Failure modes & recovery**\n- Crash during commit: WAL replay completes or transaction aborts; no torn writes.\n- Data corruption: checksums + scrubber; quarantine and rebuild from replicas/snapshots.\n- Network partition: minority cannot commit; clients receive retriable errors.\n**Security posture (defensive)**\n- Threat model: auth/authz, injection, replay/abuse, supply chain.\n- Least privilege; secrets in managed store; audit logs for sensitive ops.\n- Input normalization, parameterized queries, path traversal protections.\n**Verification strategy**\n- Property tests against a pure reference model (state machine).\n- Fuzzing of parsers/framers/validators with corpus seeds.\n- Canary + shadow traffic; invariants checked in production via assertions/metrics.\n\n**Snippet**\n```text\nImplementation sketch: factor pure state-machine core; adapters for I/O; add deterministic replay log.\n```\nHard checks: fault injection tests gate merges; perf thresholds enforced in CI.", "source": "WithinUsAI/Omega_Genesis_Coder_100k"} {"text": "Build an elite-grade solution in the domain of security engineering (defensive) for scenario: rate limiting gateway.\nPrimary language: bash.\nDifficulty: hard.\nConstraints: include invariants and failure modes, make the interface contract explicit, assume untrusted inputs; validate and sanitize, provide rollout and rollback guidance, include tests or verification strategy.\nComponent: component_vgstabl.\nAssume cold-start and memory limits are tight.\nTask: Provide SLOs, alerting, dashboards, runbooks, and incident playbook. Include chaos testing and safe rollout strategy.\n\nOutput: production blueprint plus correctness arguments and test strategy.\nOutput: SLOs + alerts + runbooks + chaos strategy.\n\n**SLOs**\n- Availability: 99.9% monthly\n- Latency: p95 < 200ms, p99 < 400ms\n- Error rate: < 0.1%\n\n**Alerts**\n- Burn-rate alerts for SLOs (fast/slow windows)\n- Saturation: CPU, memory, queue depth, DB connections\n- Dependency health: cache hit rate drop, downstream timeouts\n\n**Runbooks**\n- Triage: identify blast radius, feature-flag rollback, capacity mitigation\n- Post-incident: timeline, contributing factors, action items\n\n**Chaos**\n- Inject latency, partial outages, and restarts in staging; verify steady-state SLOs.\n\n\nHard checks: failure injection tests and performance regressions gated.", "source": "WithinUsAI/Elite_GOD_Coder_100k"} {"text": "Fix a subtle bug in a Python module used for configuration loading.\nRequirements: explain root cause briefly, provide corrected code, and add regression tests.\nConstraints: must avoid global state, must handle Windows paths safely.\nDifficulty: expert. Guarantee deterministic output ordering.\n\nDeliverable: implementation + tests.\n```python\nfrom __future__ import annotations\n\nfrom dataclasses import dataclass\nfrom pathlib import Path\nfrom typing import Iterable\nimport json\n\n\nclass ValidationError(ValueError):\n \"\"\"Raised when input validation fails.\"\"\"\n\n\ndef safe_join(base: Path, *parts: str) -> Path:\n \"\"\"Join paths while preventing traversal outside base.\"\"\"\n b = base.resolve()\n p = (b / Path(*parts)).resolve()\n if p != b and b not in p.parents:\n raise ValidationError(f\"unsafe path: {p}\")\n return p\n\n\n@dataclass(frozen=True, slots=True)\nclass Record:\n key: str\n value: int\n\n\ndef parse_jsonl(lines: Iterable[str]) -> list[Record]:\n out: list[Record] = []\n for idx, line in enumerate(lines, 1):\n s = line.strip()\n if not s:\n continue\n try:\n obj = json.loads(s)\n except json.JSONDecodeError as e:\n raise ValidationError(f\"line {idx}: invalid json\") from e\n if not isinstance(obj, dict):\n raise ValidationError(f\"line {idx}: expected object\")\n key = obj.get(\"key\")\n val = obj.get(\"value\")\n if not isinstance(key, str) or not key:\n raise ValidationError(f\"line {idx}: key must be non-empty str\")\n if not isinstance(val, int):\n raise ValidationError(f\"line {idx}: value must be int\")\n out.append(Record(key, val))\n return out\n\n\ndef write_jsonl(base: Path, rel: str, records: Iterable[Record]) -> Path:\n base.mkdir(parents=True, exist_ok=True)\n dst = safe_join(base, rel)\n dst.parent.mkdir(parents=True, exist_ok=True)\n with dst.open(\"w\", encoding=\"utf-8\", newline=\"\\n\") as f:\n for r in records:\n f.write(json.dumps({\"key\": r.key, \"value\": r.value}, ensure_ascii=False) + \"\\n\")\n return dst\n```\n\n```python\n# tests (pytest-style)\nimport json\nfrom pathlib import Path\nimport pytest\nfrom module_under_test import ValidationError, Record, parse_jsonl, write_jsonl\n\ndef test_parse_ok():\n lines = [json.dumps({\"key\":\"a\",\"value\":1}), json.dumps({\"key\":\"b\",\"value\":2})]\n assert parse_jsonl(lines) == [Record(\"a\",1), Record(\"b\",2)]\n\ndef test_parse_rejects_bad_json():\n with pytest.raises(ValidationError):\n parse_jsonl([\"{not json}\"])\n\ndef test_safe_join_blocks_traversal(tmp_path: Path):\n with pytest.raises(ValidationError):\n write_jsonl(tmp_path, \"../x.jsonl\", [Record(\"a\",1)])\n```", "source": "WithinUsAI/python_GOD_coder_100k"} {"text": "Optimize while preserving behavior and order.\n\n```python\ndef f02499(xs):\n out=[]\n for x in xs:\n if x not in out: out.append(x)\n return out\n```\nReturn `m00357.py` with types and O(n) average.\n\n```python\n# m00357.py\nfrom __future__ import annotations\nfrom typing import Iterable, List, Set, TypeVar\nT=TypeVar(\"T\")\n\ndef f02499(xs: Iterable[T]) -> List[T]:\n \"\"\"Unique items preserving first-seen order.\"\"\"\n seen: Set[T]=set()\n out: List[T]=[]\n for x in xs:\n if x in seen: continue\n seen.add(x); out.append(x)\n return out\n```", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Task type: tla_state_machine\nScenario: payment ledger\nDomain focus: kernel primitives\nPrimary language: tla+\nDifficulty: expert+\nScale/SLO: p99 < 50ms\nComponent: component_roofnrnz\nConstraints: assume adversarial inputs; validate everything, include test vectors and fuzz strategy, include backward compatibility and migration plan, avoid data races and undefined behavior, include security threat model (defensive only)\nAssume hostile inputs and targeted abuse patterns.\nDeliverable: Provide a TLA+-style state machine (pseudo), safety/liveness properties, and a model-checking strategy. Include an implementation sketch and test vectors.\n\nOutput: rigorous design + invariants + verification plan + implementation sketch.\n**Contract**\n- Inputs validated at the boundary; explicit error taxonomy.\n- Idempotency for side effects via request_id; deterministic replay.\n- Backward compatibility: additive changes by default; versioned breaking changes.\n**Invariants**\n- Safety: state transitions preserve invariants; no partial commit leaks.\n- Isolation: tenant boundary enforced; no cross-tenant reads/writes.\n- Liveness: under bounded faults and stable network, progress occurs.\n**Failure modes & recovery**\n- Duplicate requests: de-duplicate by (tenant, request_id) returning cached response.\n- Data corruption: checksums + scrubber; quarantine and rebuild from replicas/snapshots.\n- Network partition: minority cannot commit; clients receive retriable errors.\n**Security posture (defensive)**\n- Threat model: auth/authz, injection, replay/abuse, supply chain.\n- Least privilege; secrets in managed store; audit logs for sensitive ops.\n- Input normalization, parameterized queries, path traversal protections.\n**Verification strategy**\n- Fuzzing of parsers/framers/validators with corpus seeds.\n- Canary + shadow traffic; invariants checked in production via assertions/metrics.\n- Property tests against a pure reference model (state machine).\n\n**Snippet**\n```tla\nVARIABLES state, log, seen\n\nInit == state = [k \\in Keys |-> <<0, NULL>>] /\\ log = << >> /\\ seen = [r \\in ReqIds |-> NULL]\n\nPut(req, k, v) ==\n IF seen[req] # NULL THEN UNCHANGED <>\n ELSE\n LET ver == state[k][1] + 1 IN\n /\\ state' = [state EXCEPT ![k] = <>]\n /\\ log' = Append(log, <>)\n /\\ seen' = [seen EXCEPT ![req] = <<\"ok\", ver>>]\n\nSafety == \\A k \\in Keys: state[k][1] >= 0\n```\n\nExpert+ checks: mechanized invariants (or exhaustive model checking), adversarial fuzzing, and multi-region failure drills.", "source": "WithinUsAI/Omega_Genesis_Coder_100k"} {"text": "Build an elite-grade solution in the domain of realtime systems for scenario: event ingestion.\nPrimary language: python.\nDifficulty: medium.\nConstraints: document performance characteristics, assume untrusted inputs; validate and sanitize, avoid undefined behavior and data races.\nComponent: component_ltljzrp.\nAssume strict auditability and replayable history.\nTask: Implement a concurrency primitive or subsystem (lock-free queue, thread pool, async runtime component). Explain memory ordering and correctness arguments; include stress tests.\n\nOutput: rigorous solution with invariants, failure modes, and performance notes.\nOutput: correctness-focused concurrency primitive + stress tests.\n\n**Primitive**\n- Bounded MPMC queue with backpressure (blocking push/pop) OR lock-free SPSC ring buffer.\n\n**Correctness notes**\n- For lock-free: use acquire/release semantics on head/tail indices.\n- Avoid ABA by monotonic counters; ring index = counter % capacity.\n\n**Stress tests**\n- Multi-thread producers/consumers; assert item multiset preserved.\n- Use time-bounded randomized schedules; detect deadlocks.\n\n\nChecks: boundary validation and deterministic behavior verified.", "source": "WithinUsAI/Elite_GOD_Coder_100k"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: Language: JavaScript\nFramework/tooling: React\nDomain: data pipeline\nLogic challenge: JWT refresh token rotation\nTask type: multi_file_migration_repair\nDifficulty: expert\n\nReturn a rigorous engineering answer:\n- identify the hidden root cause or logical failure\n- present the corrected implementation\n- add tests that prove the fix\n- list verification commands\n- explain why naive fixes are insufficient when relevant\n\nRepository sketch:\nrepo/\n src/\n api.js\n service.js\n utils.js\n tests/\n api.test.js\n package.json\n\nFocus: Focus on staff-level problem solving with multi-file patches, rollout implications, performance and security tradeoffs.\n\nassistant: Diagnosis:\n- Staff-level diagnosis: JWT refresh token rotation impacts correctness, operability, and future maintenance, so the fix must be minimal where possible but complete where necessary.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```javascript\ntype Payload = Record;\n\nexport function normalizePayload(payload: Payload): Payload {\n if (!payload || typeof payload !== \"object\" || Array.isArray(payload)) {\n throw new TypeError(\"payload must be a plain object\");\n }\n return Object.fromEntries(\n Object.entries(payload)\n .filter(([, value]) => value !== null && value !== undefined)\n .map(([key, value]) => [String(key).trim(), value])\n );\n}\n\nexport function handleJwtRefreshTokenRotation(payload: Payload) {\n const clean = normalizePayload(payload);\n if (!(\"id\" in clean)) {\n return { ok: false, data: {}, error: \"missing id\" };\n }\n return { ok: true, data: clean, error: null };\n}\n```\n\nTests:\n```javascript\nimport { describe, it, expect } from \"vitest\";\nimport { handleJwtRefreshTokenRotation } from \"../src/service\";\n\ndescribe(\"handler\", () => {\n it(\"accepts valid input\", () => {\n expect(handleJwtRefreshTokenRotation({ id: 7, name: \"ok\", unused: null })).toEqual({\n ok: true,\n data: { id: 7, name: \"ok\" },\n error: null\n });\n });\n\n it(\"rejects missing id\", () => {\n expect(handleJwtRefreshTokenRotation({ name: \"x\" }).error).toMatch(/missing id/);\n });\n});\n```\n\nVerification:\n- `npm test`\n- `npm run lint`\n\nEngineering notes:\n- Language: JavaScript\n- Framework/tooling: React\n- Stack context: ASP.NET Core, SQL Server, EF Core, xUnit, Docker\n- Domain: data pipeline\n- Task type: multi_file_migration_repair\n- Difficulty: expert\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: Language: Java\nFramework/tooling: JUnit\nDomain: search service\nLogic challenge: monorepo toolchain skew\nTask type: distributed_debug\nDifficulty: hard\n\nReturn a rigorous engineering answer:\n- identify the hidden root cause or logical failure\n- present the corrected implementation\n- add tests that prove the fix\n- list verification commands\n- explain why naive fixes are insufficient when relevant\n\nRepository sketch:\nrepo/\n src/main/java/com/acme/App.java\n src/main/java/com/acme/Service.java\n src/test/java/com/acme/AppTest.java\n pom.xml\n\nFocus: Focus on ambiguity, misleading symptoms, hidden root causes, and high-stakes debugging.\n\nassistant: Diagnosis:\n- Hidden root cause: monorepo toolchain skew presents misleading symptoms, so the patch must target the actual logic boundary rather than the first visible failure.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```java\nimport java.util.HashMap;\nimport java.util.Map;\n\npublic final class RequestHandler {\n public static Map handleRequest(Map payload) {\n Map clean = new HashMap<>();\n for (Map.Entry entry : payload.entrySet()) {\n if (entry.getValue() != null) clean.put(entry.getKey().trim(), entry.getValue());\n }\n if (!clean.containsKey(\"id\")) throw new IllegalArgumentException(\"missing id\");\n return Map.of(\"ok\", true, \"data\", clean);\n }\n}\n```\n\nTests:\n```java\nimport static org.junit.jupiter.api.Assertions.*;\nimport java.util.Map;\nimport org.junit.jupiter.api.Test;\n\nclass RequestHandlerTest {\n @Test\n void requiresId() {\n assertThrows(IllegalArgumentException.class, () -> RequestHandler.handleRequest(Map.of(\"name\", \"x\")));\n }\n}\n```\n\nVerification:\n- `./gradlew test`\n- `mvn test`\n\nEngineering notes:\n- Language: Java\n- Framework/tooling: JUnit\n- Stack context: Spring Boot, PostgreSQL, JUnit, Gradle, Docker, GitHub Actions\n- Domain: search service\n- Task type: distributed_debug\n- Difficulty: hard\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: Project domain: artifact registry\nImplementation stack: Next.js, Node.js, Prisma, PostgreSQL, Playwright, Docker\nSoftware delivery problem: JWT refresh token rotation\nTask type: rollback_safe_migration\nDifficulty: medium\n\nReturn a complete delivery-grade response with:\n- diagnosis or design reasoning\n- implementation\n- test plan or tests\n- rollout plan\n- rollback or compatibility note\n- verification commands\n\nRepository sketch:\nrepo/\n app/\n api.py\n service.py\n models.py\n tests/\n test_api.py\n pyproject.toml\n\nFocus: Focus on shipping production software with rollout safety, acceptance criteria, telemetry, and maintenance quality.\n\nassistant: Diagnosis:\n- Root cause or delivery blocker: JWT refresh token rotation needs both implementation work and a safe shipping plan.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```python\nfrom __future__ import annotations\n\nfrom dataclasses import dataclass\nfrom typing import Any\n\n@dataclass\nclass ServiceResult:\n ok: bool\n data: dict[str, Any]\n error: str | None = None\n\ndef normalize_payload(payload: dict[str, Any]) -> dict[str, Any]:\n if not isinstance(payload, dict):\n raise TypeError(\"payload must be a dict\")\n clean: dict[str, Any] = {}\n for key, value in payload.items():\n if value is None:\n continue\n clean[str(key).strip()] = value\n return clean\n\ndef handle_jwt_refresh_token_rotation(payload: dict[str, Any]) -> ServiceResult:\n clean = normalize_payload(payload)\n if \"id\" not in clean:\n return ServiceResult(ok=False, data={}, error=\"missing id\")\n return ServiceResult(ok=True, data=clean)\n```\n\nTests:\n```python\nimport pytest\nfrom app.service import handle_jwt_refresh_token_rotation as handler\n\ndef test_handler_accepts_valid_payload():\n result = handler({\"id\": 7, \"name\": \"ok\", \"unused\": None})\n assert result.ok is True\n assert result.data == {\"id\": 7, \"name\": \"ok\"}\n\ndef test_handler_rejects_missing_id():\n result = handler({\"name\": \"x\"})\n assert result.ok is False\n assert result.error == \"missing id\"\n```\n\nVerification:\n- `pytest -q`\n- `ruff check .`\n- `python -m compileall .`\n\nEngineering notes:\n- Language: Python\n- Framework/tooling: Celery\n- Stack context: Next.js, Node.js, Prisma, PostgreSQL, Playwright, Docker\n- Domain: artifact registry\n- Task type: rollback_safe_migration\n- Difficulty: medium\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "Perform a code review for a e-commerce PR implementing search + pagination.\nTarget platform: backend (Node.js).\nRequirements: list critical issues, improvements, and provide an improved patch excerpt.\nConstraints: must avoid global state, must be observable (logs/metrics/traces), must include tests, must be production-ready.\nDifficulty: medium. Assume schema evolves frequently; design for migrations.\n\nOutput: actionable implementation and verification artifacts.\nDeliverable: code review findings + improved patch excerpt.\n\n**Critical issues**\n1. Missing input validation at boundary; potential unexpected exceptions.\n2. No idempotency / retry safety for side-effecting endpoint.\n3. No tests for edge cases (empty input, duplicates, timeouts).\n4. Observability gaps: no request_id correlation, no metrics.\n\n**Improvements**\n- Add strict validation and explicit error responses.\n- Add idempotency key support for create endpoints.\n- Add unit + integration tests with CI gating.\n- Add structured logs and basic metrics.\n\nPatch excerpt (illustrative):\n```python\nif not idem_key:\n raise HTTPException(400, \"Missing Idempotency-Key\")\n```\n\n\nChecks: input validation, tests, and safe defaults included.", "source": "WithinUsAI/GOD_Coder_100k"} {"text": "Optimize while preserving behavior and order.\n\n```python\ndef f18202(xs):\n out=[]\n for x in xs:\n if x not in out: out.append(x)\n return out\n```\nReturn `m16886.py` with types and O(n) average.\n\n```python\n# m16886.py\nfrom __future__ import annotations\nfrom typing import Iterable, List, Set, TypeVar\nT=TypeVar(\"T\")\n\ndef f18202(xs: Iterable[T]) -> List[T]:\n \"\"\"Unique items preserving first-seen order.\"\"\"\n seen: Set[T]=set()\n out: List[T]=[]\n for x in xs:\n if x in seen: continue\n seen.add(x); out.append(x)\n return out\n```", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Design and implement an algorithm for time series.\nRequirements: define inputs/outputs, implement solution with complexity analysis, and include tests.\nConstraints: must handle Windows paths safely, must include tests.\nDifficulty: medium. Ensure the API is testable via dependency injection.\n\nDeliverable: production-ready reference solution.\nProblem: compute rolling sums over events (ts:int,value:int) with window W seconds. Events may be out-of-order.\n\nComplexity: sorting O(n log n); window maintenance O(n); memory O(k).\n\n```python\nfrom __future__ import annotations\nfrom collections import deque\nfrom dataclasses import dataclass\nfrom typing import Iterable, List, Tuple\n\n@dataclass(frozen=True, slots=True)\nclass Event:\n ts: int\n value: int\n\ndef rolling_sum(events: Iterable[Event], window_s: int) -> List[Tuple[int,int]]:\n if window_s < 0:\n raise ValueError(\"window_s must be >= 0\")\n evs = sorted(events, key=lambda e: e.ts)\n q: deque[Event] = deque()\n s = 0\n out: List[Tuple[int,int]] = []\n for e in evs:\n q.append(e)\n s += e.value\n cutoff = e.ts - window_s\n while q and q[0].ts < cutoff:\n old = q.popleft()\n s -= old.value\n out.append((e.ts, s))\n return out\n```\n\n```python\nimport pytest\nfrom module_under_test import Event, rolling_sum\n\ndef test_rolling_sum():\n ev = [Event(10,1), Event(11,2), Event(20,5)]\n assert rolling_sum(ev, 5) == [(10,1),(11,3),(20,5)]\n```", "source": "WithinUsAI/python_GOD_coder_100k"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: Project domain: notification service\nImplementation stack: Rust, Axum, SQLx, Redis, Tokio, Docker\nSoftware delivery problem: streaming timeout handling\nTask type: rollback_safe_migration\nDifficulty: medium\n\nReturn a complete delivery-grade response with:\n- diagnosis or design reasoning\n- implementation\n- test plan or tests\n- rollout plan\n- rollback or compatibility note\n- verification commands\n\nRepository sketch:\nrepo/\n scripts/\n run.sh\n deploy.sh\n tests/\n smoke.sh\n\nFocus: Focus on shipping production software with rollout safety, acceptance criteria, telemetry, and maintenance quality.\n\nassistant: Diagnosis:\n- Root cause or delivery blocker: streaming timeout handling needs both implementation work and a safe shipping plan.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```bash\n#!/usr/bin/env bash\nset -euo pipefail\n\ninput=\"${1:-}\"\nif [[ -z \"$input\" ]]; then\n echo \"missing input\" >&2\n exit 1\nfi\n\nprintf '%s\n' \"$input\" | tr -d '\r'\n```\n\nTests:\n```bash\noutput=\"$(bash scripts/run.sh \"abc\")\"\ntest \"$output\" = \"abc\"\n```\n\nVerification:\n- `bash tests/smoke.sh`\n- `shellcheck scripts/*.sh`\n\nEngineering notes:\n- Language: Bash\n- Framework/tooling: curl\n- Stack context: Rust, Axum, SQLx, Redis, Tokio, Docker\n- Domain: notification service\n- Task type: rollback_safe_migration\n- Difficulty: medium\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "Fix the bug and add pytest tests.\n\n```python\ndef f74067(n: int) -> int:\n # sum 1..n inclusive\n if n < 0: raise ValueError\n total = 0\n for k in range(n): # BUG\n total += k\n return total\n```\nReturn unified diffs for `m10581.py` and `test_m10581.py`.\n\n*** Begin Patch\n*** Update File: m10581.py\n@@\n def f74067(n: int) -> int:\n@@\n- for k in range(n): # BUG\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_m10581.py\n+import pytest\n+from m10581 import f74067\n+\n+def test_small():\n+ assert f74067(7) == 28\n+\n+def test_zero():\n+ assert f74067(0) == 0\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ f74067(-1)\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Improve typing and robustness of a Python module used for validation.\nRequirements: provide type-safe APIs (generics/protocols where appropriate) and include tests.\nConstraints: must be streaming-friendly, must include docstrings, stdlib-only.\nDifficulty: medium. Guarantee deterministic output ordering.\n\nDeliverable: corrected code and verification tests.\n```python\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom typing import Callable, Generic, Iterable, Protocol, TypeVar\n\nT = TypeVar(\"T\")\nR = TypeVar(\"R\")\n\nclass Mapper(Protocol[T, R]):\n def __call__(self, x: T) -> R: ...\n\n@dataclass(frozen=True, slots=True)\nclass Batch(Generic[T]):\n items: tuple[T, ...]\n\ndef map_batch(batch: Batch[T], fn: Mapper[T, R]) -> Batch[R]:\n return Batch(items=tuple(fn(x) for x in batch.items))\n\ndef chunked(xs: Iterable[T], size: int) -> Iterable[Batch[T]]:\n if size <= 0:\n raise ValueError(\"size must be > 0\")\n buf: list[T] = []\n for x in xs:\n buf.append(x)\n if len(buf) == size:\n yield Batch(items=tuple(buf))\n buf.clear()\n if buf:\n yield Batch(items=tuple(buf))\n```\n\n```python\nimport pytest\nfrom module_under_test import Batch, map_batch, chunked\n\ndef test_map_batch():\n b = Batch(items=(1,2,3))\n assert map_batch(b, lambda x: x*2).items == (2,4,6)\n\ndef test_chunked():\n out = list(chunked([1,2,3,4,5], 2))\n assert [b.items for b in out] == [(1,2),(3,4),(5,)]\n```", "source": "WithinUsAI/python_GOD_coder_100k"} {"text": "Add a clear docstring and type hints to this function:\n\n```python\ndef f58872(s):\n return ''.join(x for x in s if x.isalnum()).lower()\n```\n\n```python\nfrom __future__ import annotations\n\ndef f58872(s: str) -> str:\n \"\"\"Normalize a string: keep only alphanumerics and lowercase the result.\"\"\"\n return \"\".join(ch for ch in s if ch.isalnum()).lower()\n```", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Build an elite-grade solution in the domain of high-performance services for scenario: feature flagging.\nPrimary language: sql.\nDifficulty: hard.\nConstraints: include tests or verification strategy, avoid undefined behavior and data races, assume untrusted inputs; validate and sanitize, design for backward compatibility and migrations, provide rollout and rollback guidance.\nComponent: component_ahrfbee.\nAssume partial network partitions occur weekly.\nTask: Optimize a hot path with profiling-driven approach; propose micro/meso optimizations, and supply a benchmark harness with acceptance thresholds.\n\nOutput: production blueprint plus correctness arguments and test strategy.\nOutput: profiling-first optimization + benchmark harness.\n\n**Plan**\n1. Establish baseline with microbench + representative dataset.\n2. Profile (CPU, allocations, syscalls).\n3. Apply optimizations: reduce allocations, reuse buffers, batch I/O, vectorize parsing where safe.\n4. Validate with regression suite and perf thresholds.\n\n**Benchmark guidance**\n- Use p50/p95 and throughput; pin CPU frequency if possible.\n- Acceptance: p95 improves ≥ X% with no correctness regressions.\n\n\nHard checks: failure injection tests and performance regressions gated.", "source": "WithinUsAI/Elite_GOD_Coder_100k"} {"text": "Optimize while preserving behavior and order.\n\n```python\ndef f19098(xs):\n out=[]\n for x in xs:\n if x not in out: out.append(x)\n return out\n```\nReturn `m17014.py` with types and O(n) average.\n\n```python\n# m17014.py\nfrom __future__ import annotations\nfrom typing import Iterable, List, Set, TypeVar\nT=TypeVar(\"T\")\n\ndef f19098(xs: Iterable[T]) -> List[T]:\n \"\"\"Unique items preserving first-seen order.\"\"\"\n seen: Set[T]=set()\n out: List[T]=[]\n for x in xs:\n if x in seen: continue\n seen.add(x); out.append(x)\n return out\n```", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Fix a bug and add tests.\n\nFile: o30op7jkyy.py\n```python\ndef qx7yo4hh_x(n: int) -> int:\n \"\"\"Sum 1..n inclusive.\"\"\"\n if n < 0:\n raise ValueError(\"n must be non-negative\")\n total = 0\n for k in range(n): # BUG: should include n\n total += k\n return total\n```\n\nReturn unified diffs for o30op7jkyy.py and test_o30op7jkyy.py (pytest).\n\n*** Begin Patch\n*** Update File: o30op7jkyy.py\n@@\n def qx7yo4hh_x(n: int) -> int:\n@@\n total = 0\n- for k in range(n): # BUG: should include n\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_o30op7jkyy.py\n+import pytest\n+from o30op7jkyy import qx7yo4hh_x\n+\n+def test_zero():\n+ assert qx7yo4hh_x(0) == 0\n+\n+def test_one():\n+ assert qx7yo4hh_x(1) == 1\n+\n+def test_small():\n+ assert qx7yo4hh_x(7) == 28\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ qx7yo4hh_x(-1)\n+\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Task type: distributed_algorithm\nScenario: multi-tenant event ingestion\nDomain focus: model checking\nPrimary language: rust\nDifficulty: expert\nScale/SLO: multi-region active-active\nComponent: component_opljsgkd\nConstraints: include backward compatibility and migration plan, explicit contracts and invariants, include failure modes and recovery, include deterministic replay plan, include security threat model (defensive only), assume adversarial inputs; validate everything, include test vectors and fuzz strategy\nAssume partial data corruption; include scrubbing strategy.\nDeliverable: Design an algorithm with message flows and correctness arguments (safety + liveness). Include failure handling and a minimal reference implementation skeleton.\n\nOutput: elite engineering answer optimized for correctness, performance, and operability.\n**Contract**\n- Inputs validated at the boundary; explicit error taxonomy.\n- Idempotency for side effects via request_id; deterministic replay.\n- Backward compatibility: additive changes by default; versioned breaking changes.\n**Invariants**\n- Isolation: tenant boundary enforced; no cross-tenant reads/writes.\n- Determinism: replay of the same event log yields identical outputs.\n- Liveness: under bounded faults and stable network, progress occurs.\n**Failure modes & recovery**\n- Data corruption: checksums + scrubber; quarantine and rebuild from replicas/snapshots.\n- Network partition: minority cannot commit; clients receive retriable errors.\n- Crash during commit: WAL replay completes or transaction aborts; no torn writes.\n**Security posture (defensive)**\n- Threat model: auth/authz, injection, replay/abuse, supply chain.\n- Least privilege; secrets in managed store; audit logs for sensitive ops.\n- Input normalization, parameterized queries, path traversal protections.\n**Verification strategy**\n- Canary + shadow traffic; invariants checked in production via assertions/metrics.\n- Deterministic simulation with fault injection (crash/partition/latency).\n- Fuzzing of parsers/framers/validators with corpus seeds.\n\n**Snippet**\n```text\nImplementation sketch: factor pure state-machine core; adapters for I/O; add deterministic replay log.\n```\nExpert checks: state-machine proof sketch + model checking; upgrade/rollback rehearsed.", "source": "WithinUsAI/Omega_Genesis_Coder_100k"} {"text": "Task type: compiler_frontend\nScenario: edge sync\nDomain focus: compiler toolchains\nPrimary language: sql\nDifficulty: hard\nScale/SLO: 50 TB/day ingestion\nComponent: component_rwsewpin\nConstraints: include security threat model (defensive only), avoid data races and undefined behavior, include deterministic replay plan, include test vectors and fuzz strategy, explicit contracts and invariants\nAssume strict auditability and replayable history.\nDeliverable: Design a DSL language frontend: lexer/parser, AST, type checking, error reporting, and tests.\n\nOutput: contract-first solution with failure modes, security posture, and test/verification strategy.\n**Contract**\n- Inputs validated at the boundary; explicit error taxonomy.\n- Idempotency for side effects via request_id; deterministic replay.\n- Backward compatibility: additive changes by default; versioned breaking changes.\n**Invariants**\n- Isolation: tenant boundary enforced; no cross-tenant reads/writes.\n- Safety: state transitions preserve invariants; no partial commit leaks.\n- Liveness: under bounded faults and stable network, progress occurs.\n**Failure modes & recovery**\n- Duplicate requests: de-duplicate by (tenant, request_id) returning cached response.\n- Network partition: minority cannot commit; clients receive retriable errors.\n- Crash during commit: WAL replay completes or transaction aborts; no torn writes.\n**Security posture (defensive)**\n- Threat model: auth/authz, injection, replay/abuse, supply chain.\n- Least privilege; secrets in managed store; audit logs for sensitive ops.\n- Input normalization, parameterized queries, path traversal protections.\n**Verification strategy**\n- Deterministic simulation with fault injection (crash/partition/latency).\n- Property tests against a pure reference model (state machine).\n- Canary + shadow traffic; invariants checked in production via assertions/metrics.\n\n**Snippet**\n```text\nImplementation sketch: factor pure state-machine core; adapters for I/O; add deterministic replay log.\n```\nHard checks: fault injection tests gate merges; perf thresholds enforced in CI.", "source": "WithinUsAI/Omega_Genesis_Coder_100k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Fix a bug and add tests.\n\nFile: xo8bzxh.py\n```python\ndef jmkyu0on3m(n: int) -> int:\n \"\"\"Sum 1..n inclusive.\"\"\"\n if n < 0:\n raise ValueError(\"n must be non-negative\")\n total = 0\n for k in range(n): # BUG: should include n\n total += k\n return total\n```\n\nReturn unified diffs for xo8bzxh.py and test_xo8bzxh.py (pytest).\n\n*** Begin Patch\n*** Update File: xo8bzxh.py\n@@\n def jmkyu0on3m(n: int) -> int:\n@@\n total = 0\n- for k in range(n): # BUG: should include n\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_xo8bzxh.py\n+import pytest\n+from xo8bzxh import jmkyu0on3m\n+\n+def test_zero():\n+ assert jmkyu0on3m(0) == 0\n+\n+def test_one():\n+ assert jmkyu0on3m(1) == 1\n+\n+def test_small():\n+ assert jmkyu0on3m(7) == 28\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ jmkyu0on3m(-1)\n+\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Fix the bug and add pytest tests.\n\n```python\ndef f26402(n: int) -> int:\n # sum 1..n inclusive\n if n < 0: raise ValueError\n total = 0\n for k in range(n): # BUG\n total += k\n return total\n```\nReturn unified diffs for `m89486.py` and `test_m89486.py`.\n\n*** Begin Patch\n*** Update File: m89486.py\n@@\n def f26402(n: int) -> int:\n@@\n- for k in range(n): # BUG\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_m89486.py\n+import pytest\n+from m89486 import f26402\n+\n+def test_small():\n+ assert f26402(7) == 28\n+\n+def test_zero():\n+ assert f26402(0) == 0\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ f26402(-1)\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: Project domain: job scheduler\nImplementation stack: GitHub Actions, Docker Compose, Kubernetes, Terraform\nSoftware delivery problem: idempotent retry design\nTask type: prd_to_patch\nDifficulty: medium\n\nReturn a complete delivery-grade response with:\n- diagnosis or design reasoning\n- implementation\n- test plan or tests\n- rollout plan\n- rollback or compatibility note\n- verification commands\n\nRepository sketch:\nrepo/\n src/App/Program.cs\n src/App/Service.cs\n tests/App.Tests/ServiceTests.cs\n App.sln\n\nFocus: Focus on shipping production software with rollout safety, acceptance criteria, telemetry, and maintenance quality.\n\nassistant: Diagnosis:\n- Root cause or delivery blocker: idempotent retry design needs both implementation work and a safe shipping plan.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```csharp\nusing System;\nusing System.Collections.Generic;\n\npublic static class RequestHandler\n{\n public static Dictionary HandleRequest(Dictionary payload)\n {\n var clean = new Dictionary();\n foreach (var entry in payload)\n {\n if (entry.Value != null)\n clean[entry.Key.Trim()] = entry.Value;\n }\n if (!clean.ContainsKey(\"id\"))\n throw new ArgumentException(\"missing id\");\n return new Dictionary\n {\n [\"ok\"] = true,\n [\"data\"] = clean\n };\n }\n}\n```\n\nTests:\n```csharp\nusing System;\nusing System.Collections.Generic;\nusing Xunit;\n\npublic class RequestHandlerTests\n{\n [Fact]\n public void RequiresId()\n {\n Assert.Throws(() => RequestHandler.HandleRequest(new Dictionary { [\"name\"] = \"x\" }));\n }\n}\n```\n\nVerification:\n- `dotnet test`\n- `dotnet build`\n\nEngineering notes:\n- Language: C#\n- Framework/tooling: EF Core\n- Stack context: GitHub Actions, Docker Compose, Kubernetes, Terraform\n- Domain: job scheduler\n- Task type: prd_to_patch\n- Difficulty: medium\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Fix a bug and add tests.\n\nFile: o5gpq8.py\n```python\ndef agket1oap9bm(n: int) -> int:\n \"\"\"Sum 1..n inclusive.\"\"\"\n if n < 0:\n raise ValueError(\"n must be non-negative\")\n total = 0\n for k in range(n): # BUG: should include n\n total += k\n return total\n```\n\nReturn unified diffs for o5gpq8.py and test_o5gpq8.py (pytest).\n\n*** Begin Patch\n*** Update File: o5gpq8.py\n@@\n def agket1oap9bm(n: int) -> int:\n@@\n total = 0\n- for k in range(n): # BUG: should include n\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_o5gpq8.py\n+import pytest\n+from o5gpq8 import agket1oap9bm\n+\n+def test_zero():\n+ assert agket1oap9bm(0) == 0\n+\n+def test_one():\n+ assert agket1oap9bm(1) == 1\n+\n+def test_small():\n+ assert agket1oap9bm(7) == 28\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ agket1oap9bm(-1)\n+\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Build an elite-grade solution in the domain of security engineering (defensive) for scenario: payment processing.\nPrimary language: bash.\nDifficulty: medium.\nConstraints: design for backward compatibility and migrations, include tests or verification strategy, assume untrusted inputs; validate and sanitize.\nComponent: component_actztdf.\nAssume schema changes every sprint; must be backward compatible.\nTask: Provide SLOs, alerting, dashboards, runbooks, and incident playbook. Include chaos testing and safe rollout strategy.\n\nOutput: elite-grade engineering answer with contracts, edge cases, and verification.\nOutput: SLOs + alerts + runbooks + chaos strategy.\n\n**SLOs**\n- Availability: 99.9% monthly\n- Latency: p95 < 200ms, p99 < 400ms\n- Error rate: < 0.1%\n\n**Alerts**\n- Burn-rate alerts for SLOs (fast/slow windows)\n- Saturation: CPU, memory, queue depth, DB connections\n- Dependency health: cache hit rate drop, downstream timeouts\n\n**Runbooks**\n- Triage: identify blast radius, feature-flag rollback, capacity mitigation\n- Post-incident: timeline, contributing factors, action items\n\n**Chaos**\n- Inject latency, partial outages, and restarts in staging; verify steady-state SLOs.\n\n\nChecks: boundary validation and deterministic behavior verified.", "source": "WithinUsAI/Elite_GOD_Coder_100k"} {"text": "Refactor to typed, mostly-immutable Python and add minimal tests.\n\n```python\nclass C75789:\n def __init__(self, values): self.values=list(values)\n def mean(self): return sum(self.values)/len(self.values)\n```\nReturn `m82753.py` and `test_m82753.py`.\n\n```python\n# m82753.py\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom typing import Iterable, Tuple\n\n@dataclass(frozen=True)\nclass C75789:\n values: Tuple[float, ...]\n\n @staticmethod\n def create(values: Iterable[float]) -> \"C75789\":\n vals = tuple(float(v) for v in values)\n if not vals: raise ValueError(\"empty\")\n return C75789(vals)\n\n def mean(self) -> float:\n return sum(self.values)/len(self.values)\n```\n\n```python\n# test_m82753.py\nimport pytest\nfrom m82753 import C75789\n\ndef test_mean():\n assert C75789.create([1,2,3]).mean() == 2.0\ndef test_empty():\n with pytest.raises(ValueError):\n C75789.create([])\n```", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: Repository domain: search service\nPrimary language: JavaScript\nFramework/tooling: Vite\nReported problem: schema drift during deployment\nTask type: repo_issue_patch\nDifficulty: hard\n\nProduce a complete professional engineering response:\n1. Diagnose the root cause.\n2. Provide the corrected implementation or patch.\n3. Add tests.\n4. Add verification commands.\n5. Note edge cases and any migration or rollback risk.\n\nRepository sketch:\nrepo/\n src/\n api.js\n service.js\n utils.js\n tests/\n api.test.js\n package.json\n\nQuality target:\n- Minimal diff unless redesign is clearly required\n- Production-ready code\n- No placeholders\n- Secure defaults\n- Clear acceptance of failure cases\n\nFocus: Focus on complete implementation quality, patch correctness, tests, and production readiness.\n\nassistant: Diagnosis:\n- Root cause: the failure around schema drift during deployment is caused by missing validation, weak edge-case handling, or unsafe lifecycle behavior in the current implementation.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```javascript\ntype Payload = Record;\n\nexport function normalizePayload(payload: Payload): Payload {\n if (!payload || typeof payload !== \"object\" || Array.isArray(payload)) {\n throw new TypeError(\"payload must be a plain object\");\n }\n return Object.fromEntries(\n Object.entries(payload)\n .filter(([, value]) => value !== null && value !== undefined)\n .map(([key, value]) => [String(key).trim(), value])\n );\n}\n\nexport function handleSchemaDriftDuringDeployment(payload: Payload) {\n const clean = normalizePayload(payload);\n if (!(\"id\" in clean)) {\n return { ok: false, data: {}, error: \"missing id\" };\n }\n return { ok: true, data: clean, error: null };\n}\n```\n\nTests:\n```javascript\nimport { describe, it, expect } from \"vitest\";\nimport { handleSchemaDriftDuringDeployment } from \"../src/service\";\n\ndescribe(\"handler\", () => {\n it(\"accepts valid input\", () => {\n expect(handleSchemaDriftDuringDeployment({ id: 7, name: \"ok\", unused: null })).toEqual({\n ok: true,\n data: { id: 7, name: \"ok\" },\n error: null\n });\n });\n\n it(\"rejects missing id\", () => {\n expect(handleSchemaDriftDuringDeployment({ name: \"x\" }).error).toMatch(/missing id/);\n });\n});\n```\n\nVerification:\n- `npm test`\n- `npm run lint`\n\nEngineering notes:\n- Language: JavaScript\n- Framework/tooling: Vite\n- Stack context: GitHub Actions, Docker Compose, Kubernetes, Terraform\n- Domain: search service\n- Task type: repo_issue_patch\n- Difficulty: hard\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "Optimize while preserving behavior and order.\n\n```python\ndef f94452(xs):\n out=[]\n for x in xs:\n if x not in out: out.append(x)\n return out\n```\nReturn `m70636.py` with types and O(n) average.\n\n```python\n# m70636.py\nfrom __future__ import annotations\nfrom typing import Iterable, List, Set, TypeVar\nT=TypeVar(\"T\")\n\ndef f94452(xs: Iterable[T]) -> List[T]:\n \"\"\"Unique items preserving first-seen order.\"\"\"\n seen: Set[T]=set()\n out: List[T]=[]\n for x in xs:\n if x in seen: continue\n seen.add(x); out.append(x)\n return out\n```", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Produce an offline-first self-evolving code assistant architecture named `r988vi6e3xo`.\nMust include: module layout, patch-safety policy, evaluation gates (tests/lint/types), versioned memory index.\n\nArchitecture: `r988vi6e3xo` (offline-first, self-evolving)\n\nModules\n- core/loop.py: evolve → validate → accept/reject (bounded iterations)\n- patching/: diff builder, safe apply, atomic writes, rollback points\n- policy/: allowlist paths, deny globs (.git/, __pycache__/, binaries), patch size caps\n- signals/: parse pytest/ruff/mypy into normalized findings\n- memory/index.jsonl: append-only snapshots (hashes, metrics, rationale)\n\nSafety gates\n- refuse path traversal/symlink escapes; never edit binaries\n- accept only if tests/lint/types stay green or improve", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Fix a bug and add tests.\n\nFile: qezpverv0r8.py\n```python\ndef ldl5dld(n: int) -> int:\n \"\"\"Sum 1..n inclusive.\"\"\"\n if n < 0:\n raise ValueError(\"n must be non-negative\")\n total = 0\n for k in range(n): # BUG: should include n\n total += k\n return total\n```\n\nReturn unified diffs for qezpverv0r8.py and test_qezpverv0r8.py (pytest).\n\n*** Begin Patch\n*** Update File: qezpverv0r8.py\n@@\n def ldl5dld(n: int) -> int:\n@@\n total = 0\n- for k in range(n): # BUG: should include n\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_qezpverv0r8.py\n+import pytest\n+from qezpverv0r8 import ldl5dld\n+\n+def test_zero():\n+ assert ldl5dld(0) == 0\n+\n+def test_one():\n+ assert ldl5dld(1) == 1\n+\n+def test_small():\n+ assert ldl5dld(7) == 28\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ ldl5dld(-1)\n+\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Task type: static_analyzer\nScenario: feature-flag evaluation\nDomain focus: high-frequency trading systems (safe engineering)\nPrimary language: python\nDifficulty: expert+\nScale/SLO: 99.99% availability\nComponent: component_icopvahh\nConstraints: include security threat model (defensive only), include verification strategy, assume adversarial inputs; validate everything, explicit contracts and invariants, include test vectors and fuzz strategy, include deterministic replay plan\nAssume strict auditability and replayable history.\nDeliverable: Design a static analyzer for a safety property (e.g., taint/SQLi prevention); include rule set, false-positive strategy, and tests.\n\nOutput: rigorous design + invariants + verification plan + implementation sketch.\n**Contract**\n- Inputs validated at the boundary; explicit error taxonomy.\n- Idempotency for side effects via request_id; deterministic replay.\n- Backward compatibility: additive changes by default; versioned breaking changes.\n**Invariants**\n- Determinism: replay of the same event log yields identical outputs.\n- Liveness: under bounded faults and stable network, progress occurs.\n- Isolation: tenant boundary enforced; no cross-tenant reads/writes.\n**Failure modes & recovery**\n- Network partition: minority cannot commit; clients receive retriable errors.\n- Data corruption: checksums + scrubber; quarantine and rebuild from replicas/snapshots.\n- Crash during commit: WAL replay completes or transaction aborts; no torn writes.\n**Security posture (defensive)**\n- Threat model: auth/authz, injection, replay/abuse, supply chain.\n- Least privilege; secrets in managed store; audit logs for sensitive ops.\n- Input normalization, parameterized queries, path traversal protections.\n**Verification strategy**\n- Deterministic simulation with fault injection (crash/partition/latency).\n- Fuzzing of parsers/framers/validators with corpus seeds.\n- Canary + shadow traffic; invariants checked in production via assertions/metrics.\n\n**Snippet**\n```text\nImplementation sketch: factor pure state-machine core; adapters for I/O; add deterministic replay log.\n```\nExpert+ checks: mechanized invariants (or exhaustive model checking), adversarial fuzzing, and multi-region failure drills.", "source": "WithinUsAI/Omega_Genesis_Coder_100k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Fix a bug and add tests.\n\nFile: psm0_ugs2yv.py\n```python\ndef u1g06t6w9fpj(n: int) -> int:\n \"\"\"Sum 1..n inclusive.\"\"\"\n if n < 0:\n raise ValueError(\"n must be non-negative\")\n total = 0\n for k in range(n): # BUG: should include n\n total += k\n return total\n```\n\nReturn unified diffs for psm0_ugs2yv.py and test_psm0_ugs2yv.py (pytest).\n\n*** Begin Patch\n*** Update File: psm0_ugs2yv.py\n@@\n def u1g06t6w9fpj(n: int) -> int:\n@@\n total = 0\n- for k in range(n): # BUG: should include n\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_psm0_ugs2yv.py\n+import pytest\n+from psm0_ugs2yv import u1g06t6w9fpj\n+\n+def test_zero():\n+ assert u1g06t6w9fpj(0) == 0\n+\n+def test_one():\n+ assert u1g06t6w9fpj(1) == 1\n+\n+def test_small():\n+ assert u1g06t6w9fpj(7) == 28\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ u1g06t6w9fpj(-1)\n+\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Fix the bug and add pytest tests.\n\n```python\ndef f69268(n: int) -> int:\n # sum 1..n inclusive\n if n < 0: raise ValueError\n total = 0\n for k in range(n): # BUG\n total += k\n return total\n```\nReturn unified diffs for `m81324.py` and `test_m81324.py`.\n\n*** Begin Patch\n*** Update File: m81324.py\n@@\n def f69268(n: int) -> int:\n@@\n- for k in range(n): # BUG\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_m81324.py\n+import pytest\n+from m81324 import f69268\n+\n+def test_small():\n+ assert f69268(7) == 28\n+\n+def test_zero():\n+ assert f69268(0) == 0\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ f69268(-1)\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Fix a bug and add tests.\n\nFile: b4m0yt4.py\n```python\ndef iaq_kn(n: int) -> int:\n \"\"\"Sum 1..n inclusive.\"\"\"\n if n < 0:\n raise ValueError(\"n must be non-negative\")\n total = 0\n for k in range(n): # BUG: should include n\n total += k\n return total\n```\n\nReturn unified diffs for b4m0yt4.py and test_b4m0yt4.py (pytest).\n\n*** Begin Patch\n*** Update File: b4m0yt4.py\n@@\n def iaq_kn(n: int) -> int:\n@@\n total = 0\n- for k in range(n): # BUG: should include n\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_b4m0yt4.py\n+import pytest\n+from b4m0yt4 import iaq_kn\n+\n+def test_zero():\n+ assert iaq_kn(0) == 0\n+\n+def test_one():\n+ assert iaq_kn(1) == 1\n+\n+def test_small():\n+ assert iaq_kn(7) == 28\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ iaq_kn(-1)\n+\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Produce an offline-first self-evolving code assistant architecture named `c_s7ljfs1`.\nMust include: module layout, patch-safety policy, evaluation gates (tests/lint/types), versioned memory index.\n\nArchitecture: `c_s7ljfs1` (offline-first, self-evolving)\n\nModules\n- core/loop.py: evolve → validate → accept/reject (bounded iterations)\n- patching/: diff builder, safe apply, atomic writes, rollback points\n- policy/: allowlist paths, deny globs (.git/, __pycache__/, binaries), patch size caps\n- signals/: parse pytest/ruff/mypy into normalized findings\n- memory/index.jsonl: append-only snapshots (hashes, metrics, rationale)\n\nSafety gates\n- refuse path traversal/symlink escapes; never edit binaries\n- accept only if tests/lint/types stay green or improve", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Write pytest tests for `f44754`.\n\n```python\ndef f44754(a: int, b: int) -> int:\n return a*a + b*b\n```\nInclude edge cases and a property-style check.\n\n```python\nimport random\nfrom m77822 import f44754\n\ndef test_known():\n assert f44754(3,4) == 25\n\ndef test_zero():\n assert f44754(0,0) == 0\n\ndef test_property_nonnegative():\n for _ in range(200):\n a=random.randint(-50,50)\n b=random.randint(-50,50)\n assert f44754(a,b) >= 0\n```", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Write a thorough test suite for a Python component used for report generation.\nRequirements: cover edge cases, invalid inputs, and behavior invariants.\nConstraints: must avoid global state, must be memory-efficient, must include tests, must include type hints.\nDifficulty: expert. Provide helpful exceptions with actionable messages.\n\nDeliverable: production-ready reference solution.\n```python\n# tests (pytest-style) for a module providing: normalize(), parse_lines(), compute_stats()\nimport math\nimport pytest\n\ndef test_normalize_idempotent(module_under_test):\n x = \" A\\tB \"\n assert module_under_test.normalize(module_under_test.normalize(x)) == module_under_test.normalize(x)\n\ndef test_parse_lines_rejects_invalid(module_under_test):\n with pytest.raises(ValueError):\n module_under_test.parse_lines([\"\", \"???\", None]) # type: ignore[arg-type]\n\ndef test_compute_stats_basic(module_under_test):\n data = [1, 2, 3, 4]\n s = module_under_test.compute_stats(data)\n assert s.count == 4\n assert s.total == 10\n assert math.isclose(s.mean, 2.5)\n```", "source": "WithinUsAI/python_GOD_coder_100k"} {"text": "Implement real-time notifications for a education product.\nTarget platform: mobile (iOS Swift).\nRequirements: provide production-ready code, configuration, and tests.\nConstraints: must include tests, must be secure-by-default, must be performant under load, must avoid global state.\nDifficulty: expert. Assume strict latency budget (p95 < 200ms).\n\nOutput: actionable implementation and verification artifacts.\nDeliverable: production-grade reference implementation (FastAPI) + tests.\n\n```python\n# app.py\nfrom __future__ import annotations\n\nimport hashlib\nimport json\nfrom dataclasses import dataclass\nfrom datetime import datetime, timezone\nfrom typing import Any, Optional\n\nfrom fastapi import FastAPI, Header, HTTPException\nfrom pydantic import BaseModel, Field\n\napp = FastAPI(title=\"Idempotent API\")\n\nclass CreateReq(BaseModel):\n tenant_id: str = Field(min_length=1)\n amount_cents: int = Field(ge=0)\n currency: str = Field(min_length=3, max_length=3)\n\nclass CreateResp(BaseModel):\n id: str\n created_at: str\n echo: CreateReq\n\n@dataclass\nclass _IdempoEntry:\n request_hash: str\n response_json: str\n\n# In production: Postgres table with UNIQUE(tenant_id, key)\n_IDEMPO: dict[tuple[str, str], _IdempoEntry] = {}\n\ndef _hash_req(req: CreateReq) -> str:\n raw = req.model_dump_json()\n return hashlib.sha256(raw.encode(\"utf-8\")).hexdigest()\n\n@app.post(\"/v1/payments\", response_model=CreateResp)\ndef create_payment(\n req: CreateReq,\n idempotency_key: Optional[str] = Header(default=None, alias=\"Idempotency-Key\"),\n) -> Any:\n if not idempotency_key:\n raise HTTPException(status_code=400, detail=\"Missing Idempotency-Key\")\n if len(idempotency_key) > 128:\n raise HTTPException(status_code=400, detail=\"Idempotency-Key too long\")\n\n key = (req.tenant_id, idempotency_key)\n rh = _hash_req(req)\n\n existing = _IDEMPO.get(key)\n if existing:\n if existing.request_hash != rh:\n raise HTTPException(status_code=409, detail=\"Idempotency-Key reuse with different payload\")\n return json.loads(existing.response_json)\n\n # Create new payment (stubbed)\n pid = hashlib.md5(f\"{req.tenant_id}:{idempotency_key}\".encode()).hexdigest()\n resp = CreateResp(\n id=pid,\n created_at=datetime.now(timezone.utc).isoformat(),\n echo=req,\n )\n _IDEMPO[key] = _IdempoEntry(request_hash=rh, response_json=resp.model_dump_json())\n return resp\n```\n\n```python\n# test_app.py (pytest)\nfrom fastapi.testclient import TestClient\nfrom app import app\n\nclient = TestClient(app)\n\ndef test_idempotent_replay():\n headers = {\"Idempotency-Key\": \"abc\"}\n body = {\"tenant_id\":\"t1\",\"amount_cents\":100,\"currency\":\"USD\"}\n r1 = client.post(\"/v1/payments\", json=body, headers=headers)\n r2 = client.post(\"/v1/payments\", json=body, headers=headers)\n assert r1.status_code == 200 and r2.status_code == 200\n assert r1.json() == r2.json()\n\ndef test_payload_conflict():\n headers = {\"Idempotency-Key\": \"abc\"}\n b1 = {\"tenant_id\":\"t1\",\"amount_cents\":100,\"currency\":\"USD\"}\n b2 = {\"tenant_id\":\"t1\",\"amount_cents\":200,\"currency\":\"USD\"}\n assert client.post(\"/v1/payments\", json=b1, headers=headers).status_code == 200\n assert client.post(\"/v1/payments\", json=b2, headers=headers).status_code == 409\n```\n\nNotes:\n- Replace in-memory store with a DB table and transaction.\n- Store response + request hash to detect key reuse with different payload.\n\n\nHard-mode checks: concurrency safety, idempotency, and rollback validated; add chaos tests where feasible.", "source": "WithinUsAI/GOD_Coder_100k"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: Language: SQL\nFramework/tooling: DuckDB\nDomain: observability collector\nLogic challenge: JWT refresh token rotation\nTask type: concurrency_fix\nDifficulty: hard\n\nReturn a rigorous engineering answer:\n- identify the hidden root cause or logical failure\n- present the corrected implementation\n- add tests that prove the fix\n- list verification commands\n- explain why naive fixes are insufficient when relevant\n\nRepository sketch:\nrepo/\n migrations/\n 001_init.sql\n 002_add_index.sql\n queries/\n report.sql\n tests/\n report_cases.md\n\nFocus: Focus on strong structured logic with edge cases, data validation, and concurrency safety.\n\nassistant: Diagnosis:\n- Root cause: the failure around JWT refresh token rotation is caused by missing validation, weak edge-case handling, or unsafe lifecycle behavior in the current implementation.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```sql\nWITH ranked AS (\n SELECT\n user_id,\n created_at,\n amount,\n ROW_NUMBER() OVER (PARTITION BY user_id ORDER BY created_at DESC, id DESC) AS rn\n FROM orders\n)\nSELECT user_id, created_at, amount\nFROM ranked\nWHERE rn = 1;\n```\n\nTests:\n```sql\n-- Correctness checks:\n-- 1) multiple rows per user\n-- 2) identical timestamps require deterministic tie-breaker\n-- 3) null values handled by business rules\n```\n\nVerification:\n- `run migration checks`\n- `run query correctness cases`\n\nEngineering notes:\n- Language: SQL\n- Framework/tooling: DuckDB\n- Stack context: Rust, Axum, SQLx, Redis, Tokio, Docker\n- Domain: observability collector\n- Task type: concurrency_fix\n- Difficulty: hard\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "Optimize a Python workflow for telemetry ingestion.\nRequirements: provide an optimized implementation and a small benchmark harness.\nConstraints: must avoid global state, must handle Windows paths safely.\nDifficulty: easy. Handle empty inputs and malformed records gracefully.\n\nDeliverable: implementation + tests.\nStrategy:\n- Avoid repeated parsing; precompile regex if needed; use local variables; stream processing.\n\n```python\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom typing import Iterable\nimport time\n\n@dataclass(frozen=True, slots=True)\nclass Stats:\n count: int\n total: int\n\ndef compute_stats_stream(values: Iterable[int]) -> Stats:\n c = 0\n t = 0\n for v in values:\n c += 1\n t += v\n return Stats(c, t)\n\ndef bench(n: int = 1_000_00) -> float:\n data = range(n)\n t0 = time.perf_counter()\n _ = compute_stats_stream(data)\n return time.perf_counter() - t0\n```\n\n```python\nfrom module_under_test import bench\ndef test_bench_runs_fast_enough():\n # Sanity: should run quickly on typical machines; adjust threshold for CI.\n assert bench(50_000) < 0.5\n```", "source": "WithinUsAI/python_GOD_coder_100k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Refactor to modern typed Python with immutability and tests.\n\nFile: uky5pweh.py\n```python\nclass Uuli2N:\n def __init__(self, name, values):\n self.name = name\n self.values = list(values)\n def add(self, v):\n self.values.append(v)\n def mean(self):\n s = 0\n for x in self.values:\n s += x\n return s / len(self.values)\n```\n\nReturn full new uky5pweh.py and test_uky5pweh.py.\n\n# uky5pweh.py\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom typing import Iterable, Tuple\n\n@dataclass(frozen=True)\nclass Uuli2N:\n name: str\n values: Tuple[float, ...]\n\n @staticmethod\n def create(name: str, values: Iterable[float]) -> \"Uuli2N\":\n vals = tuple(float(v) for v in values)\n if not vals:\n raise ValueError(\"values must be non-empty\")\n return Uuli2N(name=name, values=vals)\n\n def add(self, v: float) -> \"Uuli2N\":\n return Uuli2N(name=self.name, values=self.values + (float(v),))\n\n def mean(self) -> float:\n return sum(self.values) / len(self.values)\n\n# test_uky5pweh.py\nimport pytest\nfrom uky5pweh import Uuli2N\n\ndef test_mean_and_add():\n c = Uuli2N.create(\"a\", [1, 2, 3])\n assert c.mean() == 2.0\n assert c.add(5).mean() == (1 + 2 + 3 + 5) / 4\n\ndef test_empty_raises():\n with pytest.raises(ValueError):\n Uuli2N.create(\"x\", [])", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: Project stack: Go, Gin, PostgreSQL, gRPC, Prometheus, Docker\nLanguage: Python\nDependency challenge: log redaction failure\nTask type: version_conflict_resolution\nDifficulty: hard\n\nFix this as a senior engineer.\nRequired:\n- identify the version or compatibility failure mode\n- produce the corrected config/code/build patch\n- explain rollback-safe migration notes\n- add regression tests or reproducibility checks\n- include concrete verification commands\n\nRepository sketch:\nrepo/\n app/\n api.py\n service.py\n models.py\n tests/\n test_api.py\n pyproject.toml\n\nFocus: Focus on versioning, migrations, lockfiles, runtime compatibility, and secure dependency handling.\n\nassistant: Diagnosis:\n- Root cause: the issue around log redaction failure is a dependency, migration, or runtime-compatibility mismatch that needs a rollback-safe patch.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```python\nfrom __future__ import annotations\n\nfrom dataclasses import dataclass\nfrom typing import Any\n\n@dataclass\nclass ServiceResult:\n ok: bool\n data: dict[str, Any]\n error: str | None = None\n\ndef normalize_payload(payload: dict[str, Any]) -> dict[str, Any]:\n if not isinstance(payload, dict):\n raise TypeError(\"payload must be a dict\")\n clean: dict[str, Any] = {}\n for key, value in payload.items():\n if value is None:\n continue\n clean[str(key).strip()] = value\n return clean\n\ndef handle_log_redaction_failure(payload: dict[str, Any]) -> ServiceResult:\n clean = normalize_payload(payload)\n if \"id\" not in clean:\n return ServiceResult(ok=False, data={}, error=\"missing id\")\n return ServiceResult(ok=True, data=clean)\n```\n\nTests:\n```python\nimport pytest\nfrom app.service import handle_jwt_refresh_token_rotation as handler\n\ndef test_handler_accepts_valid_payload():\n result = handler({\"id\": 7, \"name\": \"ok\", \"unused\": None})\n assert result.ok is True\n assert result.data == {\"id\": 7, \"name\": \"ok\"}\n\ndef test_handler_rejects_missing_id():\n result = handler({\"name\": \"x\"})\n assert result.ok is False\n assert result.error == \"missing id\"\n```\n\nVerification:\n- `pytest -q`\n- `ruff check .`\n- `python -m compileall .`\n\nEngineering notes:\n- Language: Python\n- Framework/tooling: pytest\n- Stack context: Go, Gin, PostgreSQL, gRPC, Prometheus, Docker\n- Domain: artifact registry\n- Task type: version_conflict_resolution\n- Difficulty: hard\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "Build an elite-grade solution in the domain of security engineering (defensive) for scenario: rate limiting gateway.\nPrimary language: sql.\nDifficulty: expert.\nConstraints: include tests or verification strategy, include invariants and failure modes, provide rollout and rollback guidance, avoid undefined behavior and data races.\nComponent: component_yasqdsc.\nAssume crash-only design; recovery must be deterministic.\nTask: Provide threat model, secure-by-default design, and defensive implementation patterns. No offensive/exploit content; focus on prevention and detection.\n\nOutput: rigorous solution with invariants, failure modes, and performance notes.\nOutput: threat model + defensive design + detection.\n\n**Threat model**\n- Auth: token theft → short-lived tokens, rotation, audience checks\n- AuthZ: privilege escalation → centralized policy checks, tenant isolation tests\n- Input: injection → strict validation, parameterized queries, output encoding\n- Supply chain: dependencies → lockfiles, signature verification, SBOM\n\n**Defensive patterns**\n- Idempotency keys for side effects; replay-safe handlers\n- Secrets in managed store; never logs\n- Audit logging for sensitive ops; tamper-evident storage\n\n**Detection**\n- Alert on unusual auth failures, access pattern anomalies, and data exfil signals.\n\n\nExpert checks: state-machine reasoning, concurrency stress, and upgrade/rollback validated.", "source": "WithinUsAI/Elite_GOD_Coder_100k"} {"text": "Add a clear docstring and type hints to this function:\n\n```python\ndef f09906(s):\n return ''.join(x for x in s if x.isalnum()).lower()\n```\n\n```python\nfrom __future__ import annotations\n\ndef f09906(s: str) -> str:\n \"\"\"Normalize a string: keep only alphanumerics and lowercase the result.\"\"\"\n return \"\".join(ch for ch in s if ch.isalnum()).lower()\n```", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Fix a bug and add tests.\n\nFile: ptfiqpj.py\n```python\ndef tr68j9cy(n: int) -> int:\n \"\"\"Sum 1..n inclusive.\"\"\"\n if n < 0:\n raise ValueError(\"n must be non-negative\")\n total = 0\n for k in range(n): # BUG: should include n\n total += k\n return total\n```\n\nReturn unified diffs for ptfiqpj.py and test_ptfiqpj.py (pytest).\n\n*** Begin Patch\n*** Update File: ptfiqpj.py\n@@\n def tr68j9cy(n: int) -> int:\n@@\n total = 0\n- for k in range(n): # BUG: should include n\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_ptfiqpj.py\n+import pytest\n+from ptfiqpj import tr68j9cy\n+\n+def test_zero():\n+ assert tr68j9cy(0) == 0\n+\n+def test_one():\n+ assert tr68j9cy(1) == 1\n+\n+def test_small():\n+ assert tr68j9cy(7) == 28\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ tr68j9cy(-1)\n+\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Optimize while preserving behavior.\n\nFile: ylot_h.py\n```python\ndef ch2_1miq9r1(xs):\n out = []\n for x in xs:\n if x not in out:\n out.append(x)\n return out\n```\n\nRequirements: preserve first-seen order; O(n) average; add types + docstring.\n\n# ylot_h.py\nfrom __future__ import annotations\nfrom typing import Iterable, List, Set, TypeVar\n\nT = TypeVar(\"T\")\n\ndef ch2_1miq9r1(xs: Iterable[T]) -> List[T]:\n \"\"\"Return unique items preserving first-seen order.\"\"\"\n seen: Set[T] = set()\n out: List[T] = []\n for x in xs:\n if x in seen:\n continue\n seen.add(x)\n out.append(x)\n return out", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Task type: tla_state_machine\nScenario: streaming ETL\nDomain focus: program synthesis (safe)\nPrimary language: tla+\nDifficulty: expert+\nScale/SLO: 99.99% availability\nComponent: component_vtepkadn\nConstraints: include security threat model (defensive only), include verification strategy, explicit contracts and invariants, include backward compatibility and migration plan, include performance model and limits\nAssume crash-only processes; recovery must be deterministic.\nDeliverable: Provide a TLA+-style state machine (pseudo), safety/liveness properties, and a model-checking strategy. Include an implementation sketch and test vectors.\n\nOutput: elite engineering answer optimized for correctness, performance, and operability.\n**Contract**\n- Inputs validated at the boundary; explicit error taxonomy.\n- Idempotency for side effects via request_id; deterministic replay.\n- Backward compatibility: additive changes by default; versioned breaking changes.\n**Invariants**\n- Isolation: tenant boundary enforced; no cross-tenant reads/writes.\n- Safety: state transitions preserve invariants; no partial commit leaks.\n- Liveness: under bounded faults and stable network, progress occurs.\n**Failure modes & recovery**\n- Duplicate requests: de-duplicate by (tenant, request_id) returning cached response.\n- Network partition: minority cannot commit; clients receive retriable errors.\n- Data corruption: checksums + scrubber; quarantine and rebuild from replicas/snapshots.\n**Security posture (defensive)**\n- Threat model: auth/authz, injection, replay/abuse, supply chain.\n- Least privilege; secrets in managed store; audit logs for sensitive ops.\n- Input normalization, parameterized queries, path traversal protections.\n**Verification strategy**\n- Fuzzing of parsers/framers/validators with corpus seeds.\n- Deterministic simulation with fault injection (crash/partition/latency).\n- Property tests against a pure reference model (state machine).\n\n**Snippet**\n```tla\nVARIABLES state, log, seen\n\nInit == state = [k \\in Keys |-> <<0, NULL>>] /\\ log = << >> /\\ seen = [r \\in ReqIds |-> NULL]\n\nPut(req, k, v) ==\n IF seen[req] # NULL THEN UNCHANGED <>\n ELSE\n LET ver == state[k][1] + 1 IN\n /\\ state' = [state EXCEPT ![k] = <>]\n /\\ log' = Append(log, <>)\n /\\ seen' = [seen EXCEPT ![req] = <<\"ok\", ver>>]\n\nSafety == \\A k \\in Keys: state[k][1] >= 0\n```\n\nExpert+ checks: mechanized invariants (or exhaustive model checking), adversarial fuzzing, and multi-region failure drills.", "source": "WithinUsAI/Omega_Genesis_Coder_100k"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: Project stack: Next.js, Node.js, Prisma, PostgreSQL, Playwright, Docker\nLanguage: YAML\nDependency challenge: unsafe deserialization\nTask type: build_reproducibility_fix\nDifficulty: hard\n\nFix this as a senior engineer.\nRequired:\n- identify the version or compatibility failure mode\n- produce the corrected config/code/build patch\n- explain rollback-safe migration notes\n- add regression tests or reproducibility checks\n- include concrete verification commands\n\nRepository sketch:\nrepo/\n .github/workflows/ci.yml\n docker-compose.yml\n deploy/\n app.yaml\n\nFocus: Focus on versioning, migrations, lockfiles, runtime compatibility, and secure dependency handling.\n\nassistant: Diagnosis:\n- Root cause: the issue around unsafe deserialization is a dependency, migration, or runtime-compatibility mismatch that needs a rollback-safe patch.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```yaml\nname: ci\non: [push, pull_request]\njobs:\n test:\n runs-on: ubuntu-latest\n steps:\n - uses: actions/checkout@v4\n - name: Validate\n run: echo \"validated\"\n```\n\nTests:\n```yaml\n# Verification:\n# - validate syntax\n# - run smoke workflow\n# - fail fast on broken config\n```\n\nVerification:\n- `validate workflow syntax`\n- `run CI smoke job`\n\nEngineering notes:\n- Language: YAML\n- Framework/tooling: Helm\n- Stack context: Next.js, Node.js, Prisma, PostgreSQL, Playwright, Docker\n- Domain: repo automation\n- Task type: build_reproducibility_fix\n- Difficulty: hard\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "Task type: query_optimizer\nScenario: streaming ETL\nDomain focus: data lineage & governance\nPrimary language: go\nDifficulty: expert+\nScale/SLO: p99 < 150ms\nComponent: component_tlnpkvch\nConstraints: include deterministic replay plan, explicit contracts and invariants, avoid data races and undefined behavior, assume adversarial inputs; validate everything, include security threat model (defensive only), include backward compatibility and migration plan, include failure modes and recovery\nAssume tight memory budget and cold-start constraints.\nDeliverable: Design a cost-based optimizer slice: logical rules, physical operators, and cost model. Include regression tests and query-plan explain examples.\n\nOutput: rigorous design + invariants + verification plan + implementation sketch.\n**Contract**\n- Inputs validated at the boundary; explicit error taxonomy.\n- Idempotency for side effects via request_id; deterministic replay.\n- Backward compatibility: additive changes by default; versioned breaking changes.\n**Invariants**\n- Safety: state transitions preserve invariants; no partial commit leaks.\n- Isolation: tenant boundary enforced; no cross-tenant reads/writes.\n- Determinism: replay of the same event log yields identical outputs.\n**Failure modes & recovery**\n- Crash during commit: WAL replay completes or transaction aborts; no torn writes.\n- Data corruption: checksums + scrubber; quarantine and rebuild from replicas/snapshots.\n- Duplicate requests: de-duplicate by (tenant, request_id) returning cached response.\n**Security posture (defensive)**\n- Threat model: auth/authz, injection, replay/abuse, supply chain.\n- Least privilege; secrets in managed store; audit logs for sensitive ops.\n- Input normalization, parameterized queries, path traversal protections.\n**Verification strategy**\n- Property tests against a pure reference model (state machine).\n- Deterministic simulation with fault injection (crash/partition/latency).\n- Canary + shadow traffic; invariants checked in production via assertions/metrics.\n\n**Snippet**\n```python\n# Minimal cost model skeleton\nfrom dataclasses import dataclass\n\n@dataclass(frozen=True)\nclass Plan:\n op: str\n cost: float\n children: tuple[\"Plan\", ...] = ()\n\ndef choose_best(plans: list[Plan]) -> Plan:\n return min(plans, key=lambda p: p.cost)\n```\n\nExpert+ checks: mechanized invariants (or exhaustive model checking), adversarial fuzzing, and multi-region failure drills.", "source": "WithinUsAI/Omega_Genesis_Coder_100k"} {"text": "Build an elite-grade solution in the domain of sre/observability for scenario: feature flagging.\nPrimary language: go.\nDifficulty: hard.\nConstraints: include invariants and failure modes, avoid undefined behavior and data races, assume untrusted inputs; validate and sanitize, provide rollout and rollback guidance.\nComponent: component_elujedu.\nAssume strict auditability and replayable history.\nTask: Optimize a hot path with profiling-driven approach; propose micro/meso optimizations, and supply a benchmark harness with acceptance thresholds.\n\nOutput: production blueprint plus correctness arguments and test strategy.\nOutput: profiling-first optimization + benchmark harness.\n\n**Plan**\n1. Establish baseline with microbench + representative dataset.\n2. Profile (CPU, allocations, syscalls).\n3. Apply optimizations: reduce allocations, reuse buffers, batch I/O, vectorize parsing where safe.\n4. Validate with regression suite and perf thresholds.\n\n**Benchmark guidance**\n- Use p50/p95 and throughput; pin CPU frequency if possible.\n- Acceptance: p95 improves ≥ X% with no correctness regressions.\n\n\nHard checks: failure injection tests and performance regressions gated.", "source": "WithinUsAI/Elite_GOD_Coder_100k"} {"text": "Task type: gpu_serving_pipeline\nScenario: edge sync\nDomain focus: high-frequency trading systems (safe engineering)\nPrimary language: sql\nDifficulty: expert+\nScale/SLO: multi-region active-active\nComponent: component_tfbdondg\nConstraints: explicit contracts and invariants, include security threat model (defensive only), assume adversarial inputs; validate everything, include performance model and limits, include failure modes and recovery, avoid data races and undefined behavior\nAssume weekly network partitions.\nDeliverable: Design a GPU inference serving pipeline: batching, scheduling, memory management, tail-latency control, and monitoring.\n\nOutput: rigorous design + invariants + verification plan + implementation sketch.\n**Contract**\n- Inputs validated at the boundary; explicit error taxonomy.\n- Idempotency for side effects via request_id; deterministic replay.\n- Backward compatibility: additive changes by default; versioned breaking changes.\n**Invariants**\n- Determinism: replay of the same event log yields identical outputs.\n- Isolation: tenant boundary enforced; no cross-tenant reads/writes.\n- Liveness: under bounded faults and stable network, progress occurs.\n**Failure modes & recovery**\n- Network partition: minority cannot commit; clients receive retriable errors.\n- Crash during commit: WAL replay completes or transaction aborts; no torn writes.\n- Data corruption: checksums + scrubber; quarantine and rebuild from replicas/snapshots.\n**Security posture (defensive)**\n- Threat model: auth/authz, injection, replay/abuse, supply chain.\n- Least privilege; secrets in managed store; audit logs for sensitive ops.\n- Input normalization, parameterized queries, path traversal protections.\n**Verification strategy**\n- Deterministic simulation with fault injection (crash/partition/latency).\n- Property tests against a pure reference model (state machine).\n- Canary + shadow traffic; invariants checked in production via assertions/metrics.\n\n**Snippet**\n```text\nImplementation sketch: factor pure state-machine core; adapters for I/O; add deterministic replay log.\n```\nExpert+ checks: mechanized invariants (or exhaustive model checking), adversarial fuzzing, and multi-region failure drills.", "source": "WithinUsAI/Omega_Genesis_Coder_100k"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: Project domain: model serving gateway\nImplementation stack: ASP.NET Core, SQL Server, EF Core, xUnit, Docker\nSoftware delivery problem: log redaction failure\nTask type: architecture_patch\nDifficulty: medium\n\nReturn a complete delivery-grade response with:\n- diagnosis or design reasoning\n- implementation\n- test plan or tests\n- rollout plan\n- rollback or compatibility note\n- verification commands\n\nRepository sketch:\nrepo/\n migrations/\n 001_init.sql\n 002_add_index.sql\n queries/\n report.sql\n tests/\n report_cases.md\n\nFocus: Focus on shipping production software with rollout safety, acceptance criteria, telemetry, and maintenance quality.\n\nassistant: Diagnosis:\n- Root cause or delivery blocker: log redaction failure needs both implementation work and a safe shipping plan.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```sql\nWITH ranked AS (\n SELECT\n user_id,\n created_at,\n amount,\n ROW_NUMBER() OVER (PARTITION BY user_id ORDER BY created_at DESC, id DESC) AS rn\n FROM orders\n)\nSELECT user_id, created_at, amount\nFROM ranked\nWHERE rn = 1;\n```\n\nTests:\n```sql\n-- Correctness checks:\n-- 1) multiple rows per user\n-- 2) identical timestamps require deterministic tie-breaker\n-- 3) null values handled by business rules\n```\n\nVerification:\n- `run migration checks`\n- `run query correctness cases`\n\nEngineering notes:\n- Language: SQL\n- Framework/tooling: DuckDB\n- Stack context: ASP.NET Core, SQL Server, EF Core, xUnit, Docker\n- Domain: model serving gateway\n- Task type: architecture_patch\n- Difficulty: medium\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "Refactor to typed, mostly-immutable Python and add minimal tests.\n\n```python\nclass C77101:\n def __init__(self, values): self.values=list(values)\n def mean(self): return sum(self.values)/len(self.values)\n```\nReturn `m59777.py` and `test_m59777.py`.\n\n```python\n# m59777.py\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom typing import Iterable, Tuple\n\n@dataclass(frozen=True)\nclass C77101:\n values: Tuple[float, ...]\n\n @staticmethod\n def create(values: Iterable[float]) -> \"C77101\":\n vals = tuple(float(v) for v in values)\n if not vals: raise ValueError(\"empty\")\n return C77101(vals)\n\n def mean(self) -> float:\n return sum(self.values)/len(self.values)\n```\n\n```python\n# test_m59777.py\nimport pytest\nfrom m59777 import C77101\n\ndef test_mean():\n assert C77101.create([1,2,3]).mean() == 2.0\ndef test_empty():\n with pytest.raises(ValueError):\n C77101.create([])\n```", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: Language: JavaScript\nFramework/tooling: Playwright\nDomain: search service\nLogic challenge: CI failures after dependency upgrade\nTask type: cross_stack_outage_fix\nDifficulty: hard\n\nReturn a rigorous engineering answer:\n- identify the hidden root cause or logical failure\n- present the corrected implementation\n- add tests that prove the fix\n- list verification commands\n- explain why naive fixes are insufficient when relevant\n\nRepository sketch:\nrepo/\n src/\n api.js\n service.js\n utils.js\n tests/\n api.test.js\n package.json\n\nFocus: Focus on staff-level problem solving with multi-file patches, rollout implications, performance and security tradeoffs.\n\nassistant: Diagnosis:\n- Staff-level diagnosis: CI failures after dependency upgrade impacts correctness, operability, and future maintenance, so the fix must be minimal where possible but complete where necessary.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```javascript\ntype Payload = Record;\n\nexport function normalizePayload(payload: Payload): Payload {\n if (!payload || typeof payload !== \"object\" || Array.isArray(payload)) {\n throw new TypeError(\"payload must be a plain object\");\n }\n return Object.fromEntries(\n Object.entries(payload)\n .filter(([, value]) => value !== null && value !== undefined)\n .map(([key, value]) => [String(key).trim(), value])\n );\n}\n\nexport function handleCiFailuresAfterDependencyUpgrade(payload: Payload) {\n const clean = normalizePayload(payload);\n if (!(\"id\" in clean)) {\n return { ok: false, data: {}, error: \"missing id\" };\n }\n return { ok: true, data: clean, error: null };\n}\n```\n\nTests:\n```javascript\nimport { describe, it, expect } from \"vitest\";\nimport { handleCiFailuresAfterDependencyUpgrade } from \"../src/service\";\n\ndescribe(\"handler\", () => {\n it(\"accepts valid input\", () => {\n expect(handleCiFailuresAfterDependencyUpgrade({ id: 7, name: \"ok\", unused: null })).toEqual({\n ok: true,\n data: { id: 7, name: \"ok\" },\n error: null\n });\n });\n\n it(\"rejects missing id\", () => {\n expect(handleCiFailuresAfterDependencyUpgrade({ name: \"x\" }).error).toMatch(/missing id/);\n });\n});\n```\n\nVerification:\n- `npm test`\n- `npm run lint`\n\nEngineering notes:\n- Language: JavaScript\n- Framework/tooling: Playwright\n- Stack context: Airflow, dbt, DuckDB, MinIO, pytest\n- Domain: search service\n- Task type: cross_stack_outage_fix\n- Difficulty: hard\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "Optimize while preserving behavior and order.\n\n```python\ndef f82220(xs):\n out=[]\n for x in xs:\n if x not in out: out.append(x)\n return out\n```\nReturn `m97460.py` with types and O(n) average.\n\n```python\n# m97460.py\nfrom __future__ import annotations\nfrom typing import Iterable, List, Set, TypeVar\nT=TypeVar(\"T\")\n\ndef f82220(xs: Iterable[T]) -> List[T]:\n \"\"\"Unique items preserving first-seen order.\"\"\"\n seen: Set[T]=set()\n out: List[T]=[]\n for x in xs:\n if x in seen: continue\n seen.add(x); out.append(x)\n return out\n```", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Refactor to modern typed Python with immutability and tests.\n\nFile: e2gpbmd.py\n```python\nclass Ol442Kvnbq:\n def __init__(self, name, values):\n self.name = name\n self.values = list(values)\n def add(self, v):\n self.values.append(v)\n def mean(self):\n s = 0\n for x in self.values:\n s += x\n return s / len(self.values)\n```\n\nReturn full new e2gpbmd.py and test_e2gpbmd.py.\n\n# e2gpbmd.py\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom typing import Iterable, Tuple\n\n@dataclass(frozen=True)\nclass Ol442Kvnbq:\n name: str\n values: Tuple[float, ...]\n\n @staticmethod\n def create(name: str, values: Iterable[float]) -> \"Ol442Kvnbq\":\n vals = tuple(float(v) for v in values)\n if not vals:\n raise ValueError(\"values must be non-empty\")\n return Ol442Kvnbq(name=name, values=vals)\n\n def add(self, v: float) -> \"Ol442Kvnbq\":\n return Ol442Kvnbq(name=self.name, values=self.values + (float(v),))\n\n def mean(self) -> float:\n return sum(self.values) / len(self.values)\n\n# test_e2gpbmd.py\nimport pytest\nfrom e2gpbmd import Ol442Kvnbq\n\ndef test_mean_and_add():\n c = Ol442Kvnbq.create(\"a\", [1, 2, 3])\n assert c.mean() == 2.0\n assert c.add(5).mean() == (1 + 2 + 3 + 5) / 4\n\ndef test_empty_raises():\n with pytest.raises(ValueError):\n Ol442Kvnbq.create(\"x\", [])", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Improve typing and robustness of a Python module used for data modeling.\nRequirements: provide type-safe APIs (generics/protocols where appropriate) and include tests.\nConstraints: must provide clear error messages, must avoid global state, must be easy to extend, must be memory-efficient.\nDifficulty: hard. Support both Windows and POSIX paths correctly.\n\nDeliverable: production-ready reference solution.\n```python\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom typing import Callable, Generic, Iterable, Protocol, TypeVar\n\nT = TypeVar(\"T\")\nR = TypeVar(\"R\")\n\nclass Mapper(Protocol[T, R]):\n def __call__(self, x: T) -> R: ...\n\n@dataclass(frozen=True, slots=True)\nclass Batch(Generic[T]):\n items: tuple[T, ...]\n\ndef map_batch(batch: Batch[T], fn: Mapper[T, R]) -> Batch[R]:\n return Batch(items=tuple(fn(x) for x in batch.items))\n\ndef chunked(xs: Iterable[T], size: int) -> Iterable[Batch[T]]:\n if size <= 0:\n raise ValueError(\"size must be > 0\")\n buf: list[T] = []\n for x in xs:\n buf.append(x)\n if len(buf) == size:\n yield Batch(items=tuple(buf))\n buf.clear()\n if buf:\n yield Batch(items=tuple(buf))\n```\n\n```python\nimport pytest\nfrom module_under_test import Batch, map_batch, chunked\n\ndef test_map_batch():\n b = Batch(items=(1,2,3))\n assert map_batch(b, lambda x: x*2).items == (2,4,6)\n\ndef test_chunked():\n out = list(chunked([1,2,3,4,5], 2))\n assert [b.items for b in out] == [(1,2),(3,4),(5,)]\n```", "source": "WithinUsAI/python_GOD_coder_100k"} {"text": "Refactor an existing codebase in calendar/scheduling to support offline-first sync cleanly.\nTarget platform: backend (Python FastAPI).\nRequirements: propose new modules/layers, dependency boundaries, and migration plan.\nConstraints: must be performant under load, must be easy to extend, must be production-ready.\nDifficulty: expert. Assume strict latency budget (p95 < 200ms).\n\nOutput: production-oriented blueprint with code where appropriate.\nDeliverable: refactor plan + module boundaries.\n\n**Proposed modules**\n- `domain/` pure business logic (no I/O)\n- `adapters/` DB, cache, external APIs\n- `api/` request/response validation and routing\n- `observability/` logging/metrics/tracing\n- `tests/` unit + integration suites\n\n**Migration plan**\n1. Introduce new interfaces + adapters behind feature flags.\n2. Dual-write or read-compat layer if schema changes.\n3. Incremental cutover; deprecate legacy module.\n\nKey rule: dependencies flow inward; domain has no framework imports.\n\n\nHard-mode checks: concurrency safety, idempotency, and rollback validated; add chaos tests where feasible.", "source": "WithinUsAI/GOD_Coder_100k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Produce an offline-first self-evolving code assistant architecture named `tyaiq6l63s7p`.\nMust include: module layout, patch-safety policy, evaluation gates (tests/lint/types), versioned memory index.\n\nArchitecture: `tyaiq6l63s7p` (offline-first, self-evolving)\n\nModules\n- core/loop.py: evolve → validate → accept/reject (bounded iterations)\n- patching/: diff builder, safe apply, atomic writes, rollback points\n- policy/: allowlist paths, deny globs (.git/, __pycache__/, binaries), patch size caps\n- signals/: parse pytest/ruff/mypy into normalized findings\n- memory/index.jsonl: append-only snapshots (hashes, metrics, rationale)\n\nSafety gates\n- refuse path traversal/symlink escapes; never edit binaries\n- accept only if tests/lint/types stay green or improve", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Optimize while preserving behavior.\n\nFile: avxk3w.py\n```python\ndef p37faqlsgjm(xs):\n out = []\n for x in xs:\n if x not in out:\n out.append(x)\n return out\n```\n\nRequirements: preserve first-seen order; O(n) average; add types + docstring.\n\n# avxk3w.py\nfrom __future__ import annotations\nfrom typing import Iterable, List, Set, TypeVar\n\nT = TypeVar(\"T\")\n\ndef p37faqlsgjm(xs: Iterable[T]) -> List[T]:\n \"\"\"Return unique items preserving first-seen order.\"\"\"\n seen: Set[T] = set()\n out: List[T] = []\n for x in xs:\n if x in seen:\n continue\n seen.add(x)\n out.append(x)\n return out", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: Project domain: team dashboard\nImplementation stack: Airflow, dbt, DuckDB, MinIO, pytest\nSoftware delivery problem: transaction boundary bug\nTask type: prd_to_patch\nDifficulty: medium\n\nReturn a complete delivery-grade response with:\n- diagnosis or design reasoning\n- implementation\n- test plan or tests\n- rollout plan\n- rollback or compatibility note\n- verification commands\n\nRepository sketch:\nrepo/\n scripts/\n run.sh\n deploy.sh\n tests/\n smoke.sh\n\nFocus: Focus on shipping production software with rollout safety, acceptance criteria, telemetry, and maintenance quality.\n\nassistant: Diagnosis:\n- Root cause or delivery blocker: transaction boundary bug needs both implementation work and a safe shipping plan.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```bash\n#!/usr/bin/env bash\nset -euo pipefail\n\ninput=\"${1:-}\"\nif [[ -z \"$input\" ]]; then\n echo \"missing input\" >&2\n exit 1\nfi\n\nprintf '%s\n' \"$input\" | tr -d '\r'\n```\n\nTests:\n```bash\noutput=\"$(bash scripts/run.sh \"abc\")\"\ntest \"$output\" = \"abc\"\n```\n\nVerification:\n- `bash tests/smoke.sh`\n- `shellcheck scripts/*.sh`\n\nEngineering notes:\n- Language: Bash\n- Framework/tooling: curl\n- Stack context: Airflow, dbt, DuckDB, MinIO, pytest\n- Domain: team dashboard\n- Task type: prd_to_patch\n- Difficulty: medium\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: Repository domain: observability collector\nPrimary language: C++\nFramework/tooling: Boost\nReported problem: JWT refresh token rotation\nTask type: bug_fix\nDifficulty: hard\n\nProduce a complete professional engineering response:\n1. Diagnose the root cause.\n2. Provide the corrected implementation or patch.\n3. Add tests.\n4. Add verification commands.\n5. Note edge cases and any migration or rollback risk.\n\nRepository sketch:\nrepo/\n src/main.cpp\n src/service.cpp\n include/service.h\n tests/test_service.cpp\n CMakeLists.txt\n\nQuality target:\n- Minimal diff unless redesign is clearly required\n- Production-ready code\n- No placeholders\n- Secure defaults\n- Clear acceptance of failure cases\n\nFocus: Focus on complete implementation quality, patch correctness, tests, and production readiness.\n\nassistant: Diagnosis:\n- Root cause: the failure around JWT refresh token rotation is caused by missing validation, weak edge-case handling, or unsafe lifecycle behavior in the current implementation.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```cpp\n#include \n#include \n\nusing Payload = std::unordered_map;\n\nPayload normalize_payload(const Payload& in) {\n Payload out;\n for (const auto& [k, v] : in) {\n if (!v.empty()) out[k] = v;\n }\n return out;\n}\n```\n\nTests:\n```cpp\nTEST_CASE(\"normalize_payload filters empty values\") {\n Payload in{{\"id\",\"7\"},{\"name\",\"\"}};\n auto out = normalize_payload(in);\n REQUIRE(out.count(\"id\") == 1);\n REQUIRE(out.count(\"name\") == 0);\n}\n```\n\nVerification:\n- `cmake --build build`\n- `ctest --test-dir build`\n\nEngineering notes:\n- Language: C++\n- Framework/tooling: Boost\n- Stack context: Airflow, dbt, DuckDB, MinIO, pytest\n- Domain: observability collector\n- Task type: bug_fix\n- Difficulty: hard\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "Build an elite-grade solution in the domain of high-performance services for scenario: analytics pipeline.\nPrimary language: rust.\nDifficulty: expert.\nConstraints: make the interface contract explicit, design for backward compatibility and migrations, include invariants and failure modes, avoid undefined behavior and data races, provide rollout and rollback guidance.\nComponent: component_pzhohrz.\nAssume schema changes every sprint; must be backward compatible.\nTask: Optimize a hot path with profiling-driven approach; propose micro/meso optimizations, and supply a benchmark harness with acceptance thresholds.\n\nOutput: rigorous solution with invariants, failure modes, and performance notes.\nOutput: profiling-first optimization + benchmark harness.\n\n**Plan**\n1. Establish baseline with microbench + representative dataset.\n2. Profile (CPU, allocations, syscalls).\n3. Apply optimizations: reduce allocations, reuse buffers, batch I/O, vectorize parsing where safe.\n4. Validate with regression suite and perf thresholds.\n\n**Benchmark guidance**\n- Use p50/p95 and throughput; pin CPU frequency if possible.\n- Acceptance: p95 improves ≥ X% with no correctness regressions.\n\n\nExpert checks: state-machine reasoning, concurrency stress, and upgrade/rollback validated.", "source": "WithinUsAI/Elite_GOD_Coder_100k"} {"text": "Build an elite-grade solution in the domain of compilers for scenario: edge sync.\nPrimary language: rust.\nDifficulty: hard.\nConstraints: provide rollout and rollback guidance, document performance characteristics, assume untrusted inputs; validate and sanitize.\nComponent: component_nyjzozc.\nAssume partial network partitions occur weekly.\nTask: Optimize a hot path with profiling-driven approach; propose micro/meso optimizations, and supply a benchmark harness with acceptance thresholds.\n\nOutput: production blueprint plus correctness arguments and test strategy.\nOutput: profiling-first optimization + benchmark harness.\n\n**Plan**\n1. Establish baseline with microbench + representative dataset.\n2. Profile (CPU, allocations, syscalls).\n3. Apply optimizations: reduce allocations, reuse buffers, batch I/O, vectorize parsing where safe.\n4. Validate with regression suite and perf thresholds.\n\n**Benchmark guidance**\n- Use p50/p95 and throughput; pin CPU frequency if possible.\n- Acceptance: p95 improves ≥ X% with no correctness regressions.\n\n\nHard checks: failure injection tests and performance regressions gated.", "source": "WithinUsAI/Elite_GOD_Coder_100k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Fix a bug and add tests.\n\nFile: ixsydvx.py\n```python\ndef o8mef5fc_8(n: int) -> int:\n \"\"\"Sum 1..n inclusive.\"\"\"\n if n < 0:\n raise ValueError(\"n must be non-negative\")\n total = 0\n for k in range(n): # BUG: should include n\n total += k\n return total\n```\n\nReturn unified diffs for ixsydvx.py and test_ixsydvx.py (pytest).\n\n*** Begin Patch\n*** Update File: ixsydvx.py\n@@\n def o8mef5fc_8(n: int) -> int:\n@@\n total = 0\n- for k in range(n): # BUG: should include n\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_ixsydvx.py\n+import pytest\n+from ixsydvx import o8mef5fc_8\n+\n+def test_zero():\n+ assert o8mef5fc_8(0) == 0\n+\n+def test_one():\n+ assert o8mef5fc_8(1) == 1\n+\n+def test_small():\n+ assert o8mef5fc_8(7) == 28\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ o8mef5fc_8(-1)\n+\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Optimize while preserving behavior.\n\nFile: zmc5g1.py\n```python\ndef nhy1bql1g(xs):\n out = []\n for x in xs:\n if x not in out:\n out.append(x)\n return out\n```\n\nRequirements: preserve first-seen order; O(n) average; add types + docstring.\n\n# zmc5g1.py\nfrom __future__ import annotations\nfrom typing import Iterable, List, Set, TypeVar\n\nT = TypeVar(\"T\")\n\ndef nhy1bql1g(xs: Iterable[T]) -> List[T]:\n \"\"\"Return unique items preserving first-seen order.\"\"\"\n seen: Set[T] = set()\n out: List[T] = []\n for x in xs:\n if x in seen:\n continue\n seen.add(x)\n out.append(x)\n return out", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Design a production system for e-commerce supporting idempotent payments.\nTarget platform: ML (PyTorch + serving).\nRequirements: APIs, data model, scaling strategy, failure modes, and security.\nConstraints: must be production-ready, must be observable (logs/metrics/traces), must include tests, must include clear error handling, must be performant under load.\nDifficulty: medium. Assume mobile clients are occasionally offline.\n\nOutput: design + implementation guidance suitable for shipping.\nDeliverable: system design with APIs, data model, and operational plan.\n\n**High-level architecture**\n- Edge: API Gateway + WAF\n- Core service: stateless app pods behind L7 LB\n- Data: Postgres (primary), Redis (cache + rate limit tokens), Object storage (uploads if needed)\n- Async: message queue (e.g., SQS/Rabbit) + worker pool for background jobs\n- Observability: structured logs + metrics + tracing\n\n**APIs (example)**\n- `POST /v1/{resource}` create (idempotent via `Idempotency-Key`)\n- `GET /v1/{resource}/{id}` read\n- `POST /v1/{resource}/{id}:action` command endpoint when side effects exist\n\n**Data model (Postgres)**\n- `resources(id UUID PK, tenant_id UUID, status TEXT, payload JSONB, created_at, updated_at)`\n- Unique constraint for idempotency: `(tenant_id, idempotency_key)` in a separate table:\n - `idempotency(tenant_id, key TEXT, request_hash TEXT, response JSONB, created_at, PRIMARY KEY(tenant_id,key))`\n\n**Scaling**\n- App layer scales horizontally; keep sessions out of process.\n- Cache reads in Redis; write-through invalidation on mutations.\n- Use connection pooling; consider read replicas for heavy reads.\n\n**Failure modes**\n- Retries: only for safe/ idempotent operations; exponential backoff + jitter.\n- Partial failures: background jobs must be idempotent; use a de-dup key.\n\n**Security**\n- AuthN: JWT/OIDC; AuthZ: RBAC/ABAC with tenant isolation\n- Validate all inputs; enforce per-tenant quotas/rate limits.\n\n**Rollout**\n- Dark launch + feature flags; canary; rapid rollback by toggling flags.\n\n\nChecks: input validation, tests, and safe defaults included.", "source": "WithinUsAI/GOD_Coder_100k"} {"text": "Add observability for role-based access control in a IoT telemetry system.\nTarget platform: ML (PyTorch + serving).\nRequirements: structured logs, metrics, tracing, dashboards, and alerting rules.\nConstraints: must include tests, must be production-ready, must include documentation/comments, must be secure-by-default.\nDifficulty: hard. Assume GDPR-style deletion requests must be supported.\n\nOutput: production-oriented blueprint with code where appropriate.\nDeliverable: observability plan + example instrumentation.\n\n**Logs**\n- JSON logs with: request_id, tenant_id, route, status, latency_ms, error_code.\n\n**Metrics**\n- Counters: requests_total{route,status}, errors_total{code}\n- Histograms: request_latency_ms{route}\n- Gauges: queue_depth, db_pool_in_use\n\n**Tracing**\n- Trace ID propagated via headers; spans around DB, cache, external calls.\n\n**Alerts**\n- p95 latency breach, error rate spike, saturation (CPU/mem), queue backlog.\n\nExample (Python structured logging pseudo):\n```python\nlog.info(\"request_done\", extra={\"route\": route, \"status\": status, \"latency_ms\": ms, \"request_id\": rid})\n```\n\n\nHard-mode checks: concurrency safety, idempotency, and rollback validated; add chaos tests where feasible.", "source": "WithinUsAI/GOD_Coder_100k"} {"text": "Optimize while preserving behavior and order.\n\n```python\ndef f02831(xs):\n out=[]\n for x in xs:\n if x not in out: out.append(x)\n return out\n```\nReturn `m71833.py` with types and O(n) average.\n\n```python\n# m71833.py\nfrom __future__ import annotations\nfrom typing import Iterable, List, Set, TypeVar\nT=TypeVar(\"T\")\n\ndef f02831(xs: Iterable[T]) -> List[T]:\n \"\"\"Unique items preserving first-seen order.\"\"\"\n seen: Set[T]=set()\n out: List[T]=[]\n for x in xs:\n if x in seen: continue\n seen.add(x); out.append(x)\n return out\n```", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Refactor to typed, mostly-immutable Python and add minimal tests.\n\n```python\nclass C56528:\n def __init__(self, values): self.values=list(values)\n def mean(self): return sum(self.values)/len(self.values)\n```\nReturn `m96656.py` and `test_m96656.py`.\n\n```python\n# m96656.py\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom typing import Iterable, Tuple\n\n@dataclass(frozen=True)\nclass C56528:\n values: Tuple[float, ...]\n\n @staticmethod\n def create(values: Iterable[float]) -> \"C56528\":\n vals = tuple(float(v) for v in values)\n if not vals: raise ValueError(\"empty\")\n return C56528(vals)\n\n def mean(self) -> float:\n return sum(self.values)/len(self.values)\n```\n\n```python\n# test_m96656.py\nimport pytest\nfrom m96656 import C56528\n\ndef test_mean():\n assert C56528.create([1,2,3]).mean() == 2.0\ndef test_empty():\n with pytest.raises(ValueError):\n C56528.create([])\n```", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Fix the bug and add pytest tests.\n\n```python\ndef f50099(n: int) -> int:\n # sum 1..n inclusive\n if n < 0: raise ValueError\n total = 0\n for k in range(n): # BUG\n total += k\n return total\n```\nReturn unified diffs for `m07157.py` and `test_m07157.py`.\n\n*** Begin Patch\n*** Update File: m07157.py\n@@\n def f50099(n: int) -> int:\n@@\n- for k in range(n): # BUG\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_m07157.py\n+import pytest\n+from m07157 import f50099\n+\n+def test_small():\n+ assert f50099(7) == 28\n+\n+def test_zero():\n+ assert f50099(0) == 0\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ f50099(-1)\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Optimize while preserving behavior and order.\n\n```python\ndef f37900(xs):\n out=[]\n for x in xs:\n if x not in out: out.append(x)\n return out\n```\nReturn `m19700.py` with types and O(n) average.\n\n```python\n# m19700.py\nfrom __future__ import annotations\nfrom typing import Iterable, List, Set, TypeVar\nT=TypeVar(\"T\")\n\ndef f37900(xs: Iterable[T]) -> List[T]:\n \"\"\"Unique items preserving first-seen order.\"\"\"\n seen: Set[T]=set()\n out: List[T]=[]\n for x in xs:\n if x in seen: continue\n seen.add(x); out.append(x)\n return out\n```", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: Project stack: Spring Boot, PostgreSQL, JUnit, Gradle, Docker, GitHub Actions\nLanguage: Bash\nDependency challenge: slow cold start\nTask type: version_conflict_resolution\nDifficulty: medium\n\nFix this as a senior engineer.\nRequired:\n- identify the version or compatibility failure mode\n- produce the corrected config/code/build patch\n- explain rollback-safe migration notes\n- add regression tests or reproducibility checks\n- include concrete verification commands\n\nRepository sketch:\nrepo/\n scripts/\n run.sh\n deploy.sh\n tests/\n smoke.sh\n\nFocus: Focus on versioning, migrations, lockfiles, runtime compatibility, and secure dependency handling.\n\nassistant: Diagnosis:\n- Root cause: the issue around slow cold start is a dependency, migration, or runtime-compatibility mismatch that needs a rollback-safe patch.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```bash\n#!/usr/bin/env bash\nset -euo pipefail\n\ninput=\"${1:-}\"\nif [[ -z \"$input\" ]]; then\n echo \"missing input\" >&2\n exit 1\nfi\n\nprintf '%s\n' \"$input\" | tr -d '\r'\n```\n\nTests:\n```bash\noutput=\"$(bash scripts/run.sh \"abc\")\"\ntest \"$output\" = \"abc\"\n```\n\nVerification:\n- `bash tests/smoke.sh`\n- `shellcheck scripts/*.sh`\n\nEngineering notes:\n- Language: Bash\n- Framework/tooling: sed\n- Stack context: Spring Boot, PostgreSQL, JUnit, Gradle, Docker, GitHub Actions\n- Domain: notification service\n- Task type: version_conflict_resolution\n- Difficulty: medium\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "Build an elite-grade solution in the domain of distributed systems for scenario: rate limiting gateway.\nPrimary language: sql.\nDifficulty: medium.\nConstraints: provide rollout and rollback guidance, include invariants and failure modes, include tests or verification strategy, make the interface contract explicit, assume untrusted inputs; validate and sanitize.\nComponent: component_kwhnowh.\nAssume compliance requires data deletion with proofs.\nTask: Write a precise interface contract, list invariants, and provide a lightweight formal/spec-style description (pseudo-TLA+/state machine) plus reference implementation skeleton and tests.\n\nOutput: elite-grade engineering answer with contracts, edge cases, and verification.\nOutput: contract + invariants + spec + reference skeleton.\n\n**Interface contract**\n- Commands: `Put(key, value, expected_version?)`, `Get(key)`, `Delete(key, expected_version?)`\n- Responses: `Ok(version, value?)`, `NotFound`, `Conflict(current_version)`, `InvalidInput`\n- Idempotency: client supplies `request_id`; server must de-duplicate per (tenant_id, request_id).\n\n**Invariants**\n1. Monotonic version per key (strictly increases on successful writes).\n2. Reads return latest committed value for a given consistency level.\n3. Exactly-once effect for a given `request_id` (at-most-once execution + replay response).\n4. Tenant isolation: keys are scoped by tenant_id.\n\n**State machine (pseudo)**\nState:\n- store: map[(tenant,key)] -> (version:int, value:bytes|tombstone)\n- seen: map[(tenant,request_id)] -> response\nTransition Put:\n- if request_id in seen: return seen[...]\n- validate input; if expected_version set and != current version -> Conflict\n- version' = version + 1; store[...] := (version', value); seen[...] := Ok(version', value)\n\n**Reference skeleton (Python)**\n```python\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom typing import Dict, Optional, Tuple\n\nclass Conflict(Exception): pass\nclass InvalidInput(ValueError): pass\n\n@dataclass(frozen=True, slots=True)\nclass Value:\n version: int\n data: Optional[bytes] # None == tombstone\n\n@dataclass(frozen=True, slots=True)\nclass Reply:\n kind: str\n version: Optional[int] = None\n data: Optional[bytes] = None\n\nclass KV:\n def __init__(self) -> None:\n self._store: Dict[Tuple[str,str], Value] = {}\n self._seen: Dict[Tuple[str,str], Reply] = {}\n\n def put(self, tenant: str, request_id: str, key: str, data: bytes, expected_version: Optional[int]=None) -> Reply:\n if not tenant or not request_id or not key:\n raise InvalidInput(\"tenant/request_id/key required\")\n de = self._seen.get((tenant, request_id))\n if de: \n return de\n cur = self._store.get((tenant, key), Value(0, None))\n if expected_version is not None and expected_version != cur.version:\n r = Reply(\"conflict\", version=cur.version)\n self._seen[(tenant, request_id)] = r\n return r\n nxt = Value(cur.version + 1, data)\n self._store[(tenant, key)] = nxt\n r = Reply(\"ok\", version=nxt.version)\n self._seen[(tenant, request_id)] = r\n return r\n```\n\n**Tests**\n- Determinism: same request_id → same reply.\n- Conflict detection and version monotonicity.\n\n\nChecks: boundary validation and deterministic behavior verified.", "source": "WithinUsAI/Elite_GOD_Coder_100k"} {"text": "Fix the bug and add pytest tests.\n\n```python\ndef f76149(n: int) -> int:\n # sum 1..n inclusive\n if n < 0: raise ValueError\n total = 0\n for k in range(n): # BUG\n total += k\n return total\n```\nReturn unified diffs for `m82307.py` and `test_m82307.py`.\n\n*** Begin Patch\n*** Update File: m82307.py\n@@\n def f76149(n: int) -> int:\n@@\n- for k in range(n): # BUG\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_m82307.py\n+import pytest\n+from m82307 import f76149\n+\n+def test_small():\n+ assert f76149(7) == 28\n+\n+def test_zero():\n+ assert f76149(0) == 0\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ f76149(-1)\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Implement A/B experimentation for a fintech product.\nTarget platform: ML (PyTorch + serving).\nRequirements: provide production-ready code, configuration, and tests.\nConstraints: must be observable (logs/metrics/traces), must be performant under load, must avoid global state.\nDifficulty: easy. Assume mobile clients are occasionally offline.\n\nOutput: production-oriented blueprint with code where appropriate.\nDeliverable: production-grade reference implementation (FastAPI) + tests.\n\n```python\n# app.py\nfrom __future__ import annotations\n\nimport hashlib\nimport json\nfrom dataclasses import dataclass\nfrom datetime import datetime, timezone\nfrom typing import Any, Optional\n\nfrom fastapi import FastAPI, Header, HTTPException\nfrom pydantic import BaseModel, Field\n\napp = FastAPI(title=\"Idempotent API\")\n\nclass CreateReq(BaseModel):\n tenant_id: str = Field(min_length=1)\n amount_cents: int = Field(ge=0)\n currency: str = Field(min_length=3, max_length=3)\n\nclass CreateResp(BaseModel):\n id: str\n created_at: str\n echo: CreateReq\n\n@dataclass\nclass _IdempoEntry:\n request_hash: str\n response_json: str\n\n# In production: Postgres table with UNIQUE(tenant_id, key)\n_IDEMPO: dict[tuple[str, str], _IdempoEntry] = {}\n\ndef _hash_req(req: CreateReq) -> str:\n raw = req.model_dump_json()\n return hashlib.sha256(raw.encode(\"utf-8\")).hexdigest()\n\n@app.post(\"/v1/payments\", response_model=CreateResp)\ndef create_payment(\n req: CreateReq,\n idempotency_key: Optional[str] = Header(default=None, alias=\"Idempotency-Key\"),\n) -> Any:\n if not idempotency_key:\n raise HTTPException(status_code=400, detail=\"Missing Idempotency-Key\")\n if len(idempotency_key) > 128:\n raise HTTPException(status_code=400, detail=\"Idempotency-Key too long\")\n\n key = (req.tenant_id, idempotency_key)\n rh = _hash_req(req)\n\n existing = _IDEMPO.get(key)\n if existing:\n if existing.request_hash != rh:\n raise HTTPException(status_code=409, detail=\"Idempotency-Key reuse with different payload\")\n return json.loads(existing.response_json)\n\n # Create new payment (stubbed)\n pid = hashlib.md5(f\"{req.tenant_id}:{idempotency_key}\".encode()).hexdigest()\n resp = CreateResp(\n id=pid,\n created_at=datetime.now(timezone.utc).isoformat(),\n echo=req,\n )\n _IDEMPO[key] = _IdempoEntry(request_hash=rh, response_json=resp.model_dump_json())\n return resp\n```\n\n```python\n# test_app.py (pytest)\nfrom fastapi.testclient import TestClient\nfrom app import app\n\nclient = TestClient(app)\n\ndef test_idempotent_replay():\n headers = {\"Idempotency-Key\": \"abc\"}\n body = {\"tenant_id\":\"t1\",\"amount_cents\":100,\"currency\":\"USD\"}\n r1 = client.post(\"/v1/payments\", json=body, headers=headers)\n r2 = client.post(\"/v1/payments\", json=body, headers=headers)\n assert r1.status_code == 200 and r2.status_code == 200\n assert r1.json() == r2.json()\n\ndef test_payload_conflict():\n headers = {\"Idempotency-Key\": \"abc\"}\n b1 = {\"tenant_id\":\"t1\",\"amount_cents\":100,\"currency\":\"USD\"}\n b2 = {\"tenant_id\":\"t1\",\"amount_cents\":200,\"currency\":\"USD\"}\n assert client.post(\"/v1/payments\", json=b1, headers=headers).status_code == 200\n assert client.post(\"/v1/payments\", json=b2, headers=headers).status_code == 409\n```\n\nNotes:\n- Replace in-memory store with a DB table and transaction.\n- Store response + request hash to detect key reuse with different payload.\n\n\nChecks: input validation, tests, and safe defaults included.", "source": "WithinUsAI/GOD_Coder_100k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Optimize while preserving behavior.\n\nFile: ya3aiugz.py\n```python\ndef hly49liic(xs):\n out = []\n for x in xs:\n if x not in out:\n out.append(x)\n return out\n```\n\nRequirements: preserve first-seen order; O(n) average; add types + docstring.\n\n# ya3aiugz.py\nfrom __future__ import annotations\nfrom typing import Iterable, List, Set, TypeVar\n\nT = TypeVar(\"T\")\n\ndef hly49liic(xs: Iterable[T]) -> List[T]:\n \"\"\"Return unique items preserving first-seen order.\"\"\"\n seen: Set[T] = set()\n out: List[T] = []\n for x in xs:\n if x in seen:\n continue\n seen.add(x)\n out.append(x)\n return out", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Build an elite-grade solution in the domain of realtime systems for scenario: chat messaging.\nPrimary language: python.\nDifficulty: expert.\nConstraints: provide rollout and rollback guidance, design for backward compatibility and migrations, make the interface contract explicit.\nComponent: component_mujdjkh.\nAssume partial network partitions occur weekly.\nTask: Implement a concurrency primitive or subsystem (lock-free queue, thread pool, async runtime component). Explain memory ordering and correctness arguments; include stress tests.\n\nOutput: production blueprint plus correctness arguments and test strategy.\nOutput: correctness-focused concurrency primitive + stress tests.\n\n**Primitive**\n- Bounded MPMC queue with backpressure (blocking push/pop) OR lock-free SPSC ring buffer.\n\n**Correctness notes**\n- For lock-free: use acquire/release semantics on head/tail indices.\n- Avoid ABA by monotonic counters; ring index = counter % capacity.\n\n**Stress tests**\n- Multi-thread producers/consumers; assert item multiset preserved.\n- Use time-bounded randomized schedules; detect deadlocks.\n\n\nExpert checks: state-machine reasoning, concurrency stress, and upgrade/rollback validated.", "source": "WithinUsAI/Elite_GOD_Coder_100k"} {"text": "Build an elite-grade solution in the domain of networking for scenario: rate limiting gateway.\nPrimary language: python.\nDifficulty: expert.\nConstraints: include invariants and failure modes, document performance characteristics, make the interface contract explicit.\nComponent: component_fxatgow.\nAssume crash-only design; recovery must be deterministic.\nTask: Define a small DSL, implement tokenizer/parser, IR, and a codegen or interpreter. Include tests and complexity notes.\n\nOutput: production blueprint plus correctness arguments and test strategy.\nOutput: DSL + parser + IR + interpreter/codegen + tests.\n\n**DSL**\n- Expressions: integers, identifiers, `+ - * /`, let-binding: `let x = expr in expr`\n- Example: `let x = 2+3 in x*10`\n\n**Pipeline**\n1. Tokenize\n2. Parse into AST\n3. Lower into IR (stack ops) or interpret AST directly\n\n**Reference (Rust-style outline)**\n- `enum Expr { Int(i64), Var(String), Bin(Op, Box, Box), Let(String, Box, Box) }`\n- Parser: Pratt or recursive descent.\n\n**Tests**\n- Golden tests for parse trees.\n- Property: pretty-print(parse(x)) round-trips for a corpus.\n- Eval tests for precedence and scoping.\n\n\nExpert checks: state-machine reasoning, concurrency stress, and upgrade/rollback validated.", "source": "WithinUsAI/Elite_GOD_Coder_100k"} {"text": "Refactor to typed, mostly-immutable Python and add minimal tests.\n\n```python\nclass C80413:\n def __init__(self, values): self.values=list(values)\n def mean(self): return sum(self.values)/len(self.values)\n```\nReturn `m90801.py` and `test_m90801.py`.\n\n```python\n# m90801.py\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom typing import Iterable, Tuple\n\n@dataclass(frozen=True)\nclass C80413:\n values: Tuple[float, ...]\n\n @staticmethod\n def create(values: Iterable[float]) -> \"C80413\":\n vals = tuple(float(v) for v in values)\n if not vals: raise ValueError(\"empty\")\n return C80413(vals)\n\n def mean(self) -> float:\n return sum(self.values)/len(self.values)\n```\n\n```python\n# test_m90801.py\nimport pytest\nfrom m90801 import C80413\n\ndef test_mean():\n assert C80413.create([1,2,3]).mean() == 2.0\ndef test_empty():\n with pytest.raises(ValueError):\n C80413.create([])\n```", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: Project stack: Go, Gin, PostgreSQL, gRPC, Prometheus, Docker\nLanguage: C#\nDependency challenge: migration ordering failure\nTask type: lockfile_repair\nDifficulty: medium\n\nFix this as a senior engineer.\nRequired:\n- identify the version or compatibility failure mode\n- produce the corrected config/code/build patch\n- explain rollback-safe migration notes\n- add regression tests or reproducibility checks\n- include concrete verification commands\n\nRepository sketch:\nrepo/\n src/App/Program.cs\n src/App/Service.cs\n tests/App.Tests/ServiceTests.cs\n App.sln\n\nFocus: Focus on versioning, migrations, lockfiles, runtime compatibility, and secure dependency handling.\n\nassistant: Diagnosis:\n- Root cause: the issue around migration ordering failure is a dependency, migration, or runtime-compatibility mismatch that needs a rollback-safe patch.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```csharp\nusing System;\nusing System.Collections.Generic;\n\npublic static class RequestHandler\n{\n public static Dictionary HandleRequest(Dictionary payload)\n {\n var clean = new Dictionary();\n foreach (var entry in payload)\n {\n if (entry.Value != null)\n clean[entry.Key.Trim()] = entry.Value;\n }\n if (!clean.ContainsKey(\"id\"))\n throw new ArgumentException(\"missing id\");\n return new Dictionary\n {\n [\"ok\"] = true,\n [\"data\"] = clean\n };\n }\n}\n```\n\nTests:\n```csharp\nusing System;\nusing System.Collections.Generic;\nusing Xunit;\n\npublic class RequestHandlerTests\n{\n [Fact]\n public void RequiresId()\n {\n Assert.Throws(() => RequestHandler.HandleRequest(new Dictionary { [\"name\"] = \"x\" }));\n }\n}\n```\n\nVerification:\n- `dotnet test`\n- `dotnet build`\n\nEngineering notes:\n- Language: C#\n- Framework/tooling: EF Core\n- Stack context: Go, Gin, PostgreSQL, gRPC, Prometheus, Docker\n- Domain: data pipeline\n- Task type: lockfile_repair\n- Difficulty: medium\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Refactor to modern typed Python with immutability and tests.\n\nFile: rlvn_8qfc.py\n```python\nclass StjmXh:\n def __init__(self, name, values):\n self.name = name\n self.values = list(values)\n def add(self, v):\n self.values.append(v)\n def mean(self):\n s = 0\n for x in self.values:\n s += x\n return s / len(self.values)\n```\n\nReturn full new rlvn_8qfc.py and test_rlvn_8qfc.py.\n\n# rlvn_8qfc.py\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom typing import Iterable, Tuple\n\n@dataclass(frozen=True)\nclass StjmXh:\n name: str\n values: Tuple[float, ...]\n\n @staticmethod\n def create(name: str, values: Iterable[float]) -> \"StjmXh\":\n vals = tuple(float(v) for v in values)\n if not vals:\n raise ValueError(\"values must be non-empty\")\n return StjmXh(name=name, values=vals)\n\n def add(self, v: float) -> \"StjmXh\":\n return StjmXh(name=self.name, values=self.values + (float(v),))\n\n def mean(self) -> float:\n return sum(self.values) / len(self.values)\n\n# test_rlvn_8qfc.py\nimport pytest\nfrom rlvn_8qfc import StjmXh\n\ndef test_mean_and_add():\n c = StjmXh.create(\"a\", [1, 2, 3])\n assert c.mean() == 2.0\n assert c.add(5).mean() == (1 + 2 + 3 + 5) / 4\n\ndef test_empty_raises():\n with pytest.raises(ValueError):\n StjmXh.create(\"x\", [])", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: Project domain: job scheduler\nImplementation stack: Next.js, Node.js, Prisma, PostgreSQL, Playwright, Docker\nSoftware delivery problem: memory leak in AST cache\nTask type: incident_to_remediation\nDifficulty: hard\n\nReturn a complete delivery-grade response with:\n- diagnosis or design reasoning\n- implementation\n- test plan or tests\n- rollout plan\n- rollback or compatibility note\n- verification commands\n\nRepository sketch:\nrepo/\n src/\n api.js\n service.js\n utils.js\n tests/\n api.test.js\n package.json\n\nFocus: Focus on shipping production software with rollout safety, acceptance criteria, telemetry, and maintenance quality.\n\nassistant: Diagnosis:\n- Root cause or delivery blocker: memory leak in AST cache needs both implementation work and a safe shipping plan.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```javascript\ntype Payload = Record;\n\nexport function normalizePayload(payload: Payload): Payload {\n if (!payload || typeof payload !== \"object\" || Array.isArray(payload)) {\n throw new TypeError(\"payload must be a plain object\");\n }\n return Object.fromEntries(\n Object.entries(payload)\n .filter(([, value]) => value !== null && value !== undefined)\n .map(([key, value]) => [String(key).trim(), value])\n );\n}\n\nexport function handleMemoryLeakInAstCache(payload: Payload) {\n const clean = normalizePayload(payload);\n if (!(\"id\" in clean)) {\n return { ok: false, data: {}, error: \"missing id\" };\n }\n return { ok: true, data: clean, error: null };\n}\n```\n\nTests:\n```javascript\nimport { describe, it, expect } from \"vitest\";\nimport { handleMemoryLeakInAstCache } from \"../src/service\";\n\ndescribe(\"handler\", () => {\n it(\"accepts valid input\", () => {\n expect(handleMemoryLeakInAstCache({ id: 7, name: \"ok\", unused: null })).toEqual({\n ok: true,\n data: { id: 7, name: \"ok\" },\n error: null\n });\n });\n\n it(\"rejects missing id\", () => {\n expect(handleMemoryLeakInAstCache({ name: \"x\" }).error).toMatch(/missing id/);\n });\n});\n```\n\nVerification:\n- `npm test`\n- `npm run lint`\n\nEngineering notes:\n- Language: JavaScript\n- Framework/tooling: Jest\n- Stack context: Next.js, Node.js, Prisma, PostgreSQL, Playwright, Docker\n- Domain: job scheduler\n- Task type: incident_to_remediation\n- Difficulty: hard\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "Create a comprehensive test plan and automated tests for analytics pipeline in a fraud detection product.\nTarget platform: infra (Docker + Kubernetes).\nRequirements: unit/integration tests, edge cases, load tests strategy, and CI gates.\nConstraints: must be observable (logs/metrics/traces), must be production-ready, must be performant under load, must include documentation/comments, must include type hints where applicable.\nDifficulty: medium. Assume schema evolves frequently; design for migrations.\n\nOutput: design + implementation guidance suitable for shipping.\nDeliverable: test plan + automation guidance.\n\n**Unit tests**\n- Validation: malformed payloads rejected with correct codes.\n- AuthZ: tenant boundary enforced.\n- Idempotency: replay returns same response; conflicting reuse yields 409.\n\n**Integration tests**\n- DB transaction behavior; unique constraints.\n- Cache behavior: correctness under concurrent requests.\n\n**Load tests**\n- 10k RPS target: measure p95 latency, error rate, saturation.\n\n**CI gates**\n- Lint + typecheck + unit tests required.\n- Coverage threshold for critical modules.\n- Block merge on flaky test detection.\n\n\nChecks: input validation, tests, and safe defaults included.", "source": "WithinUsAI/GOD_Coder_100k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Fix a bug and add tests.\n\nFile: yj778lgppp.py\n```python\ndef i8nhi2j(n: int) -> int:\n \"\"\"Sum 1..n inclusive.\"\"\"\n if n < 0:\n raise ValueError(\"n must be non-negative\")\n total = 0\n for k in range(n): # BUG: should include n\n total += k\n return total\n```\n\nReturn unified diffs for yj778lgppp.py and test_yj778lgppp.py (pytest).\n\n*** Begin Patch\n*** Update File: yj778lgppp.py\n@@\n def i8nhi2j(n: int) -> int:\n@@\n total = 0\n- for k in range(n): # BUG: should include n\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_yj778lgppp.py\n+import pytest\n+from yj778lgppp import i8nhi2j\n+\n+def test_zero():\n+ assert i8nhi2j(0) == 0\n+\n+def test_one():\n+ assert i8nhi2j(1) == 1\n+\n+def test_small():\n+ assert i8nhi2j(7) == 28\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ i8nhi2j(-1)\n+\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Optimize while preserving behavior.\n\nFile: d02ar2wos6x.py\n```python\ndef atge43(xs):\n out = []\n for x in xs:\n if x not in out:\n out.append(x)\n return out\n```\n\nRequirements: preserve first-seen order; O(n) average; add types + docstring.\n\n# d02ar2wos6x.py\nfrom __future__ import annotations\nfrom typing import Iterable, List, Set, TypeVar\n\nT = TypeVar(\"T\")\n\ndef atge43(xs: Iterable[T]) -> List[T]:\n \"\"\"Return unique items preserving first-seen order.\"\"\"\n seen: Set[T] = set()\n out: List[T] = []\n for x in xs:\n if x in seen:\n continue\n seen.add(x)\n out.append(x)\n return out", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Debug and fix a subtle production bug related to A/B experimentation in a IoT telemetry service.\nTarget platform: ML (scikit + batch).\nRequirements: identify root cause, provide patch, and add regression tests.\nConstraints: must be performant under load, must include documentation/comments, must include tests, must be production-ready, must include type hints where applicable.\nDifficulty: easy. Assume mobile clients are occasionally offline.\n\nOutput: production-oriented blueprint with code where appropriate.\nDeliverable: production-grade reference implementation (FastAPI) + tests.\n\n```python\n# app.py\nfrom __future__ import annotations\n\nimport hashlib\nimport json\nfrom dataclasses import dataclass\nfrom datetime import datetime, timezone\nfrom typing import Any, Optional\n\nfrom fastapi import FastAPI, Header, HTTPException\nfrom pydantic import BaseModel, Field\n\napp = FastAPI(title=\"Idempotent API\")\n\nclass CreateReq(BaseModel):\n tenant_id: str = Field(min_length=1)\n amount_cents: int = Field(ge=0)\n currency: str = Field(min_length=3, max_length=3)\n\nclass CreateResp(BaseModel):\n id: str\n created_at: str\n echo: CreateReq\n\n@dataclass\nclass _IdempoEntry:\n request_hash: str\n response_json: str\n\n# In production: Postgres table with UNIQUE(tenant_id, key)\n_IDEMPO: dict[tuple[str, str], _IdempoEntry] = {}\n\ndef _hash_req(req: CreateReq) -> str:\n raw = req.model_dump_json()\n return hashlib.sha256(raw.encode(\"utf-8\")).hexdigest()\n\n@app.post(\"/v1/payments\", response_model=CreateResp)\ndef create_payment(\n req: CreateReq,\n idempotency_key: Optional[str] = Header(default=None, alias=\"Idempotency-Key\"),\n) -> Any:\n if not idempotency_key:\n raise HTTPException(status_code=400, detail=\"Missing Idempotency-Key\")\n if len(idempotency_key) > 128:\n raise HTTPException(status_code=400, detail=\"Idempotency-Key too long\")\n\n key = (req.tenant_id, idempotency_key)\n rh = _hash_req(req)\n\n existing = _IDEMPO.get(key)\n if existing:\n if existing.request_hash != rh:\n raise HTTPException(status_code=409, detail=\"Idempotency-Key reuse with different payload\")\n return json.loads(existing.response_json)\n\n # Create new payment (stubbed)\n pid = hashlib.md5(f\"{req.tenant_id}:{idempotency_key}\".encode()).hexdigest()\n resp = CreateResp(\n id=pid,\n created_at=datetime.now(timezone.utc).isoformat(),\n echo=req,\n )\n _IDEMPO[key] = _IdempoEntry(request_hash=rh, response_json=resp.model_dump_json())\n return resp\n```\n\n```python\n# test_app.py (pytest)\nfrom fastapi.testclient import TestClient\nfrom app import app\n\nclient = TestClient(app)\n\ndef test_idempotent_replay():\n headers = {\"Idempotency-Key\": \"abc\"}\n body = {\"tenant_id\":\"t1\",\"amount_cents\":100,\"currency\":\"USD\"}\n r1 = client.post(\"/v1/payments\", json=body, headers=headers)\n r2 = client.post(\"/v1/payments\", json=body, headers=headers)\n assert r1.status_code == 200 and r2.status_code == 200\n assert r1.json() == r2.json()\n\ndef test_payload_conflict():\n headers = {\"Idempotency-Key\": \"abc\"}\n b1 = {\"tenant_id\":\"t1\",\"amount_cents\":100,\"currency\":\"USD\"}\n b2 = {\"tenant_id\":\"t1\",\"amount_cents\":200,\"currency\":\"USD\"}\n assert client.post(\"/v1/payments\", json=b1, headers=headers).status_code == 200\n assert client.post(\"/v1/payments\", json=b2, headers=headers).status_code == 409\n```\n\nNotes:\n- Replace in-memory store with a DB table and transaction.\n- Store response + request hash to detect key reuse with different payload.\n\n\nChecks: input validation, tests, and safe defaults included.", "source": "WithinUsAI/GOD_Coder_100k"} {"text": "Improve typing and robustness of a Python module used for file synchronization.\nRequirements: provide type-safe APIs (generics/protocols where appropriate) and include tests.\nConstraints: must be easy to extend, must include tests, must avoid global state.\nDifficulty: expert. Guarantee deterministic output ordering.\n\nDeliverable: production-ready reference solution.\n```python\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom typing import Callable, Generic, Iterable, Protocol, TypeVar\n\nT = TypeVar(\"T\")\nR = TypeVar(\"R\")\n\nclass Mapper(Protocol[T, R]):\n def __call__(self, x: T) -> R: ...\n\n@dataclass(frozen=True, slots=True)\nclass Batch(Generic[T]):\n items: tuple[T, ...]\n\ndef map_batch(batch: Batch[T], fn: Mapper[T, R]) -> Batch[R]:\n return Batch(items=tuple(fn(x) for x in batch.items))\n\ndef chunked(xs: Iterable[T], size: int) -> Iterable[Batch[T]]:\n if size <= 0:\n raise ValueError(\"size must be > 0\")\n buf: list[T] = []\n for x in xs:\n buf.append(x)\n if len(buf) == size:\n yield Batch(items=tuple(buf))\n buf.clear()\n if buf:\n yield Batch(items=tuple(buf))\n```\n\n```python\nimport pytest\nfrom module_under_test import Batch, map_batch, chunked\n\ndef test_map_batch():\n b = Batch(items=(1,2,3))\n assert map_batch(b, lambda x: x*2).items == (2,4,6)\n\ndef test_chunked():\n out = list(chunked([1,2,3,4,5], 2))\n assert [b.items for b in out] == [(1,2),(3,4),(5,)]\n```", "source": "WithinUsAI/python_GOD_coder_100k"} {"text": "Task type: secure_architecture\nScenario: identity and access\nDomain focus: cryptography engineering (defensive)\nPrimary language: python\nDifficulty: expert\nScale/SLO: 1M msgs/min\nComponent: component_wleyjfcp\nConstraints: include security threat model (defensive only), include failure modes and recovery, include backward compatibility and migration plan, include performance model and limits, assume adversarial inputs; validate everything, include verification strategy, explicit contracts and invariants\nAssume partial data corruption; include scrubbing strategy.\nDeliverable: Provide a defensive threat model and secure-by-default architecture; include monitoring/detection and tests (no offensive content).\n\nOutput: contract-first solution with failure modes, security posture, and test/verification strategy.\n**Contract**\n- Inputs validated at the boundary; explicit error taxonomy.\n- Idempotency for side effects via request_id; deterministic replay.\n- Backward compatibility: additive changes by default; versioned breaking changes.\n**Invariants**\n- Isolation: tenant boundary enforced; no cross-tenant reads/writes.\n- Determinism: replay of the same event log yields identical outputs.\n- Liveness: under bounded faults and stable network, progress occurs.\n**Failure modes & recovery**\n- Crash during commit: WAL replay completes or transaction aborts; no torn writes.\n- Data corruption: checksums + scrubber; quarantine and rebuild from replicas/snapshots.\n- Network partition: minority cannot commit; clients receive retriable errors.\n**Security posture (defensive)**\n- Threat model: auth/authz, injection, replay/abuse, supply chain.\n- Least privilege; secrets in managed store; audit logs for sensitive ops.\n- Input normalization, parameterized queries, path traversal protections.\n**Verification strategy**\n- Canary + shadow traffic; invariants checked in production via assertions/metrics.\n- Property tests against a pure reference model (state machine).\n- Fuzzing of parsers/framers/validators with corpus seeds.\n\n**Snippet**\n```text\nImplementation sketch: factor pure state-machine core; adapters for I/O; add deterministic replay log.\n```\nExpert checks: state-machine proof sketch + model checking; upgrade/rollback rehearsed.", "source": "WithinUsAI/Omega_Genesis_Coder_100k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Produce an offline-first self-evolving code assistant architecture named `jf_mtopaw`.\nMust include: module layout, patch-safety policy, evaluation gates (tests/lint/types), versioned memory index.\n\nArchitecture: `jf_mtopaw` (offline-first, self-evolving)\n\nModules\n- core/loop.py: evolve → validate → accept/reject (bounded iterations)\n- patching/: diff builder, safe apply, atomic writes, rollback points\n- policy/: allowlist paths, deny globs (.git/, __pycache__/, binaries), patch size caps\n- signals/: parse pytest/ruff/mypy into normalized findings\n- memory/index.jsonl: append-only snapshots (hashes, metrics, rationale)\n\nSafety gates\n- refuse path traversal/symlink escapes; never edit binaries\n- accept only if tests/lint/types stay green or improve", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Optimize while preserving behavior and order.\n\n```python\ndef f07878(xs):\n out=[]\n for x in xs:\n if x not in out: out.append(x)\n return out\n```\nReturn `m72554.py` with types and O(n) average.\n\n```python\n# m72554.py\nfrom __future__ import annotations\nfrom typing import Iterable, List, Set, TypeVar\nT=TypeVar(\"T\")\n\ndef f07878(xs: Iterable[T]) -> List[T]:\n \"\"\"Unique items preserving first-seen order.\"\"\"\n seen: Set[T]=set()\n out: List[T]=[]\n for x in xs:\n if x in seen: continue\n seen.add(x); out.append(x)\n return out\n```", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Build an elite-grade solution in the domain of stream processing for scenario: rate limiting gateway.\nPrimary language: rust.\nDifficulty: medium.\nConstraints: document performance characteristics, include invariants and failure modes, avoid undefined behavior and data races, design for backward compatibility and migrations, include tests or verification strategy.\nComponent: component_kldhftc.\nAssume crash-only design; recovery must be deterministic.\nTask: Provide threat model, secure-by-default design, and defensive implementation patterns. No offensive/exploit content; focus on prevention and detection.\n\nOutput: elite-grade engineering answer with contracts, edge cases, and verification.\nOutput: threat model + defensive design + detection.\n\n**Threat model**\n- Auth: token theft → short-lived tokens, rotation, audience checks\n- AuthZ: privilege escalation → centralized policy checks, tenant isolation tests\n- Input: injection → strict validation, parameterized queries, output encoding\n- Supply chain: dependencies → lockfiles, signature verification, SBOM\n\n**Defensive patterns**\n- Idempotency keys for side effects; replay-safe handlers\n- Secrets in managed store; never logs\n- Audit logging for sensitive ops; tamper-evident storage\n\n**Detection**\n- Alert on unusual auth failures, access pattern anomalies, and data exfil signals.\n\n\nChecks: boundary validation and deterministic behavior verified.", "source": "WithinUsAI/Elite_GOD_Coder_100k"} {"text": "Task type: compiler_backend_ir\nScenario: feature-flag evaluation\nDomain focus: observability platforms\nPrimary language: rust\nDifficulty: expert\nScale/SLO: multi-region active-active\nComponent: component_aepnjhuq\nConstraints: include failure modes and recovery, assume adversarial inputs; validate everything, include performance model and limits, include verification strategy, avoid data races and undefined behavior, include security threat model (defensive only)\nAssume crash-only processes; recovery must be deterministic.\nDeliverable: Design an IR and lowering pipeline; include an optimization pass and correctness checks. Provide minimal code skeleton and tests.\n\nOutput: elite engineering answer optimized for correctness, performance, and operability.\n**Contract**\n- Inputs validated at the boundary; explicit error taxonomy.\n- Idempotency for side effects via request_id; deterministic replay.\n- Backward compatibility: additive changes by default; versioned breaking changes.\n**Invariants**\n- Liveness: under bounded faults and stable network, progress occurs.\n- Isolation: tenant boundary enforced; no cross-tenant reads/writes.\n- Safety: state transitions preserve invariants; no partial commit leaks.\n**Failure modes & recovery**\n- Data corruption: checksums + scrubber; quarantine and rebuild from replicas/snapshots.\n- Duplicate requests: de-duplicate by (tenant, request_id) returning cached response.\n- Network partition: minority cannot commit; clients receive retriable errors.\n**Security posture (defensive)**\n- Threat model: auth/authz, injection, replay/abuse, supply chain.\n- Least privilege; secrets in managed store; audit logs for sensitive ops.\n- Input normalization, parameterized queries, path traversal protections.\n**Verification strategy**\n- Canary + shadow traffic; invariants checked in production via assertions/metrics.\n- Fuzzing of parsers/framers/validators with corpus seeds.\n- Property tests against a pure reference model (state machine).\n\n**Snippet**\n```text\nImplementation sketch: factor pure state-machine core; adapters for I/O; add deterministic replay log.\n```\nExpert checks: state-machine proof sketch + model checking; upgrade/rollback rehearsed.", "source": "WithinUsAI/Omega_Genesis_Coder_100k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Optimize while preserving behavior.\n\nFile: sjvnctx.py\n```python\ndef qmxvzb(xs):\n out = []\n for x in xs:\n if x not in out:\n out.append(x)\n return out\n```\n\nRequirements: preserve first-seen order; O(n) average; add types + docstring.\n\n# sjvnctx.py\nfrom __future__ import annotations\nfrom typing import Iterable, List, Set, TypeVar\n\nT = TypeVar(\"T\")\n\ndef qmxvzb(xs: Iterable[T]) -> List[T]:\n \"\"\"Return unique items preserving first-seen order.\"\"\"\n seen: Set[T] = set()\n out: List[T] = []\n for x in xs:\n if x in seen:\n continue\n seen.add(x)\n out.append(x)\n return out", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Refactor to modern typed Python with immutability and tests.\n\nFile: arjkhb_va4h.py\n```python\nclass J83C6Cd:\n def __init__(self, name, values):\n self.name = name\n self.values = list(values)\n def add(self, v):\n self.values.append(v)\n def mean(self):\n s = 0\n for x in self.values:\n s += x\n return s / len(self.values)\n```\n\nReturn full new arjkhb_va4h.py and test_arjkhb_va4h.py.\n\n# arjkhb_va4h.py\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom typing import Iterable, Tuple\n\n@dataclass(frozen=True)\nclass J83C6Cd:\n name: str\n values: Tuple[float, ...]\n\n @staticmethod\n def create(name: str, values: Iterable[float]) -> \"J83C6Cd\":\n vals = tuple(float(v) for v in values)\n if not vals:\n raise ValueError(\"values must be non-empty\")\n return J83C6Cd(name=name, values=vals)\n\n def add(self, v: float) -> \"J83C6Cd\":\n return J83C6Cd(name=self.name, values=self.values + (float(v),))\n\n def mean(self) -> float:\n return sum(self.values) / len(self.values)\n\n# test_arjkhb_va4h.py\nimport pytest\nfrom arjkhb_va4h import J83C6Cd\n\ndef test_mean_and_add():\n c = J83C6Cd.create(\"a\", [1, 2, 3])\n assert c.mean() == 2.0\n assert c.add(5).mean() == (1 + 2 + 3 + 5) / 4\n\ndef test_empty_raises():\n with pytest.raises(ValueError):\n J83C6Cd.create(\"x\", [])", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Fix a bug and add tests.\n\nFile: sitllyirn8f.py\n```python\ndef excn4w(n: int) -> int:\n \"\"\"Sum 1..n inclusive.\"\"\"\n if n < 0:\n raise ValueError(\"n must be non-negative\")\n total = 0\n for k in range(n): # BUG: should include n\n total += k\n return total\n```\n\nReturn unified diffs for sitllyirn8f.py and test_sitllyirn8f.py (pytest).\n\n*** Begin Patch\n*** Update File: sitllyirn8f.py\n@@\n def excn4w(n: int) -> int:\n@@\n total = 0\n- for k in range(n): # BUG: should include n\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_sitllyirn8f.py\n+import pytest\n+from sitllyirn8f import excn4w\n+\n+def test_zero():\n+ assert excn4w(0) == 0\n+\n+def test_one():\n+ assert excn4w(1) == 1\n+\n+def test_small():\n+ assert excn4w(7) == 28\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ excn4w(-1)\n+\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Fix a bug and add tests.\n\nFile: lhkaoqc0au.py\n```python\ndef giiu_x(n: int) -> int:\n \"\"\"Sum 1..n inclusive.\"\"\"\n if n < 0:\n raise ValueError(\"n must be non-negative\")\n total = 0\n for k in range(n): # BUG: should include n\n total += k\n return total\n```\n\nReturn unified diffs for lhkaoqc0au.py and test_lhkaoqc0au.py (pytest).\n\n*** Begin Patch\n*** Update File: lhkaoqc0au.py\n@@\n def giiu_x(n: int) -> int:\n@@\n total = 0\n- for k in range(n): # BUG: should include n\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_lhkaoqc0au.py\n+import pytest\n+from lhkaoqc0au import giiu_x\n+\n+def test_zero():\n+ assert giiu_x(0) == 0\n+\n+def test_one():\n+ assert giiu_x(1) == 1\n+\n+def test_small():\n+ assert giiu_x(7) == 28\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ giiu_x(-1)\n+\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: Project stack: Go, Gin, PostgreSQL, gRPC, Prometheus, Docker\nLanguage: Java\nDependency challenge: rate-limit bypass\nTask type: build_reproducibility_fix\nDifficulty: hard\n\nFix this as a senior engineer.\nRequired:\n- identify the version or compatibility failure mode\n- produce the corrected config/code/build patch\n- explain rollback-safe migration notes\n- add regression tests or reproducibility checks\n- include concrete verification commands\n\nRepository sketch:\nrepo/\n src/main/java/com/acme/App.java\n src/main/java/com/acme/Service.java\n src/test/java/com/acme/AppTest.java\n pom.xml\n\nFocus: Focus on versioning, migrations, lockfiles, runtime compatibility, and secure dependency handling.\n\nassistant: Diagnosis:\n- Root cause: the issue around rate-limit bypass is a dependency, migration, or runtime-compatibility mismatch that needs a rollback-safe patch.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```java\nimport java.util.HashMap;\nimport java.util.Map;\n\npublic final class RequestHandler {\n public static Map handleRequest(Map payload) {\n Map clean = new HashMap<>();\n for (Map.Entry entry : payload.entrySet()) {\n if (entry.getValue() != null) clean.put(entry.getKey().trim(), entry.getValue());\n }\n if (!clean.containsKey(\"id\")) throw new IllegalArgumentException(\"missing id\");\n return Map.of(\"ok\", true, \"data\", clean);\n }\n}\n```\n\nTests:\n```java\nimport static org.junit.jupiter.api.Assertions.*;\nimport java.util.Map;\nimport org.junit.jupiter.api.Test;\n\nclass RequestHandlerTest {\n @Test\n void requiresId() {\n assertThrows(IllegalArgumentException.class, () -> RequestHandler.handleRequest(Map.of(\"name\", \"x\")));\n }\n}\n```\n\nVerification:\n- `./gradlew test`\n- `mvn test`\n\nEngineering notes:\n- Language: Java\n- Framework/tooling: Hibernate\n- Stack context: Go, Gin, PostgreSQL, gRPC, Prometheus, Docker\n- Domain: reporting engine\n- Task type: build_reproducibility_fix\n- Difficulty: hard\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "Optimize while preserving behavior and order.\n\n```python\ndef f99789(xs):\n out=[]\n for x in xs:\n if x not in out: out.append(x)\n return out\n```\nReturn `m42827.py` with types and O(n) average.\n\n```python\n# m42827.py\nfrom __future__ import annotations\nfrom typing import Iterable, List, Set, TypeVar\nT=TypeVar(\"T\")\n\ndef f99789(xs: Iterable[T]) -> List[T]:\n \"\"\"Unique items preserving first-seen order.\"\"\"\n seen: Set[T]=set()\n out: List[T]=[]\n for x in xs:\n if x in seen: continue\n seen.add(x); out.append(x)\n return out\n```", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Build an elite-grade solution in the domain of gpu compute for scenario: event ingestion.\nPrimary language: sql.\nDifficulty: medium.\nConstraints: make the interface contract explicit, include invariants and failure modes, include tests or verification strategy, design for backward compatibility and migrations, assume untrusted inputs; validate and sanitize.\nComponent: component_jycsbua.\nAssume crash-only design; recovery must be deterministic.\nTask: Optimize a hot path with profiling-driven approach; propose micro/meso optimizations, and supply a benchmark harness with acceptance thresholds.\n\nOutput: elite-grade engineering answer with contracts, edge cases, and verification.\nOutput: profiling-first optimization + benchmark harness.\n\n**Plan**\n1. Establish baseline with microbench + representative dataset.\n2. Profile (CPU, allocations, syscalls).\n3. Apply optimizations: reduce allocations, reuse buffers, batch I/O, vectorize parsing where safe.\n4. Validate with regression suite and perf thresholds.\n\n**Benchmark guidance**\n- Use p50/p95 and throughput; pin CPU frequency if possible.\n- Acceptance: p95 improves ≥ X% with no correctness regressions.\n\n\nChecks: boundary validation and deterministic behavior verified.", "source": "WithinUsAI/Elite_GOD_Coder_100k"} {"text": "Add a clear docstring and type hints to this function:\n\n```python\ndef f89000(s):\n return ''.join(x for x in s if x.isalnum()).lower()\n```\n\n```python\nfrom __future__ import annotations\n\ndef f89000(s: str) -> str:\n \"\"\"Normalize a string: keep only alphanumerics and lowercase the result.\"\"\"\n return \"\".join(ch for ch in s if ch.isalnum()).lower()\n```", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Implement a concurrent Python solution for event dispatching.\nRequirements: choose appropriate concurrency model, handle cancellation/timeouts, include tests.\nConstraints: must avoid global state, stdlib-only, must be streaming-friendly, must be easy to extend.\nDifficulty: expert. Guarantee deterministic output ordering.\n\nDeliverable: API + reference implementation + tests.\n```python\nfrom __future__ import annotations\nimport asyncio\nfrom dataclasses import dataclass\nfrom typing import Awaitable, Callable, Iterable, Optional\n\n@dataclass(frozen=True, slots=True)\nclass JobResult:\n ok: bool\n value: Optional[int]\n error: Optional[str]\n\nasync def run_bounded(\n factories: Iterable[Callable[[], Awaitable[int]]],\n *,\n limit: int = 10,\n timeout_s: float = 5.0,\n) -> list[JobResult]:\n if limit <= 0:\n raise ValueError(\"limit must be > 0\")\n sem = asyncio.Semaphore(limit)\n results: list[JobResult] = []\n\n async def one(factory: Callable[[], Awaitable[int]]) -> None:\n async with sem:\n try:\n v = await asyncio.wait_for(factory(), timeout=timeout_s)\n results.append(JobResult(True, v, None))\n except Exception as e:\n results.append(JobResult(False, None, str(e)))\n\n tasks = [asyncio.create_task(one(f)) for f in factories]\n try:\n await asyncio.gather(*tasks)\n finally:\n for t in tasks:\n if not t.done():\n t.cancel()\n return results\n```\n\n```python\nimport asyncio\nimport pytest\nfrom module_under_test import run_bounded\n\n@pytest.mark.asyncio\nasync def test_run_bounded_collects():\n async def work(x: int) -> int:\n await asyncio.sleep(0.01)\n return x\n fs = [(lambda i=i: work(i)) for i in range(30)]\n out = await run_bounded(fs, limit=5, timeout_s=1.0)\n assert len(out) == 30\n assert all(r.ok for r in out)\n```", "source": "WithinUsAI/python_GOD_coder_100k"} {"text": "Refactor a Python module used for rate limiting into a clean, extensible design.\nRequirements: outline the new architecture briefly, then provide the refactored code and tests.\nConstraints: must include type hints, must provide clear error messages.\nDifficulty: easy. Support both Windows and POSIX paths correctly.\n\nDeliverable: API + reference implementation + tests.\nArchitecture:\n- Public facade class coordinating concerns (parsing, validation, persistence)\n- Small pure functions for testability\n- No global state; dependency injection for filesystem I/O\n\n```python\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom pathlib import Path\nfrom typing import Protocol, Iterable\nimport json\n\nclass Store(Protocol):\n def write_text(self, path: Path, data: str) -> None: ...\n\nclass FSStore:\n def write_text(self, path: Path, data: str) -> None:\n path.parent.mkdir(parents=True, exist_ok=True)\n path.write_text(data, encoding=\"utf-8\")\n\n@dataclass(frozen=True, slots=True)\nclass Item:\n name: str\n qty: int\n\ndef parse_items(lines: Iterable[str]) -> list[Item]:\n out: list[Item] = []\n for i, line in enumerate(lines, 1):\n s = line.strip()\n if not s:\n continue\n obj = json.loads(s)\n if not isinstance(obj, dict):\n raise ValueError(f\"line {i}: expected object\")\n name = obj.get(\"name\")\n qty = obj.get(\"qty\")\n if not isinstance(name, str) or not name:\n raise ValueError(f\"line {i}: name must be str\")\n if not isinstance(qty, int) or qty < 0:\n raise ValueError(f\"line {i}: qty must be non-negative int\")\n out.append(Item(name, qty))\n return out\n\nclass InventoryWriter:\n def __init__(self, base_dir: Path, store: Store | None = None) -> None:\n self._base = base_dir\n self._store: Store = store or FSStore()\n\n def write(self, rel_path: str, items: list[Item]) -> Path:\n dst = (self._base / rel_path).resolve()\n base = self._base.resolve()\n if dst != base and base not in dst.parents:\n raise ValueError(\"unsafe path traversal\")\n payload = json.dumps([item.__dict__ for item in items], ensure_ascii=False)\n self._store.write_text(dst, payload)\n return dst\n```\n\n```python\nimport json\nfrom pathlib import Path\nimport pytest\nfrom module_under_test import InventoryWriter, parse_items\n\ndef test_parse_items_valid():\n lines = [json.dumps({\"name\":\"x\",\"qty\":1})]\n assert parse_items(lines)[0].name == \"x\"\n\ndef test_writer_blocks_traversal(tmp_path: Path):\n w = InventoryWriter(tmp_path)\n with pytest.raises(ValueError):\n w.write(\"../evil.json\", [])\n```", "source": "WithinUsAI/python_GOD_coder_100k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Fix a bug and add tests.\n\nFile: nnyzz4j2g.py\n```python\ndef yt5p148y(n: int) -> int:\n \"\"\"Sum 1..n inclusive.\"\"\"\n if n < 0:\n raise ValueError(\"n must be non-negative\")\n total = 0\n for k in range(n): # BUG: should include n\n total += k\n return total\n```\n\nReturn unified diffs for nnyzz4j2g.py and test_nnyzz4j2g.py (pytest).\n\n*** Begin Patch\n*** Update File: nnyzz4j2g.py\n@@\n def yt5p148y(n: int) -> int:\n@@\n total = 0\n- for k in range(n): # BUG: should include n\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_nnyzz4j2g.py\n+import pytest\n+from nnyzz4j2g import yt5p148y\n+\n+def test_zero():\n+ assert yt5p148y(0) == 0\n+\n+def test_one():\n+ assert yt5p148y(1) == 1\n+\n+def test_small():\n+ assert yt5p148y(7) == 28\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ yt5p148y(-1)\n+\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Task type: compiler_frontend\nScenario: real-time notification hub\nDomain focus: constraint solving\nPrimary language: go\nDifficulty: expert+\nScale/SLO: 100k RPS peak\nComponent: component_sfhskgkj\nConstraints: avoid data races and undefined behavior, include failure modes and recovery, include backward compatibility and migration plan, include security threat model (defensive only), explicit contracts and invariants, include verification strategy\nAssume crash-only processes; recovery must be deterministic.\nDeliverable: Design a DSL language frontend: lexer/parser, AST, type checking, error reporting, and tests.\n\nOutput: elite engineering answer optimized for correctness, performance, and operability.\n**Contract**\n- Inputs validated at the boundary; explicit error taxonomy.\n- Idempotency for side effects via request_id; deterministic replay.\n- Backward compatibility: additive changes by default; versioned breaking changes.\n**Invariants**\n- Isolation: tenant boundary enforced; no cross-tenant reads/writes.\n- Safety: state transitions preserve invariants; no partial commit leaks.\n- Liveness: under bounded faults and stable network, progress occurs.\n**Failure modes & recovery**\n- Network partition: minority cannot commit; clients receive retriable errors.\n- Duplicate requests: de-duplicate by (tenant, request_id) returning cached response.\n- Crash during commit: WAL replay completes or transaction aborts; no torn writes.\n**Security posture (defensive)**\n- Threat model: auth/authz, injection, replay/abuse, supply chain.\n- Least privilege; secrets in managed store; audit logs for sensitive ops.\n- Input normalization, parameterized queries, path traversal protections.\n**Verification strategy**\n- Property tests against a pure reference model (state machine).\n- Fuzzing of parsers/framers/validators with corpus seeds.\n- Canary + shadow traffic; invariants checked in production via assertions/metrics.\n\n**Snippet**\n```text\nImplementation sketch: factor pure state-machine core; adapters for I/O; add deterministic replay log.\n```\nExpert+ checks: mechanized invariants (or exhaustive model checking), adversarial fuzzing, and multi-region failure drills.", "source": "WithinUsAI/Omega_Genesis_Coder_100k"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: Repository domain: feature flag service\nPrimary language: Python\nFramework/tooling: Pydantic\nReported problem: memory leak in AST cache\nTask type: test_repair\nDifficulty: hard\n\nProduce a complete professional engineering response:\n1. Diagnose the root cause.\n2. Provide the corrected implementation or patch.\n3. Add tests.\n4. Add verification commands.\n5. Note edge cases and any migration or rollback risk.\n\nRepository sketch:\nrepo/\n app/\n api.py\n service.py\n models.py\n tests/\n test_api.py\n pyproject.toml\n\nQuality target:\n- Minimal diff unless redesign is clearly required\n- Production-ready code\n- No placeholders\n- Secure defaults\n- Clear acceptance of failure cases\n\nFocus: Focus on complete implementation quality, patch correctness, tests, and production readiness.\n\nassistant: Diagnosis:\n- Root cause: the failure around memory leak in AST cache is caused by missing validation, weak edge-case handling, or unsafe lifecycle behavior in the current implementation.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```python\nfrom __future__ import annotations\n\nfrom dataclasses import dataclass\nfrom typing import Any\n\n@dataclass\nclass ServiceResult:\n ok: bool\n data: dict[str, Any]\n error: str | None = None\n\ndef normalize_payload(payload: dict[str, Any]) -> dict[str, Any]:\n if not isinstance(payload, dict):\n raise TypeError(\"payload must be a dict\")\n clean: dict[str, Any] = {}\n for key, value in payload.items():\n if value is None:\n continue\n clean[str(key).strip()] = value\n return clean\n\ndef handle_memory_leak_in_ast_cache(payload: dict[str, Any]) -> ServiceResult:\n clean = normalize_payload(payload)\n if \"id\" not in clean:\n return ServiceResult(ok=False, data={}, error=\"missing id\")\n return ServiceResult(ok=True, data=clean)\n```\n\nTests:\n```python\nimport pytest\nfrom app.service import handle_jwt_refresh_token_rotation as handler\n\ndef test_handler_accepts_valid_payload():\n result = handler({\"id\": 7, \"name\": \"ok\", \"unused\": None})\n assert result.ok is True\n assert result.data == {\"id\": 7, \"name\": \"ok\"}\n\ndef test_handler_rejects_missing_id():\n result = handler({\"name\": \"x\"})\n assert result.ok is False\n assert result.error == \"missing id\"\n```\n\nVerification:\n- `pytest -q`\n- `ruff check .`\n- `python -m compileall .`\n\nEngineering notes:\n- Language: Python\n- Framework/tooling: Pydantic\n- Stack context: GitHub Actions, Docker Compose, Kubernetes, Terraform\n- Domain: feature flag service\n- Task type: test_repair\n- Difficulty: hard\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Fix a bug and add tests.\n\nFile: tysvxqhil9z.py\n```python\ndef ql9gl0(n: int) -> int:\n \"\"\"Sum 1..n inclusive.\"\"\"\n if n < 0:\n raise ValueError(\"n must be non-negative\")\n total = 0\n for k in range(n): # BUG: should include n\n total += k\n return total\n```\n\nReturn unified diffs for tysvxqhil9z.py and test_tysvxqhil9z.py (pytest).\n\n*** Begin Patch\n*** Update File: tysvxqhil9z.py\n@@\n def ql9gl0(n: int) -> int:\n@@\n total = 0\n- for k in range(n): # BUG: should include n\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_tysvxqhil9z.py\n+import pytest\n+from tysvxqhil9z import ql9gl0\n+\n+def test_zero():\n+ assert ql9gl0(0) == 0\n+\n+def test_one():\n+ assert ql9gl0(1) == 1\n+\n+def test_small():\n+ assert ql9gl0(7) == 28\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ ql9gl0(-1)\n+\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Refactor to typed, mostly-immutable Python and add minimal tests.\n\n```python\nclass C33077:\n def __init__(self, values): self.values=list(values)\n def mean(self): return sum(self.values)/len(self.values)\n```\nReturn `m17929.py` and `test_m17929.py`.\n\n```python\n# m17929.py\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom typing import Iterable, Tuple\n\n@dataclass(frozen=True)\nclass C33077:\n values: Tuple[float, ...]\n\n @staticmethod\n def create(values: Iterable[float]) -> \"C33077\":\n vals = tuple(float(v) for v in values)\n if not vals: raise ValueError(\"empty\")\n return C33077(vals)\n\n def mean(self) -> float:\n return sum(self.values)/len(self.values)\n```\n\n```python\n# test_m17929.py\nimport pytest\nfrom m17929 import C33077\n\ndef test_mean():\n assert C33077.create([1,2,3]).mean() == 2.0\ndef test_empty():\n with pytest.raises(ValueError):\n C33077.create([])\n```", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: Language: SQL\nFramework/tooling: DuckDB\nDomain: job scheduler\nLogic challenge: JWT refresh token rotation\nTask type: performance_bottleneck_patch\nDifficulty: hard\n\nReturn a rigorous engineering answer:\n- identify the hidden root cause or logical failure\n- present the corrected implementation\n- add tests that prove the fix\n- list verification commands\n- explain why naive fixes are insufficient when relevant\n\nRepository sketch:\nrepo/\n migrations/\n 001_init.sql\n 002_add_index.sql\n queries/\n report.sql\n tests/\n report_cases.md\n\nFocus: Focus on ambiguity, misleading symptoms, hidden root causes, and high-stakes debugging.\n\nassistant: Diagnosis:\n- Hidden root cause: JWT refresh token rotation presents misleading symptoms, so the patch must target the actual logic boundary rather than the first visible failure.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```sql\nWITH ranked AS (\n SELECT\n user_id,\n created_at,\n amount,\n ROW_NUMBER() OVER (PARTITION BY user_id ORDER BY created_at DESC, id DESC) AS rn\n FROM orders\n)\nSELECT user_id, created_at, amount\nFROM ranked\nWHERE rn = 1;\n```\n\nTests:\n```sql\n-- Correctness checks:\n-- 1) multiple rows per user\n-- 2) identical timestamps require deterministic tie-breaker\n-- 3) null values handled by business rules\n```\n\nVerification:\n- `run migration checks`\n- `run query correctness cases`\n\nEngineering notes:\n- Language: SQL\n- Framework/tooling: DuckDB\n- Stack context: FastAPI, PostgreSQL, Redis, Celery, pytest, Docker\n- Domain: job scheduler\n- Task type: performance_bottleneck_patch\n- Difficulty: hard\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "Optimize while preserving behavior and order.\n\n```python\ndef f85814(xs):\n out=[]\n for x in xs:\n if x not in out: out.append(x)\n return out\n```\nReturn `m69402.py` with types and O(n) average.\n\n```python\n# m69402.py\nfrom __future__ import annotations\nfrom typing import Iterable, List, Set, TypeVar\nT=TypeVar(\"T\")\n\ndef f85814(xs: Iterable[T]) -> List[T]:\n \"\"\"Unique items preserving first-seen order.\"\"\"\n seen: Set[T]=set()\n out: List[T]=[]\n for x in xs:\n if x in seen: continue\n seen.add(x); out.append(x)\n return out\n```", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Fix a bug and add tests.\n\nFile: s5wtvlfb.py\n```python\ndef zrcjr5(n: int) -> int:\n \"\"\"Sum 1..n inclusive.\"\"\"\n if n < 0:\n raise ValueError(\"n must be non-negative\")\n total = 0\n for k in range(n): # BUG: should include n\n total += k\n return total\n```\n\nReturn unified diffs for s5wtvlfb.py and test_s5wtvlfb.py (pytest).\n\n*** Begin Patch\n*** Update File: s5wtvlfb.py\n@@\n def zrcjr5(n: int) -> int:\n@@\n total = 0\n- for k in range(n): # BUG: should include n\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_s5wtvlfb.py\n+import pytest\n+from s5wtvlfb import zrcjr5\n+\n+def test_zero():\n+ assert zrcjr5(0) == 0\n+\n+def test_one():\n+ assert zrcjr5(1) == 1\n+\n+def test_small():\n+ assert zrcjr5(7) == 28\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ zrcjr5(-1)\n+\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Task type: mechanized_spec\nScenario: rate limit gateway\nDomain focus: constraint solving\nPrimary language: lean\nDifficulty: hard\nScale/SLO: 1M msgs/min\nComponent: component_qklskqkt\nConstraints: assume adversarial inputs; validate everything, include deterministic replay plan, include test vectors and fuzz strategy, explicit contracts and invariants, include security threat model (defensive only), include failure modes and recovery\nAssume weekly network partitions.\nDeliverable: Provide a mechanized-style spec outline (Lean-like), key definitions, and a proof plan. Include executable reference code skeleton and tests.\n\nOutput: rigorous design + invariants + verification plan + implementation sketch.\n**Contract**\n- Inputs validated at the boundary; explicit error taxonomy.\n- Idempotency for side effects via request_id; deterministic replay.\n- Backward compatibility: additive changes by default; versioned breaking changes.\n**Invariants**\n- Liveness: under bounded faults and stable network, progress occurs.\n- Isolation: tenant boundary enforced; no cross-tenant reads/writes.\n- Safety: state transitions preserve invariants; no partial commit leaks.\n**Failure modes & recovery**\n- Network partition: minority cannot commit; clients receive retriable errors.\n- Data corruption: checksums + scrubber; quarantine and rebuild from replicas/snapshots.\n- Duplicate requests: de-duplicate by (tenant, request_id) returning cached response.\n**Security posture (defensive)**\n- Threat model: auth/authz, injection, replay/abuse, supply chain.\n- Least privilege; secrets in managed store; audit logs for sensitive ops.\n- Input normalization, parameterized queries, path traversal protections.\n**Verification strategy**\n- Canary + shadow traffic; invariants checked in production via assertions/metrics.\n- Property tests against a pure reference model (state machine).\n- Fuzzing of parsers/framers/validators with corpus seeds.\n\n**Snippet**\n```lean\n-- Pseudo-Lean outline\nstructure State where\n ver : Nat\n val : Option ByteArray\n\ndef invariant (s : State) : Prop := True\n\ntheorem step_preserves_invariant :\n ∀ s, invariant s → ∀ s', Step s s' → invariant s' := by\n intro s hs s' hstep\n -- proof plan: case analysis on transition; trivial here\n trivial\n```\n\nHard checks: fault injection tests gate merges; perf thresholds enforced in CI.", "source": "WithinUsAI/Omega_Genesis_Coder_100k"} {"text": "Write pytest tests for `f18413`.\n\n```python\ndef f18413(a: int, b: int) -> int:\n return a*a + b*b\n```\nInclude edge cases and a property-style check.\n\n```python\nimport random\nfrom m74059 import f18413\n\ndef test_known():\n assert f18413(3,4) == 25\n\ndef test_zero():\n assert f18413(0,0) == 0\n\ndef test_property_nonnegative():\n for _ in range(200):\n a=random.randint(-50,50)\n b=random.randint(-50,50)\n assert f18413(a,b) >= 0\n```", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: System domain: auth service\nStack: GitHub Actions, Docker Compose, Kubernetes, Terraform\nCross-layer incident: broken pagination cursor\nTask type: observability_debug_fix\nDifficulty: hard\n\nSolve this as a complete-project engineer.\nOutput must include:\n- root cause across layers\n- final implementation patch\n- tests touching at least two layers\n- deployment or observability note\n- verification commands\n\nRepository sketch:\nrepo/\n src/main/java/com/acme/App.java\n src/main/java/com/acme/Service.java\n src/test/java/com/acme/AppTest.java\n pom.xml\n\nFocus: Focus on multi-layer debugging across frontend, backend, database, CI, caching, and deployment.\n\nassistant: Diagnosis:\n- Root cause: broken pagination cursor crosses service boundaries, so the fix must align code, contracts, tests, and deployment behavior.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```java\nimport java.util.HashMap;\nimport java.util.Map;\n\npublic final class RequestHandler {\n public static Map handleRequest(Map payload) {\n Map clean = new HashMap<>();\n for (Map.Entry entry : payload.entrySet()) {\n if (entry.getValue() != null) clean.put(entry.getKey().trim(), entry.getValue());\n }\n if (!clean.containsKey(\"id\")) throw new IllegalArgumentException(\"missing id\");\n return Map.of(\"ok\", true, \"data\", clean);\n }\n}\n```\n\nTests:\n```java\nimport static org.junit.jupiter.api.Assertions.*;\nimport java.util.Map;\nimport org.junit.jupiter.api.Test;\n\nclass RequestHandlerTest {\n @Test\n void requiresId() {\n assertThrows(IllegalArgumentException.class, () -> RequestHandler.handleRequest(Map.of(\"name\", \"x\")));\n }\n}\n```\n\nVerification:\n- `./gradlew test`\n- `mvn test`\n\nEngineering notes:\n- Language: Java\n- Framework/tooling: Hibernate\n- Stack context: GitHub Actions, Docker Compose, Kubernetes, Terraform\n- Domain: auth service\n- Task type: observability_debug_fix\n- Difficulty: hard\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: Language: Rust\nFramework/tooling: SQLx\nDomain: model serving gateway\nLogic challenge: mismatched API contract\nTask type: performance_bottleneck_patch\nDifficulty: hard\n\nReturn a rigorous engineering answer:\n- identify the hidden root cause or logical failure\n- present the corrected implementation\n- add tests that prove the fix\n- list verification commands\n- explain why naive fixes are insufficient when relevant\n\nRepository sketch:\nrepo/\n src/main.rs\n src/lib.rs\n src/service.rs\n src/store.rs\n tests/integration.rs\n Cargo.toml\n\nFocus: Focus on ambiguity, misleading symptoms, hidden root causes, and high-stakes debugging.\n\nassistant: Diagnosis:\n- Hidden root cause: mismatched API contract presents misleading symptoms, so the patch must target the actual logic boundary rather than the first visible failure.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```rust\nuse std::collections::HashMap;\n\npub fn normalize_payload(payload: HashMap) -> HashMap {\n payload\n .into_iter()\n .filter(|(_, v)| !v.trim().is_empty())\n .collect()\n}\n```\n\nTests:\n```rust\n#[test]\nfn normalize_payload_filters_empty_values() {\n use std::collections::HashMap;\n let mut payload = HashMap::new();\n payload.insert(\"id\".to_string(), \"7\".to_string());\n payload.insert(\"name\".to_string(), \"\".to_string());\n let out = normalize_payload(payload);\n assert!(out.contains_key(\"id\"));\n assert!(!out.contains_key(\"name\"));\n}\n```\n\nVerification:\n- `cargo test`\n- `cargo clippy -- -D warnings`\n\nEngineering notes:\n- Language: Rust\n- Framework/tooling: SQLx\n- Stack context: ASP.NET Core, SQL Server, EF Core, xUnit, Docker\n- Domain: model serving gateway\n- Task type: performance_bottleneck_patch\n- Difficulty: hard\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "Optimize while preserving behavior and order.\n\n```python\ndef f74091(xs):\n out=[]\n for x in xs:\n if x not in out: out.append(x)\n return out\n```\nReturn `m82013.py` with types and O(n) average.\n\n```python\n# m82013.py\nfrom __future__ import annotations\nfrom typing import Iterable, List, Set, TypeVar\nT=TypeVar(\"T\")\n\ndef f74091(xs: Iterable[T]) -> List[T]:\n \"\"\"Unique items preserving first-seen order.\"\"\"\n seen: Set[T]=set()\n out: List[T]=[]\n for x in xs:\n if x in seen: continue\n seen.add(x); out.append(x)\n return out\n```", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Refactor an existing codebase in fintech to support role-based access control cleanly.\nTarget platform: data (SQL + Python).\nRequirements: propose new modules/layers, dependency boundaries, and migration plan.\nConstraints: must include documentation/comments, must be performant under load, must include tests, must include type hints where applicable, must avoid global state.\nDifficulty: expert. Assume strict latency budget (p95 < 200ms).\n\nOutput: design + implementation guidance suitable for shipping.\nDeliverable: refactor plan + module boundaries.\n\n**Proposed modules**\n- `domain/` pure business logic (no I/O)\n- `adapters/` DB, cache, external APIs\n- `api/` request/response validation and routing\n- `observability/` logging/metrics/tracing\n- `tests/` unit + integration suites\n\n**Migration plan**\n1. Introduce new interfaces + adapters behind feature flags.\n2. Dual-write or read-compat layer if schema changes.\n3. Incremental cutover; deprecate legacy module.\n\nKey rule: dependencies flow inward; domain has no framework imports.\n\n\nHard-mode checks: concurrency safety, idempotency, and rollback validated; add chaos tests where feasible.", "source": "WithinUsAI/GOD_Coder_100k"} {"text": "Implement a concurrent Python solution for file synchronization.\nRequirements: choose appropriate concurrency model, handle cancellation/timeouts, include tests.\nConstraints: must be streaming-friendly, must provide clear error messages.\nDifficulty: easy. Guarantee deterministic output ordering.\n\nDeliverable: corrected code and verification tests.\n```python\nfrom __future__ import annotations\nimport asyncio\nfrom dataclasses import dataclass\nfrom typing import Awaitable, Callable, Iterable, Optional\n\n@dataclass(frozen=True, slots=True)\nclass JobResult:\n ok: bool\n value: Optional[int]\n error: Optional[str]\n\nasync def run_bounded(\n factories: Iterable[Callable[[], Awaitable[int]]],\n *,\n limit: int = 10,\n timeout_s: float = 5.0,\n) -> list[JobResult]:\n if limit <= 0:\n raise ValueError(\"limit must be > 0\")\n sem = asyncio.Semaphore(limit)\n results: list[JobResult] = []\n\n async def one(factory: Callable[[], Awaitable[int]]) -> None:\n async with sem:\n try:\n v = await asyncio.wait_for(factory(), timeout=timeout_s)\n results.append(JobResult(True, v, None))\n except Exception as e:\n results.append(JobResult(False, None, str(e)))\n\n tasks = [asyncio.create_task(one(f)) for f in factories]\n try:\n await asyncio.gather(*tasks)\n finally:\n for t in tasks:\n if not t.done():\n t.cancel()\n return results\n```\n\n```python\nimport asyncio\nimport pytest\nfrom module_under_test import run_bounded\n\n@pytest.mark.asyncio\nasync def test_run_bounded_collects():\n async def work(x: int) -> int:\n await asyncio.sleep(0.01)\n return x\n fs = [(lambda i=i: work(i)) for i in range(30)]\n out = await run_bounded(fs, limit=5, timeout_s=1.0)\n assert len(out) == 30\n assert all(r.ok for r in out)\n```", "source": "WithinUsAI/python_GOD_coder_100k"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: Project stack: Airflow, dbt, DuckDB, MinIO, pytest\nLanguage: Bash\nDependency challenge: N+1 query explosion\nTask type: lockfile_repair\nDifficulty: hard\n\nFix this as a senior engineer.\nRequired:\n- identify the version or compatibility failure mode\n- produce the corrected config/code/build patch\n- explain rollback-safe migration notes\n- add regression tests or reproducibility checks\n- include concrete verification commands\n\nRepository sketch:\nrepo/\n scripts/\n run.sh\n deploy.sh\n tests/\n smoke.sh\n\nFocus: Focus on versioning, migrations, lockfiles, runtime compatibility, and secure dependency handling.\n\nassistant: Diagnosis:\n- Root cause: the issue around N+1 query explosion is a dependency, migration, or runtime-compatibility mismatch that needs a rollback-safe patch.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```bash\n#!/usr/bin/env bash\nset -euo pipefail\n\ninput=\"${1:-}\"\nif [[ -z \"$input\" ]]; then\n echo \"missing input\" >&2\n exit 1\nfi\n\nprintf '%s\n' \"$input\" | tr -d '\r'\n```\n\nTests:\n```bash\noutput=\"$(bash scripts/run.sh \"abc\")\"\ntest \"$output\" = \"abc\"\n```\n\nVerification:\n- `bash tests/smoke.sh`\n- `shellcheck scripts/*.sh`\n\nEngineering notes:\n- Language: Bash\n- Framework/tooling: curl\n- Stack context: Airflow, dbt, DuckDB, MinIO, pytest\n- Domain: benchmark harness\n- Task type: lockfile_repair\n- Difficulty: hard\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "Build an elite-grade solution in the domain of gpu compute for scenario: event ingestion.\nPrimary language: python.\nDifficulty: expert.\nConstraints: document performance characteristics, provide rollout and rollback guidance, avoid undefined behavior and data races, include invariants and failure modes, assume untrusted inputs; validate and sanitize.\nComponent: component_ffmgili.\nAssume cold-start and memory limits are tight.\nTask: Provide SLOs, alerting, dashboards, runbooks, and incident playbook. Include chaos testing and safe rollout strategy.\n\nOutput: elite-grade engineering answer with contracts, edge cases, and verification.\nOutput: SLOs + alerts + runbooks + chaos strategy.\n\n**SLOs**\n- Availability: 99.9% monthly\n- Latency: p95 < 200ms, p99 < 400ms\n- Error rate: < 0.1%\n\n**Alerts**\n- Burn-rate alerts for SLOs (fast/slow windows)\n- Saturation: CPU, memory, queue depth, DB connections\n- Dependency health: cache hit rate drop, downstream timeouts\n\n**Runbooks**\n- Triage: identify blast radius, feature-flag rollback, capacity mitigation\n- Post-incident: timeline, contributing factors, action items\n\n**Chaos**\n- Inject latency, partial outages, and restarts in staging; verify steady-state SLOs.\n\n\nExpert checks: state-machine reasoning, concurrency stress, and upgrade/rollback validated.", "source": "WithinUsAI/Elite_GOD_Coder_100k"} {"text": "Task type: distributed_algorithm\nScenario: real-time notification hub\nDomain focus: real-time scheduling\nPrimary language: go\nDifficulty: hard\nScale/SLO: 100k RPS peak\nComponent: component_gbwzpnhj\nConstraints: explicit contracts and invariants, include backward compatibility and migration plan, include deterministic replay plan, include security threat model (defensive only), include verification strategy, avoid data races and undefined behavior, include test vectors and fuzz strategy\nAssume strict auditability and replayable history.\nDeliverable: Design an algorithm with message flows and correctness arguments (safety + liveness). Include failure handling and a minimal reference implementation skeleton.\n\nOutput: contract-first solution with failure modes, security posture, and test/verification strategy.\n**Contract**\n- Inputs validated at the boundary; explicit error taxonomy.\n- Idempotency for side effects via request_id; deterministic replay.\n- Backward compatibility: additive changes by default; versioned breaking changes.\n**Invariants**\n- Determinism: replay of the same event log yields identical outputs.\n- Isolation: tenant boundary enforced; no cross-tenant reads/writes.\n- Liveness: under bounded faults and stable network, progress occurs.\n**Failure modes & recovery**\n- Crash during commit: WAL replay completes or transaction aborts; no torn writes.\n- Duplicate requests: de-duplicate by (tenant, request_id) returning cached response.\n- Network partition: minority cannot commit; clients receive retriable errors.\n**Security posture (defensive)**\n- Threat model: auth/authz, injection, replay/abuse, supply chain.\n- Least privilege; secrets in managed store; audit logs for sensitive ops.\n- Input normalization, parameterized queries, path traversal protections.\n**Verification strategy**\n- Fuzzing of parsers/framers/validators with corpus seeds.\n- Property tests against a pure reference model (state machine).\n- Deterministic simulation with fault injection (crash/partition/latency).\n\n**Snippet**\n```text\nImplementation sketch: factor pure state-machine core; adapters for I/O; add deterministic replay log.\n```\nHard checks: fault injection tests gate merges; perf thresholds enforced in CI.", "source": "WithinUsAI/Omega_Genesis_Coder_100k"} {"text": "Task type: smt_constraint_model\nScenario: payment ledger\nDomain focus: static analysis\nPrimary language: python\nDifficulty: expert+\nScale/SLO: 50 TB/day ingestion\nComponent: component_ogoqhyey\nConstraints: include test vectors and fuzz strategy, include deterministic replay plan, include failure modes and recovery, explicit contracts and invariants, assume adversarial inputs; validate everything, avoid data races and undefined behavior\nAssume schema changes every sprint; must be backward compatible.\nDeliverable: Provide an SMT constraint model (or Python-to-SMT) for correctness/optimization; include sample instances and how to validate solutions.\n\nOutput: rigorous design + invariants + verification plan + implementation sketch.\n**Contract**\n- Inputs validated at the boundary; explicit error taxonomy.\n- Idempotency for side effects via request_id; deterministic replay.\n- Backward compatibility: additive changes by default; versioned breaking changes.\n**Invariants**\n- Safety: state transitions preserve invariants; no partial commit leaks.\n- Liveness: under bounded faults and stable network, progress occurs.\n- Determinism: replay of the same event log yields identical outputs.\n**Failure modes & recovery**\n- Network partition: minority cannot commit; clients receive retriable errors.\n- Duplicate requests: de-duplicate by (tenant, request_id) returning cached response.\n- Crash during commit: WAL replay completes or transaction aborts; no torn writes.\n**Security posture (defensive)**\n- Threat model: auth/authz, injection, replay/abuse, supply chain.\n- Least privilege; secrets in managed store; audit logs for sensitive ops.\n- Input normalization, parameterized queries, path traversal protections.\n**Verification strategy**\n- Fuzzing of parsers/framers/validators with corpus seeds.\n- Deterministic simulation with fault injection (crash/partition/latency).\n- Property tests against a pure reference model (state machine).\n\n**Snippet**\n```smtlib\n; Find an assignment minimizing cost while satisfying constraints\n(declare-const x Int)\n(declare-const y Int)\n(assert (and (>= x 0) (>= y 0) (<= (+ x y) 10)))\n(minimize (+ (* 3 x) (* 2 y)))\n(check-sat)\n(get-model)\n```\n\nExpert+ checks: mechanized invariants (or exhaustive model checking), adversarial fuzzing, and multi-region failure drills.", "source": "WithinUsAI/Omega_Genesis_Coder_100k"} {"text": "Design and implement an algorithm for event dispatching.\nRequirements: define inputs/outputs, implement solution with complexity analysis, and include tests.\nConstraints: must be easy to extend, must include type hints, must provide clear error messages, must include docstrings.\nDifficulty: easy. Ensure the API is testable via dependency injection.\n\nDeliverable: API + reference implementation + tests.\nProblem: compute rolling sums over events (ts:int,value:int) with window W seconds. Events may be out-of-order.\n\nComplexity: sorting O(n log n); window maintenance O(n); memory O(k).\n\n```python\nfrom __future__ import annotations\nfrom collections import deque\nfrom dataclasses import dataclass\nfrom typing import Iterable, List, Tuple\n\n@dataclass(frozen=True, slots=True)\nclass Event:\n ts: int\n value: int\n\ndef rolling_sum(events: Iterable[Event], window_s: int) -> List[Tuple[int,int]]:\n if window_s < 0:\n raise ValueError(\"window_s must be >= 0\")\n evs = sorted(events, key=lambda e: e.ts)\n q: deque[Event] = deque()\n s = 0\n out: List[Tuple[int,int]] = []\n for e in evs:\n q.append(e)\n s += e.value\n cutoff = e.ts - window_s\n while q and q[0].ts < cutoff:\n old = q.popleft()\n s -= old.value\n out.append((e.ts, s))\n return out\n```\n\n```python\nimport pytest\nfrom module_under_test import Event, rolling_sum\n\ndef test_rolling_sum():\n ev = [Event(10,1), Event(11,2), Event(20,5)]\n assert rolling_sum(ev, 5) == [(10,1),(11,3),(20,5)]\n```", "source": "WithinUsAI/python_GOD_coder_100k"} {"text": "Task type: storage_engine\nScenario: time-series metrics store\nDomain focus: formal verification\nPrimary language: bash\nDifficulty: expert\nScale/SLO: 50 TB/day ingestion\nComponent: component_ukhxbqkh\nConstraints: include verification strategy, assume adversarial inputs; validate everything, include failure modes and recovery, include backward compatibility and migration plan, avoid data races and undefined behavior, explicit contracts and invariants\nAssume hostile inputs and targeted abuse patterns.\nDeliverable: Design a storage engine subsystem (WAL, snapshots, compaction). Include crash recovery invariants and a benchmark plan.\n\nOutput: contract-first solution with failure modes, security posture, and test/verification strategy.\n**Contract**\n- Inputs validated at the boundary; explicit error taxonomy.\n- Idempotency for side effects via request_id; deterministic replay.\n- Backward compatibility: additive changes by default; versioned breaking changes.\n**Invariants**\n- Isolation: tenant boundary enforced; no cross-tenant reads/writes.\n- Liveness: under bounded faults and stable network, progress occurs.\n- Determinism: replay of the same event log yields identical outputs.\n**Failure modes & recovery**\n- Crash during commit: WAL replay completes or transaction aborts; no torn writes.\n- Data corruption: checksums + scrubber; quarantine and rebuild from replicas/snapshots.\n- Duplicate requests: de-duplicate by (tenant, request_id) returning cached response.\n**Security posture (defensive)**\n- Threat model: auth/authz, injection, replay/abuse, supply chain.\n- Least privilege; secrets in managed store; audit logs for sensitive ops.\n- Input normalization, parameterized queries, path traversal protections.\n**Verification strategy**\n- Canary + shadow traffic; invariants checked in production via assertions/metrics.\n- Deterministic simulation with fault injection (crash/partition/latency).\n- Property tests against a pure reference model (state machine).\n\n**Snippet**\n```text\nImplementation sketch: factor pure state-machine core; adapters for I/O; add deterministic replay log.\n```\nExpert checks: state-machine proof sketch + model checking; upgrade/rollback rehearsed.", "source": "WithinUsAI/Omega_Genesis_Coder_100k"} {"text": "Task type: program_synthesis_safe\nScenario: time-series metrics store\nDomain focus: data lineage & governance\nPrimary language: sql\nDifficulty: expert\nScale/SLO: 1M msgs/min\nComponent: component_yqyervnn\nConstraints: include test vectors and fuzz strategy, explicit contracts and invariants, include security threat model (defensive only), include verification strategy, avoid data races and undefined behavior, include performance model and limits, assume adversarial inputs; validate everything\nAssume crash-only processes; recovery must be deterministic.\nDeliverable: Design a program-synthesis workflow that generates code from specs safely; include guardrails and verification.\n\nOutput: elite engineering answer optimized for correctness, performance, and operability.\n**Contract**\n- Inputs validated at the boundary; explicit error taxonomy.\n- Idempotency for side effects via request_id; deterministic replay.\n- Backward compatibility: additive changes by default; versioned breaking changes.\n**Invariants**\n- Determinism: replay of the same event log yields identical outputs.\n- Safety: state transitions preserve invariants; no partial commit leaks.\n- Isolation: tenant boundary enforced; no cross-tenant reads/writes.\n**Failure modes & recovery**\n- Crash during commit: WAL replay completes or transaction aborts; no torn writes.\n- Duplicate requests: de-duplicate by (tenant, request_id) returning cached response.\n- Network partition: minority cannot commit; clients receive retriable errors.\n**Security posture (defensive)**\n- Threat model: auth/authz, injection, replay/abuse, supply chain.\n- Least privilege; secrets in managed store; audit logs for sensitive ops.\n- Input normalization, parameterized queries, path traversal protections.\n**Verification strategy**\n- Fuzzing of parsers/framers/validators with corpus seeds.\n- Deterministic simulation with fault injection (crash/partition/latency).\n- Canary + shadow traffic; invariants checked in production via assertions/metrics.\n\n**Snippet**\n```text\nImplementation sketch: factor pure state-machine core; adapters for I/O; add deterministic replay log.\n```\nExpert checks: state-machine proof sketch + model checking; upgrade/rollback rehearsed.", "source": "WithinUsAI/Omega_Genesis_Coder_100k"} {"text": "Build an elite-grade solution in the domain of ml systems for scenario: rate limiting gateway.\nPrimary language: rust.\nDifficulty: hard.\nConstraints: include invariants and failure modes, make the interface contract explicit, include tests or verification strategy, document performance characteristics.\nComponent: component_wrmvuex.\nAssume partial network partitions occur weekly.\nTask: Implement a concurrency primitive or subsystem (lock-free queue, thread pool, async runtime component). Explain memory ordering and correctness arguments; include stress tests.\n\nOutput: elite-grade engineering answer with contracts, edge cases, and verification.\nOutput: correctness-focused concurrency primitive + stress tests.\n\n**Primitive**\n- Bounded MPMC queue with backpressure (blocking push/pop) OR lock-free SPSC ring buffer.\n\n**Correctness notes**\n- For lock-free: use acquire/release semantics on head/tail indices.\n- Avoid ABA by monotonic counters; ring index = counter % capacity.\n\n**Stress tests**\n- Multi-thread producers/consumers; assert item multiset preserved.\n- Use time-bounded randomized schedules; detect deadlocks.\n\n\nHard checks: failure injection tests and performance regressions gated.", "source": "WithinUsAI/Elite_GOD_Coder_100k"} {"text": "Design a small, production-grade Python API for report generation.\nRequirements: define data models and interfaces, implement reference version, include tests.\nConstraints: stdlib-only, must include type hints, must provide clear error messages, must be memory-efficient.\nDifficulty: medium. Support both Windows and POSIX paths correctly.\n\nDeliverable: API + reference implementation + tests.\nArchitecture:\n- Public facade class coordinating concerns (parsing, validation, persistence)\n- Small pure functions for testability\n- No global state; dependency injection for filesystem I/O\n\n```python\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom pathlib import Path\nfrom typing import Protocol, Iterable\nimport json\n\nclass Store(Protocol):\n def write_text(self, path: Path, data: str) -> None: ...\n\nclass FSStore:\n def write_text(self, path: Path, data: str) -> None:\n path.parent.mkdir(parents=True, exist_ok=True)\n path.write_text(data, encoding=\"utf-8\")\n\n@dataclass(frozen=True, slots=True)\nclass Item:\n name: str\n qty: int\n\ndef parse_items(lines: Iterable[str]) -> list[Item]:\n out: list[Item] = []\n for i, line in enumerate(lines, 1):\n s = line.strip()\n if not s:\n continue\n obj = json.loads(s)\n if not isinstance(obj, dict):\n raise ValueError(f\"line {i}: expected object\")\n name = obj.get(\"name\")\n qty = obj.get(\"qty\")\n if not isinstance(name, str) or not name:\n raise ValueError(f\"line {i}: name must be str\")\n if not isinstance(qty, int) or qty < 0:\n raise ValueError(f\"line {i}: qty must be non-negative int\")\n out.append(Item(name, qty))\n return out\n\nclass InventoryWriter:\n def __init__(self, base_dir: Path, store: Store | None = None) -> None:\n self._base = base_dir\n self._store: Store = store or FSStore()\n\n def write(self, rel_path: str, items: list[Item]) -> Path:\n dst = (self._base / rel_path).resolve()\n base = self._base.resolve()\n if dst != base and base not in dst.parents:\n raise ValueError(\"unsafe path traversal\")\n payload = json.dumps([item.__dict__ for item in items], ensure_ascii=False)\n self._store.write_text(dst, payload)\n return dst\n```\n\n```python\nimport json\nfrom pathlib import Path\nimport pytest\nfrom module_under_test import InventoryWriter, parse_items\n\ndef test_parse_items_valid():\n lines = [json.dumps({\"name\":\"x\",\"qty\":1})]\n assert parse_items(lines)[0].name == \"x\"\n\ndef test_writer_blocks_traversal(tmp_path: Path):\n w = InventoryWriter(tmp_path)\n with pytest.raises(ValueError):\n w.write(\"../evil.json\", [])\n```", "source": "WithinUsAI/python_GOD_coder_100k"} {"text": "Task type: perf_microarchitecture\nScenario: streaming ETL\nDomain focus: high-frequency trading systems (safe engineering)\nPrimary language: python\nDifficulty: expert+\nScale/SLO: 100k RPS peak\nComponent: component_ebwagjol\nConstraints: include security threat model (defensive only), avoid data races and undefined behavior, include backward compatibility and migration plan, include test vectors and fuzz strategy, explicit contracts and invariants\nAssume tight memory budget and cold-start constraints.\nDeliverable: Provide performance engineering plan: profiling, hot-path redesign, cache behavior assumptions, and microbench harness.\n\nOutput: elite engineering answer optimized for correctness, performance, and operability.\n**Contract**\n- Inputs validated at the boundary; explicit error taxonomy.\n- Idempotency for side effects via request_id; deterministic replay.\n- Backward compatibility: additive changes by default; versioned breaking changes.\n**Invariants**\n- Isolation: tenant boundary enforced; no cross-tenant reads/writes.\n- Safety: state transitions preserve invariants; no partial commit leaks.\n- Determinism: replay of the same event log yields identical outputs.\n**Failure modes & recovery**\n- Data corruption: checksums + scrubber; quarantine and rebuild from replicas/snapshots.\n- Network partition: minority cannot commit; clients receive retriable errors.\n- Duplicate requests: de-duplicate by (tenant, request_id) returning cached response.\n**Security posture (defensive)**\n- Threat model: auth/authz, injection, replay/abuse, supply chain.\n- Least privilege; secrets in managed store; audit logs for sensitive ops.\n- Input normalization, parameterized queries, path traversal protections.\n**Verification strategy**\n- Property tests against a pure reference model (state machine).\n- Fuzzing of parsers/framers/validators with corpus seeds.\n- Deterministic simulation with fault injection (crash/partition/latency).\n\n**Snippet**\n```text\nImplementation sketch: factor pure state-machine core; adapters for I/O; add deterministic replay log.\n```\nExpert+ checks: mechanized invariants (or exhaustive model checking), adversarial fuzzing, and multi-region failure drills.", "source": "WithinUsAI/Omega_Genesis_Coder_100k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Produce an offline-first self-evolving code assistant architecture named `ce_p3r_ujelm`.\nMust include: module layout, patch-safety policy, evaluation gates (tests/lint/types), versioned memory index.\n\nArchitecture: `ce_p3r_ujelm` (offline-first, self-evolving)\n\nModules\n- core/loop.py: evolve → validate → accept/reject (bounded iterations)\n- patching/: diff builder, safe apply, atomic writes, rollback points\n- policy/: allowlist paths, deny globs (.git/, __pycache__/, binaries), patch size caps\n- signals/: parse pytest/ruff/mypy into normalized findings\n- memory/index.jsonl: append-only snapshots (hashes, metrics, rationale)\n\nSafety gates\n- refuse path traversal/symlink escapes; never edit binaries\n- accept only if tests/lint/types stay green or improve", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Debug and fix a subtle production bug related to file uploads in a healthtech service.\nTarget platform: mobile (iOS Swift).\nRequirements: identify root cause, provide patch, and add regression tests.\nConstraints: must be production-ready, must avoid global state, must include tests, must be performant under load.\nDifficulty: medium. Assume PII must be protected.\n\nOutput: production-oriented blueprint with code where appropriate.\nDeliverable: production-grade reference implementation (FastAPI) + tests.\n\n```python\n# app.py\nfrom __future__ import annotations\n\nimport hashlib\nimport json\nfrom dataclasses import dataclass\nfrom datetime import datetime, timezone\nfrom typing import Any, Optional\n\nfrom fastapi import FastAPI, Header, HTTPException\nfrom pydantic import BaseModel, Field\n\napp = FastAPI(title=\"Idempotent API\")\n\nclass CreateReq(BaseModel):\n tenant_id: str = Field(min_length=1)\n amount_cents: int = Field(ge=0)\n currency: str = Field(min_length=3, max_length=3)\n\nclass CreateResp(BaseModel):\n id: str\n created_at: str\n echo: CreateReq\n\n@dataclass\nclass _IdempoEntry:\n request_hash: str\n response_json: str\n\n# In production: Postgres table with UNIQUE(tenant_id, key)\n_IDEMPO: dict[tuple[str, str], _IdempoEntry] = {}\n\ndef _hash_req(req: CreateReq) -> str:\n raw = req.model_dump_json()\n return hashlib.sha256(raw.encode(\"utf-8\")).hexdigest()\n\n@app.post(\"/v1/payments\", response_model=CreateResp)\ndef create_payment(\n req: CreateReq,\n idempotency_key: Optional[str] = Header(default=None, alias=\"Idempotency-Key\"),\n) -> Any:\n if not idempotency_key:\n raise HTTPException(status_code=400, detail=\"Missing Idempotency-Key\")\n if len(idempotency_key) > 128:\n raise HTTPException(status_code=400, detail=\"Idempotency-Key too long\")\n\n key = (req.tenant_id, idempotency_key)\n rh = _hash_req(req)\n\n existing = _IDEMPO.get(key)\n if existing:\n if existing.request_hash != rh:\n raise HTTPException(status_code=409, detail=\"Idempotency-Key reuse with different payload\")\n return json.loads(existing.response_json)\n\n # Create new payment (stubbed)\n pid = hashlib.md5(f\"{req.tenant_id}:{idempotency_key}\".encode()).hexdigest()\n resp = CreateResp(\n id=pid,\n created_at=datetime.now(timezone.utc).isoformat(),\n echo=req,\n )\n _IDEMPO[key] = _IdempoEntry(request_hash=rh, response_json=resp.model_dump_json())\n return resp\n```\n\n```python\n# test_app.py (pytest)\nfrom fastapi.testclient import TestClient\nfrom app import app\n\nclient = TestClient(app)\n\ndef test_idempotent_replay():\n headers = {\"Idempotency-Key\": \"abc\"}\n body = {\"tenant_id\":\"t1\",\"amount_cents\":100,\"currency\":\"USD\"}\n r1 = client.post(\"/v1/payments\", json=body, headers=headers)\n r2 = client.post(\"/v1/payments\", json=body, headers=headers)\n assert r1.status_code == 200 and r2.status_code == 200\n assert r1.json() == r2.json()\n\ndef test_payload_conflict():\n headers = {\"Idempotency-Key\": \"abc\"}\n b1 = {\"tenant_id\":\"t1\",\"amount_cents\":100,\"currency\":\"USD\"}\n b2 = {\"tenant_id\":\"t1\",\"amount_cents\":200,\"currency\":\"USD\"}\n assert client.post(\"/v1/payments\", json=b1, headers=headers).status_code == 200\n assert client.post(\"/v1/payments\", json=b2, headers=headers).status_code == 409\n```\n\nNotes:\n- Replace in-memory store with a DB table and transaction.\n- Store response + request hash to detect key reuse with different payload.\n\n\nChecks: input validation, tests, and safe defaults included.", "source": "WithinUsAI/GOD_Coder_100k"} {"text": "Optimize while preserving behavior and order.\n\n```python\ndef f63060(xs):\n out=[]\n for x in xs:\n if x not in out: out.append(x)\n return out\n```\nReturn `m37580.py` with types and O(n) average.\n\n```python\n# m37580.py\nfrom __future__ import annotations\nfrom typing import Iterable, List, Set, TypeVar\nT=TypeVar(\"T\")\n\ndef f63060(xs: Iterable[T]) -> List[T]:\n \"\"\"Unique items preserving first-seen order.\"\"\"\n seen: Set[T]=set()\n out: List[T]=[]\n for x in xs:\n if x in seen: continue\n seen.add(x); out.append(x)\n return out\n```", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Fix a bug and add tests.\n\nFile: ep3nzu3x3.py\n```python\ndef vo22ktz15cl0(n: int) -> int:\n \"\"\"Sum 1..n inclusive.\"\"\"\n if n < 0:\n raise ValueError(\"n must be non-negative\")\n total = 0\n for k in range(n): # BUG: should include n\n total += k\n return total\n```\n\nReturn unified diffs for ep3nzu3x3.py and test_ep3nzu3x3.py (pytest).\n\n*** Begin Patch\n*** Update File: ep3nzu3x3.py\n@@\n def vo22ktz15cl0(n: int) -> int:\n@@\n total = 0\n- for k in range(n): # BUG: should include n\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_ep3nzu3x3.py\n+import pytest\n+from ep3nzu3x3 import vo22ktz15cl0\n+\n+def test_zero():\n+ assert vo22ktz15cl0(0) == 0\n+\n+def test_one():\n+ assert vo22ktz15cl0(1) == 1\n+\n+def test_small():\n+ assert vo22ktz15cl0(7) == 28\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ vo22ktz15cl0(-1)\n+\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Refactor a Python module used for validation into a clean, extensible design.\nRequirements: outline the new architecture briefly, then provide the refactored code and tests.\nConstraints: must be memory-efficient, must include docstrings, must be streaming-friendly, must handle Windows paths safely.\nDifficulty: expert. Include a small CLI example if relevant.\n\nDeliverable: corrected code and verification tests.\nArchitecture:\n- Public facade class coordinating concerns (parsing, validation, persistence)\n- Small pure functions for testability\n- No global state; dependency injection for filesystem I/O\n\n```python\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom pathlib import Path\nfrom typing import Protocol, Iterable\nimport json\n\nclass Store(Protocol):\n def write_text(self, path: Path, data: str) -> None: ...\n\nclass FSStore:\n def write_text(self, path: Path, data: str) -> None:\n path.parent.mkdir(parents=True, exist_ok=True)\n path.write_text(data, encoding=\"utf-8\")\n\n@dataclass(frozen=True, slots=True)\nclass Item:\n name: str\n qty: int\n\ndef parse_items(lines: Iterable[str]) -> list[Item]:\n out: list[Item] = []\n for i, line in enumerate(lines, 1):\n s = line.strip()\n if not s:\n continue\n obj = json.loads(s)\n if not isinstance(obj, dict):\n raise ValueError(f\"line {i}: expected object\")\n name = obj.get(\"name\")\n qty = obj.get(\"qty\")\n if not isinstance(name, str) or not name:\n raise ValueError(f\"line {i}: name must be str\")\n if not isinstance(qty, int) or qty < 0:\n raise ValueError(f\"line {i}: qty must be non-negative int\")\n out.append(Item(name, qty))\n return out\n\nclass InventoryWriter:\n def __init__(self, base_dir: Path, store: Store | None = None) -> None:\n self._base = base_dir\n self._store: Store = store or FSStore()\n\n def write(self, rel_path: str, items: list[Item]) -> Path:\n dst = (self._base / rel_path).resolve()\n base = self._base.resolve()\n if dst != base and base not in dst.parents:\n raise ValueError(\"unsafe path traversal\")\n payload = json.dumps([item.__dict__ for item in items], ensure_ascii=False)\n self._store.write_text(dst, payload)\n return dst\n```\n\n```python\nimport json\nfrom pathlib import Path\nimport pytest\nfrom module_under_test import InventoryWriter, parse_items\n\ndef test_parse_items_valid():\n lines = [json.dumps({\"name\":\"x\",\"qty\":1})]\n assert parse_items(lines)[0].name == \"x\"\n\ndef test_writer_blocks_traversal(tmp_path: Path):\n w = InventoryWriter(tmp_path)\n with pytest.raises(ValueError):\n w.write(\"../evil.json\", [])\n```", "source": "WithinUsAI/python_GOD_coder_100k"} {"text": "Implement a concurrent Python solution for CLI tooling.\nRequirements: choose appropriate concurrency model, handle cancellation/timeouts, include tests.\nConstraints: must provide clear error messages, must handle Windows paths safely, must be memory-efficient.\nDifficulty: medium. Ensure the API is testable via dependency injection.\n\nDeliverable: API + reference implementation + tests.\n```python\nfrom __future__ import annotations\nimport asyncio\nfrom dataclasses import dataclass\nfrom typing import Awaitable, Callable, Iterable, Optional\n\n@dataclass(frozen=True, slots=True)\nclass JobResult:\n ok: bool\n value: Optional[int]\n error: Optional[str]\n\nasync def run_bounded(\n factories: Iterable[Callable[[], Awaitable[int]]],\n *,\n limit: int = 10,\n timeout_s: float = 5.0,\n) -> list[JobResult]:\n if limit <= 0:\n raise ValueError(\"limit must be > 0\")\n sem = asyncio.Semaphore(limit)\n results: list[JobResult] = []\n\n async def one(factory: Callable[[], Awaitable[int]]) -> None:\n async with sem:\n try:\n v = await asyncio.wait_for(factory(), timeout=timeout_s)\n results.append(JobResult(True, v, None))\n except Exception as e:\n results.append(JobResult(False, None, str(e)))\n\n tasks = [asyncio.create_task(one(f)) for f in factories]\n try:\n await asyncio.gather(*tasks)\n finally:\n for t in tasks:\n if not t.done():\n t.cancel()\n return results\n```\n\n```python\nimport asyncio\nimport pytest\nfrom module_under_test import run_bounded\n\n@pytest.mark.asyncio\nasync def test_run_bounded_collects():\n async def work(x: int) -> int:\n await asyncio.sleep(0.01)\n return x\n fs = [(lambda i=i: work(i)) for i in range(30)]\n out = await run_bounded(fs, limit=5, timeout_s=1.0)\n assert len(out) == 30\n assert all(r.ok for r in out)\n```", "source": "WithinUsAI/python_GOD_coder_100k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Refactor to modern typed Python with immutability and tests.\n\nFile: u1ihq55.py\n```python\nclass Zqtnuzdm:\n def __init__(self, name, values):\n self.name = name\n self.values = list(values)\n def add(self, v):\n self.values.append(v)\n def mean(self):\n s = 0\n for x in self.values:\n s += x\n return s / len(self.values)\n```\n\nReturn full new u1ihq55.py and test_u1ihq55.py.\n\n# u1ihq55.py\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom typing import Iterable, Tuple\n\n@dataclass(frozen=True)\nclass Zqtnuzdm:\n name: str\n values: Tuple[float, ...]\n\n @staticmethod\n def create(name: str, values: Iterable[float]) -> \"Zqtnuzdm\":\n vals = tuple(float(v) for v in values)\n if not vals:\n raise ValueError(\"values must be non-empty\")\n return Zqtnuzdm(name=name, values=vals)\n\n def add(self, v: float) -> \"Zqtnuzdm\":\n return Zqtnuzdm(name=self.name, values=self.values + (float(v),))\n\n def mean(self) -> float:\n return sum(self.values) / len(self.values)\n\n# test_u1ihq55.py\nimport pytest\nfrom u1ihq55 import Zqtnuzdm\n\ndef test_mean_and_add():\n c = Zqtnuzdm.create(\"a\", [1, 2, 3])\n assert c.mean() == 2.0\n assert c.add(5).mean() == (1 + 2 + 3 + 5) / 4\n\ndef test_empty_raises():\n with pytest.raises(ValueError):\n Zqtnuzdm.create(\"x\", [])", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Write pytest tests for `f10025`.\n\n```python\ndef f10025(a: int, b: int) -> int:\n return a*a + b*b\n```\nInclude edge cases and a property-style check.\n\n```python\nimport random\nfrom m58575 import f10025\n\ndef test_known():\n assert f10025(3,4) == 25\n\ndef test_zero():\n assert f10025(0,0) == 0\n\ndef test_property_nonnegative():\n for _ in range(200):\n a=random.randint(-50,50)\n b=random.randint(-50,50)\n assert f10025(a,b) >= 0\n```", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Refactor to typed, mostly-immutable Python and add minimal tests.\n\n```python\nclass C16352:\n def __init__(self, values): self.values=list(values)\n def mean(self): return sum(self.values)/len(self.values)\n```\nReturn `m55104.py` and `test_m55104.py`.\n\n```python\n# m55104.py\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom typing import Iterable, Tuple\n\n@dataclass(frozen=True)\nclass C16352:\n values: Tuple[float, ...]\n\n @staticmethod\n def create(values: Iterable[float]) -> \"C16352\":\n vals = tuple(float(v) for v in values)\n if not vals: raise ValueError(\"empty\")\n return C16352(vals)\n\n def mean(self) -> float:\n return sum(self.values)/len(self.values)\n```\n\n```python\n# test_m55104.py\nimport pytest\nfrom m55104 import C16352\n\ndef test_mean():\n assert C16352.create([1,2,3]).mean() == 2.0\ndef test_empty():\n with pytest.raises(ValueError):\n C16352.create([])\n```", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Refactor to typed, mostly-immutable Python and add minimal tests.\n\n```python\nclass C32893:\n def __init__(self, values): self.values=list(values)\n def mean(self): return sum(self.values)/len(self.values)\n```\nReturn `m71761.py` and `test_m71761.py`.\n\n```python\n# m71761.py\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom typing import Iterable, Tuple\n\n@dataclass(frozen=True)\nclass C32893:\n values: Tuple[float, ...]\n\n @staticmethod\n def create(values: Iterable[float]) -> \"C32893\":\n vals = tuple(float(v) for v in values)\n if not vals: raise ValueError(\"empty\")\n return C32893(vals)\n\n def mean(self) -> float:\n return sum(self.values)/len(self.values)\n```\n\n```python\n# test_m71761.py\nimport pytest\nfrom m71761 import C32893\n\ndef test_mean():\n assert C32893.create([1,2,3]).mean() == 2.0\ndef test_empty():\n with pytest.raises(ValueError):\n C32893.create([])\n```", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Fix the bug and add pytest tests.\n\n```python\ndef f69517(n: int) -> int:\n # sum 1..n inclusive\n if n < 0: raise ValueError\n total = 0\n for k in range(n): # BUG\n total += k\n return total\n```\nReturn unified diffs for `m09931.py` and `test_m09931.py`.\n\n*** Begin Patch\n*** Update File: m09931.py\n@@\n def f69517(n: int) -> int:\n@@\n- for k in range(n): # BUG\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_m09931.py\n+import pytest\n+from m09931 import f69517\n+\n+def test_small():\n+ assert f69517(7) == 28\n+\n+def test_zero():\n+ assert f69517(0) == 0\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ f69517(-1)\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: Language: Java\nFramework/tooling: Spring Boot\nDomain: repo automation\nLogic challenge: race condition on worker shutdown\nTask type: misleading_symptom_debug\nDifficulty: hard\n\nReturn a rigorous engineering answer:\n- identify the hidden root cause or logical failure\n- present the corrected implementation\n- add tests that prove the fix\n- list verification commands\n- explain why naive fixes are insufficient when relevant\n\nRepository sketch:\nrepo/\n src/main/java/com/acme/App.java\n src/main/java/com/acme/Service.java\n src/test/java/com/acme/AppTest.java\n pom.xml\n\nFocus: Focus on ambiguity, misleading symptoms, hidden root causes, and high-stakes debugging.\n\nassistant: Diagnosis:\n- Hidden root cause: race condition on worker shutdown presents misleading symptoms, so the patch must target the actual logic boundary rather than the first visible failure.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```java\nimport java.util.HashMap;\nimport java.util.Map;\n\npublic final class RequestHandler {\n public static Map handleRequest(Map payload) {\n Map clean = new HashMap<>();\n for (Map.Entry entry : payload.entrySet()) {\n if (entry.getValue() != null) clean.put(entry.getKey().trim(), entry.getValue());\n }\n if (!clean.containsKey(\"id\")) throw new IllegalArgumentException(\"missing id\");\n return Map.of(\"ok\", true, \"data\", clean);\n }\n}\n```\n\nTests:\n```java\nimport static org.junit.jupiter.api.Assertions.*;\nimport java.util.Map;\nimport org.junit.jupiter.api.Test;\n\nclass RequestHandlerTest {\n @Test\n void requiresId() {\n assertThrows(IllegalArgumentException.class, () -> RequestHandler.handleRequest(Map.of(\"name\", \"x\")));\n }\n}\n```\n\nVerification:\n- `./gradlew test`\n- `mvn test`\n\nEngineering notes:\n- Language: Java\n- Framework/tooling: Spring Boot\n- Stack context: GitHub Actions, Docker Compose, Kubernetes, Terraform\n- Domain: repo automation\n- Task type: misleading_symptom_debug\n- Difficulty: hard\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "Write pytest tests for `f56149`.\n\n```python\ndef f56149(a: int, b: int) -> int:\n return a*a + b*b\n```\nInclude edge cases and a property-style check.\n\n```python\nimport random\nfrom m22307 import f56149\n\ndef test_known():\n assert f56149(3,4) == 25\n\ndef test_zero():\n assert f56149(0,0) == 0\n\ndef test_property_nonnegative():\n for _ in range(200):\n a=random.randint(-50,50)\n b=random.randint(-50,50)\n assert f56149(a,b) >= 0\n```", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Add a clear docstring and type hints to this function:\n\n```python\ndef f91062(s):\n return ''.join(x for x in s if x.isalnum()).lower()\n```\n\n```python\nfrom __future__ import annotations\n\ndef f91062(s: str) -> str:\n \"\"\"Normalize a string: keep only alphanumerics and lowercase the result.\"\"\"\n return \"\".join(ch for ch in s if ch.isalnum()).lower()\n```", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Debug and fix a subtle production bug related to real-time notifications in a IoT telemetry service.\nTarget platform: infra (Docker + Kubernetes).\nRequirements: identify root cause, provide patch, and add regression tests.\nConstraints: must be observable (logs/metrics/traces), must include type hints where applicable, must be performant under load, must be secure-by-default, must include tests.\nDifficulty: medium. Assume GDPR-style deletion requests must be supported.\n\nOutput: design + implementation guidance suitable for shipping.\nDeliverable: production-grade reference implementation (FastAPI) + tests.\n\n```python\n# app.py\nfrom __future__ import annotations\n\nimport hashlib\nimport json\nfrom dataclasses import dataclass\nfrom datetime import datetime, timezone\nfrom typing import Any, Optional\n\nfrom fastapi import FastAPI, Header, HTTPException\nfrom pydantic import BaseModel, Field\n\napp = FastAPI(title=\"Idempotent API\")\n\nclass CreateReq(BaseModel):\n tenant_id: str = Field(min_length=1)\n amount_cents: int = Field(ge=0)\n currency: str = Field(min_length=3, max_length=3)\n\nclass CreateResp(BaseModel):\n id: str\n created_at: str\n echo: CreateReq\n\n@dataclass\nclass _IdempoEntry:\n request_hash: str\n response_json: str\n\n# In production: Postgres table with UNIQUE(tenant_id, key)\n_IDEMPO: dict[tuple[str, str], _IdempoEntry] = {}\n\ndef _hash_req(req: CreateReq) -> str:\n raw = req.model_dump_json()\n return hashlib.sha256(raw.encode(\"utf-8\")).hexdigest()\n\n@app.post(\"/v1/payments\", response_model=CreateResp)\ndef create_payment(\n req: CreateReq,\n idempotency_key: Optional[str] = Header(default=None, alias=\"Idempotency-Key\"),\n) -> Any:\n if not idempotency_key:\n raise HTTPException(status_code=400, detail=\"Missing Idempotency-Key\")\n if len(idempotency_key) > 128:\n raise HTTPException(status_code=400, detail=\"Idempotency-Key too long\")\n\n key = (req.tenant_id, idempotency_key)\n rh = _hash_req(req)\n\n existing = _IDEMPO.get(key)\n if existing:\n if existing.request_hash != rh:\n raise HTTPException(status_code=409, detail=\"Idempotency-Key reuse with different payload\")\n return json.loads(existing.response_json)\n\n # Create new payment (stubbed)\n pid = hashlib.md5(f\"{req.tenant_id}:{idempotency_key}\".encode()).hexdigest()\n resp = CreateResp(\n id=pid,\n created_at=datetime.now(timezone.utc).isoformat(),\n echo=req,\n )\n _IDEMPO[key] = _IdempoEntry(request_hash=rh, response_json=resp.model_dump_json())\n return resp\n```\n\n```python\n# test_app.py (pytest)\nfrom fastapi.testclient import TestClient\nfrom app import app\n\nclient = TestClient(app)\n\ndef test_idempotent_replay():\n headers = {\"Idempotency-Key\": \"abc\"}\n body = {\"tenant_id\":\"t1\",\"amount_cents\":100,\"currency\":\"USD\"}\n r1 = client.post(\"/v1/payments\", json=body, headers=headers)\n r2 = client.post(\"/v1/payments\", json=body, headers=headers)\n assert r1.status_code == 200 and r2.status_code == 200\n assert r1.json() == r2.json()\n\ndef test_payload_conflict():\n headers = {\"Idempotency-Key\": \"abc\"}\n b1 = {\"tenant_id\":\"t1\",\"amount_cents\":100,\"currency\":\"USD\"}\n b2 = {\"tenant_id\":\"t1\",\"amount_cents\":200,\"currency\":\"USD\"}\n assert client.post(\"/v1/payments\", json=b1, headers=headers).status_code == 200\n assert client.post(\"/v1/payments\", json=b2, headers=headers).status_code == 409\n```\n\nNotes:\n- Replace in-memory store with a DB table and transaction.\n- Store response + request hash to detect key reuse with different payload.\n\n\nChecks: input validation, tests, and safe defaults included.", "source": "WithinUsAI/GOD_Coder_100k"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: Project stack: Rust, Axum, SQLx, Redis, Tokio, Docker\nLanguage: JavaScript\nDependency challenge: partial checkpoint corruption\nTask type: version_conflict_resolution\nDifficulty: medium\n\nFix this as a senior engineer.\nRequired:\n- identify the version or compatibility failure mode\n- produce the corrected config/code/build patch\n- explain rollback-safe migration notes\n- add regression tests or reproducibility checks\n- include concrete verification commands\n\nRepository sketch:\nrepo/\n src/\n api.js\n service.js\n utils.js\n tests/\n api.test.js\n package.json\n\nFocus: Focus on versioning, migrations, lockfiles, runtime compatibility, and secure dependency handling.\n\nassistant: Diagnosis:\n- Root cause: the issue around partial checkpoint corruption is a dependency, migration, or runtime-compatibility mismatch that needs a rollback-safe patch.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```javascript\ntype Payload = Record;\n\nexport function normalizePayload(payload: Payload): Payload {\n if (!payload || typeof payload !== \"object\" || Array.isArray(payload)) {\n throw new TypeError(\"payload must be a plain object\");\n }\n return Object.fromEntries(\n Object.entries(payload)\n .filter(([, value]) => value !== null && value !== undefined)\n .map(([key, value]) => [String(key).trim(), value])\n );\n}\n\nexport function handlePartialCheckpointCorruption(payload: Payload) {\n const clean = normalizePayload(payload);\n if (!(\"id\" in clean)) {\n return { ok: false, data: {}, error: \"missing id\" };\n }\n return { ok: true, data: clean, error: null };\n}\n```\n\nTests:\n```javascript\nimport { describe, it, expect } from \"vitest\";\nimport { handlePartialCheckpointCorruption } from \"../src/service\";\n\ndescribe(\"handler\", () => {\n it(\"accepts valid input\", () => {\n expect(handlePartialCheckpointCorruption({ id: 7, name: \"ok\", unused: null })).toEqual({\n ok: true,\n data: { id: 7, name: \"ok\" },\n error: null\n });\n });\n\n it(\"rejects missing id\", () => {\n expect(handlePartialCheckpointCorruption({ name: \"x\" }).error).toMatch(/missing id/);\n });\n});\n```\n\nVerification:\n- `npm test`\n- `npm run lint`\n\nEngineering notes:\n- Language: JavaScript\n- Framework/tooling: Vite\n- Stack context: Rust, Axum, SQLx, Redis, Tokio, Docker\n- Domain: payments platform\n- Task type: version_conflict_resolution\n- Difficulty: medium\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Refactor to modern typed Python with immutability and tests.\n\nFile: keac_u.py\n```python\nclass I55Ts9Qgh:\n def __init__(self, name, values):\n self.name = name\n self.values = list(values)\n def add(self, v):\n self.values.append(v)\n def mean(self):\n s = 0\n for x in self.values:\n s += x\n return s / len(self.values)\n```\n\nReturn full new keac_u.py and test_keac_u.py.\n\n# keac_u.py\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom typing import Iterable, Tuple\n\n@dataclass(frozen=True)\nclass I55Ts9Qgh:\n name: str\n values: Tuple[float, ...]\n\n @staticmethod\n def create(name: str, values: Iterable[float]) -> \"I55Ts9Qgh\":\n vals = tuple(float(v) for v in values)\n if not vals:\n raise ValueError(\"values must be non-empty\")\n return I55Ts9Qgh(name=name, values=vals)\n\n def add(self, v: float) -> \"I55Ts9Qgh\":\n return I55Ts9Qgh(name=self.name, values=self.values + (float(v),))\n\n def mean(self) -> float:\n return sum(self.values) / len(self.values)\n\n# test_keac_u.py\nimport pytest\nfrom keac_u import I55Ts9Qgh\n\ndef test_mean_and_add():\n c = I55Ts9Qgh.create(\"a\", [1, 2, 3])\n assert c.mean() == 2.0\n assert c.add(5).mean() == (1 + 2 + 3 + 5) / 4\n\ndef test_empty_raises():\n with pytest.raises(ValueError):\n I55Ts9Qgh.create(\"x\", [])", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Build an elite-grade solution in the domain of operating systems for scenario: analytics pipeline.\nPrimary language: typescript.\nDifficulty: hard.\nConstraints: provide rollout and rollback guidance, include tests or verification strategy, assume untrusted inputs; validate and sanitize, include invariants and failure modes.\nComponent: component_kkqoxfp.\nAssume crash-only design; recovery must be deterministic.\nTask: Provide a cross-language reference (API contract + implementation in two languages) and compatibility tests.\n\nOutput: production blueprint plus correctness arguments and test strategy.\nOutput: API contract + two implementations + compat tests.\n\n**Contract**\n- JSON schema for request/response; strict field validation; explicit version.\n\n**Example**\n- Implement validator + handler in Python and TypeScript.\n- Compatibility tests: same inputs produce equivalent outputs; reject unknown fields when in strict mode.\n\n\nHard checks: failure injection tests and performance regressions gated.", "source": "WithinUsAI/Elite_GOD_Coder_100k"} {"text": "Implement real-time notifications for a social media product.\nTarget platform: mobile (iOS Swift).\nRequirements: provide production-ready code, configuration, and tests.\nConstraints: must be performant under load, must be observable (logs/metrics/traces), must include clear error handling, must include type hints where applicable, must be secure-by-default.\nDifficulty: easy. Assume schema evolves frequently; design for migrations.\n\nOutput: design + implementation guidance suitable for shipping.\nDeliverable: production-grade reference implementation (FastAPI) + tests.\n\n```python\n# app.py\nfrom __future__ import annotations\n\nimport hashlib\nimport json\nfrom dataclasses import dataclass\nfrom datetime import datetime, timezone\nfrom typing import Any, Optional\n\nfrom fastapi import FastAPI, Header, HTTPException\nfrom pydantic import BaseModel, Field\n\napp = FastAPI(title=\"Idempotent API\")\n\nclass CreateReq(BaseModel):\n tenant_id: str = Field(min_length=1)\n amount_cents: int = Field(ge=0)\n currency: str = Field(min_length=3, max_length=3)\n\nclass CreateResp(BaseModel):\n id: str\n created_at: str\n echo: CreateReq\n\n@dataclass\nclass _IdempoEntry:\n request_hash: str\n response_json: str\n\n# In production: Postgres table with UNIQUE(tenant_id, key)\n_IDEMPO: dict[tuple[str, str], _IdempoEntry] = {}\n\ndef _hash_req(req: CreateReq) -> str:\n raw = req.model_dump_json()\n return hashlib.sha256(raw.encode(\"utf-8\")).hexdigest()\n\n@app.post(\"/v1/payments\", response_model=CreateResp)\ndef create_payment(\n req: CreateReq,\n idempotency_key: Optional[str] = Header(default=None, alias=\"Idempotency-Key\"),\n) -> Any:\n if not idempotency_key:\n raise HTTPException(status_code=400, detail=\"Missing Idempotency-Key\")\n if len(idempotency_key) > 128:\n raise HTTPException(status_code=400, detail=\"Idempotency-Key too long\")\n\n key = (req.tenant_id, idempotency_key)\n rh = _hash_req(req)\n\n existing = _IDEMPO.get(key)\n if existing:\n if existing.request_hash != rh:\n raise HTTPException(status_code=409, detail=\"Idempotency-Key reuse with different payload\")\n return json.loads(existing.response_json)\n\n # Create new payment (stubbed)\n pid = hashlib.md5(f\"{req.tenant_id}:{idempotency_key}\".encode()).hexdigest()\n resp = CreateResp(\n id=pid,\n created_at=datetime.now(timezone.utc).isoformat(),\n echo=req,\n )\n _IDEMPO[key] = _IdempoEntry(request_hash=rh, response_json=resp.model_dump_json())\n return resp\n```\n\n```python\n# test_app.py (pytest)\nfrom fastapi.testclient import TestClient\nfrom app import app\n\nclient = TestClient(app)\n\ndef test_idempotent_replay():\n headers = {\"Idempotency-Key\": \"abc\"}\n body = {\"tenant_id\":\"t1\",\"amount_cents\":100,\"currency\":\"USD\"}\n r1 = client.post(\"/v1/payments\", json=body, headers=headers)\n r2 = client.post(\"/v1/payments\", json=body, headers=headers)\n assert r1.status_code == 200 and r2.status_code == 200\n assert r1.json() == r2.json()\n\ndef test_payload_conflict():\n headers = {\"Idempotency-Key\": \"abc\"}\n b1 = {\"tenant_id\":\"t1\",\"amount_cents\":100,\"currency\":\"USD\"}\n b2 = {\"tenant_id\":\"t1\",\"amount_cents\":200,\"currency\":\"USD\"}\n assert client.post(\"/v1/payments\", json=b1, headers=headers).status_code == 200\n assert client.post(\"/v1/payments\", json=b2, headers=headers).status_code == 409\n```\n\nNotes:\n- Replace in-memory store with a DB table and transaction.\n- Store response + request hash to detect key reuse with different payload.\n\n\nChecks: input validation, tests, and safe defaults included.", "source": "WithinUsAI/GOD_Coder_100k"} {"text": "Add a clear docstring and type hints to this function:\n\n```python\ndef f18938(s):\n return ''.join(x for x in s if x.isalnum()).lower()\n```\n\n```python\nfrom __future__ import annotations\n\ndef f18938(s: str) -> str:\n \"\"\"Normalize a string: keep only alphanumerics and lowercase the result.\"\"\"\n return \"\".join(ch for ch in s if ch.isalnum()).lower()\n```", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Debug and fix a subtle production bug related to multi-tenant isolation in a developer tooling service.\nTarget platform: mobile (iOS Swift).\nRequirements: identify root cause, provide patch, and add regression tests.\nConstraints: must avoid global state, must include clear error handling, must include tests.\nDifficulty: expert. Include rollback strategy.\n\nOutput: design + implementation guidance suitable for shipping.\nDeliverable: production-grade reference implementation (FastAPI) + tests.\n\n```python\n# app.py\nfrom __future__ import annotations\n\nimport hashlib\nimport json\nfrom dataclasses import dataclass\nfrom datetime import datetime, timezone\nfrom typing import Any, Optional\n\nfrom fastapi import FastAPI, Header, HTTPException\nfrom pydantic import BaseModel, Field\n\napp = FastAPI(title=\"Idempotent API\")\n\nclass CreateReq(BaseModel):\n tenant_id: str = Field(min_length=1)\n amount_cents: int = Field(ge=0)\n currency: str = Field(min_length=3, max_length=3)\n\nclass CreateResp(BaseModel):\n id: str\n created_at: str\n echo: CreateReq\n\n@dataclass\nclass _IdempoEntry:\n request_hash: str\n response_json: str\n\n# In production: Postgres table with UNIQUE(tenant_id, key)\n_IDEMPO: dict[tuple[str, str], _IdempoEntry] = {}\n\ndef _hash_req(req: CreateReq) -> str:\n raw = req.model_dump_json()\n return hashlib.sha256(raw.encode(\"utf-8\")).hexdigest()\n\n@app.post(\"/v1/payments\", response_model=CreateResp)\ndef create_payment(\n req: CreateReq,\n idempotency_key: Optional[str] = Header(default=None, alias=\"Idempotency-Key\"),\n) -> Any:\n if not idempotency_key:\n raise HTTPException(status_code=400, detail=\"Missing Idempotency-Key\")\n if len(idempotency_key) > 128:\n raise HTTPException(status_code=400, detail=\"Idempotency-Key too long\")\n\n key = (req.tenant_id, idempotency_key)\n rh = _hash_req(req)\n\n existing = _IDEMPO.get(key)\n if existing:\n if existing.request_hash != rh:\n raise HTTPException(status_code=409, detail=\"Idempotency-Key reuse with different payload\")\n return json.loads(existing.response_json)\n\n # Create new payment (stubbed)\n pid = hashlib.md5(f\"{req.tenant_id}:{idempotency_key}\".encode()).hexdigest()\n resp = CreateResp(\n id=pid,\n created_at=datetime.now(timezone.utc).isoformat(),\n echo=req,\n )\n _IDEMPO[key] = _IdempoEntry(request_hash=rh, response_json=resp.model_dump_json())\n return resp\n```\n\n```python\n# test_app.py (pytest)\nfrom fastapi.testclient import TestClient\nfrom app import app\n\nclient = TestClient(app)\n\ndef test_idempotent_replay():\n headers = {\"Idempotency-Key\": \"abc\"}\n body = {\"tenant_id\":\"t1\",\"amount_cents\":100,\"currency\":\"USD\"}\n r1 = client.post(\"/v1/payments\", json=body, headers=headers)\n r2 = client.post(\"/v1/payments\", json=body, headers=headers)\n assert r1.status_code == 200 and r2.status_code == 200\n assert r1.json() == r2.json()\n\ndef test_payload_conflict():\n headers = {\"Idempotency-Key\": \"abc\"}\n b1 = {\"tenant_id\":\"t1\",\"amount_cents\":100,\"currency\":\"USD\"}\n b2 = {\"tenant_id\":\"t1\",\"amount_cents\":200,\"currency\":\"USD\"}\n assert client.post(\"/v1/payments\", json=b1, headers=headers).status_code == 200\n assert client.post(\"/v1/payments\", json=b2, headers=headers).status_code == 409\n```\n\nNotes:\n- Replace in-memory store with a DB table and transaction.\n- Store response + request hash to detect key reuse with different payload.\n\n\nHard-mode checks: concurrency safety, idempotency, and rollback validated; add chaos tests where feasible.", "source": "WithinUsAI/GOD_Coder_100k"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: Language: Java\nFramework/tooling: Spring Boot\nDomain: repo automation\nLogic challenge: slow cold start\nTask type: distributed_debug\nDifficulty: hard\n\nReturn a rigorous engineering answer:\n- identify the hidden root cause or logical failure\n- present the corrected implementation\n- add tests that prove the fix\n- list verification commands\n- explain why naive fixes are insufficient when relevant\n\nRepository sketch:\nrepo/\n src/main/java/com/acme/App.java\n src/main/java/com/acme/Service.java\n src/test/java/com/acme/AppTest.java\n pom.xml\n\nFocus: Focus on ambiguity, misleading symptoms, hidden root causes, and high-stakes debugging.\n\nassistant: Diagnosis:\n- Hidden root cause: slow cold start presents misleading symptoms, so the patch must target the actual logic boundary rather than the first visible failure.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```java\nimport java.util.HashMap;\nimport java.util.Map;\n\npublic final class RequestHandler {\n public static Map handleRequest(Map payload) {\n Map clean = new HashMap<>();\n for (Map.Entry entry : payload.entrySet()) {\n if (entry.getValue() != null) clean.put(entry.getKey().trim(), entry.getValue());\n }\n if (!clean.containsKey(\"id\")) throw new IllegalArgumentException(\"missing id\");\n return Map.of(\"ok\", true, \"data\", clean);\n }\n}\n```\n\nTests:\n```java\nimport static org.junit.jupiter.api.Assertions.*;\nimport java.util.Map;\nimport org.junit.jupiter.api.Test;\n\nclass RequestHandlerTest {\n @Test\n void requiresId() {\n assertThrows(IllegalArgumentException.class, () -> RequestHandler.handleRequest(Map.of(\"name\", \"x\")));\n }\n}\n```\n\nVerification:\n- `./gradlew test`\n- `mvn test`\n\nEngineering notes:\n- Language: Java\n- Framework/tooling: Spring Boot\n- Stack context: Go, Gin, PostgreSQL, gRPC, Prometheus, Docker\n- Domain: repo automation\n- Task type: distributed_debug\n- Difficulty: hard\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "Refactor an existing codebase in healthtech to support real-time notifications cleanly.\nTarget platform: mobile (Android Kotlin).\nRequirements: propose new modules/layers, dependency boundaries, and migration plan.\nConstraints: must be production-ready, must be performant under load, must include clear error handling, must be secure-by-default.\nDifficulty: easy. Assume strict latency budget (p95 < 200ms).\n\nOutput: actionable implementation and verification artifacts.\nDeliverable: refactor plan + module boundaries.\n\n**Proposed modules**\n- `domain/` pure business logic (no I/O)\n- `adapters/` DB, cache, external APIs\n- `api/` request/response validation and routing\n- `observability/` logging/metrics/tracing\n- `tests/` unit + integration suites\n\n**Migration plan**\n1. Introduce new interfaces + adapters behind feature flags.\n2. Dual-write or read-compat layer if schema changes.\n3. Incremental cutover; deprecate legacy module.\n\nKey rule: dependencies flow inward; domain has no framework imports.\n\n\nChecks: input validation, tests, and safe defaults included.", "source": "WithinUsAI/GOD_Coder_100k"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: Language: C++\nFramework/tooling: STL\nDomain: developer platform\nLogic challenge: transaction boundary bug\nTask type: state_machine_patch\nDifficulty: medium\n\nReturn a rigorous engineering answer:\n- identify the hidden root cause or logical failure\n- present the corrected implementation\n- add tests that prove the fix\n- list verification commands\n- explain why naive fixes are insufficient when relevant\n\nRepository sketch:\nrepo/\n src/main.cpp\n src/service.cpp\n include/service.h\n tests/test_service.cpp\n CMakeLists.txt\n\nFocus: Focus on strong structured logic with edge cases, data validation, and concurrency safety.\n\nassistant: Diagnosis:\n- Root cause: the failure around transaction boundary bug is caused by missing validation, weak edge-case handling, or unsafe lifecycle behavior in the current implementation.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```cpp\n#include \n#include \n\nusing Payload = std::unordered_map;\n\nPayload normalize_payload(const Payload& in) {\n Payload out;\n for (const auto& [k, v] : in) {\n if (!v.empty()) out[k] = v;\n }\n return out;\n}\n```\n\nTests:\n```cpp\nTEST_CASE(\"normalize_payload filters empty values\") {\n Payload in{{\"id\",\"7\"},{\"name\",\"\"}};\n auto out = normalize_payload(in);\n REQUIRE(out.count(\"id\") == 1);\n REQUIRE(out.count(\"name\") == 0);\n}\n```\n\nVerification:\n- `cmake --build build`\n- `ctest --test-dir build`\n\nEngineering notes:\n- Language: C++\n- Framework/tooling: STL\n- Stack context: FastAPI, PostgreSQL, Redis, Celery, pytest, Docker\n- Domain: developer platform\n- Task type: state_machine_patch\n- Difficulty: medium\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "Write a thorough test suite for a Python component used for CLI tooling.\nRequirements: cover edge cases, invalid inputs, and behavior invariants.\nConstraints: must be memory-efficient, stdlib-only.\nDifficulty: easy. Provide helpful exceptions with actionable messages.\n\nDeliverable: corrected code and verification tests.\n```python\n# tests (pytest-style) for a module providing: normalize(), parse_lines(), compute_stats()\nimport math\nimport pytest\n\ndef test_normalize_idempotent(module_under_test):\n x = \" A\\tB \"\n assert module_under_test.normalize(module_under_test.normalize(x)) == module_under_test.normalize(x)\n\ndef test_parse_lines_rejects_invalid(module_under_test):\n with pytest.raises(ValueError):\n module_under_test.parse_lines([\"\", \"???\", None]) # type: ignore[arg-type]\n\ndef test_compute_stats_basic(module_under_test):\n data = [1, 2, 3, 4]\n s = module_under_test.compute_stats(data)\n assert s.count == 4\n assert s.total == 10\n assert math.isclose(s.mean, 2.5)\n```", "source": "WithinUsAI/python_GOD_coder_100k"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: Language: Bash\nFramework/tooling: jq\nDomain: auth service\nLogic challenge: streaming timeout handling\nTask type: concurrency_fix\nDifficulty: hard\n\nReturn a rigorous engineering answer:\n- identify the hidden root cause or logical failure\n- present the corrected implementation\n- add tests that prove the fix\n- list verification commands\n- explain why naive fixes are insufficient when relevant\n\nRepository sketch:\nrepo/\n scripts/\n run.sh\n deploy.sh\n tests/\n smoke.sh\n\nFocus: Focus on strong structured logic with edge cases, data validation, and concurrency safety.\n\nassistant: Diagnosis:\n- Root cause: the failure around streaming timeout handling is caused by missing validation, weak edge-case handling, or unsafe lifecycle behavior in the current implementation.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```bash\n#!/usr/bin/env bash\nset -euo pipefail\n\ninput=\"${1:-}\"\nif [[ -z \"$input\" ]]; then\n echo \"missing input\" >&2\n exit 1\nfi\n\nprintf '%s\n' \"$input\" | tr -d '\r'\n```\n\nTests:\n```bash\noutput=\"$(bash scripts/run.sh \"abc\")\"\ntest \"$output\" = \"abc\"\n```\n\nVerification:\n- `bash tests/smoke.sh`\n- `shellcheck scripts/*.sh`\n\nEngineering notes:\n- Language: Bash\n- Framework/tooling: jq\n- Stack context: Airflow, dbt, DuckDB, MinIO, pytest\n- Domain: auth service\n- Task type: concurrency_fix\n- Difficulty: hard\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Fix a bug and add tests.\n\nFile: ilkltmi.py\n```python\ndef d2r9uakiz83(n: int) -> int:\n \"\"\"Sum 1..n inclusive.\"\"\"\n if n < 0:\n raise ValueError(\"n must be non-negative\")\n total = 0\n for k in range(n): # BUG: should include n\n total += k\n return total\n```\n\nReturn unified diffs for ilkltmi.py and test_ilkltmi.py (pytest).\n\n*** Begin Patch\n*** Update File: ilkltmi.py\n@@\n def d2r9uakiz83(n: int) -> int:\n@@\n total = 0\n- for k in range(n): # BUG: should include n\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_ilkltmi.py\n+import pytest\n+from ilkltmi import d2r9uakiz83\n+\n+def test_zero():\n+ assert d2r9uakiz83(0) == 0\n+\n+def test_one():\n+ assert d2r9uakiz83(1) == 1\n+\n+def test_small():\n+ assert d2r9uakiz83(7) == 28\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ d2r9uakiz83(-1)\n+\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: Project stack: Rust, Axum, SQLx, Redis, Tokio, Docker\nLanguage: Bash\nDependency challenge: slow cold start\nTask type: lockfile_repair\nDifficulty: medium\n\nFix this as a senior engineer.\nRequired:\n- identify the version or compatibility failure mode\n- produce the corrected config/code/build patch\n- explain rollback-safe migration notes\n- add regression tests or reproducibility checks\n- include concrete verification commands\n\nRepository sketch:\nrepo/\n scripts/\n run.sh\n deploy.sh\n tests/\n smoke.sh\n\nFocus: Focus on versioning, migrations, lockfiles, runtime compatibility, and secure dependency handling.\n\nassistant: Diagnosis:\n- Root cause: the issue around slow cold start is a dependency, migration, or runtime-compatibility mismatch that needs a rollback-safe patch.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```bash\n#!/usr/bin/env bash\nset -euo pipefail\n\ninput=\"${1:-}\"\nif [[ -z \"$input\" ]]; then\n echo \"missing input\" >&2\n exit 1\nfi\n\nprintf '%s\n' \"$input\" | tr -d '\r'\n```\n\nTests:\n```bash\noutput=\"$(bash scripts/run.sh \"abc\")\"\ntest \"$output\" = \"abc\"\n```\n\nVerification:\n- `bash tests/smoke.sh`\n- `shellcheck scripts/*.sh`\n\nEngineering notes:\n- Language: Bash\n- Framework/tooling: awk\n- Stack context: Rust, Axum, SQLx, Redis, Tokio, Docker\n- Domain: auth service\n- Task type: lockfile_repair\n- Difficulty: medium\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "Task type: query_optimizer\nScenario: edge sync\nDomain focus: runtime systems\nPrimary language: sql\nDifficulty: hard\nScale/SLO: p99 < 150ms\nComponent: component_wkwokuma\nConstraints: include test vectors and fuzz strategy, include verification strategy, include backward compatibility and migration plan, include security threat model (defensive only), include performance model and limits, assume adversarial inputs; validate everything\nAssume partial data corruption; include scrubbing strategy.\nDeliverable: Design a cost-based optimizer slice: logical rules, physical operators, and cost model. Include regression tests and query-plan explain examples.\n\nOutput: elite engineering answer optimized for correctness, performance, and operability.\n**Contract**\n- Inputs validated at the boundary; explicit error taxonomy.\n- Idempotency for side effects via request_id; deterministic replay.\n- Backward compatibility: additive changes by default; versioned breaking changes.\n**Invariants**\n- Determinism: replay of the same event log yields identical outputs.\n- Liveness: under bounded faults and stable network, progress occurs.\n- Isolation: tenant boundary enforced; no cross-tenant reads/writes.\n**Failure modes & recovery**\n- Crash during commit: WAL replay completes or transaction aborts; no torn writes.\n- Duplicate requests: de-duplicate by (tenant, request_id) returning cached response.\n- Data corruption: checksums + scrubber; quarantine and rebuild from replicas/snapshots.\n**Security posture (defensive)**\n- Threat model: auth/authz, injection, replay/abuse, supply chain.\n- Least privilege; secrets in managed store; audit logs for sensitive ops.\n- Input normalization, parameterized queries, path traversal protections.\n**Verification strategy**\n- Property tests against a pure reference model (state machine).\n- Canary + shadow traffic; invariants checked in production via assertions/metrics.\n- Fuzzing of parsers/framers/validators with corpus seeds.\n\n**Snippet**\n```python\n# Minimal cost model skeleton\nfrom dataclasses import dataclass\n\n@dataclass(frozen=True)\nclass Plan:\n op: str\n cost: float\n children: tuple[\"Plan\", ...] = ()\n\ndef choose_best(plans: list[Plan]) -> Plan:\n return min(plans, key=lambda p: p.cost)\n```\n\nHard checks: fault injection tests gate merges; perf thresholds enforced in CI.", "source": "WithinUsAI/Omega_Genesis_Coder_100k"} {"text": "Fix a subtle bug in a Python module used for ETL pipelines.\nRequirements: explain root cause briefly, provide corrected code, and add regression tests.\nConstraints: must be streaming-friendly, must be easy to extend.\nDifficulty: easy. Avoid quadratic behavior on large inputs.\n\nDeliverable: production-ready reference solution.\n```python\nfrom __future__ import annotations\n\nfrom dataclasses import dataclass\nfrom pathlib import Path\nfrom typing import Iterable\nimport json\n\n\nclass ValidationError(ValueError):\n \"\"\"Raised when input validation fails.\"\"\"\n\n\ndef safe_join(base: Path, *parts: str) -> Path:\n \"\"\"Join paths while preventing traversal outside base.\"\"\"\n b = base.resolve()\n p = (b / Path(*parts)).resolve()\n if p != b and b not in p.parents:\n raise ValidationError(f\"unsafe path: {p}\")\n return p\n\n\n@dataclass(frozen=True, slots=True)\nclass Record:\n key: str\n value: int\n\n\ndef parse_jsonl(lines: Iterable[str]) -> list[Record]:\n out: list[Record] = []\n for idx, line in enumerate(lines, 1):\n s = line.strip()\n if not s:\n continue\n try:\n obj = json.loads(s)\n except json.JSONDecodeError as e:\n raise ValidationError(f\"line {idx}: invalid json\") from e\n if not isinstance(obj, dict):\n raise ValidationError(f\"line {idx}: expected object\")\n key = obj.get(\"key\")\n val = obj.get(\"value\")\n if not isinstance(key, str) or not key:\n raise ValidationError(f\"line {idx}: key must be non-empty str\")\n if not isinstance(val, int):\n raise ValidationError(f\"line {idx}: value must be int\")\n out.append(Record(key, val))\n return out\n\n\ndef write_jsonl(base: Path, rel: str, records: Iterable[Record]) -> Path:\n base.mkdir(parents=True, exist_ok=True)\n dst = safe_join(base, rel)\n dst.parent.mkdir(parents=True, exist_ok=True)\n with dst.open(\"w\", encoding=\"utf-8\", newline=\"\\n\") as f:\n for r in records:\n f.write(json.dumps({\"key\": r.key, \"value\": r.value}, ensure_ascii=False) + \"\\n\")\n return dst\n```\n\n```python\n# tests (pytest-style)\nimport json\nfrom pathlib import Path\nimport pytest\nfrom module_under_test import ValidationError, Record, parse_jsonl, write_jsonl\n\ndef test_parse_ok():\n lines = [json.dumps({\"key\":\"a\",\"value\":1}), json.dumps({\"key\":\"b\",\"value\":2})]\n assert parse_jsonl(lines) == [Record(\"a\",1), Record(\"b\",2)]\n\ndef test_parse_rejects_bad_json():\n with pytest.raises(ValidationError):\n parse_jsonl([\"{not json}\"])\n\ndef test_safe_join_blocks_traversal(tmp_path: Path):\n with pytest.raises(ValidationError):\n write_jsonl(tmp_path, \"../x.jsonl\", [Record(\"a\",1)])\n```", "source": "WithinUsAI/python_GOD_coder_100k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Produce an offline-first self-evolving code assistant architecture named `wmgjxci8qh`.\nMust include: module layout, patch-safety policy, evaluation gates (tests/lint/types), versioned memory index.\n\nArchitecture: `wmgjxci8qh` (offline-first, self-evolving)\n\nModules\n- core/loop.py: evolve → validate → accept/reject (bounded iterations)\n- patching/: diff builder, safe apply, atomic writes, rollback points\n- policy/: allowlist paths, deny globs (.git/, __pycache__/, binaries), patch size caps\n- signals/: parse pytest/ruff/mypy into normalized findings\n- memory/index.jsonl: append-only snapshots (hashes, metrics, rationale)\n\nSafety gates\n- refuse path traversal/symlink escapes; never edit binaries\n- accept only if tests/lint/types stay green or improve", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Fix the bug and add pytest tests.\n\n```python\ndef f94469(n: int) -> int:\n # sum 1..n inclusive\n if n < 0: raise ValueError\n total = 0\n for k in range(n): # BUG\n total += k\n return total\n```\nReturn unified diffs for `m42067.py` and `test_m42067.py`.\n\n*** Begin Patch\n*** Update File: m42067.py\n@@\n def f94469(n: int) -> int:\n@@\n- for k in range(n): # BUG\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_m42067.py\n+import pytest\n+from m42067 import f94469\n+\n+def test_small():\n+ assert f94469(7) == 28\n+\n+def test_zero():\n+ assert f94469(0) == 0\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ f94469(-1)\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Optimize while preserving behavior.\n\nFile: kc6l4wx.py\n```python\ndef g10ar1x2w(xs):\n out = []\n for x in xs:\n if x not in out:\n out.append(x)\n return out\n```\n\nRequirements: preserve first-seen order; O(n) average; add types + docstring.\n\n# kc6l4wx.py\nfrom __future__ import annotations\nfrom typing import Iterable, List, Set, TypeVar\n\nT = TypeVar(\"T\")\n\ndef g10ar1x2w(xs: Iterable[T]) -> List[T]:\n \"\"\"Return unique items preserving first-seen order.\"\"\"\n seen: Set[T] = set()\n out: List[T] = []\n for x in xs:\n if x in seen:\n continue\n seen.add(x)\n out.append(x)\n return out", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Build an elite-grade solution in the domain of networking for scenario: analytics pipeline.\nPrimary language: typescript.\nDifficulty: expert.\nConstraints: include invariants and failure modes, include tests or verification strategy, provide rollout and rollback guidance, make the interface contract explicit, design for backward compatibility and migrations.\nComponent: component_slvyrnj.\nAssume 50k RPS and p99 < 250ms.\nTask: Write a precise interface contract, list invariants, and provide a lightweight formal/spec-style description (pseudo-TLA+/state machine) plus reference implementation skeleton and tests.\n\nOutput: elite-grade engineering answer with contracts, edge cases, and verification.\nOutput: contract + invariants + spec + reference skeleton.\n\n**Interface contract**\n- Commands: `Put(key, value, expected_version?)`, `Get(key)`, `Delete(key, expected_version?)`\n- Responses: `Ok(version, value?)`, `NotFound`, `Conflict(current_version)`, `InvalidInput`\n- Idempotency: client supplies `request_id`; server must de-duplicate per (tenant_id, request_id).\n\n**Invariants**\n1. Monotonic version per key (strictly increases on successful writes).\n2. Reads return latest committed value for a given consistency level.\n3. Exactly-once effect for a given `request_id` (at-most-once execution + replay response).\n4. Tenant isolation: keys are scoped by tenant_id.\n\n**State machine (pseudo)**\nState:\n- store: map[(tenant,key)] -> (version:int, value:bytes|tombstone)\n- seen: map[(tenant,request_id)] -> response\nTransition Put:\n- if request_id in seen: return seen[...]\n- validate input; if expected_version set and != current version -> Conflict\n- version' = version + 1; store[...] := (version', value); seen[...] := Ok(version', value)\n\n**Reference skeleton (Python)**\n```python\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom typing import Dict, Optional, Tuple\n\nclass Conflict(Exception): pass\nclass InvalidInput(ValueError): pass\n\n@dataclass(frozen=True, slots=True)\nclass Value:\n version: int\n data: Optional[bytes] # None == tombstone\n\n@dataclass(frozen=True, slots=True)\nclass Reply:\n kind: str\n version: Optional[int] = None\n data: Optional[bytes] = None\n\nclass KV:\n def __init__(self) -> None:\n self._store: Dict[Tuple[str,str], Value] = {}\n self._seen: Dict[Tuple[str,str], Reply] = {}\n\n def put(self, tenant: str, request_id: str, key: str, data: bytes, expected_version: Optional[int]=None) -> Reply:\n if not tenant or not request_id or not key:\n raise InvalidInput(\"tenant/request_id/key required\")\n de = self._seen.get((tenant, request_id))\n if de: \n return de\n cur = self._store.get((tenant, key), Value(0, None))\n if expected_version is not None and expected_version != cur.version:\n r = Reply(\"conflict\", version=cur.version)\n self._seen[(tenant, request_id)] = r\n return r\n nxt = Value(cur.version + 1, data)\n self._store[(tenant, key)] = nxt\n r = Reply(\"ok\", version=nxt.version)\n self._seen[(tenant, request_id)] = r\n return r\n```\n\n**Tests**\n- Determinism: same request_id → same reply.\n- Conflict detection and version monotonicity.\n\n\nExpert checks: state-machine reasoning, concurrency stress, and upgrade/rollback validated.", "source": "WithinUsAI/Elite_GOD_Coder_100k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Optimize while preserving behavior.\n\nFile: j6oruk.py\n```python\ndef n0sdhz(xs):\n out = []\n for x in xs:\n if x not in out:\n out.append(x)\n return out\n```\n\nRequirements: preserve first-seen order; O(n) average; add types + docstring.\n\n# j6oruk.py\nfrom __future__ import annotations\nfrom typing import Iterable, List, Set, TypeVar\n\nT = TypeVar(\"T\")\n\ndef n0sdhz(xs: Iterable[T]) -> List[T]:\n \"\"\"Return unique items preserving first-seen order.\"\"\"\n seen: Set[T] = set()\n out: List[T] = []\n for x in xs:\n if x in seen:\n continue\n seen.add(x)\n out.append(x)\n return out", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Fix a subtle bug in a Python module used for configuration loading.\nRequirements: explain root cause briefly, provide corrected code, and add regression tests.\nConstraints: must include docstrings, must include type hints, must avoid global state.\nDifficulty: hard. Provide helpful exceptions with actionable messages.\n\nDeliverable: API + reference implementation + tests.\n```python\nfrom __future__ import annotations\n\nfrom dataclasses import dataclass\nfrom pathlib import Path\nfrom typing import Iterable\nimport json\n\n\nclass ValidationError(ValueError):\n \"\"\"Raised when input validation fails.\"\"\"\n\n\ndef safe_join(base: Path, *parts: str) -> Path:\n \"\"\"Join paths while preventing traversal outside base.\"\"\"\n b = base.resolve()\n p = (b / Path(*parts)).resolve()\n if p != b and b not in p.parents:\n raise ValidationError(f\"unsafe path: {p}\")\n return p\n\n\n@dataclass(frozen=True, slots=True)\nclass Record:\n key: str\n value: int\n\n\ndef parse_jsonl(lines: Iterable[str]) -> list[Record]:\n out: list[Record] = []\n for idx, line in enumerate(lines, 1):\n s = line.strip()\n if not s:\n continue\n try:\n obj = json.loads(s)\n except json.JSONDecodeError as e:\n raise ValidationError(f\"line {idx}: invalid json\") from e\n if not isinstance(obj, dict):\n raise ValidationError(f\"line {idx}: expected object\")\n key = obj.get(\"key\")\n val = obj.get(\"value\")\n if not isinstance(key, str) or not key:\n raise ValidationError(f\"line {idx}: key must be non-empty str\")\n if not isinstance(val, int):\n raise ValidationError(f\"line {idx}: value must be int\")\n out.append(Record(key, val))\n return out\n\n\ndef write_jsonl(base: Path, rel: str, records: Iterable[Record]) -> Path:\n base.mkdir(parents=True, exist_ok=True)\n dst = safe_join(base, rel)\n dst.parent.mkdir(parents=True, exist_ok=True)\n with dst.open(\"w\", encoding=\"utf-8\", newline=\"\\n\") as f:\n for r in records:\n f.write(json.dumps({\"key\": r.key, \"value\": r.value}, ensure_ascii=False) + \"\\n\")\n return dst\n```\n\n```python\n# tests (pytest-style)\nimport json\nfrom pathlib import Path\nimport pytest\nfrom module_under_test import ValidationError, Record, parse_jsonl, write_jsonl\n\ndef test_parse_ok():\n lines = [json.dumps({\"key\":\"a\",\"value\":1}), json.dumps({\"key\":\"b\",\"value\":2})]\n assert parse_jsonl(lines) == [Record(\"a\",1), Record(\"b\",2)]\n\ndef test_parse_rejects_bad_json():\n with pytest.raises(ValidationError):\n parse_jsonl([\"{not json}\"])\n\ndef test_safe_join_blocks_traversal(tmp_path: Path):\n with pytest.raises(ValidationError):\n write_jsonl(tmp_path, \"../x.jsonl\", [Record(\"a\",1)])\n```", "source": "WithinUsAI/python_GOD_coder_100k"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: Language: JavaScript\nFramework/tooling: Vite\nDomain: data pipeline\nLogic challenge: N+1 query explosion\nTask type: state_machine_patch\nDifficulty: hard\n\nReturn a rigorous engineering answer:\n- identify the hidden root cause or logical failure\n- present the corrected implementation\n- add tests that prove the fix\n- list verification commands\n- explain why naive fixes are insufficient when relevant\n\nRepository sketch:\nrepo/\n src/\n api.js\n service.js\n utils.js\n tests/\n api.test.js\n package.json\n\nFocus: Focus on strong structured logic with edge cases, data validation, and concurrency safety.\n\nassistant: Diagnosis:\n- Root cause: the failure around N+1 query explosion is caused by missing validation, weak edge-case handling, or unsafe lifecycle behavior in the current implementation.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```javascript\ntype Payload = Record;\n\nexport function normalizePayload(payload: Payload): Payload {\n if (!payload || typeof payload !== \"object\" || Array.isArray(payload)) {\n throw new TypeError(\"payload must be a plain object\");\n }\n return Object.fromEntries(\n Object.entries(payload)\n .filter(([, value]) => value !== null && value !== undefined)\n .map(([key, value]) => [String(key).trim(), value])\n );\n}\n\nexport function handleN+1QueryExplosion(payload: Payload) {\n const clean = normalizePayload(payload);\n if (!(\"id\" in clean)) {\n return { ok: false, data: {}, error: \"missing id\" };\n }\n return { ok: true, data: clean, error: null };\n}\n```\n\nTests:\n```javascript\nimport { describe, it, expect } from \"vitest\";\nimport { handleN+1QueryExplosion } from \"../src/service\";\n\ndescribe(\"handler\", () => {\n it(\"accepts valid input\", () => {\n expect(handleN+1QueryExplosion({ id: 7, name: \"ok\", unused: null })).toEqual({\n ok: true,\n data: { id: 7, name: \"ok\" },\n error: null\n });\n });\n\n it(\"rejects missing id\", () => {\n expect(handleN+1QueryExplosion({ name: \"x\" }).error).toMatch(/missing id/);\n });\n});\n```\n\nVerification:\n- `npm test`\n- `npm run lint`\n\nEngineering notes:\n- Language: JavaScript\n- Framework/tooling: Vite\n- Stack context: Next.js, Node.js, Prisma, PostgreSQL, Playwright, Docker\n- Domain: data pipeline\n- Task type: state_machine_patch\n- Difficulty: hard\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "Task type: runtime_gc\nScenario: graph query service\nDomain focus: high-frequency trading systems (safe engineering)\nPrimary language: rust\nDifficulty: hard\nScale/SLO: multi-region active-active\nComponent: component_zypxwydm\nConstraints: explicit contracts and invariants, include backward compatibility and migration plan, include security threat model (defensive only), assume adversarial inputs; validate everything, include failure modes and recovery, include deterministic replay plan, include verification strategy\nAssume strict auditability and replayable history.\nDeliverable: Design a GC/runtime component (mark-sweep/arena/RC hybrid); include pause-time strategy and tests.\n\nOutput: elite engineering answer optimized for correctness, performance, and operability.\n**Contract**\n- Inputs validated at the boundary; explicit error taxonomy.\n- Idempotency for side effects via request_id; deterministic replay.\n- Backward compatibility: additive changes by default; versioned breaking changes.\n**Invariants**\n- Liveness: under bounded faults and stable network, progress occurs.\n- Safety: state transitions preserve invariants; no partial commit leaks.\n- Isolation: tenant boundary enforced; no cross-tenant reads/writes.\n**Failure modes & recovery**\n- Duplicate requests: de-duplicate by (tenant, request_id) returning cached response.\n- Data corruption: checksums + scrubber; quarantine and rebuild from replicas/snapshots.\n- Crash during commit: WAL replay completes or transaction aborts; no torn writes.\n**Security posture (defensive)**\n- Threat model: auth/authz, injection, replay/abuse, supply chain.\n- Least privilege; secrets in managed store; audit logs for sensitive ops.\n- Input normalization, parameterized queries, path traversal protections.\n**Verification strategy**\n- Canary + shadow traffic; invariants checked in production via assertions/metrics.\n- Property tests against a pure reference model (state machine).\n- Deterministic simulation with fault injection (crash/partition/latency).\n\n**Snippet**\n```text\nImplementation sketch: factor pure state-machine core; adapters for I/O; add deterministic replay log.\n```\nHard checks: fault injection tests gate merges; perf thresholds enforced in CI.", "source": "WithinUsAI/Omega_Genesis_Coder_100k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Fix a bug and add tests.\n\nFile: h7qsttk.py\n```python\ndef x6232_a40_g(n: int) -> int:\n \"\"\"Sum 1..n inclusive.\"\"\"\n if n < 0:\n raise ValueError(\"n must be non-negative\")\n total = 0\n for k in range(n): # BUG: should include n\n total += k\n return total\n```\n\nReturn unified diffs for h7qsttk.py and test_h7qsttk.py (pytest).\n\n*** Begin Patch\n*** Update File: h7qsttk.py\n@@\n def x6232_a40_g(n: int) -> int:\n@@\n total = 0\n- for k in range(n): # BUG: should include n\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_h7qsttk.py\n+import pytest\n+from h7qsttk import x6232_a40_g\n+\n+def test_zero():\n+ assert x6232_a40_g(0) == 0\n+\n+def test_one():\n+ assert x6232_a40_g(1) == 1\n+\n+def test_small():\n+ assert x6232_a40_g(7) == 28\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ x6232_a40_g(-1)\n+\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Refactor to modern typed Python with immutability and tests.\n\nFile: p49ypddo.py\n```python\nclass Tsz165Z:\n def __init__(self, name, values):\n self.name = name\n self.values = list(values)\n def add(self, v):\n self.values.append(v)\n def mean(self):\n s = 0\n for x in self.values:\n s += x\n return s / len(self.values)\n```\n\nReturn full new p49ypddo.py and test_p49ypddo.py.\n\n# p49ypddo.py\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom typing import Iterable, Tuple\n\n@dataclass(frozen=True)\nclass Tsz165Z:\n name: str\n values: Tuple[float, ...]\n\n @staticmethod\n def create(name: str, values: Iterable[float]) -> \"Tsz165Z\":\n vals = tuple(float(v) for v in values)\n if not vals:\n raise ValueError(\"values must be non-empty\")\n return Tsz165Z(name=name, values=vals)\n\n def add(self, v: float) -> \"Tsz165Z\":\n return Tsz165Z(name=self.name, values=self.values + (float(v),))\n\n def mean(self) -> float:\n return sum(self.values) / len(self.values)\n\n# test_p49ypddo.py\nimport pytest\nfrom p49ypddo import Tsz165Z\n\ndef test_mean_and_add():\n c = Tsz165Z.create(\"a\", [1, 2, 3])\n assert c.mean() == 2.0\n assert c.add(5).mean() == (1 + 2 + 3 + 5) / 4\n\ndef test_empty_raises():\n with pytest.raises(ValueError):\n Tsz165Z.create(\"x\", [])", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Task type: static_analyzer\nScenario: feature-flag evaluation\nDomain focus: consensus & replication\nPrimary language: go\nDifficulty: expert+\nScale/SLO: multi-region active-active\nComponent: component_ipfffkyh\nConstraints: include failure modes and recovery, include performance model and limits, avoid data races and undefined behavior, include verification strategy, assume adversarial inputs; validate everything, explicit contracts and invariants, include deterministic replay plan\nAssume crash-only processes; recovery must be deterministic.\nDeliverable: Design a static analyzer for a safety property (e.g., taint/SQLi prevention); include rule set, false-positive strategy, and tests.\n\nOutput: contract-first solution with failure modes, security posture, and test/verification strategy.\n**Contract**\n- Inputs validated at the boundary; explicit error taxonomy.\n- Idempotency for side effects via request_id; deterministic replay.\n- Backward compatibility: additive changes by default; versioned breaking changes.\n**Invariants**\n- Liveness: under bounded faults and stable network, progress occurs.\n- Isolation: tenant boundary enforced; no cross-tenant reads/writes.\n- Determinism: replay of the same event log yields identical outputs.\n**Failure modes & recovery**\n- Duplicate requests: de-duplicate by (tenant, request_id) returning cached response.\n- Data corruption: checksums + scrubber; quarantine and rebuild from replicas/snapshots.\n- Network partition: minority cannot commit; clients receive retriable errors.\n**Security posture (defensive)**\n- Threat model: auth/authz, injection, replay/abuse, supply chain.\n- Least privilege; secrets in managed store; audit logs for sensitive ops.\n- Input normalization, parameterized queries, path traversal protections.\n**Verification strategy**\n- Property tests against a pure reference model (state machine).\n- Canary + shadow traffic; invariants checked in production via assertions/metrics.\n- Deterministic simulation with fault injection (crash/partition/latency).\n\n**Snippet**\n```text\nImplementation sketch: factor pure state-machine core; adapters for I/O; add deterministic replay log.\n```\nExpert+ checks: mechanized invariants (or exhaustive model checking), adversarial fuzzing, and multi-region failure drills.", "source": "WithinUsAI/Omega_Genesis_Coder_100k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Produce an offline-first self-evolving code assistant architecture named `jlf0e_k2i`.\nMust include: module layout, patch-safety policy, evaluation gates (tests/lint/types), versioned memory index.\n\nArchitecture: `jlf0e_k2i` (offline-first, self-evolving)\n\nModules\n- core/loop.py: evolve → validate → accept/reject (bounded iterations)\n- patching/: diff builder, safe apply, atomic writes, rollback points\n- policy/: allowlist paths, deny globs (.git/, __pycache__/, binaries), patch size caps\n- signals/: parse pytest/ruff/mypy into normalized findings\n- memory/index.jsonl: append-only snapshots (hashes, metrics, rationale)\n\nSafety gates\n- refuse path traversal/symlink escapes; never edit binaries\n- accept only if tests/lint/types stay green or improve", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Debug and fix a subtle production bug related to background jobs in a document processing service.\nTarget platform: infra (Terraform).\nRequirements: identify root cause, provide patch, and add regression tests.\nConstraints: must be secure-by-default, must include clear error handling, must include tests, must avoid global state, must be performant under load.\nDifficulty: expert. Assume mobile clients are occasionally offline.\n\nOutput: actionable implementation and verification artifacts.\nDeliverable: production-grade reference implementation (FastAPI) + tests.\n\n```python\n# app.py\nfrom __future__ import annotations\n\nimport hashlib\nimport json\nfrom dataclasses import dataclass\nfrom datetime import datetime, timezone\nfrom typing import Any, Optional\n\nfrom fastapi import FastAPI, Header, HTTPException\nfrom pydantic import BaseModel, Field\n\napp = FastAPI(title=\"Idempotent API\")\n\nclass CreateReq(BaseModel):\n tenant_id: str = Field(min_length=1)\n amount_cents: int = Field(ge=0)\n currency: str = Field(min_length=3, max_length=3)\n\nclass CreateResp(BaseModel):\n id: str\n created_at: str\n echo: CreateReq\n\n@dataclass\nclass _IdempoEntry:\n request_hash: str\n response_json: str\n\n# In production: Postgres table with UNIQUE(tenant_id, key)\n_IDEMPO: dict[tuple[str, str], _IdempoEntry] = {}\n\ndef _hash_req(req: CreateReq) -> str:\n raw = req.model_dump_json()\n return hashlib.sha256(raw.encode(\"utf-8\")).hexdigest()\n\n@app.post(\"/v1/payments\", response_model=CreateResp)\ndef create_payment(\n req: CreateReq,\n idempotency_key: Optional[str] = Header(default=None, alias=\"Idempotency-Key\"),\n) -> Any:\n if not idempotency_key:\n raise HTTPException(status_code=400, detail=\"Missing Idempotency-Key\")\n if len(idempotency_key) > 128:\n raise HTTPException(status_code=400, detail=\"Idempotency-Key too long\")\n\n key = (req.tenant_id, idempotency_key)\n rh = _hash_req(req)\n\n existing = _IDEMPO.get(key)\n if existing:\n if existing.request_hash != rh:\n raise HTTPException(status_code=409, detail=\"Idempotency-Key reuse with different payload\")\n return json.loads(existing.response_json)\n\n # Create new payment (stubbed)\n pid = hashlib.md5(f\"{req.tenant_id}:{idempotency_key}\".encode()).hexdigest()\n resp = CreateResp(\n id=pid,\n created_at=datetime.now(timezone.utc).isoformat(),\n echo=req,\n )\n _IDEMPO[key] = _IdempoEntry(request_hash=rh, response_json=resp.model_dump_json())\n return resp\n```\n\n```python\n# test_app.py (pytest)\nfrom fastapi.testclient import TestClient\nfrom app import app\n\nclient = TestClient(app)\n\ndef test_idempotent_replay():\n headers = {\"Idempotency-Key\": \"abc\"}\n body = {\"tenant_id\":\"t1\",\"amount_cents\":100,\"currency\":\"USD\"}\n r1 = client.post(\"/v1/payments\", json=body, headers=headers)\n r2 = client.post(\"/v1/payments\", json=body, headers=headers)\n assert r1.status_code == 200 and r2.status_code == 200\n assert r1.json() == r2.json()\n\ndef test_payload_conflict():\n headers = {\"Idempotency-Key\": \"abc\"}\n b1 = {\"tenant_id\":\"t1\",\"amount_cents\":100,\"currency\":\"USD\"}\n b2 = {\"tenant_id\":\"t1\",\"amount_cents\":200,\"currency\":\"USD\"}\n assert client.post(\"/v1/payments\", json=b1, headers=headers).status_code == 200\n assert client.post(\"/v1/payments\", json=b2, headers=headers).status_code == 409\n```\n\nNotes:\n- Replace in-memory store with a DB table and transaction.\n- Store response + request hash to detect key reuse with different payload.\n\n\nHard-mode checks: concurrency safety, idempotency, and rollback validated; add chaos tests where feasible.", "source": "WithinUsAI/GOD_Coder_100k"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: Language: YAML\nFramework/tooling: GitHub Actions\nDomain: reporting engine\nLogic challenge: build reproducibility failure\nTask type: monorepo_toolchain_recovery\nDifficulty: expert\n\nReturn a rigorous engineering answer:\n- identify the hidden root cause or logical failure\n- present the corrected implementation\n- add tests that prove the fix\n- list verification commands\n- explain why naive fixes are insufficient when relevant\n\nRepository sketch:\nrepo/\n .github/workflows/ci.yml\n docker-compose.yml\n deploy/\n app.yaml\n\nFocus: Focus on staff-level problem solving with multi-file patches, rollout implications, performance and security tradeoffs.\n\nassistant: Diagnosis:\n- Staff-level diagnosis: build reproducibility failure impacts correctness, operability, and future maintenance, so the fix must be minimal where possible but complete where necessary.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```yaml\nname: ci\non: [push, pull_request]\njobs:\n test:\n runs-on: ubuntu-latest\n steps:\n - uses: actions/checkout@v4\n - name: Validate\n run: echo \"validated\"\n```\n\nTests:\n```yaml\n# Verification:\n# - validate syntax\n# - run smoke workflow\n# - fail fast on broken config\n```\n\nVerification:\n- `validate workflow syntax`\n- `run CI smoke job`\n\nEngineering notes:\n- Language: YAML\n- Framework/tooling: GitHub Actions\n- Stack context: Airflow, dbt, DuckDB, MinIO, pytest\n- Domain: reporting engine\n- Task type: monorepo_toolchain_recovery\n- Difficulty: expert\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "Write a thorough test suite for a Python component used for rate limiting.\nRequirements: cover edge cases, invalid inputs, and behavior invariants.\nConstraints: must include tests, must avoid global state.\nDifficulty: hard. Avoid quadratic behavior on large inputs.\n\nDeliverable: corrected code and verification tests.\n```python\n# tests (pytest-style) for a module providing: normalize(), parse_lines(), compute_stats()\nimport math\nimport pytest\n\ndef test_normalize_idempotent(module_under_test):\n x = \" A\\tB \"\n assert module_under_test.normalize(module_under_test.normalize(x)) == module_under_test.normalize(x)\n\ndef test_parse_lines_rejects_invalid(module_under_test):\n with pytest.raises(ValueError):\n module_under_test.parse_lines([\"\", \"???\", None]) # type: ignore[arg-type]\n\ndef test_compute_stats_basic(module_under_test):\n data = [1, 2, 3, 4]\n s = module_under_test.compute_stats(data)\n assert s.count == 4\n assert s.total == 10\n assert math.isclose(s.mean, 2.5)\n```", "source": "WithinUsAI/python_GOD_coder_100k"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: Project domain: artifact registry\nImplementation stack: Spring Boot, PostgreSQL, JUnit, Gradle, Docker, GitHub Actions\nSoftware delivery problem: transaction boundary bug\nTask type: prd_to_patch\nDifficulty: medium\n\nReturn a complete delivery-grade response with:\n- diagnosis or design reasoning\n- implementation\n- test plan or tests\n- rollout plan\n- rollback or compatibility note\n- verification commands\n\nRepository sketch:\nrepo/\n src/\n api.js\n service.js\n utils.js\n tests/\n api.test.js\n package.json\n\nFocus: Focus on shipping production software with rollout safety, acceptance criteria, telemetry, and maintenance quality.\n\nassistant: Diagnosis:\n- Root cause or delivery blocker: transaction boundary bug needs both implementation work and a safe shipping plan.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```javascript\ntype Payload = Record;\n\nexport function normalizePayload(payload: Payload): Payload {\n if (!payload || typeof payload !== \"object\" || Array.isArray(payload)) {\n throw new TypeError(\"payload must be a plain object\");\n }\n return Object.fromEntries(\n Object.entries(payload)\n .filter(([, value]) => value !== null && value !== undefined)\n .map(([key, value]) => [String(key).trim(), value])\n );\n}\n\nexport function handleTransactionBoundaryBug(payload: Payload) {\n const clean = normalizePayload(payload);\n if (!(\"id\" in clean)) {\n return { ok: false, data: {}, error: \"missing id\" };\n }\n return { ok: true, data: clean, error: null };\n}\n```\n\nTests:\n```javascript\nimport { describe, it, expect } from \"vitest\";\nimport { handleTransactionBoundaryBug } from \"../src/service\";\n\ndescribe(\"handler\", () => {\n it(\"accepts valid input\", () => {\n expect(handleTransactionBoundaryBug({ id: 7, name: \"ok\", unused: null })).toEqual({\n ok: true,\n data: { id: 7, name: \"ok\" },\n error: null\n });\n });\n\n it(\"rejects missing id\", () => {\n expect(handleTransactionBoundaryBug({ name: \"x\" }).error).toMatch(/missing id/);\n });\n});\n```\n\nVerification:\n- `npm test`\n- `npm run lint`\n\nEngineering notes:\n- Language: JavaScript\n- Framework/tooling: Jest\n- Stack context: Spring Boot, PostgreSQL, JUnit, Gradle, Docker, GitHub Actions\n- Domain: artifact registry\n- Task type: prd_to_patch\n- Difficulty: medium\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Fix a bug and add tests.\n\nFile: upovlxz1m4v.py\n```python\ndef ecxsk81h(n: int) -> int:\n \"\"\"Sum 1..n inclusive.\"\"\"\n if n < 0:\n raise ValueError(\"n must be non-negative\")\n total = 0\n for k in range(n): # BUG: should include n\n total += k\n return total\n```\n\nReturn unified diffs for upovlxz1m4v.py and test_upovlxz1m4v.py (pytest).\n\n*** Begin Patch\n*** Update File: upovlxz1m4v.py\n@@\n def ecxsk81h(n: int) -> int:\n@@\n total = 0\n- for k in range(n): # BUG: should include n\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_upovlxz1m4v.py\n+import pytest\n+from upovlxz1m4v import ecxsk81h\n+\n+def test_zero():\n+ assert ecxsk81h(0) == 0\n+\n+def test_one():\n+ assert ecxsk81h(1) == 1\n+\n+def test_small():\n+ assert ecxsk81h(7) == 28\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ ecxsk81h(-1)\n+\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Write secure, defensive Python code for CLI tooling.\nRequirements: input validation, safe file handling, prevent path traversal, include tests.\nConstraints: must be memory-efficient, stdlib-only.\nDifficulty: expert. Avoid quadratic behavior on large inputs.\n\nDeliverable: production-ready reference solution.\n```python\nfrom __future__ import annotations\n\nfrom dataclasses import dataclass\nfrom pathlib import Path\nfrom typing import Iterable\nimport json\n\n\nclass ValidationError(ValueError):\n \"\"\"Raised when input validation fails.\"\"\"\n\n\ndef safe_join(base: Path, *parts: str) -> Path:\n \"\"\"Join paths while preventing traversal outside base.\"\"\"\n b = base.resolve()\n p = (b / Path(*parts)).resolve()\n if p != b and b not in p.parents:\n raise ValidationError(f\"unsafe path: {p}\")\n return p\n\n\n@dataclass(frozen=True, slots=True)\nclass Record:\n key: str\n value: int\n\n\ndef parse_jsonl(lines: Iterable[str]) -> list[Record]:\n out: list[Record] = []\n for idx, line in enumerate(lines, 1):\n s = line.strip()\n if not s:\n continue\n try:\n obj = json.loads(s)\n except json.JSONDecodeError as e:\n raise ValidationError(f\"line {idx}: invalid json\") from e\n if not isinstance(obj, dict):\n raise ValidationError(f\"line {idx}: expected object\")\n key = obj.get(\"key\")\n val = obj.get(\"value\")\n if not isinstance(key, str) or not key:\n raise ValidationError(f\"line {idx}: key must be non-empty str\")\n if not isinstance(val, int):\n raise ValidationError(f\"line {idx}: value must be int\")\n out.append(Record(key, val))\n return out\n\n\ndef write_jsonl(base: Path, rel: str, records: Iterable[Record]) -> Path:\n base.mkdir(parents=True, exist_ok=True)\n dst = safe_join(base, rel)\n dst.parent.mkdir(parents=True, exist_ok=True)\n with dst.open(\"w\", encoding=\"utf-8\", newline=\"\\n\") as f:\n for r in records:\n f.write(json.dumps({\"key\": r.key, \"value\": r.value}, ensure_ascii=False) + \"\\n\")\n return dst\n```\n\n```python\n# tests (pytest-style)\nimport json\nfrom pathlib import Path\nimport pytest\nfrom module_under_test import ValidationError, Record, parse_jsonl, write_jsonl\n\ndef test_parse_ok():\n lines = [json.dumps({\"key\":\"a\",\"value\":1}), json.dumps({\"key\":\"b\",\"value\":2})]\n assert parse_jsonl(lines) == [Record(\"a\",1), Record(\"b\",2)]\n\ndef test_parse_rejects_bad_json():\n with pytest.raises(ValidationError):\n parse_jsonl([\"{not json}\"])\n\ndef test_safe_join_blocks_traversal(tmp_path: Path):\n with pytest.raises(ValidationError):\n write_jsonl(tmp_path, \"../x.jsonl\", [Record(\"a\",1)])\n```", "source": "WithinUsAI/python_GOD_coder_100k"} {"text": "Fix the bug and add pytest tests.\n\n```python\ndef f95053(n: int) -> int:\n # sum 1..n inclusive\n if n < 0: raise ValueError\n total = 0\n for k in range(n): # BUG\n total += k\n return total\n```\nReturn unified diffs for `m13579.py` and `test_m13579.py`.\n\n*** Begin Patch\n*** Update File: m13579.py\n@@\n def f95053(n: int) -> int:\n@@\n- for k in range(n): # BUG\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_m13579.py\n+import pytest\n+from m13579 import f95053\n+\n+def test_small():\n+ assert f95053(7) == 28\n+\n+def test_zero():\n+ assert f95053(0) == 0\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ f95053(-1)\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: Language: TypeScript\nFramework/tooling: NestJS\nDomain: document processing API\nLogic challenge: gRPC retry storm\nTask type: state_machine_patch\nDifficulty: medium\n\nReturn a rigorous engineering answer:\n- identify the hidden root cause or logical failure\n- present the corrected implementation\n- add tests that prove the fix\n- list verification commands\n- explain why naive fixes are insufficient when relevant\n\nRepository sketch:\nrepo/\n src/\n api.ts\n service.ts\n schema.ts\n tests/\n api.test.ts\n package.json\n\nFocus: Focus on strong structured logic with edge cases, data validation, and concurrency safety.\n\nassistant: Diagnosis:\n- Root cause: the failure around gRPC retry storm is caused by missing validation, weak edge-case handling, or unsafe lifecycle behavior in the current implementation.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```ts\ntype Payload = Record;\n\nexport function normalizePayload(payload: Payload): Payload {\n if (!payload || typeof payload !== \"object\" || Array.isArray(payload)) {\n throw new TypeError(\"payload must be a plain object\");\n }\n return Object.fromEntries(\n Object.entries(payload)\n .filter(([, value]) => value !== null && value !== undefined)\n .map(([key, value]) => [String(key).trim(), value])\n );\n}\n\nexport function handleGrpcRetryStorm(payload: Payload) {\n const clean = normalizePayload(payload);\n if (!(\"id\" in clean)) {\n return { ok: false, data: {}, error: \"missing id\" };\n }\n return { ok: true, data: clean, error: null };\n}\n```\n\nTests:\n```ts\nimport { describe, it, expect } from \"vitest\";\nimport { handleGrpcRetryStorm } from \"../src/service\";\n\ndescribe(\"handler\", () => {\n it(\"accepts valid input\", () => {\n expect(handleGrpcRetryStorm({ id: 7, name: \"ok\", unused: null })).toEqual({\n ok: true,\n data: { id: 7, name: \"ok\" },\n error: null\n });\n });\n\n it(\"rejects missing id\", () => {\n expect(handleGrpcRetryStorm({ name: \"x\" }).error).toMatch(/missing id/);\n });\n});\n```\n\nVerification:\n- `npm test`\n- `npm run typecheck`\n- `npm run lint`\n\nEngineering notes:\n- Language: TypeScript\n- Framework/tooling: NestJS\n- Stack context: Rust, Axum, SQLx, Redis, Tokio, Docker\n- Domain: document processing API\n- Task type: state_machine_patch\n- Difficulty: medium\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Optimize while preserving behavior.\n\nFile: pjyltqs7u8.py\n```python\ndef s5iqjix(xs):\n out = []\n for x in xs:\n if x not in out:\n out.append(x)\n return out\n```\n\nRequirements: preserve first-seen order; O(n) average; add types + docstring.\n\n# pjyltqs7u8.py\nfrom __future__ import annotations\nfrom typing import Iterable, List, Set, TypeVar\n\nT = TypeVar(\"T\")\n\ndef s5iqjix(xs: Iterable[T]) -> List[T]:\n \"\"\"Return unique items preserving first-seen order.\"\"\"\n seen: Set[T] = set()\n out: List[T] = []\n for x in xs:\n if x in seen:\n continue\n seen.add(x)\n out.append(x)\n return out", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Optimize while preserving behavior and order.\n\n```python\ndef f01888(xs):\n out=[]\n for x in xs:\n if x not in out: out.append(x)\n return out\n```\nReturn `m85984.py` with types and O(n) average.\n\n```python\n# m85984.py\nfrom __future__ import annotations\nfrom typing import Iterable, List, Set, TypeVar\nT=TypeVar(\"T\")\n\ndef f01888(xs: Iterable[T]) -> List[T]:\n \"\"\"Unique items preserving first-seen order.\"\"\"\n seen: Set[T]=set()\n out: List[T]=[]\n for x in xs:\n if x in seen: continue\n seen.add(x); out.append(x)\n return out\n```", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Write secure, defensive Python code for time series.\nRequirements: input validation, safe file handling, prevent path traversal, include tests.\nConstraints: must provide clear error messages, must be streaming-friendly, must include tests.\nDifficulty: easy. Provide helpful exceptions with actionable messages.\n\nDeliverable: implementation + tests.\n```python\nfrom __future__ import annotations\n\nfrom dataclasses import dataclass\nfrom pathlib import Path\nfrom typing import Iterable\nimport json\n\n\nclass ValidationError(ValueError):\n \"\"\"Raised when input validation fails.\"\"\"\n\n\ndef safe_join(base: Path, *parts: str) -> Path:\n \"\"\"Join paths while preventing traversal outside base.\"\"\"\n b = base.resolve()\n p = (b / Path(*parts)).resolve()\n if p != b and b not in p.parents:\n raise ValidationError(f\"unsafe path: {p}\")\n return p\n\n\n@dataclass(frozen=True, slots=True)\nclass Record:\n key: str\n value: int\n\n\ndef parse_jsonl(lines: Iterable[str]) -> list[Record]:\n out: list[Record] = []\n for idx, line in enumerate(lines, 1):\n s = line.strip()\n if not s:\n continue\n try:\n obj = json.loads(s)\n except json.JSONDecodeError as e:\n raise ValidationError(f\"line {idx}: invalid json\") from e\n if not isinstance(obj, dict):\n raise ValidationError(f\"line {idx}: expected object\")\n key = obj.get(\"key\")\n val = obj.get(\"value\")\n if not isinstance(key, str) or not key:\n raise ValidationError(f\"line {idx}: key must be non-empty str\")\n if not isinstance(val, int):\n raise ValidationError(f\"line {idx}: value must be int\")\n out.append(Record(key, val))\n return out\n\n\ndef write_jsonl(base: Path, rel: str, records: Iterable[Record]) -> Path:\n base.mkdir(parents=True, exist_ok=True)\n dst = safe_join(base, rel)\n dst.parent.mkdir(parents=True, exist_ok=True)\n with dst.open(\"w\", encoding=\"utf-8\", newline=\"\\n\") as f:\n for r in records:\n f.write(json.dumps({\"key\": r.key, \"value\": r.value}, ensure_ascii=False) + \"\\n\")\n return dst\n```\n\n```python\n# tests (pytest-style)\nimport json\nfrom pathlib import Path\nimport pytest\nfrom module_under_test import ValidationError, Record, parse_jsonl, write_jsonl\n\ndef test_parse_ok():\n lines = [json.dumps({\"key\":\"a\",\"value\":1}), json.dumps({\"key\":\"b\",\"value\":2})]\n assert parse_jsonl(lines) == [Record(\"a\",1), Record(\"b\",2)]\n\ndef test_parse_rejects_bad_json():\n with pytest.raises(ValidationError):\n parse_jsonl([\"{not json}\"])\n\ndef test_safe_join_blocks_traversal(tmp_path: Path):\n with pytest.raises(ValidationError):\n write_jsonl(tmp_path, \"../x.jsonl\", [Record(\"a\",1)])\n```", "source": "WithinUsAI/python_GOD_coder_100k"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: Repository domain: developer platform\nPrimary language: Python\nFramework/tooling: pytest\nReported problem: race condition on worker shutdown\nTask type: feature_delivery\nDifficulty: hard\n\nProduce a complete professional engineering response:\n1. Diagnose the root cause.\n2. Provide the corrected implementation or patch.\n3. Add tests.\n4. Add verification commands.\n5. Note edge cases and any migration or rollback risk.\n\nRepository sketch:\nrepo/\n app/\n api.py\n service.py\n models.py\n tests/\n test_api.py\n pyproject.toml\n\nQuality target:\n- Minimal diff unless redesign is clearly required\n- Production-ready code\n- No placeholders\n- Secure defaults\n- Clear acceptance of failure cases\n\nFocus: Focus on complete implementation quality, patch correctness, tests, and production readiness.\n\nassistant: Diagnosis:\n- Root cause: the failure around race condition on worker shutdown is caused by missing validation, weak edge-case handling, or unsafe lifecycle behavior in the current implementation.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```python\nfrom __future__ import annotations\n\nfrom dataclasses import dataclass\nfrom typing import Any\n\n@dataclass\nclass ServiceResult:\n ok: bool\n data: dict[str, Any]\n error: str | None = None\n\ndef normalize_payload(payload: dict[str, Any]) -> dict[str, Any]:\n if not isinstance(payload, dict):\n raise TypeError(\"payload must be a dict\")\n clean: dict[str, Any] = {}\n for key, value in payload.items():\n if value is None:\n continue\n clean[str(key).strip()] = value\n return clean\n\ndef handle_race_condition_on_worker_shutdown(payload: dict[str, Any]) -> ServiceResult:\n clean = normalize_payload(payload)\n if \"id\" not in clean:\n return ServiceResult(ok=False, data={}, error=\"missing id\")\n return ServiceResult(ok=True, data=clean)\n```\n\nTests:\n```python\nimport pytest\nfrom app.service import handle_jwt_refresh_token_rotation as handler\n\ndef test_handler_accepts_valid_payload():\n result = handler({\"id\": 7, \"name\": \"ok\", \"unused\": None})\n assert result.ok is True\n assert result.data == {\"id\": 7, \"name\": \"ok\"}\n\ndef test_handler_rejects_missing_id():\n result = handler({\"name\": \"x\"})\n assert result.ok is False\n assert result.error == \"missing id\"\n```\n\nVerification:\n- `pytest -q`\n- `ruff check .`\n- `python -m compileall .`\n\nEngineering notes:\n- Language: Python\n- Framework/tooling: pytest\n- Stack context: Go, Gin, PostgreSQL, gRPC, Prometheus, Docker\n- Domain: developer platform\n- Task type: feature_delivery\n- Difficulty: hard\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "Design CI/CD for a customer support service delivering caching.\nTarget platform: infra (Docker + Kubernetes).\nRequirements: pipelines, checks, artifact strategy, deployments, and rollbacks.\nConstraints: must be production-ready, must be performant under load, must be easy to extend.\nDifficulty: easy. Assume mobile clients are occasionally offline.\n\nOutput: design + implementation guidance suitable for shipping.\nDeliverable: CI/CD pipeline (GitHub Actions) with quality gates.\n\n```yaml\nname: ci\non:\n pull_request:\n push:\n branches: [main]\n\njobs:\n test:\n runs-on: ubuntu-latest\n steps:\n - uses: actions/checkout@v4\n - uses: actions/setup-python@v5\n with:\n python-version: \"3.11\"\n - run: python -m pip install -U pip\n - run: pip install -r requirements.txt\n - run: pip install -r requirements-dev.txt\n - run: ruff check .\n - run: mypy .\n - run: pytest -q --maxfail=1 --disable-warnings\n\n docker:\n needs: test\n runs-on: ubuntu-latest\n steps:\n - uses: actions/checkout@v4\n - uses: docker/setup-buildx-action@v3\n - run: docker build -t app:${{ github.sha }} .\n```\n\nDeployment strategy:\n- main → build → deploy to staging → smoke tests → canary to prod.\n- Rollback: redeploy previous image + DB migration rollback plan.\n\n\nChecks: input validation, tests, and safe defaults included.", "source": "WithinUsAI/GOD_Coder_100k"} {"text": "Task type: smt_constraint_model\nScenario: edge sync\nDomain focus: network protocols\nPrimary language: python\nDifficulty: expert+\nScale/SLO: 50 TB/day ingestion\nComponent: component_ztrqmsbf\nConstraints: include test vectors and fuzz strategy, include verification strategy, include security threat model (defensive only), include deterministic replay plan, avoid data races and undefined behavior, explicit contracts and invariants\nAssume partial data corruption; include scrubbing strategy.\nDeliverable: Provide an SMT constraint model (or Python-to-SMT) for correctness/optimization; include sample instances and how to validate solutions.\n\nOutput: rigorous design + invariants + verification plan + implementation sketch.\n**Contract**\n- Inputs validated at the boundary; explicit error taxonomy.\n- Idempotency for side effects via request_id; deterministic replay.\n- Backward compatibility: additive changes by default; versioned breaking changes.\n**Invariants**\n- Determinism: replay of the same event log yields identical outputs.\n- Isolation: tenant boundary enforced; no cross-tenant reads/writes.\n- Liveness: under bounded faults and stable network, progress occurs.\n**Failure modes & recovery**\n- Network partition: minority cannot commit; clients receive retriable errors.\n- Crash during commit: WAL replay completes or transaction aborts; no torn writes.\n- Data corruption: checksums + scrubber; quarantine and rebuild from replicas/snapshots.\n**Security posture (defensive)**\n- Threat model: auth/authz, injection, replay/abuse, supply chain.\n- Least privilege; secrets in managed store; audit logs for sensitive ops.\n- Input normalization, parameterized queries, path traversal protections.\n**Verification strategy**\n- Property tests against a pure reference model (state machine).\n- Canary + shadow traffic; invariants checked in production via assertions/metrics.\n- Deterministic simulation with fault injection (crash/partition/latency).\n\n**Snippet**\n```smtlib\n; Find an assignment minimizing cost while satisfying constraints\n(declare-const x Int)\n(declare-const y Int)\n(assert (and (>= x 0) (>= y 0) (<= (+ x y) 10)))\n(minimize (+ (* 3 x) (* 2 y)))\n(check-sat)\n(get-model)\n```\n\nExpert+ checks: mechanized invariants (or exhaustive model checking), adversarial fuzzing, and multi-region failure drills.", "source": "WithinUsAI/Omega_Genesis_Coder_100k"} {"text": "Create a comprehensive test plan and automated tests for background jobs in a document processing product.\nTarget platform: ML (scikit + batch).\nRequirements: unit/integration tests, edge cases, load tests strategy, and CI gates.\nConstraints: must include documentation/comments, must avoid global state, must be performant under load, must be secure-by-default.\nDifficulty: expert. Assume strict latency budget (p95 < 200ms).\n\nOutput: design + implementation guidance suitable for shipping.\nDeliverable: test plan + automation guidance.\n\n**Unit tests**\n- Validation: malformed payloads rejected with correct codes.\n- AuthZ: tenant boundary enforced.\n- Idempotency: replay returns same response; conflicting reuse yields 409.\n\n**Integration tests**\n- DB transaction behavior; unique constraints.\n- Cache behavior: correctness under concurrent requests.\n\n**Load tests**\n- 10k RPS target: measure p95 latency, error rate, saturation.\n\n**CI gates**\n- Lint + typecheck + unit tests required.\n- Coverage threshold for critical modules.\n- Block merge on flaky test detection.\n\n\nHard-mode checks: concurrency safety, idempotency, and rollback validated; add chaos tests where feasible.", "source": "WithinUsAI/GOD_Coder_100k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Optimize while preserving behavior.\n\nFile: oaa2h7qo3o.py\n```python\ndef a3zv9sr(xs):\n out = []\n for x in xs:\n if x not in out:\n out.append(x)\n return out\n```\n\nRequirements: preserve first-seen order; O(n) average; add types + docstring.\n\n# oaa2h7qo3o.py\nfrom __future__ import annotations\nfrom typing import Iterable, List, Set, TypeVar\n\nT = TypeVar(\"T\")\n\ndef a3zv9sr(xs: Iterable[T]) -> List[T]:\n \"\"\"Return unique items preserving first-seen order.\"\"\"\n seen: Set[T] = set()\n out: List[T] = []\n for x in xs:\n if x in seen:\n continue\n seen.add(x)\n out.append(x)\n return out", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Produce an offline-first self-evolving code assistant architecture named `z3rfg77y`.\nMust include: module layout, patch-safety policy, evaluation gates (tests/lint/types), versioned memory index.\n\nArchitecture: `z3rfg77y` (offline-first, self-evolving)\n\nModules\n- core/loop.py: evolve → validate → accept/reject (bounded iterations)\n- patching/: diff builder, safe apply, atomic writes, rollback points\n- policy/: allowlist paths, deny globs (.git/, __pycache__/, binaries), patch size caps\n- signals/: parse pytest/ruff/mypy into normalized findings\n- memory/index.jsonl: append-only snapshots (hashes, metrics, rationale)\n\nSafety gates\n- refuse path traversal/symlink escapes; never edit binaries\n- accept only if tests/lint/types stay green or improve", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Implement rate limiting for a calendar/scheduling product.\nTarget platform: ML (scikit + batch).\nRequirements: provide production-ready code, configuration, and tests.\nConstraints: must be observable (logs/metrics/traces), must include documentation/comments, must include tests, must be secure-by-default.\nDifficulty: easy. Include rollback strategy.\n\nOutput: engineering-grade answer with edge cases covered.\nDeliverable: production-grade reference implementation (FastAPI) + tests.\n\n```python\n# app.py\nfrom __future__ import annotations\n\nimport hashlib\nimport json\nfrom dataclasses import dataclass\nfrom datetime import datetime, timezone\nfrom typing import Any, Optional\n\nfrom fastapi import FastAPI, Header, HTTPException\nfrom pydantic import BaseModel, Field\n\napp = FastAPI(title=\"Idempotent API\")\n\nclass CreateReq(BaseModel):\n tenant_id: str = Field(min_length=1)\n amount_cents: int = Field(ge=0)\n currency: str = Field(min_length=3, max_length=3)\n\nclass CreateResp(BaseModel):\n id: str\n created_at: str\n echo: CreateReq\n\n@dataclass\nclass _IdempoEntry:\n request_hash: str\n response_json: str\n\n# In production: Postgres table with UNIQUE(tenant_id, key)\n_IDEMPO: dict[tuple[str, str], _IdempoEntry] = {}\n\ndef _hash_req(req: CreateReq) -> str:\n raw = req.model_dump_json()\n return hashlib.sha256(raw.encode(\"utf-8\")).hexdigest()\n\n@app.post(\"/v1/payments\", response_model=CreateResp)\ndef create_payment(\n req: CreateReq,\n idempotency_key: Optional[str] = Header(default=None, alias=\"Idempotency-Key\"),\n) -> Any:\n if not idempotency_key:\n raise HTTPException(status_code=400, detail=\"Missing Idempotency-Key\")\n if len(idempotency_key) > 128:\n raise HTTPException(status_code=400, detail=\"Idempotency-Key too long\")\n\n key = (req.tenant_id, idempotency_key)\n rh = _hash_req(req)\n\n existing = _IDEMPO.get(key)\n if existing:\n if existing.request_hash != rh:\n raise HTTPException(status_code=409, detail=\"Idempotency-Key reuse with different payload\")\n return json.loads(existing.response_json)\n\n # Create new payment (stubbed)\n pid = hashlib.md5(f\"{req.tenant_id}:{idempotency_key}\".encode()).hexdigest()\n resp = CreateResp(\n id=pid,\n created_at=datetime.now(timezone.utc).isoformat(),\n echo=req,\n )\n _IDEMPO[key] = _IdempoEntry(request_hash=rh, response_json=resp.model_dump_json())\n return resp\n```\n\n```python\n# test_app.py (pytest)\nfrom fastapi.testclient import TestClient\nfrom app import app\n\nclient = TestClient(app)\n\ndef test_idempotent_replay():\n headers = {\"Idempotency-Key\": \"abc\"}\n body = {\"tenant_id\":\"t1\",\"amount_cents\":100,\"currency\":\"USD\"}\n r1 = client.post(\"/v1/payments\", json=body, headers=headers)\n r2 = client.post(\"/v1/payments\", json=body, headers=headers)\n assert r1.status_code == 200 and r2.status_code == 200\n assert r1.json() == r2.json()\n\ndef test_payload_conflict():\n headers = {\"Idempotency-Key\": \"abc\"}\n b1 = {\"tenant_id\":\"t1\",\"amount_cents\":100,\"currency\":\"USD\"}\n b2 = {\"tenant_id\":\"t1\",\"amount_cents\":200,\"currency\":\"USD\"}\n assert client.post(\"/v1/payments\", json=b1, headers=headers).status_code == 200\n assert client.post(\"/v1/payments\", json=b2, headers=headers).status_code == 409\n```\n\nNotes:\n- Replace in-memory store with a DB table and transaction.\n- Store response + request hash to detect key reuse with different payload.\n\n\nChecks: input validation, tests, and safe defaults included.", "source": "WithinUsAI/GOD_Coder_100k"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: Language: Bash\nFramework/tooling: jq\nDomain: data pipeline\nLogic challenge: invalid rollback sequence\nTask type: state_machine_patch\nDifficulty: hard\n\nReturn a rigorous engineering answer:\n- identify the hidden root cause or logical failure\n- present the corrected implementation\n- add tests that prove the fix\n- list verification commands\n- explain why naive fixes are insufficient when relevant\n\nRepository sketch:\nrepo/\n scripts/\n run.sh\n deploy.sh\n tests/\n smoke.sh\n\nFocus: Focus on strong structured logic with edge cases, data validation, and concurrency safety.\n\nassistant: Diagnosis:\n- Root cause: the failure around invalid rollback sequence is caused by missing validation, weak edge-case handling, or unsafe lifecycle behavior in the current implementation.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```bash\n#!/usr/bin/env bash\nset -euo pipefail\n\ninput=\"${1:-}\"\nif [[ -z \"$input\" ]]; then\n echo \"missing input\" >&2\n exit 1\nfi\n\nprintf '%s\n' \"$input\" | tr -d '\r'\n```\n\nTests:\n```bash\noutput=\"$(bash scripts/run.sh \"abc\")\"\ntest \"$output\" = \"abc\"\n```\n\nVerification:\n- `bash tests/smoke.sh`\n- `shellcheck scripts/*.sh`\n\nEngineering notes:\n- Language: Bash\n- Framework/tooling: jq\n- Stack context: Airflow, dbt, DuckDB, MinIO, pytest\n- Domain: data pipeline\n- Task type: state_machine_patch\n- Difficulty: hard\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Fix a bug and add tests.\n\nFile: h6btvce.py\n```python\ndef u8fxrn7(n: int) -> int:\n \"\"\"Sum 1..n inclusive.\"\"\"\n if n < 0:\n raise ValueError(\"n must be non-negative\")\n total = 0\n for k in range(n): # BUG: should include n\n total += k\n return total\n```\n\nReturn unified diffs for h6btvce.py and test_h6btvce.py (pytest).\n\n*** Begin Patch\n*** Update File: h6btvce.py\n@@\n def u8fxrn7(n: int) -> int:\n@@\n total = 0\n- for k in range(n): # BUG: should include n\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_h6btvce.py\n+import pytest\n+from h6btvce import u8fxrn7\n+\n+def test_zero():\n+ assert u8fxrn7(0) == 0\n+\n+def test_one():\n+ assert u8fxrn7(1) == 1\n+\n+def test_small():\n+ assert u8fxrn7(7) == 28\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ u8fxrn7(-1)\n+\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Refactor to typed, mostly-immutable Python and add minimal tests.\n\n```python\nclass C20632:\n def __init__(self, values): self.values=list(values)\n def mean(self): return sum(self.values)/len(self.values)\n```\nReturn `m24664.py` and `test_m24664.py`.\n\n```python\n# m24664.py\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom typing import Iterable, Tuple\n\n@dataclass(frozen=True)\nclass C20632:\n values: Tuple[float, ...]\n\n @staticmethod\n def create(values: Iterable[float]) -> \"C20632\":\n vals = tuple(float(v) for v in values)\n if not vals: raise ValueError(\"empty\")\n return C20632(vals)\n\n def mean(self) -> float:\n return sum(self.values)/len(self.values)\n```\n\n```python\n# test_m24664.py\nimport pytest\nfrom m24664 import C20632\n\ndef test_mean():\n assert C20632.create([1,2,3]).mean() == 2.0\ndef test_empty():\n with pytest.raises(ValueError):\n C20632.create([])\n```", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Produce an offline-first self-evolving code assistant architecture named `as0hsdqq`.\nMust include: module layout, patch-safety policy, evaluation gates (tests/lint/types), versioned memory index.\n\nArchitecture: `as0hsdqq` (offline-first, self-evolving)\n\nModules\n- core/loop.py: evolve → validate → accept/reject (bounded iterations)\n- patching/: diff builder, safe apply, atomic writes, rollback points\n- policy/: allowlist paths, deny globs (.git/, __pycache__/, binaries), patch size caps\n- signals/: parse pytest/ruff/mypy into normalized findings\n- memory/index.jsonl: append-only snapshots (hashes, metrics, rationale)\n\nSafety gates\n- refuse path traversal/symlink escapes; never edit binaries\n- accept only if tests/lint/types stay green or improve", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Fix the bug and add pytest tests.\n\n```python\ndef f98147(n: int) -> int:\n # sum 1..n inclusive\n if n < 0: raise ValueError\n total = 0\n for k in range(n): # BUG\n total += k\n return total\n```\nReturn unified diffs for `m14021.py` and `test_m14021.py`.\n\n*** Begin Patch\n*** Update File: m14021.py\n@@\n def f98147(n: int) -> int:\n@@\n- for k in range(n): # BUG\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_m14021.py\n+import pytest\n+from m14021 import f98147\n+\n+def test_small():\n+ assert f98147(7) == 28\n+\n+def test_zero():\n+ assert f98147(0) == 0\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ f98147(-1)\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Perform a code review for a fraud detection PR implementing offline-first sync.\nTarget platform: mobile (iOS Swift).\nRequirements: list critical issues, improvements, and provide an improved patch excerpt.\nConstraints: must be production-ready, must avoid global state, must be performant under load, must include documentation/comments.\nDifficulty: medium. Assume GDPR-style deletion requests must be supported.\n\nOutput: production-oriented blueprint with code where appropriate.\nDeliverable: code review findings + improved patch excerpt.\n\n**Critical issues**\n1. Missing input validation at boundary; potential unexpected exceptions.\n2. No idempotency / retry safety for side-effecting endpoint.\n3. No tests for edge cases (empty input, duplicates, timeouts).\n4. Observability gaps: no request_id correlation, no metrics.\n\n**Improvements**\n- Add strict validation and explicit error responses.\n- Add idempotency key support for create endpoints.\n- Add unit + integration tests with CI gating.\n- Add structured logs and basic metrics.\n\nPatch excerpt (illustrative):\n```python\nif not idem_key:\n raise HTTPException(400, \"Missing Idempotency-Key\")\n```\n\n\nChecks: input validation, tests, and safe defaults included.", "source": "WithinUsAI/GOD_Coder_100k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Refactor to modern typed Python with immutability and tests.\n\nFile: emzjc0vdz.py\n```python\nclass X9Hzozuz0K2:\n def __init__(self, name, values):\n self.name = name\n self.values = list(values)\n def add(self, v):\n self.values.append(v)\n def mean(self):\n s = 0\n for x in self.values:\n s += x\n return s / len(self.values)\n```\n\nReturn full new emzjc0vdz.py and test_emzjc0vdz.py.\n\n# emzjc0vdz.py\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom typing import Iterable, Tuple\n\n@dataclass(frozen=True)\nclass X9Hzozuz0K2:\n name: str\n values: Tuple[float, ...]\n\n @staticmethod\n def create(name: str, values: Iterable[float]) -> \"X9Hzozuz0K2\":\n vals = tuple(float(v) for v in values)\n if not vals:\n raise ValueError(\"values must be non-empty\")\n return X9Hzozuz0K2(name=name, values=vals)\n\n def add(self, v: float) -> \"X9Hzozuz0K2\":\n return X9Hzozuz0K2(name=self.name, values=self.values + (float(v),))\n\n def mean(self) -> float:\n return sum(self.values) / len(self.values)\n\n# test_emzjc0vdz.py\nimport pytest\nfrom emzjc0vdz import X9Hzozuz0K2\n\ndef test_mean_and_add():\n c = X9Hzozuz0K2.create(\"a\", [1, 2, 3])\n assert c.mean() == 2.0\n assert c.add(5).mean() == (1 + 2 + 3 + 5) / 4\n\ndef test_empty_raises():\n with pytest.raises(ValueError):\n X9Hzozuz0K2.create(\"x\", [])", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Refactor to modern typed Python with immutability and tests.\n\nFile: dtwnwj7.py\n```python\nclass C6A7O6:\n def __init__(self, name, values):\n self.name = name\n self.values = list(values)\n def add(self, v):\n self.values.append(v)\n def mean(self):\n s = 0\n for x in self.values:\n s += x\n return s / len(self.values)\n```\n\nReturn full new dtwnwj7.py and test_dtwnwj7.py.\n\n# dtwnwj7.py\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom typing import Iterable, Tuple\n\n@dataclass(frozen=True)\nclass C6A7O6:\n name: str\n values: Tuple[float, ...]\n\n @staticmethod\n def create(name: str, values: Iterable[float]) -> \"C6A7O6\":\n vals = tuple(float(v) for v in values)\n if not vals:\n raise ValueError(\"values must be non-empty\")\n return C6A7O6(name=name, values=vals)\n\n def add(self, v: float) -> \"C6A7O6\":\n return C6A7O6(name=self.name, values=self.values + (float(v),))\n\n def mean(self) -> float:\n return sum(self.values) / len(self.values)\n\n# test_dtwnwj7.py\nimport pytest\nfrom dtwnwj7 import C6A7O6\n\ndef test_mean_and_add():\n c = C6A7O6.create(\"a\", [1, 2, 3])\n assert c.mean() == 2.0\n assert c.add(5).mean() == (1 + 2 + 3 + 5) / 4\n\ndef test_empty_raises():\n with pytest.raises(ValueError):\n C6A7O6.create(\"x\", [])", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: Language: C#\nFramework/tooling: ASP.NET Core\nDomain: observability collector\nLogic challenge: log redaction failure\nTask type: cross_stack_outage_fix\nDifficulty: hard\n\nReturn a rigorous engineering answer:\n- identify the hidden root cause or logical failure\n- present the corrected implementation\n- add tests that prove the fix\n- list verification commands\n- explain why naive fixes are insufficient when relevant\n\nRepository sketch:\nrepo/\n src/App/Program.cs\n src/App/Service.cs\n tests/App.Tests/ServiceTests.cs\n App.sln\n\nFocus: Focus on staff-level problem solving with multi-file patches, rollout implications, performance and security tradeoffs.\n\nassistant: Diagnosis:\n- Staff-level diagnosis: log redaction failure impacts correctness, operability, and future maintenance, so the fix must be minimal where possible but complete where necessary.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```csharp\nusing System;\nusing System.Collections.Generic;\n\npublic static class RequestHandler\n{\n public static Dictionary HandleRequest(Dictionary payload)\n {\n var clean = new Dictionary();\n foreach (var entry in payload)\n {\n if (entry.Value != null)\n clean[entry.Key.Trim()] = entry.Value;\n }\n if (!clean.ContainsKey(\"id\"))\n throw new ArgumentException(\"missing id\");\n return new Dictionary\n {\n [\"ok\"] = true,\n [\"data\"] = clean\n };\n }\n}\n```\n\nTests:\n```csharp\nusing System;\nusing System.Collections.Generic;\nusing Xunit;\n\npublic class RequestHandlerTests\n{\n [Fact]\n public void RequiresId()\n {\n Assert.Throws(() => RequestHandler.HandleRequest(new Dictionary { [\"name\"] = \"x\" }));\n }\n}\n```\n\nVerification:\n- `dotnet test`\n- `dotnet build`\n\nEngineering notes:\n- Language: C#\n- Framework/tooling: ASP.NET Core\n- Stack context: GitHub Actions, Docker Compose, Kubernetes, Terraform\n- Domain: observability collector\n- Task type: cross_stack_outage_fix\n- Difficulty: hard\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "Task type: secure_architecture\nScenario: rate limit gateway\nDomain focus: zero-downtime migrations\nPrimary language: typescript\nDifficulty: expert\nScale/SLO: p99 < 50ms\nComponent: component_frivisjx\nConstraints: include backward compatibility and migration plan, assume adversarial inputs; validate everything, include verification strategy, include test vectors and fuzz strategy, include performance model and limits, explicit contracts and invariants, include security threat model (defensive only)\nAssume tight memory budget and cold-start constraints.\nDeliverable: Provide a defensive threat model and secure-by-default architecture; include monitoring/detection and tests (no offensive content).\n\nOutput: contract-first solution with failure modes, security posture, and test/verification strategy.\n**Contract**\n- Inputs validated at the boundary; explicit error taxonomy.\n- Idempotency for side effects via request_id; deterministic replay.\n- Backward compatibility: additive changes by default; versioned breaking changes.\n**Invariants**\n- Liveness: under bounded faults and stable network, progress occurs.\n- Isolation: tenant boundary enforced; no cross-tenant reads/writes.\n- Determinism: replay of the same event log yields identical outputs.\n**Failure modes & recovery**\n- Network partition: minority cannot commit; clients receive retriable errors.\n- Crash during commit: WAL replay completes or transaction aborts; no torn writes.\n- Data corruption: checksums + scrubber; quarantine and rebuild from replicas/snapshots.\n**Security posture (defensive)**\n- Threat model: auth/authz, injection, replay/abuse, supply chain.\n- Least privilege; secrets in managed store; audit logs for sensitive ops.\n- Input normalization, parameterized queries, path traversal protections.\n**Verification strategy**\n- Canary + shadow traffic; invariants checked in production via assertions/metrics.\n- Deterministic simulation with fault injection (crash/partition/latency).\n- Property tests against a pure reference model (state machine).\n\n**Snippet**\n```text\nImplementation sketch: factor pure state-machine core; adapters for I/O; add deterministic replay log.\n```\nExpert checks: state-machine proof sketch + model checking; upgrade/rollback rehearsed.", "source": "WithinUsAI/Omega_Genesis_Coder_100k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Fix a bug and add tests.\n\nFile: ao1m2_5fpx.py\n```python\ndef tqq7pf872xee(n: int) -> int:\n \"\"\"Sum 1..n inclusive.\"\"\"\n if n < 0:\n raise ValueError(\"n must be non-negative\")\n total = 0\n for k in range(n): # BUG: should include n\n total += k\n return total\n```\n\nReturn unified diffs for ao1m2_5fpx.py and test_ao1m2_5fpx.py (pytest).\n\n*** Begin Patch\n*** Update File: ao1m2_5fpx.py\n@@\n def tqq7pf872xee(n: int) -> int:\n@@\n total = 0\n- for k in range(n): # BUG: should include n\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_ao1m2_5fpx.py\n+import pytest\n+from ao1m2_5fpx import tqq7pf872xee\n+\n+def test_zero():\n+ assert tqq7pf872xee(0) == 0\n+\n+def test_one():\n+ assert tqq7pf872xee(1) == 1\n+\n+def test_small():\n+ assert tqq7pf872xee(7) == 28\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ tqq7pf872xee(-1)\n+\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Build an elite-grade solution in the domain of security engineering (defensive) for scenario: chat messaging.\nPrimary language: sql.\nDifficulty: expert.\nConstraints: document performance characteristics, make the interface contract explicit, design for backward compatibility and migrations, include tests or verification strategy.\nComponent: component_wpxipaq.\nAssume compliance requires data deletion with proofs.\nTask: Implement or outline a storage/indexing subsystem (LSM/B-Tree, WAL, snapshots). Include transaction/consistency considerations and benchmark plan.\n\nOutput: elite-grade engineering answer with contracts, edge cases, and verification.\nOutput: storage design + WAL + compaction + benchmarks.\n\n**Design**\n- WAL (append-only) for durability; fsync policy configurable.\n- Memtable (in-memory) → flush to immutable SSTables.\n- LSM compaction tiers; bloom filters per SSTable for point-lookups.\n- Manifest tracks SSTable set; atomic pointer swap on updates.\n\n**Correctness**\n- Crash recovery: replay WAL to rebuild memtable; manifest ensures last consistent set.\n- Reads: merge memtable + SSTables newest→oldest; tombstones override older values.\n\n**Bench plan**\n- Workloads: write-heavy, read-heavy, mixed; measure p50/p95 latency and write amplification.\n- Track compaction debt and space amplification.\n\n**Test plan**\n- Fuzz crash points: kill after WAL append / after manifest update; verify invariants on restart.\n\n\nExpert checks: state-machine reasoning, concurrency stress, and upgrade/rollback validated.", "source": "WithinUsAI/Elite_GOD_Coder_100k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Refactor to modern typed Python with immutability and tests.\n\nFile: cc49jy1_4.py\n```python\nclass O0Cu0Joo0:\n def __init__(self, name, values):\n self.name = name\n self.values = list(values)\n def add(self, v):\n self.values.append(v)\n def mean(self):\n s = 0\n for x in self.values:\n s += x\n return s / len(self.values)\n```\n\nReturn full new cc49jy1_4.py and test_cc49jy1_4.py.\n\n# cc49jy1_4.py\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom typing import Iterable, Tuple\n\n@dataclass(frozen=True)\nclass O0Cu0Joo0:\n name: str\n values: Tuple[float, ...]\n\n @staticmethod\n def create(name: str, values: Iterable[float]) -> \"O0Cu0Joo0\":\n vals = tuple(float(v) for v in values)\n if not vals:\n raise ValueError(\"values must be non-empty\")\n return O0Cu0Joo0(name=name, values=vals)\n\n def add(self, v: float) -> \"O0Cu0Joo0\":\n return O0Cu0Joo0(name=self.name, values=self.values + (float(v),))\n\n def mean(self) -> float:\n return sum(self.values) / len(self.values)\n\n# test_cc49jy1_4.py\nimport pytest\nfrom cc49jy1_4 import O0Cu0Joo0\n\ndef test_mean_and_add():\n c = O0Cu0Joo0.create(\"a\", [1, 2, 3])\n assert c.mean() == 2.0\n assert c.add(5).mean() == (1 + 2 + 3 + 5) / 4\n\ndef test_empty_raises():\n with pytest.raises(ValueError):\n O0Cu0Joo0.create(\"x\", [])", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Refactor to modern typed Python with immutability and tests.\n\nFile: hc6nl87pii.py\n```python\nclass Qe4Et7Fsbo4S:\n def __init__(self, name, values):\n self.name = name\n self.values = list(values)\n def add(self, v):\n self.values.append(v)\n def mean(self):\n s = 0\n for x in self.values:\n s += x\n return s / len(self.values)\n```\n\nReturn full new hc6nl87pii.py and test_hc6nl87pii.py.\n\n# hc6nl87pii.py\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom typing import Iterable, Tuple\n\n@dataclass(frozen=True)\nclass Qe4Et7Fsbo4S:\n name: str\n values: Tuple[float, ...]\n\n @staticmethod\n def create(name: str, values: Iterable[float]) -> \"Qe4Et7Fsbo4S\":\n vals = tuple(float(v) for v in values)\n if not vals:\n raise ValueError(\"values must be non-empty\")\n return Qe4Et7Fsbo4S(name=name, values=vals)\n\n def add(self, v: float) -> \"Qe4Et7Fsbo4S\":\n return Qe4Et7Fsbo4S(name=self.name, values=self.values + (float(v),))\n\n def mean(self) -> float:\n return sum(self.values) / len(self.values)\n\n# test_hc6nl87pii.py\nimport pytest\nfrom hc6nl87pii import Qe4Et7Fsbo4S\n\ndef test_mean_and_add():\n c = Qe4Et7Fsbo4S.create(\"a\", [1, 2, 3])\n assert c.mean() == 2.0\n assert c.add(5).mean() == (1 + 2 + 3 + 5) / 4\n\ndef test_empty_raises():\n with pytest.raises(ValueError):\n Qe4Et7Fsbo4S.create(\"x\", [])", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Refactor to modern typed Python with immutability and tests.\n\nFile: q2lzb0ue.py\n```python\nclass B0Prj1CcQ:\n def __init__(self, name, values):\n self.name = name\n self.values = list(values)\n def add(self, v):\n self.values.append(v)\n def mean(self):\n s = 0\n for x in self.values:\n s += x\n return s / len(self.values)\n```\n\nReturn full new q2lzb0ue.py and test_q2lzb0ue.py.\n\n# q2lzb0ue.py\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom typing import Iterable, Tuple\n\n@dataclass(frozen=True)\nclass B0Prj1CcQ:\n name: str\n values: Tuple[float, ...]\n\n @staticmethod\n def create(name: str, values: Iterable[float]) -> \"B0Prj1CcQ\":\n vals = tuple(float(v) for v in values)\n if not vals:\n raise ValueError(\"values must be non-empty\")\n return B0Prj1CcQ(name=name, values=vals)\n\n def add(self, v: float) -> \"B0Prj1CcQ\":\n return B0Prj1CcQ(name=self.name, values=self.values + (float(v),))\n\n def mean(self) -> float:\n return sum(self.values) / len(self.values)\n\n# test_q2lzb0ue.py\nimport pytest\nfrom q2lzb0ue import B0Prj1CcQ\n\ndef test_mean_and_add():\n c = B0Prj1CcQ.create(\"a\", [1, 2, 3])\n assert c.mean() == 2.0\n assert c.add(5).mean() == (1 + 2 + 3 + 5) / 4\n\ndef test_empty_raises():\n with pytest.raises(ValueError):\n B0Prj1CcQ.create(\"x\", [])", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Build an elite-grade solution in the domain of sre/observability for scenario: feature flagging.\nPrimary language: sql.\nDifficulty: expert.\nConstraints: include invariants and failure modes, include tests or verification strategy, assume untrusted inputs; validate and sanitize.\nComponent: component_gowfpxi.\nAssume partial network partitions occur weekly.\nTask: Write a precise interface contract, list invariants, and provide a lightweight formal/spec-style description (pseudo-TLA+/state machine) plus reference implementation skeleton and tests.\n\nOutput: elite-grade engineering answer with contracts, edge cases, and verification.\nOutput: contract + invariants + spec + reference skeleton.\n\n**Interface contract**\n- Commands: `Put(key, value, expected_version?)`, `Get(key)`, `Delete(key, expected_version?)`\n- Responses: `Ok(version, value?)`, `NotFound`, `Conflict(current_version)`, `InvalidInput`\n- Idempotency: client supplies `request_id`; server must de-duplicate per (tenant_id, request_id).\n\n**Invariants**\n1. Monotonic version per key (strictly increases on successful writes).\n2. Reads return latest committed value for a given consistency level.\n3. Exactly-once effect for a given `request_id` (at-most-once execution + replay response).\n4. Tenant isolation: keys are scoped by tenant_id.\n\n**State machine (pseudo)**\nState:\n- store: map[(tenant,key)] -> (version:int, value:bytes|tombstone)\n- seen: map[(tenant,request_id)] -> response\nTransition Put:\n- if request_id in seen: return seen[...]\n- validate input; if expected_version set and != current version -> Conflict\n- version' = version + 1; store[...] := (version', value); seen[...] := Ok(version', value)\n\n**Reference skeleton (Python)**\n```python\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom typing import Dict, Optional, Tuple\n\nclass Conflict(Exception): pass\nclass InvalidInput(ValueError): pass\n\n@dataclass(frozen=True, slots=True)\nclass Value:\n version: int\n data: Optional[bytes] # None == tombstone\n\n@dataclass(frozen=True, slots=True)\nclass Reply:\n kind: str\n version: Optional[int] = None\n data: Optional[bytes] = None\n\nclass KV:\n def __init__(self) -> None:\n self._store: Dict[Tuple[str,str], Value] = {}\n self._seen: Dict[Tuple[str,str], Reply] = {}\n\n def put(self, tenant: str, request_id: str, key: str, data: bytes, expected_version: Optional[int]=None) -> Reply:\n if not tenant or not request_id or not key:\n raise InvalidInput(\"tenant/request_id/key required\")\n de = self._seen.get((tenant, request_id))\n if de: \n return de\n cur = self._store.get((tenant, key), Value(0, None))\n if expected_version is not None and expected_version != cur.version:\n r = Reply(\"conflict\", version=cur.version)\n self._seen[(tenant, request_id)] = r\n return r\n nxt = Value(cur.version + 1, data)\n self._store[(tenant, key)] = nxt\n r = Reply(\"ok\", version=nxt.version)\n self._seen[(tenant, request_id)] = r\n return r\n```\n\n**Tests**\n- Determinism: same request_id → same reply.\n- Conflict detection and version monotonicity.\n\n\nExpert checks: state-machine reasoning, concurrency stress, and upgrade/rollback validated.", "source": "WithinUsAI/Elite_GOD_Coder_100k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Fix a bug and add tests.\n\nFile: sighjx23q47p.py\n```python\ndef rsr95q(n: int) -> int:\n \"\"\"Sum 1..n inclusive.\"\"\"\n if n < 0:\n raise ValueError(\"n must be non-negative\")\n total = 0\n for k in range(n): # BUG: should include n\n total += k\n return total\n```\n\nReturn unified diffs for sighjx23q47p.py and test_sighjx23q47p.py (pytest).\n\n*** Begin Patch\n*** Update File: sighjx23q47p.py\n@@\n def rsr95q(n: int) -> int:\n@@\n total = 0\n- for k in range(n): # BUG: should include n\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_sighjx23q47p.py\n+import pytest\n+from sighjx23q47p import rsr95q\n+\n+def test_zero():\n+ assert rsr95q(0) == 0\n+\n+def test_one():\n+ assert rsr95q(1) == 1\n+\n+def test_small():\n+ assert rsr95q(7) == 28\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ rsr95q(-1)\n+\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Fix a bug and add tests.\n\nFile: woew8glknpus.py\n```python\ndef r7d0_qa4w6(n: int) -> int:\n \"\"\"Sum 1..n inclusive.\"\"\"\n if n < 0:\n raise ValueError(\"n must be non-negative\")\n total = 0\n for k in range(n): # BUG: should include n\n total += k\n return total\n```\n\nReturn unified diffs for woew8glknpus.py and test_woew8glknpus.py (pytest).\n\n*** Begin Patch\n*** Update File: woew8glknpus.py\n@@\n def r7d0_qa4w6(n: int) -> int:\n@@\n total = 0\n- for k in range(n): # BUG: should include n\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_woew8glknpus.py\n+import pytest\n+from woew8glknpus import r7d0_qa4w6\n+\n+def test_zero():\n+ assert r7d0_qa4w6(0) == 0\n+\n+def test_one():\n+ assert r7d0_qa4w6(1) == 1\n+\n+def test_small():\n+ assert r7d0_qa4w6(7) == 28\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ r7d0_qa4w6(-1)\n+\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Fix the bug and add pytest tests.\n\n```python\ndef f74140(n: int) -> int:\n # sum 1..n inclusive\n if n < 0: raise ValueError\n total = 0\n for k in range(n): # BUG\n total += k\n return total\n```\nReturn unified diffs for `m82020.py` and `test_m82020.py`.\n\n*** Begin Patch\n*** Update File: m82020.py\n@@\n def f74140(n: int) -> int:\n@@\n- for k in range(n): # BUG\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_m82020.py\n+import pytest\n+from m82020 import f74140\n+\n+def test_small():\n+ assert f74140(7) == 28\n+\n+def test_zero():\n+ assert f74140(0) == 0\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ f74140(-1)\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Fix the bug and add pytest tests.\n\n```python\ndef f70958(n: int) -> int:\n # sum 1..n inclusive\n if n < 0: raise ValueError\n total = 0\n for k in range(n): # BUG\n total += k\n return total\n```\nReturn unified diffs for `m52994.py` and `test_m52994.py`.\n\n*** Begin Patch\n*** Update File: m52994.py\n@@\n def f70958(n: int) -> int:\n@@\n- for k in range(n): # BUG\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_m52994.py\n+import pytest\n+from m52994 import f70958\n+\n+def test_small():\n+ assert f70958(7) == 28\n+\n+def test_zero():\n+ assert f70958(0) == 0\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ f70958(-1)\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Build an elite-grade solution in the domain of security engineering (defensive) for scenario: rate limiting gateway.\nPrimary language: python.\nDifficulty: medium.\nConstraints: avoid undefined behavior and data races, provide rollout and rollback guidance, assume untrusted inputs; validate and sanitize, design for backward compatibility and migrations.\nComponent: component_ggtckgt.\nAssume partial network partitions occur weekly.\nTask: Provide SLOs, alerting, dashboards, runbooks, and incident playbook. Include chaos testing and safe rollout strategy.\n\nOutput: rigorous solution with invariants, failure modes, and performance notes.\nOutput: SLOs + alerts + runbooks + chaos strategy.\n\n**SLOs**\n- Availability: 99.9% monthly\n- Latency: p95 < 200ms, p99 < 400ms\n- Error rate: < 0.1%\n\n**Alerts**\n- Burn-rate alerts for SLOs (fast/slow windows)\n- Saturation: CPU, memory, queue depth, DB connections\n- Dependency health: cache hit rate drop, downstream timeouts\n\n**Runbooks**\n- Triage: identify blast radius, feature-flag rollback, capacity mitigation\n- Post-incident: timeline, contributing factors, action items\n\n**Chaos**\n- Inject latency, partial outages, and restarts in staging; verify steady-state SLOs.\n\n\nChecks: boundary validation and deterministic behavior verified.", "source": "WithinUsAI/Elite_GOD_Coder_100k"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: Language: JavaScript\nFramework/tooling: React\nDomain: repo automation\nLogic challenge: log redaction failure\nTask type: backwards_compatible_redesign\nDifficulty: hard\n\nReturn a rigorous engineering answer:\n- identify the hidden root cause or logical failure\n- present the corrected implementation\n- add tests that prove the fix\n- list verification commands\n- explain why naive fixes are insufficient when relevant\n\nRepository sketch:\nrepo/\n src/\n api.js\n service.js\n utils.js\n tests/\n api.test.js\n package.json\n\nFocus: Focus on staff-level problem solving with multi-file patches, rollout implications, performance and security tradeoffs.\n\nassistant: Diagnosis:\n- Staff-level diagnosis: log redaction failure impacts correctness, operability, and future maintenance, so the fix must be minimal where possible but complete where necessary.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```javascript\ntype Payload = Record;\n\nexport function normalizePayload(payload: Payload): Payload {\n if (!payload || typeof payload !== \"object\" || Array.isArray(payload)) {\n throw new TypeError(\"payload must be a plain object\");\n }\n return Object.fromEntries(\n Object.entries(payload)\n .filter(([, value]) => value !== null && value !== undefined)\n .map(([key, value]) => [String(key).trim(), value])\n );\n}\n\nexport function handleLogRedactionFailure(payload: Payload) {\n const clean = normalizePayload(payload);\n if (!(\"id\" in clean)) {\n return { ok: false, data: {}, error: \"missing id\" };\n }\n return { ok: true, data: clean, error: null };\n}\n```\n\nTests:\n```javascript\nimport { describe, it, expect } from \"vitest\";\nimport { handleLogRedactionFailure } from \"../src/service\";\n\ndescribe(\"handler\", () => {\n it(\"accepts valid input\", () => {\n expect(handleLogRedactionFailure({ id: 7, name: \"ok\", unused: null })).toEqual({\n ok: true,\n data: { id: 7, name: \"ok\" },\n error: null\n });\n });\n\n it(\"rejects missing id\", () => {\n expect(handleLogRedactionFailure({ name: \"x\" }).error).toMatch(/missing id/);\n });\n});\n```\n\nVerification:\n- `npm test`\n- `npm run lint`\n\nEngineering notes:\n- Language: JavaScript\n- Framework/tooling: React\n- Stack context: Airflow, dbt, DuckDB, MinIO, pytest\n- Domain: repo automation\n- Task type: backwards_compatible_redesign\n- Difficulty: hard\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Refactor to modern typed Python with immutability and tests.\n\nFile: jd74e4uj.py\n```python\nclass Aei122Jmcon:\n def __init__(self, name, values):\n self.name = name\n self.values = list(values)\n def add(self, v):\n self.values.append(v)\n def mean(self):\n s = 0\n for x in self.values:\n s += x\n return s / len(self.values)\n```\n\nReturn full new jd74e4uj.py and test_jd74e4uj.py.\n\n# jd74e4uj.py\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom typing import Iterable, Tuple\n\n@dataclass(frozen=True)\nclass Aei122Jmcon:\n name: str\n values: Tuple[float, ...]\n\n @staticmethod\n def create(name: str, values: Iterable[float]) -> \"Aei122Jmcon\":\n vals = tuple(float(v) for v in values)\n if not vals:\n raise ValueError(\"values must be non-empty\")\n return Aei122Jmcon(name=name, values=vals)\n\n def add(self, v: float) -> \"Aei122Jmcon\":\n return Aei122Jmcon(name=self.name, values=self.values + (float(v),))\n\n def mean(self) -> float:\n return sum(self.values) / len(self.values)\n\n# test_jd74e4uj.py\nimport pytest\nfrom jd74e4uj import Aei122Jmcon\n\ndef test_mean_and_add():\n c = Aei122Jmcon.create(\"a\", [1, 2, 3])\n assert c.mean() == 2.0\n assert c.add(5).mean() == (1 + 2 + 3 + 5) / 4\n\ndef test_empty_raises():\n with pytest.raises(ValueError):\n Aei122Jmcon.create(\"x\", [])", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Fix a bug and add tests.\n\nFile: bs6l580rwo.py\n```python\ndef z_jrpvhz2w8(n: int) -> int:\n \"\"\"Sum 1..n inclusive.\"\"\"\n if n < 0:\n raise ValueError(\"n must be non-negative\")\n total = 0\n for k in range(n): # BUG: should include n\n total += k\n return total\n```\n\nReturn unified diffs for bs6l580rwo.py and test_bs6l580rwo.py (pytest).\n\n*** Begin Patch\n*** Update File: bs6l580rwo.py\n@@\n def z_jrpvhz2w8(n: int) -> int:\n@@\n total = 0\n- for k in range(n): # BUG: should include n\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_bs6l580rwo.py\n+import pytest\n+from bs6l580rwo import z_jrpvhz2w8\n+\n+def test_zero():\n+ assert z_jrpvhz2w8(0) == 0\n+\n+def test_one():\n+ assert z_jrpvhz2w8(1) == 1\n+\n+def test_small():\n+ assert z_jrpvhz2w8(7) == 28\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ z_jrpvhz2w8(-1)\n+\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Provision infrastructure for a enterprise SaaS workload providing role-based access control.\nTarget platform: backend (Go).\nRequirements: IaC (Terraform or Kubernetes YAML), networking, secrets, autoscaling.\nConstraints: must be easy to extend, must include type hints where applicable, must be production-ready.\nDifficulty: hard. Assume mobile clients are occasionally offline.\n\nOutput: design + implementation guidance suitable for shipping.\nDeliverable: Kubernetes deployment + basic security posture.\n\n```yaml\napiVersion: apps/v1\nkind: Deployment\nmetadata:\n name: app\nspec:\n replicas: 3\n selector:\n matchLabels: { app: app }\n template:\n metadata:\n labels: { app: app }\n spec:\n containers:\n - name: app\n image: app:latest\n ports: [{ containerPort: 8080 }]\n readinessProbe:\n httpGet: { path: /healthz, port: 8080 }\n resources:\n requests: { cpu: \"200m\", memory: \"256Mi\" }\n limits: { cpu: \"1\", memory: \"1Gi\" }\n```\n\nAdditions:\n- NetworkPolicy to restrict egress/ingress.\n- Secrets via external secret store; rotate regularly.\n- HPA for autoscaling; PodDisruptionBudget for availability.\n\n\nHard-mode checks: concurrency safety, idempotency, and rollback validated; add chaos tests where feasible.", "source": "WithinUsAI/GOD_Coder_100k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Fix a bug and add tests.\n\nFile: zog6ftll32to.py\n```python\ndef nui8s5wa6fa(n: int) -> int:\n \"\"\"Sum 1..n inclusive.\"\"\"\n if n < 0:\n raise ValueError(\"n must be non-negative\")\n total = 0\n for k in range(n): # BUG: should include n\n total += k\n return total\n```\n\nReturn unified diffs for zog6ftll32to.py and test_zog6ftll32to.py (pytest).\n\n*** Begin Patch\n*** Update File: zog6ftll32to.py\n@@\n def nui8s5wa6fa(n: int) -> int:\n@@\n total = 0\n- for k in range(n): # BUG: should include n\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_zog6ftll32to.py\n+import pytest\n+from zog6ftll32to import nui8s5wa6fa\n+\n+def test_zero():\n+ assert nui8s5wa6fa(0) == 0\n+\n+def test_one():\n+ assert nui8s5wa6fa(1) == 1\n+\n+def test_small():\n+ assert nui8s5wa6fa(7) == 28\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ nui8s5wa6fa(-1)\n+\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Fix a bug and add tests.\n\nFile: ct6tmocvibrt.py\n```python\ndef q__8j0f(n: int) -> int:\n \"\"\"Sum 1..n inclusive.\"\"\"\n if n < 0:\n raise ValueError(\"n must be non-negative\")\n total = 0\n for k in range(n): # BUG: should include n\n total += k\n return total\n```\n\nReturn unified diffs for ct6tmocvibrt.py and test_ct6tmocvibrt.py (pytest).\n\n*** Begin Patch\n*** Update File: ct6tmocvibrt.py\n@@\n def q__8j0f(n: int) -> int:\n@@\n total = 0\n- for k in range(n): # BUG: should include n\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_ct6tmocvibrt.py\n+import pytest\n+from ct6tmocvibrt import q__8j0f\n+\n+def test_zero():\n+ assert q__8j0f(0) == 0\n+\n+def test_one():\n+ assert q__8j0f(1) == 1\n+\n+def test_small():\n+ assert q__8j0f(7) == 28\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ q__8j0f(-1)\n+\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Implement search + pagination for a enterprise SaaS product.\nTarget platform: mobile (Android Kotlin).\nRequirements: provide production-ready code, configuration, and tests.\nConstraints: must include type hints where applicable, must include clear error handling, must be secure-by-default, must be performant under load.\nDifficulty: hard. Assume GDPR-style deletion requests must be supported.\n\nOutput: actionable implementation and verification artifacts.\nDeliverable: production-grade reference implementation (FastAPI) + tests.\n\n```python\n# app.py\nfrom __future__ import annotations\n\nimport hashlib\nimport json\nfrom dataclasses import dataclass\nfrom datetime import datetime, timezone\nfrom typing import Any, Optional\n\nfrom fastapi import FastAPI, Header, HTTPException\nfrom pydantic import BaseModel, Field\n\napp = FastAPI(title=\"Idempotent API\")\n\nclass CreateReq(BaseModel):\n tenant_id: str = Field(min_length=1)\n amount_cents: int = Field(ge=0)\n currency: str = Field(min_length=3, max_length=3)\n\nclass CreateResp(BaseModel):\n id: str\n created_at: str\n echo: CreateReq\n\n@dataclass\nclass _IdempoEntry:\n request_hash: str\n response_json: str\n\n# In production: Postgres table with UNIQUE(tenant_id, key)\n_IDEMPO: dict[tuple[str, str], _IdempoEntry] = {}\n\ndef _hash_req(req: CreateReq) -> str:\n raw = req.model_dump_json()\n return hashlib.sha256(raw.encode(\"utf-8\")).hexdigest()\n\n@app.post(\"/v1/payments\", response_model=CreateResp)\ndef create_payment(\n req: CreateReq,\n idempotency_key: Optional[str] = Header(default=None, alias=\"Idempotency-Key\"),\n) -> Any:\n if not idempotency_key:\n raise HTTPException(status_code=400, detail=\"Missing Idempotency-Key\")\n if len(idempotency_key) > 128:\n raise HTTPException(status_code=400, detail=\"Idempotency-Key too long\")\n\n key = (req.tenant_id, idempotency_key)\n rh = _hash_req(req)\n\n existing = _IDEMPO.get(key)\n if existing:\n if existing.request_hash != rh:\n raise HTTPException(status_code=409, detail=\"Idempotency-Key reuse with different payload\")\n return json.loads(existing.response_json)\n\n # Create new payment (stubbed)\n pid = hashlib.md5(f\"{req.tenant_id}:{idempotency_key}\".encode()).hexdigest()\n resp = CreateResp(\n id=pid,\n created_at=datetime.now(timezone.utc).isoformat(),\n echo=req,\n )\n _IDEMPO[key] = _IdempoEntry(request_hash=rh, response_json=resp.model_dump_json())\n return resp\n```\n\n```python\n# test_app.py (pytest)\nfrom fastapi.testclient import TestClient\nfrom app import app\n\nclient = TestClient(app)\n\ndef test_idempotent_replay():\n headers = {\"Idempotency-Key\": \"abc\"}\n body = {\"tenant_id\":\"t1\",\"amount_cents\":100,\"currency\":\"USD\"}\n r1 = client.post(\"/v1/payments\", json=body, headers=headers)\n r2 = client.post(\"/v1/payments\", json=body, headers=headers)\n assert r1.status_code == 200 and r2.status_code == 200\n assert r1.json() == r2.json()\n\ndef test_payload_conflict():\n headers = {\"Idempotency-Key\": \"abc\"}\n b1 = {\"tenant_id\":\"t1\",\"amount_cents\":100,\"currency\":\"USD\"}\n b2 = {\"tenant_id\":\"t1\",\"amount_cents\":200,\"currency\":\"USD\"}\n assert client.post(\"/v1/payments\", json=b1, headers=headers).status_code == 200\n assert client.post(\"/v1/payments\", json=b2, headers=headers).status_code == 409\n```\n\nNotes:\n- Replace in-memory store with a DB table and transaction.\n- Store response + request hash to detect key reuse with different payload.\n\n\nHard-mode checks: concurrency safety, idempotency, and rollback validated; add chaos tests where feasible.", "source": "WithinUsAI/GOD_Coder_100k"} {"text": "Task type: lockfree_primitive\nScenario: streaming ETL\nDomain focus: runtime systems\nPrimary language: cpp\nDifficulty: expert\nScale/SLO: p99 < 50ms\nComponent: component_rxpqevea\nConstraints: include verification strategy, include backward compatibility and migration plan, include failure modes and recovery, include security threat model (defensive only), avoid data races and undefined behavior, include deterministic replay plan, include performance model and limits\nAssume weekly network partitions.\nDeliverable: Design a lock-free primitive with memory ordering reasoning and stress tests (no UB).\n\nOutput: contract-first solution with failure modes, security posture, and test/verification strategy.\n**Contract**\n- Inputs validated at the boundary; explicit error taxonomy.\n- Idempotency for side effects via request_id; deterministic replay.\n- Backward compatibility: additive changes by default; versioned breaking changes.\n**Invariants**\n- Liveness: under bounded faults and stable network, progress occurs.\n- Isolation: tenant boundary enforced; no cross-tenant reads/writes.\n- Safety: state transitions preserve invariants; no partial commit leaks.\n**Failure modes & recovery**\n- Data corruption: checksums + scrubber; quarantine and rebuild from replicas/snapshots.\n- Network partition: minority cannot commit; clients receive retriable errors.\n- Crash during commit: WAL replay completes or transaction aborts; no torn writes.\n**Security posture (defensive)**\n- Threat model: auth/authz, injection, replay/abuse, supply chain.\n- Least privilege; secrets in managed store; audit logs for sensitive ops.\n- Input normalization, parameterized queries, path traversal protections.\n**Verification strategy**\n- Property tests against a pure reference model (state machine).\n- Deterministic simulation with fault injection (crash/partition/latency).\n- Canary + shadow traffic; invariants checked in production via assertions/metrics.\n\n**Snippet**\n```rust\n// Skeleton: SPSC ring buffer with acquire/release (outline)\nuse std::sync::atomic::{AtomicUsize, Ordering};\n\npub struct Ring {\n buf: Vec>,\n head: AtomicUsize,\n tail: AtomicUsize,\n cap: usize,\n}\n\n// Correctness sketch: producer uses Release on tail store, consumer uses Acquire on tail load.\n```\n\nExpert checks: state-machine proof sketch + model checking; upgrade/rollback rehearsed.", "source": "WithinUsAI/Omega_Genesis_Coder_100k"} {"text": "Debug and fix a subtle production bug related to caching in a e-commerce service.\nTarget platform: backend (Go).\nRequirements: identify root cause, provide patch, and add regression tests.\nConstraints: must include type hints where applicable, must be observable (logs/metrics/traces), must include documentation/comments.\nDifficulty: hard. Include rollback strategy.\n\nOutput: production-oriented blueprint with code where appropriate.\nDeliverable: production-grade reference implementation (FastAPI) + tests.\n\n```python\n# app.py\nfrom __future__ import annotations\n\nimport hashlib\nimport json\nfrom dataclasses import dataclass\nfrom datetime import datetime, timezone\nfrom typing import Any, Optional\n\nfrom fastapi import FastAPI, Header, HTTPException\nfrom pydantic import BaseModel, Field\n\napp = FastAPI(title=\"Idempotent API\")\n\nclass CreateReq(BaseModel):\n tenant_id: str = Field(min_length=1)\n amount_cents: int = Field(ge=0)\n currency: str = Field(min_length=3, max_length=3)\n\nclass CreateResp(BaseModel):\n id: str\n created_at: str\n echo: CreateReq\n\n@dataclass\nclass _IdempoEntry:\n request_hash: str\n response_json: str\n\n# In production: Postgres table with UNIQUE(tenant_id, key)\n_IDEMPO: dict[tuple[str, str], _IdempoEntry] = {}\n\ndef _hash_req(req: CreateReq) -> str:\n raw = req.model_dump_json()\n return hashlib.sha256(raw.encode(\"utf-8\")).hexdigest()\n\n@app.post(\"/v1/payments\", response_model=CreateResp)\ndef create_payment(\n req: CreateReq,\n idempotency_key: Optional[str] = Header(default=None, alias=\"Idempotency-Key\"),\n) -> Any:\n if not idempotency_key:\n raise HTTPException(status_code=400, detail=\"Missing Idempotency-Key\")\n if len(idempotency_key) > 128:\n raise HTTPException(status_code=400, detail=\"Idempotency-Key too long\")\n\n key = (req.tenant_id, idempotency_key)\n rh = _hash_req(req)\n\n existing = _IDEMPO.get(key)\n if existing:\n if existing.request_hash != rh:\n raise HTTPException(status_code=409, detail=\"Idempotency-Key reuse with different payload\")\n return json.loads(existing.response_json)\n\n # Create new payment (stubbed)\n pid = hashlib.md5(f\"{req.tenant_id}:{idempotency_key}\".encode()).hexdigest()\n resp = CreateResp(\n id=pid,\n created_at=datetime.now(timezone.utc).isoformat(),\n echo=req,\n )\n _IDEMPO[key] = _IdempoEntry(request_hash=rh, response_json=resp.model_dump_json())\n return resp\n```\n\n```python\n# test_app.py (pytest)\nfrom fastapi.testclient import TestClient\nfrom app import app\n\nclient = TestClient(app)\n\ndef test_idempotent_replay():\n headers = {\"Idempotency-Key\": \"abc\"}\n body = {\"tenant_id\":\"t1\",\"amount_cents\":100,\"currency\":\"USD\"}\n r1 = client.post(\"/v1/payments\", json=body, headers=headers)\n r2 = client.post(\"/v1/payments\", json=body, headers=headers)\n assert r1.status_code == 200 and r2.status_code == 200\n assert r1.json() == r2.json()\n\ndef test_payload_conflict():\n headers = {\"Idempotency-Key\": \"abc\"}\n b1 = {\"tenant_id\":\"t1\",\"amount_cents\":100,\"currency\":\"USD\"}\n b2 = {\"tenant_id\":\"t1\",\"amount_cents\":200,\"currency\":\"USD\"}\n assert client.post(\"/v1/payments\", json=b1, headers=headers).status_code == 200\n assert client.post(\"/v1/payments\", json=b2, headers=headers).status_code == 409\n```\n\nNotes:\n- Replace in-memory store with a DB table and transaction.\n- Store response + request hash to detect key reuse with different payload.\n\n\nHard-mode checks: concurrency safety, idempotency, and rollback validated; add chaos tests where feasible.", "source": "WithinUsAI/GOD_Coder_100k"} {"text": "Design a small, production-grade Python API for task scheduling.\nRequirements: define data models and interfaces, implement reference version, include tests.\nConstraints: must include docstrings, must include tests.\nDifficulty: hard. Avoid quadratic behavior on large inputs.\n\nDeliverable: API + reference implementation + tests.\nArchitecture:\n- Public facade class coordinating concerns (parsing, validation, persistence)\n- Small pure functions for testability\n- No global state; dependency injection for filesystem I/O\n\n```python\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom pathlib import Path\nfrom typing import Protocol, Iterable\nimport json\n\nclass Store(Protocol):\n def write_text(self, path: Path, data: str) -> None: ...\n\nclass FSStore:\n def write_text(self, path: Path, data: str) -> None:\n path.parent.mkdir(parents=True, exist_ok=True)\n path.write_text(data, encoding=\"utf-8\")\n\n@dataclass(frozen=True, slots=True)\nclass Item:\n name: str\n qty: int\n\ndef parse_items(lines: Iterable[str]) -> list[Item]:\n out: list[Item] = []\n for i, line in enumerate(lines, 1):\n s = line.strip()\n if not s:\n continue\n obj = json.loads(s)\n if not isinstance(obj, dict):\n raise ValueError(f\"line {i}: expected object\")\n name = obj.get(\"name\")\n qty = obj.get(\"qty\")\n if not isinstance(name, str) or not name:\n raise ValueError(f\"line {i}: name must be str\")\n if not isinstance(qty, int) or qty < 0:\n raise ValueError(f\"line {i}: qty must be non-negative int\")\n out.append(Item(name, qty))\n return out\n\nclass InventoryWriter:\n def __init__(self, base_dir: Path, store: Store | None = None) -> None:\n self._base = base_dir\n self._store: Store = store or FSStore()\n\n def write(self, rel_path: str, items: list[Item]) -> Path:\n dst = (self._base / rel_path).resolve()\n base = self._base.resolve()\n if dst != base and base not in dst.parents:\n raise ValueError(\"unsafe path traversal\")\n payload = json.dumps([item.__dict__ for item in items], ensure_ascii=False)\n self._store.write_text(dst, payload)\n return dst\n```\n\n```python\nimport json\nfrom pathlib import Path\nimport pytest\nfrom module_under_test import InventoryWriter, parse_items\n\ndef test_parse_items_valid():\n lines = [json.dumps({\"name\":\"x\",\"qty\":1})]\n assert parse_items(lines)[0].name == \"x\"\n\ndef test_writer_blocks_traversal(tmp_path: Path):\n w = InventoryWriter(tmp_path)\n with pytest.raises(ValueError):\n w.write(\"../evil.json\", [])\n```", "source": "WithinUsAI/python_GOD_coder_100k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Produce an offline-first self-evolving code assistant architecture named `wb1ajfq`.\nMust include: module layout, patch-safety policy, evaluation gates (tests/lint/types), versioned memory index.\n\nArchitecture: `wb1ajfq` (offline-first, self-evolving)\n\nModules\n- core/loop.py: evolve → validate → accept/reject (bounded iterations)\n- patching/: diff builder, safe apply, atomic writes, rollback points\n- policy/: allowlist paths, deny globs (.git/, __pycache__/, binaries), patch size caps\n- signals/: parse pytest/ruff/mypy into normalized findings\n- memory/index.jsonl: append-only snapshots (hashes, metrics, rationale)\n\nSafety gates\n- refuse path traversal/symlink escapes; never edit binaries\n- accept only if tests/lint/types stay green or improve", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Build an elite-grade solution in the domain of high-performance services for scenario: inventory & ordering.\nPrimary language: bash.\nDifficulty: expert.\nConstraints: include invariants and failure modes, make the interface contract explicit, provide rollout and rollback guidance, include tests or verification strategy, avoid undefined behavior and data races.\nComponent: component_qvudkgn.\nAssume partial network partitions occur weekly.\nTask: Provide SLOs, alerting, dashboards, runbooks, and incident playbook. Include chaos testing and safe rollout strategy.\n\nOutput: rigorous solution with invariants, failure modes, and performance notes.\nOutput: SLOs + alerts + runbooks + chaos strategy.\n\n**SLOs**\n- Availability: 99.9% monthly\n- Latency: p95 < 200ms, p99 < 400ms\n- Error rate: < 0.1%\n\n**Alerts**\n- Burn-rate alerts for SLOs (fast/slow windows)\n- Saturation: CPU, memory, queue depth, DB connections\n- Dependency health: cache hit rate drop, downstream timeouts\n\n**Runbooks**\n- Triage: identify blast radius, feature-flag rollback, capacity mitigation\n- Post-incident: timeline, contributing factors, action items\n\n**Chaos**\n- Inject latency, partial outages, and restarts in staging; verify steady-state SLOs.\n\n\nExpert checks: state-machine reasoning, concurrency stress, and upgrade/rollback validated.", "source": "WithinUsAI/Elite_GOD_Coder_100k"} {"text": "Refactor to typed, mostly-immutable Python and add minimal tests.\n\n```python\nclass C69869:\n def __init__(self, values): self.values=list(values)\n def mean(self): return sum(self.values)/len(self.values)\n```\nReturn `m66913.py` and `test_m66913.py`.\n\n```python\n# m66913.py\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom typing import Iterable, Tuple\n\n@dataclass(frozen=True)\nclass C69869:\n values: Tuple[float, ...]\n\n @staticmethod\n def create(values: Iterable[float]) -> \"C69869\":\n vals = tuple(float(v) for v in values)\n if not vals: raise ValueError(\"empty\")\n return C69869(vals)\n\n def mean(self) -> float:\n return sum(self.values)/len(self.values)\n```\n\n```python\n# test_m66913.py\nimport pytest\nfrom m66913 import C69869\n\ndef test_mean():\n assert C69869.create([1,2,3]).mean() == 2.0\ndef test_empty():\n with pytest.raises(ValueError):\n C69869.create([])\n```", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Refactor to modern typed Python with immutability and tests.\n\nFile: w7cpgby8_xu.py\n```python\nclass Gmdw7Njuc:\n def __init__(self, name, values):\n self.name = name\n self.values = list(values)\n def add(self, v):\n self.values.append(v)\n def mean(self):\n s = 0\n for x in self.values:\n s += x\n return s / len(self.values)\n```\n\nReturn full new w7cpgby8_xu.py and test_w7cpgby8_xu.py.\n\n# w7cpgby8_xu.py\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom typing import Iterable, Tuple\n\n@dataclass(frozen=True)\nclass Gmdw7Njuc:\n name: str\n values: Tuple[float, ...]\n\n @staticmethod\n def create(name: str, values: Iterable[float]) -> \"Gmdw7Njuc\":\n vals = tuple(float(v) for v in values)\n if not vals:\n raise ValueError(\"values must be non-empty\")\n return Gmdw7Njuc(name=name, values=vals)\n\n def add(self, v: float) -> \"Gmdw7Njuc\":\n return Gmdw7Njuc(name=self.name, values=self.values + (float(v),))\n\n def mean(self) -> float:\n return sum(self.values) / len(self.values)\n\n# test_w7cpgby8_xu.py\nimport pytest\nfrom w7cpgby8_xu import Gmdw7Njuc\n\ndef test_mean_and_add():\n c = Gmdw7Njuc.create(\"a\", [1, 2, 3])\n assert c.mean() == 2.0\n assert c.add(5).mean() == (1 + 2 + 3 + 5) / 4\n\ndef test_empty_raises():\n with pytest.raises(ValueError):\n Gmdw7Njuc.create(\"x\", [])", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Refactor to typed, mostly-immutable Python and add minimal tests.\n\n```python\nclass C55989:\n def __init__(self, values): self.values=list(values)\n def mean(self): return sum(self.values)/len(self.values)\n```\nReturn `m58153.py` and `test_m58153.py`.\n\n```python\n# m58153.py\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom typing import Iterable, Tuple\n\n@dataclass(frozen=True)\nclass C55989:\n values: Tuple[float, ...]\n\n @staticmethod\n def create(values: Iterable[float]) -> \"C55989\":\n vals = tuple(float(v) for v in values)\n if not vals: raise ValueError(\"empty\")\n return C55989(vals)\n\n def mean(self) -> float:\n return sum(self.values)/len(self.values)\n```\n\n```python\n# test_m58153.py\nimport pytest\nfrom m58153 import C55989\n\ndef test_mean():\n assert C55989.create([1,2,3]).mean() == 2.0\ndef test_empty():\n with pytest.raises(ValueError):\n C55989.create([])\n```", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Fix a bug and add tests.\n\nFile: i0fpo75ek9.py\n```python\ndef hx7o8xi1_(n: int) -> int:\n \"\"\"Sum 1..n inclusive.\"\"\"\n if n < 0:\n raise ValueError(\"n must be non-negative\")\n total = 0\n for k in range(n): # BUG: should include n\n total += k\n return total\n```\n\nReturn unified diffs for i0fpo75ek9.py and test_i0fpo75ek9.py (pytest).\n\n*** Begin Patch\n*** Update File: i0fpo75ek9.py\n@@\n def hx7o8xi1_(n: int) -> int:\n@@\n total = 0\n- for k in range(n): # BUG: should include n\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_i0fpo75ek9.py\n+import pytest\n+from i0fpo75ek9 import hx7o8xi1_\n+\n+def test_zero():\n+ assert hx7o8xi1_(0) == 0\n+\n+def test_one():\n+ assert hx7o8xi1_(1) == 1\n+\n+def test_small():\n+ assert hx7o8xi1_(7) == 28\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ hx7o8xi1_(-1)\n+\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Design CI/CD for a developer tooling service delivering A/B experimentation.\nTarget platform: mobile (iOS Swift).\nRequirements: pipelines, checks, artifact strategy, deployments, and rollbacks.\nConstraints: must include tests, must include clear error handling, must include type hints where applicable, must be secure-by-default, must be performant under load.\nDifficulty: medium. Include rollback strategy.\n\nOutput: design + implementation guidance suitable for shipping.\nDeliverable: CI/CD pipeline (GitHub Actions) with quality gates.\n\n```yaml\nname: ci\non:\n pull_request:\n push:\n branches: [main]\n\njobs:\n test:\n runs-on: ubuntu-latest\n steps:\n - uses: actions/checkout@v4\n - uses: actions/setup-python@v5\n with:\n python-version: \"3.11\"\n - run: python -m pip install -U pip\n - run: pip install -r requirements.txt\n - run: pip install -r requirements-dev.txt\n - run: ruff check .\n - run: mypy .\n - run: pytest -q --maxfail=1 --disable-warnings\n\n docker:\n needs: test\n runs-on: ubuntu-latest\n steps:\n - uses: actions/checkout@v4\n - uses: docker/setup-buildx-action@v3\n - run: docker build -t app:${{ github.sha }} .\n```\n\nDeployment strategy:\n- main → build → deploy to staging → smoke tests → canary to prod.\n- Rollback: redeploy previous image + DB migration rollback plan.\n\n\nChecks: input validation, tests, and safe defaults included.", "source": "WithinUsAI/GOD_Coder_100k"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: Project domain: document processing API\nImplementation stack: Go, Gin, PostgreSQL, gRPC, Prometheus, Docker\nSoftware delivery problem: schema drift during deployment\nTask type: test_strategy_implementation\nDifficulty: hard\n\nReturn a complete delivery-grade response with:\n- diagnosis or design reasoning\n- implementation\n- test plan or tests\n- rollout plan\n- rollback or compatibility note\n- verification commands\n\nRepository sketch:\nrepo/\n .github/workflows/ci.yml\n docker-compose.yml\n deploy/\n app.yaml\n\nFocus: Focus on shipping production software with rollout safety, acceptance criteria, telemetry, and maintenance quality.\n\nassistant: Diagnosis:\n- Root cause or delivery blocker: schema drift during deployment needs both implementation work and a safe shipping plan.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```yaml\nname: ci\non: [push, pull_request]\njobs:\n test:\n runs-on: ubuntu-latest\n steps:\n - uses: actions/checkout@v4\n - name: Validate\n run: echo \"validated\"\n```\n\nTests:\n```yaml\n# Verification:\n# - validate syntax\n# - run smoke workflow\n# - fail fast on broken config\n```\n\nVerification:\n- `validate workflow syntax`\n- `run CI smoke job`\n\nEngineering notes:\n- Language: YAML\n- Framework/tooling: Kubernetes\n- Stack context: Go, Gin, PostgreSQL, gRPC, Prometheus, Docker\n- Domain: document processing API\n- Task type: test_strategy_implementation\n- Difficulty: hard\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "Fix a subtle bug in a Python module used for telemetry ingestion.\nRequirements: explain root cause briefly, provide corrected code, and add regression tests.\nConstraints: must be easy to extend, must include tests, must be memory-efficient, must include type hints.\nDifficulty: expert. Provide helpful exceptions with actionable messages.\n\nDeliverable: API + reference implementation + tests.\n```python\nfrom __future__ import annotations\n\nfrom dataclasses import dataclass\nfrom pathlib import Path\nfrom typing import Iterable\nimport json\n\n\nclass ValidationError(ValueError):\n \"\"\"Raised when input validation fails.\"\"\"\n\n\ndef safe_join(base: Path, *parts: str) -> Path:\n \"\"\"Join paths while preventing traversal outside base.\"\"\"\n b = base.resolve()\n p = (b / Path(*parts)).resolve()\n if p != b and b not in p.parents:\n raise ValidationError(f\"unsafe path: {p}\")\n return p\n\n\n@dataclass(frozen=True, slots=True)\nclass Record:\n key: str\n value: int\n\n\ndef parse_jsonl(lines: Iterable[str]) -> list[Record]:\n out: list[Record] = []\n for idx, line in enumerate(lines, 1):\n s = line.strip()\n if not s:\n continue\n try:\n obj = json.loads(s)\n except json.JSONDecodeError as e:\n raise ValidationError(f\"line {idx}: invalid json\") from e\n if not isinstance(obj, dict):\n raise ValidationError(f\"line {idx}: expected object\")\n key = obj.get(\"key\")\n val = obj.get(\"value\")\n if not isinstance(key, str) or not key:\n raise ValidationError(f\"line {idx}: key must be non-empty str\")\n if not isinstance(val, int):\n raise ValidationError(f\"line {idx}: value must be int\")\n out.append(Record(key, val))\n return out\n\n\ndef write_jsonl(base: Path, rel: str, records: Iterable[Record]) -> Path:\n base.mkdir(parents=True, exist_ok=True)\n dst = safe_join(base, rel)\n dst.parent.mkdir(parents=True, exist_ok=True)\n with dst.open(\"w\", encoding=\"utf-8\", newline=\"\\n\") as f:\n for r in records:\n f.write(json.dumps({\"key\": r.key, \"value\": r.value}, ensure_ascii=False) + \"\\n\")\n return dst\n```\n\n```python\n# tests (pytest-style)\nimport json\nfrom pathlib import Path\nimport pytest\nfrom module_under_test import ValidationError, Record, parse_jsonl, write_jsonl\n\ndef test_parse_ok():\n lines = [json.dumps({\"key\":\"a\",\"value\":1}), json.dumps({\"key\":\"b\",\"value\":2})]\n assert parse_jsonl(lines) == [Record(\"a\",1), Record(\"b\",2)]\n\ndef test_parse_rejects_bad_json():\n with pytest.raises(ValidationError):\n parse_jsonl([\"{not json}\"])\n\ndef test_safe_join_blocks_traversal(tmp_path: Path):\n with pytest.raises(ValidationError):\n write_jsonl(tmp_path, \"../x.jsonl\", [Record(\"a\",1)])\n```", "source": "WithinUsAI/python_GOD_coder_100k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Refactor to modern typed Python with immutability and tests.\n\nFile: xj_mzq9d.py\n```python\nclass R4Y24D:\n def __init__(self, name, values):\n self.name = name\n self.values = list(values)\n def add(self, v):\n self.values.append(v)\n def mean(self):\n s = 0\n for x in self.values:\n s += x\n return s / len(self.values)\n```\n\nReturn full new xj_mzq9d.py and test_xj_mzq9d.py.\n\n# xj_mzq9d.py\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom typing import Iterable, Tuple\n\n@dataclass(frozen=True)\nclass R4Y24D:\n name: str\n values: Tuple[float, ...]\n\n @staticmethod\n def create(name: str, values: Iterable[float]) -> \"R4Y24D\":\n vals = tuple(float(v) for v in values)\n if not vals:\n raise ValueError(\"values must be non-empty\")\n return R4Y24D(name=name, values=vals)\n\n def add(self, v: float) -> \"R4Y24D\":\n return R4Y24D(name=self.name, values=self.values + (float(v),))\n\n def mean(self) -> float:\n return sum(self.values) / len(self.values)\n\n# test_xj_mzq9d.py\nimport pytest\nfrom xj_mzq9d import R4Y24D\n\ndef test_mean_and_add():\n c = R4Y24D.create(\"a\", [1, 2, 3])\n assert c.mean() == 2.0\n assert c.add(5).mean() == (1 + 2 + 3 + 5) / 4\n\ndef test_empty_raises():\n with pytest.raises(ValueError):\n R4Y24D.create(\"x\", [])", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Produce an offline-first self-evolving code assistant architecture named `dijtmt412jsx`.\nMust include: module layout, patch-safety policy, evaluation gates (tests/lint/types), versioned memory index.\n\nArchitecture: `dijtmt412jsx` (offline-first, self-evolving)\n\nModules\n- core/loop.py: evolve → validate → accept/reject (bounded iterations)\n- patching/: diff builder, safe apply, atomic writes, rollback points\n- policy/: allowlist paths, deny globs (.git/, __pycache__/, binaries), patch size caps\n- signals/: parse pytest/ruff/mypy into normalized findings\n- memory/index.jsonl: append-only snapshots (hashes, metrics, rationale)\n\nSafety gates\n- refuse path traversal/symlink escapes; never edit binaries\n- accept only if tests/lint/types stay green or improve", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Produce an offline-first self-evolving code assistant architecture named `lewp26cre7v`.\nMust include: module layout, patch-safety policy, evaluation gates (tests/lint/types), versioned memory index.\n\nArchitecture: `lewp26cre7v` (offline-first, self-evolving)\n\nModules\n- core/loop.py: evolve → validate → accept/reject (bounded iterations)\n- patching/: diff builder, safe apply, atomic writes, rollback points\n- policy/: allowlist paths, deny globs (.git/, __pycache__/, binaries), patch size caps\n- signals/: parse pytest/ruff/mypy into normalized findings\n- memory/index.jsonl: append-only snapshots (hashes, metrics, rationale)\n\nSafety gates\n- refuse path traversal/symlink escapes; never edit binaries\n- accept only if tests/lint/types stay green or improve", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Optimize while preserving behavior.\n\nFile: ekr8wxiwu.py\n```python\ndef s9cz8l_1u(xs):\n out = []\n for x in xs:\n if x not in out:\n out.append(x)\n return out\n```\n\nRequirements: preserve first-seen order; O(n) average; add types + docstring.\n\n# ekr8wxiwu.py\nfrom __future__ import annotations\nfrom typing import Iterable, List, Set, TypeVar\n\nT = TypeVar(\"T\")\n\ndef s9cz8l_1u(xs: Iterable[T]) -> List[T]:\n \"\"\"Return unique items preserving first-seen order.\"\"\"\n seen: Set[T] = set()\n out: List[T] = []\n for x in xs:\n if x in seen:\n continue\n seen.add(x)\n out.append(x)\n return out", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Fix a bug and add tests.\n\nFile: dl8agth6mbmb.py\n```python\ndef jodacvwi66(n: int) -> int:\n \"\"\"Sum 1..n inclusive.\"\"\"\n if n < 0:\n raise ValueError(\"n must be non-negative\")\n total = 0\n for k in range(n): # BUG: should include n\n total += k\n return total\n```\n\nReturn unified diffs for dl8agth6mbmb.py and test_dl8agth6mbmb.py (pytest).\n\n*** Begin Patch\n*** Update File: dl8agth6mbmb.py\n@@\n def jodacvwi66(n: int) -> int:\n@@\n total = 0\n- for k in range(n): # BUG: should include n\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_dl8agth6mbmb.py\n+import pytest\n+from dl8agth6mbmb import jodacvwi66\n+\n+def test_zero():\n+ assert jodacvwi66(0) == 0\n+\n+def test_one():\n+ assert jodacvwi66(1) == 1\n+\n+def test_small():\n+ assert jodacvwi66(7) == 28\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ jodacvwi66(-1)\n+\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Build an elite-grade solution in the domain of distributed systems for scenario: payment processing.\nPrimary language: typescript.\nDifficulty: expert.\nConstraints: avoid undefined behavior and data races, assume untrusted inputs; validate and sanitize, include invariants and failure modes, document performance characteristics, make the interface contract explicit.\nComponent: component_gkgtzco.\nAssume compliance requires data deletion with proofs.\nTask: Provide threat model, secure-by-default design, and defensive implementation patterns. No offensive/exploit content; focus on prevention and detection.\n\nOutput: rigorous solution with invariants, failure modes, and performance notes.\nOutput: threat model + defensive design + detection.\n\n**Threat model**\n- Auth: token theft → short-lived tokens, rotation, audience checks\n- AuthZ: privilege escalation → centralized policy checks, tenant isolation tests\n- Input: injection → strict validation, parameterized queries, output encoding\n- Supply chain: dependencies → lockfiles, signature verification, SBOM\n\n**Defensive patterns**\n- Idempotency keys for side effects; replay-safe handlers\n- Secrets in managed store; never logs\n- Audit logging for sensitive ops; tamper-evident storage\n\n**Detection**\n- Alert on unusual auth failures, access pattern anomalies, and data exfil signals.\n\n\nExpert checks: state-machine reasoning, concurrency stress, and upgrade/rollback validated.", "source": "WithinUsAI/Elite_GOD_Coder_100k"} {"text": "Design a production system for customer support supporting audit logs.\nTarget platform: ML (PyTorch + serving).\nRequirements: APIs, data model, scaling strategy, failure modes, and security.\nConstraints: must include clear error handling, must be observable (logs/metrics/traces), must be production-ready, must include type hints where applicable.\nDifficulty: hard. Assume schema evolves frequently; design for migrations.\n\nOutput: design + implementation guidance suitable for shipping.\nDeliverable: system design with APIs, data model, and operational plan.\n\n**High-level architecture**\n- Edge: API Gateway + WAF\n- Core service: stateless app pods behind L7 LB\n- Data: Postgres (primary), Redis (cache + rate limit tokens), Object storage (uploads if needed)\n- Async: message queue (e.g., SQS/Rabbit) + worker pool for background jobs\n- Observability: structured logs + metrics + tracing\n\n**APIs (example)**\n- `POST /v1/{resource}` create (idempotent via `Idempotency-Key`)\n- `GET /v1/{resource}/{id}` read\n- `POST /v1/{resource}/{id}:action` command endpoint when side effects exist\n\n**Data model (Postgres)**\n- `resources(id UUID PK, tenant_id UUID, status TEXT, payload JSONB, created_at, updated_at)`\n- Unique constraint for idempotency: `(tenant_id, idempotency_key)` in a separate table:\n - `idempotency(tenant_id, key TEXT, request_hash TEXT, response JSONB, created_at, PRIMARY KEY(tenant_id,key))`\n\n**Scaling**\n- App layer scales horizontally; keep sessions out of process.\n- Cache reads in Redis; write-through invalidation on mutations.\n- Use connection pooling; consider read replicas for heavy reads.\n\n**Failure modes**\n- Retries: only for safe/ idempotent operations; exponential backoff + jitter.\n- Partial failures: background jobs must be idempotent; use a de-dup key.\n\n**Security**\n- AuthN: JWT/OIDC; AuthZ: RBAC/ABAC with tenant isolation\n- Validate all inputs; enforce per-tenant quotas/rate limits.\n\n**Rollout**\n- Dark launch + feature flags; canary; rapid rollback by toggling flags.\n\n\nHard-mode checks: concurrency safety, idempotency, and rollback validated; add chaos tests where feasible.", "source": "WithinUsAI/GOD_Coder_100k"} {"text": "Task type: compiler_frontend\nScenario: edge sync\nDomain focus: large-scale ML systems\nPrimary language: go\nDifficulty: expert\nScale/SLO: 50 TB/day ingestion\nComponent: component_cuzupwyq\nConstraints: avoid data races and undefined behavior, include backward compatibility and migration plan, include failure modes and recovery, include test vectors and fuzz strategy, include security threat model (defensive only)\nAssume schema changes every sprint; must be backward compatible.\nDeliverable: Design a DSL language frontend: lexer/parser, AST, type checking, error reporting, and tests.\n\nOutput: rigorous design + invariants + verification plan + implementation sketch.\n**Contract**\n- Inputs validated at the boundary; explicit error taxonomy.\n- Idempotency for side effects via request_id; deterministic replay.\n- Backward compatibility: additive changes by default; versioned breaking changes.\n**Invariants**\n- Determinism: replay of the same event log yields identical outputs.\n- Isolation: tenant boundary enforced; no cross-tenant reads/writes.\n- Safety: state transitions preserve invariants; no partial commit leaks.\n**Failure modes & recovery**\n- Network partition: minority cannot commit; clients receive retriable errors.\n- Duplicate requests: de-duplicate by (tenant, request_id) returning cached response.\n- Crash during commit: WAL replay completes or transaction aborts; no torn writes.\n**Security posture (defensive)**\n- Threat model: auth/authz, injection, replay/abuse, supply chain.\n- Least privilege; secrets in managed store; audit logs for sensitive ops.\n- Input normalization, parameterized queries, path traversal protections.\n**Verification strategy**\n- Property tests against a pure reference model (state machine).\n- Canary + shadow traffic; invariants checked in production via assertions/metrics.\n- Fuzzing of parsers/framers/validators with corpus seeds.\n\n**Snippet**\n```text\nImplementation sketch: factor pure state-machine core; adapters for I/O; add deterministic replay log.\n```\nExpert checks: state-machine proof sketch + model checking; upgrade/rollback rehearsed.", "source": "WithinUsAI/Omega_Genesis_Coder_100k"} {"text": "Fix the bug and add pytest tests.\n\n```python\ndef f98907(n: int) -> int:\n # sum 1..n inclusive\n if n < 0: raise ValueError\n total = 0\n for k in range(n): # BUG\n total += k\n return total\n```\nReturn unified diffs for `m42701.py` and `test_m42701.py`.\n\n*** Begin Patch\n*** Update File: m42701.py\n@@\n def f98907(n: int) -> int:\n@@\n- for k in range(n): # BUG\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_m42701.py\n+import pytest\n+from m42701 import f98907\n+\n+def test_small():\n+ assert f98907(7) == 28\n+\n+def test_zero():\n+ assert f98907(0) == 0\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ f98907(-1)\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Refactor to modern typed Python with immutability and tests.\n\nFile: noq2sd0.py\n```python\nclass Wreukg6Qdpve:\n def __init__(self, name, values):\n self.name = name\n self.values = list(values)\n def add(self, v):\n self.values.append(v)\n def mean(self):\n s = 0\n for x in self.values:\n s += x\n return s / len(self.values)\n```\n\nReturn full new noq2sd0.py and test_noq2sd0.py.\n\n# noq2sd0.py\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom typing import Iterable, Tuple\n\n@dataclass(frozen=True)\nclass Wreukg6Qdpve:\n name: str\n values: Tuple[float, ...]\n\n @staticmethod\n def create(name: str, values: Iterable[float]) -> \"Wreukg6Qdpve\":\n vals = tuple(float(v) for v in values)\n if not vals:\n raise ValueError(\"values must be non-empty\")\n return Wreukg6Qdpve(name=name, values=vals)\n\n def add(self, v: float) -> \"Wreukg6Qdpve\":\n return Wreukg6Qdpve(name=self.name, values=self.values + (float(v),))\n\n def mean(self) -> float:\n return sum(self.values) / len(self.values)\n\n# test_noq2sd0.py\nimport pytest\nfrom noq2sd0 import Wreukg6Qdpve\n\ndef test_mean_and_add():\n c = Wreukg6Qdpve.create(\"a\", [1, 2, 3])\n assert c.mean() == 2.0\n assert c.add(5).mean() == (1 + 2 + 3 + 5) / 4\n\ndef test_empty_raises():\n with pytest.raises(ValueError):\n Wreukg6Qdpve.create(\"x\", [])", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Fix a bug and add tests.\n\nFile: xgitnp.py\n```python\ndef fu17sjy7(n: int) -> int:\n \"\"\"Sum 1..n inclusive.\"\"\"\n if n < 0:\n raise ValueError(\"n must be non-negative\")\n total = 0\n for k in range(n): # BUG: should include n\n total += k\n return total\n```\n\nReturn unified diffs for xgitnp.py and test_xgitnp.py (pytest).\n\n*** Begin Patch\n*** Update File: xgitnp.py\n@@\n def fu17sjy7(n: int) -> int:\n@@\n total = 0\n- for k in range(n): # BUG: should include n\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_xgitnp.py\n+import pytest\n+from xgitnp import fu17sjy7\n+\n+def test_zero():\n+ assert fu17sjy7(0) == 0\n+\n+def test_one():\n+ assert fu17sjy7(1) == 1\n+\n+def test_small():\n+ assert fu17sjy7(7) == 28\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ fu17sjy7(-1)\n+\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Fix the bug and add pytest tests.\n\n```python\ndef f99670(n: int) -> int:\n # sum 1..n inclusive\n if n < 0: raise ValueError\n total = 0\n for k in range(n): # BUG\n total += k\n return total\n```\nReturn unified diffs for `m42810.py` and `test_m42810.py`.\n\n*** Begin Patch\n*** Update File: m42810.py\n@@\n def f99670(n: int) -> int:\n@@\n- for k in range(n): # BUG\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_m42810.py\n+import pytest\n+from m42810 import f99670\n+\n+def test_small():\n+ assert f99670(7) == 28\n+\n+def test_zero():\n+ assert f99670(0) == 0\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ f99670(-1)\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Refactor to modern typed Python with immutability and tests.\n\nFile: putd1u.py\n```python\nclass F3J8Jh10Y:\n def __init__(self, name, values):\n self.name = name\n self.values = list(values)\n def add(self, v):\n self.values.append(v)\n def mean(self):\n s = 0\n for x in self.values:\n s += x\n return s / len(self.values)\n```\n\nReturn full new putd1u.py and test_putd1u.py.\n\n# putd1u.py\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom typing import Iterable, Tuple\n\n@dataclass(frozen=True)\nclass F3J8Jh10Y:\n name: str\n values: Tuple[float, ...]\n\n @staticmethod\n def create(name: str, values: Iterable[float]) -> \"F3J8Jh10Y\":\n vals = tuple(float(v) for v in values)\n if not vals:\n raise ValueError(\"values must be non-empty\")\n return F3J8Jh10Y(name=name, values=vals)\n\n def add(self, v: float) -> \"F3J8Jh10Y\":\n return F3J8Jh10Y(name=self.name, values=self.values + (float(v),))\n\n def mean(self) -> float:\n return sum(self.values) / len(self.values)\n\n# test_putd1u.py\nimport pytest\nfrom putd1u import F3J8Jh10Y\n\ndef test_mean_and_add():\n c = F3J8Jh10Y.create(\"a\", [1, 2, 3])\n assert c.mean() == 2.0\n assert c.add(5).mean() == (1 + 2 + 3 + 5) / 4\n\ndef test_empty_raises():\n with pytest.raises(ValueError):\n F3J8Jh10Y.create(\"x\", [])", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Fix a bug and add tests.\n\nFile: ssjc0g76_.py\n```python\ndef kcz97n7fj(n: int) -> int:\n \"\"\"Sum 1..n inclusive.\"\"\"\n if n < 0:\n raise ValueError(\"n must be non-negative\")\n total = 0\n for k in range(n): # BUG: should include n\n total += k\n return total\n```\n\nReturn unified diffs for ssjc0g76_.py and test_ssjc0g76_.py (pytest).\n\n*** Begin Patch\n*** Update File: ssjc0g76_.py\n@@\n def kcz97n7fj(n: int) -> int:\n@@\n total = 0\n- for k in range(n): # BUG: should include n\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_ssjc0g76_.py\n+import pytest\n+from ssjc0g76_ import kcz97n7fj\n+\n+def test_zero():\n+ assert kcz97n7fj(0) == 0\n+\n+def test_one():\n+ assert kcz97n7fj(1) == 1\n+\n+def test_small():\n+ assert kcz97n7fj(7) == 28\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ kcz97n7fj(-1)\n+\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Task type: lockfree_primitive\nScenario: streaming ETL\nDomain focus: constraint solving\nPrimary language: cpp\nDifficulty: hard\nScale/SLO: 1M msgs/min\nComponent: component_oirczvsp\nConstraints: avoid data races and undefined behavior, include backward compatibility and migration plan, include test vectors and fuzz strategy, include performance model and limits, explicit contracts and invariants, assume adversarial inputs; validate everything\nAssume hostile inputs and targeted abuse patterns.\nDeliverable: Design a lock-free primitive with memory ordering reasoning and stress tests (no UB).\n\nOutput: contract-first solution with failure modes, security posture, and test/verification strategy.\n**Contract**\n- Inputs validated at the boundary; explicit error taxonomy.\n- Idempotency for side effects via request_id; deterministic replay.\n- Backward compatibility: additive changes by default; versioned breaking changes.\n**Invariants**\n- Isolation: tenant boundary enforced; no cross-tenant reads/writes.\n- Liveness: under bounded faults and stable network, progress occurs.\n- Determinism: replay of the same event log yields identical outputs.\n**Failure modes & recovery**\n- Duplicate requests: de-duplicate by (tenant, request_id) returning cached response.\n- Crash during commit: WAL replay completes or transaction aborts; no torn writes.\n- Network partition: minority cannot commit; clients receive retriable errors.\n**Security posture (defensive)**\n- Threat model: auth/authz, injection, replay/abuse, supply chain.\n- Least privilege; secrets in managed store; audit logs for sensitive ops.\n- Input normalization, parameterized queries, path traversal protections.\n**Verification strategy**\n- Canary + shadow traffic; invariants checked in production via assertions/metrics.\n- Fuzzing of parsers/framers/validators with corpus seeds.\n- Property tests against a pure reference model (state machine).\n\n**Snippet**\n```rust\n// Skeleton: SPSC ring buffer with acquire/release (outline)\nuse std::sync::atomic::{AtomicUsize, Ordering};\n\npub struct Ring {\n buf: Vec>,\n head: AtomicUsize,\n tail: AtomicUsize,\n cap: usize,\n}\n\n// Correctness sketch: producer uses Release on tail store, consumer uses Acquire on tail load.\n```\n\nHard checks: fault injection tests gate merges; perf thresholds enforced in CI.", "source": "WithinUsAI/Omega_Genesis_Coder_100k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Fix a bug and add tests.\n\nFile: lwrulc436dl.py\n```python\ndef a4ja0eu4gsc7(n: int) -> int:\n \"\"\"Sum 1..n inclusive.\"\"\"\n if n < 0:\n raise ValueError(\"n must be non-negative\")\n total = 0\n for k in range(n): # BUG: should include n\n total += k\n return total\n```\n\nReturn unified diffs for lwrulc436dl.py and test_lwrulc436dl.py (pytest).\n\n*** Begin Patch\n*** Update File: lwrulc436dl.py\n@@\n def a4ja0eu4gsc7(n: int) -> int:\n@@\n total = 0\n- for k in range(n): # BUG: should include n\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_lwrulc436dl.py\n+import pytest\n+from lwrulc436dl import a4ja0eu4gsc7\n+\n+def test_zero():\n+ assert a4ja0eu4gsc7(0) == 0\n+\n+def test_one():\n+ assert a4ja0eu4gsc7(1) == 1\n+\n+def test_small():\n+ assert a4ja0eu4gsc7(7) == 28\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ a4ja0eu4gsc7(-1)\n+\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: Language: Bash\nFramework/tooling: curl\nDomain: observability collector\nLogic challenge: CI failures after dependency upgrade\nTask type: cross_stack_outage_fix\nDifficulty: expert\n\nReturn a rigorous engineering answer:\n- identify the hidden root cause or logical failure\n- present the corrected implementation\n- add tests that prove the fix\n- list verification commands\n- explain why naive fixes are insufficient when relevant\n\nRepository sketch:\nrepo/\n scripts/\n run.sh\n deploy.sh\n tests/\n smoke.sh\n\nFocus: Focus on staff-level problem solving with multi-file patches, rollout implications, performance and security tradeoffs.\n\nassistant: Diagnosis:\n- Staff-level diagnosis: CI failures after dependency upgrade impacts correctness, operability, and future maintenance, so the fix must be minimal where possible but complete where necessary.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```bash\n#!/usr/bin/env bash\nset -euo pipefail\n\ninput=\"${1:-}\"\nif [[ -z \"$input\" ]]; then\n echo \"missing input\" >&2\n exit 1\nfi\n\nprintf '%s\n' \"$input\" | tr -d '\r'\n```\n\nTests:\n```bash\noutput=\"$(bash scripts/run.sh \"abc\")\"\ntest \"$output\" = \"abc\"\n```\n\nVerification:\n- `bash tests/smoke.sh`\n- `shellcheck scripts/*.sh`\n\nEngineering notes:\n- Language: Bash\n- Framework/tooling: curl\n- Stack context: ASP.NET Core, SQL Server, EF Core, xUnit, Docker\n- Domain: observability collector\n- Task type: cross_stack_outage_fix\n- Difficulty: expert\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "Refactor an existing codebase in customer support to support caching cleanly.\nTarget platform: infra (Docker + Kubernetes).\nRequirements: propose new modules/layers, dependency boundaries, and migration plan.\nConstraints: must be production-ready, must include clear error handling, must include tests.\nDifficulty: easy. Assume schema evolves frequently; design for migrations.\n\nOutput: production-oriented blueprint with code where appropriate.\nDeliverable: refactor plan + module boundaries.\n\n**Proposed modules**\n- `domain/` pure business logic (no I/O)\n- `adapters/` DB, cache, external APIs\n- `api/` request/response validation and routing\n- `observability/` logging/metrics/tracing\n- `tests/` unit + integration suites\n\n**Migration plan**\n1. Introduce new interfaces + adapters behind feature flags.\n2. Dual-write or read-compat layer if schema changes.\n3. Incremental cutover; deprecate legacy module.\n\nKey rule: dependencies flow inward; domain has no framework imports.\n\n\nChecks: input validation, tests, and safe defaults included.", "source": "WithinUsAI/GOD_Coder_100k"} {"text": "Refactor to typed, mostly-immutable Python and add minimal tests.\n\n```python\nclass C27826:\n def __init__(self, values): self.values=list(values)\n def mean(self): return sum(self.values)/len(self.values)\n```\nReturn `m40602.py` and `test_m40602.py`.\n\n```python\n# m40602.py\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom typing import Iterable, Tuple\n\n@dataclass(frozen=True)\nclass C27826:\n values: Tuple[float, ...]\n\n @staticmethod\n def create(values: Iterable[float]) -> \"C27826\":\n vals = tuple(float(v) for v in values)\n if not vals: raise ValueError(\"empty\")\n return C27826(vals)\n\n def mean(self) -> float:\n return sum(self.values)/len(self.values)\n```\n\n```python\n# test_m40602.py\nimport pytest\nfrom m40602 import C27826\n\ndef test_mean():\n assert C27826.create([1,2,3]).mean() == 2.0\ndef test_empty():\n with pytest.raises(ValueError):\n C27826.create([])\n```", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: Language: Java\nFramework/tooling: Gradle\nDomain: repo automation\nLogic challenge: mismatched API contract\nTask type: multi_file_migration_repair\nDifficulty: hard\n\nReturn a rigorous engineering answer:\n- identify the hidden root cause or logical failure\n- present the corrected implementation\n- add tests that prove the fix\n- list verification commands\n- explain why naive fixes are insufficient when relevant\n\nRepository sketch:\nrepo/\n src/main/java/com/acme/App.java\n src/main/java/com/acme/Service.java\n src/test/java/com/acme/AppTest.java\n pom.xml\n\nFocus: Focus on staff-level problem solving with multi-file patches, rollout implications, performance and security tradeoffs.\n\nassistant: Diagnosis:\n- Staff-level diagnosis: mismatched API contract impacts correctness, operability, and future maintenance, so the fix must be minimal where possible but complete where necessary.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```java\nimport java.util.HashMap;\nimport java.util.Map;\n\npublic final class RequestHandler {\n public static Map handleRequest(Map payload) {\n Map clean = new HashMap<>();\n for (Map.Entry entry : payload.entrySet()) {\n if (entry.getValue() != null) clean.put(entry.getKey().trim(), entry.getValue());\n }\n if (!clean.containsKey(\"id\")) throw new IllegalArgumentException(\"missing id\");\n return Map.of(\"ok\", true, \"data\", clean);\n }\n}\n```\n\nTests:\n```java\nimport static org.junit.jupiter.api.Assertions.*;\nimport java.util.Map;\nimport org.junit.jupiter.api.Test;\n\nclass RequestHandlerTest {\n @Test\n void requiresId() {\n assertThrows(IllegalArgumentException.class, () -> RequestHandler.handleRequest(Map.of(\"name\", \"x\")));\n }\n}\n```\n\nVerification:\n- `./gradlew test`\n- `mvn test`\n\nEngineering notes:\n- Language: Java\n- Framework/tooling: Gradle\n- Stack context: Go, Gin, PostgreSQL, gRPC, Prometheus, Docker\n- Domain: repo automation\n- Task type: multi_file_migration_repair\n- Difficulty: hard\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "Design CI/CD for a content moderation service delivering file uploads.\nTarget platform: mobile (Android Kotlin).\nRequirements: pipelines, checks, artifact strategy, deployments, and rollbacks.\nConstraints: must include documentation/comments, must include clear error handling, must be secure-by-default.\nDifficulty: easy. Assume untrusted input; validate everything.\n\nOutput: engineering-grade answer with edge cases covered.\nDeliverable: CI/CD pipeline (GitHub Actions) with quality gates.\n\n```yaml\nname: ci\non:\n pull_request:\n push:\n branches: [main]\n\njobs:\n test:\n runs-on: ubuntu-latest\n steps:\n - uses: actions/checkout@v4\n - uses: actions/setup-python@v5\n with:\n python-version: \"3.11\"\n - run: python -m pip install -U pip\n - run: pip install -r requirements.txt\n - run: pip install -r requirements-dev.txt\n - run: ruff check .\n - run: mypy .\n - run: pytest -q --maxfail=1 --disable-warnings\n\n docker:\n needs: test\n runs-on: ubuntu-latest\n steps:\n - uses: actions/checkout@v4\n - uses: docker/setup-buildx-action@v3\n - run: docker build -t app:${{ github.sha }} .\n```\n\nDeployment strategy:\n- main → build → deploy to staging → smoke tests → canary to prod.\n- Rollback: redeploy previous image + DB migration rollback plan.\n\n\nChecks: input validation, tests, and safe defaults included.", "source": "WithinUsAI/GOD_Coder_100k"} {"text": "Task type: secure_architecture\nScenario: time-series metrics store\nDomain focus: data lineage & governance\nPrimary language: typescript\nDifficulty: hard\nScale/SLO: 1M msgs/min\nComponent: component_jpkgeeak\nConstraints: include verification strategy, include security threat model (defensive only), explicit contracts and invariants, avoid data races and undefined behavior, include failure modes and recovery, assume adversarial inputs; validate everything, include test vectors and fuzz strategy\nAssume tight memory budget and cold-start constraints.\nDeliverable: Provide a defensive threat model and secure-by-default architecture; include monitoring/detection and tests (no offensive content).\n\nOutput: rigorous design + invariants + verification plan + implementation sketch.\n**Contract**\n- Inputs validated at the boundary; explicit error taxonomy.\n- Idempotency for side effects via request_id; deterministic replay.\n- Backward compatibility: additive changes by default; versioned breaking changes.\n**Invariants**\n- Determinism: replay of the same event log yields identical outputs.\n- Liveness: under bounded faults and stable network, progress occurs.\n- Isolation: tenant boundary enforced; no cross-tenant reads/writes.\n**Failure modes & recovery**\n- Crash during commit: WAL replay completes or transaction aborts; no torn writes.\n- Duplicate requests: de-duplicate by (tenant, request_id) returning cached response.\n- Network partition: minority cannot commit; clients receive retriable errors.\n**Security posture (defensive)**\n- Threat model: auth/authz, injection, replay/abuse, supply chain.\n- Least privilege; secrets in managed store; audit logs for sensitive ops.\n- Input normalization, parameterized queries, path traversal protections.\n**Verification strategy**\n- Deterministic simulation with fault injection (crash/partition/latency).\n- Canary + shadow traffic; invariants checked in production via assertions/metrics.\n- Property tests against a pure reference model (state machine).\n\n**Snippet**\n```text\nImplementation sketch: factor pure state-machine core; adapters for I/O; add deterministic replay log.\n```\nHard checks: fault injection tests gate merges; perf thresholds enforced in CI.", "source": "WithinUsAI/Omega_Genesis_Coder_100k"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: Project stack: Spring Boot, PostgreSQL, JUnit, Gradle, Docker, GitHub Actions\nLanguage: Go\nDependency challenge: partial checkpoint corruption\nTask type: cve_dependency_remediation\nDifficulty: medium\n\nFix this as a senior engineer.\nRequired:\n- identify the version or compatibility failure mode\n- produce the corrected config/code/build patch\n- explain rollback-safe migration notes\n- add regression tests or reproducibility checks\n- include concrete verification commands\n\nRepository sketch:\nrepo/\n cmd/server/main.go\n internal/service/service.go\n internal/store/store.go\n internal/api/api.go\n service_test.go\n go.mod\n\nFocus: Focus on versioning, migrations, lockfiles, runtime compatibility, and secure dependency handling.\n\nassistant: Diagnosis:\n- Root cause: the issue around partial checkpoint corruption is a dependency, migration, or runtime-compatibility mismatch that needs a rollback-safe patch.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```go\npackage service\n\nimport \"fmt\"\n\nfunc NormalizePayload(payload map[string]any) map[string]any {\n\tout := make(map[string]any)\n\tfor k, v := range payload {\n\t\tif v == nil {\n\t\t\tcontinue\n\t\t}\n\t\tout[k] = v\n\t}\n\treturn out\n}\n\nfunc Handle(payload map[string]any) (map[string]any, error) {\n\tclean := NormalizePayload(payload)\n\tif _, ok := clean[\"id\"]; !ok {\n\t\treturn nil, fmt.Errorf(\"missing id\")\n\t}\n\treturn map[string]any{\"ok\": true, \"data\": clean}, nil\n}\n```\n\nTests:\n```go\npackage service\n\nimport \"testing\"\n\nfunc TestHandle(t *testing.T) {\n\tgot, err := Handle(map[string]any{\"id\": 7, \"name\": \"ok\", \"unused\": nil})\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tif got[\"ok\"] != true {\n\t\tt.Fatalf(\"expected ok=true\")\n\t}\n\tif _, err := Handle(map[string]any{\"name\": \"x\"}); err == nil {\n\t\tt.Fatalf(\"expected missing id error\")\n\t}\n}\n```\n\nVerification:\n- `go test ./...`\n- `go vet ./...`\n\nEngineering notes:\n- Language: Go\n- Framework/tooling: net/http\n- Stack context: Spring Boot, PostgreSQL, JUnit, Gradle, Docker, GitHub Actions\n- Domain: reporting engine\n- Task type: cve_dependency_remediation\n- Difficulty: medium\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "Build an elite-grade solution in the domain of ml systems for scenario: time-series metrics.\nPrimary language: sql.\nDifficulty: expert.\nConstraints: document performance characteristics, assume untrusted inputs; validate and sanitize, provide rollout and rollback guidance, avoid undefined behavior and data races.\nComponent: component_flgttgo.\nAssume schema changes every sprint; must be backward compatible.\nTask: Provide threat model, secure-by-default design, and defensive implementation patterns. No offensive/exploit content; focus on prevention and detection.\n\nOutput: rigorous solution with invariants, failure modes, and performance notes.\nOutput: threat model + defensive design + detection.\n\n**Threat model**\n- Auth: token theft → short-lived tokens, rotation, audience checks\n- AuthZ: privilege escalation → centralized policy checks, tenant isolation tests\n- Input: injection → strict validation, parameterized queries, output encoding\n- Supply chain: dependencies → lockfiles, signature verification, SBOM\n\n**Defensive patterns**\n- Idempotency keys for side effects; replay-safe handlers\n- Secrets in managed store; never logs\n- Audit logging for sensitive ops; tamper-evident storage\n\n**Detection**\n- Alert on unusual auth failures, access pattern anomalies, and data exfil signals.\n\n\nExpert checks: state-machine reasoning, concurrency stress, and upgrade/rollback validated.", "source": "WithinUsAI/Elite_GOD_Coder_100k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Fix a bug and add tests.\n\nFile: ln1lt1th.py\n```python\ndef uha9t5as6c75(n: int) -> int:\n \"\"\"Sum 1..n inclusive.\"\"\"\n if n < 0:\n raise ValueError(\"n must be non-negative\")\n total = 0\n for k in range(n): # BUG: should include n\n total += k\n return total\n```\n\nReturn unified diffs for ln1lt1th.py and test_ln1lt1th.py (pytest).\n\n*** Begin Patch\n*** Update File: ln1lt1th.py\n@@\n def uha9t5as6c75(n: int) -> int:\n@@\n total = 0\n- for k in range(n): # BUG: should include n\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_ln1lt1th.py\n+import pytest\n+from ln1lt1th import uha9t5as6c75\n+\n+def test_zero():\n+ assert uha9t5as6c75(0) == 0\n+\n+def test_one():\n+ assert uha9t5as6c75(1) == 1\n+\n+def test_small():\n+ assert uha9t5as6c75(7) == 28\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ uha9t5as6c75(-1)\n+\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Produce an offline-first self-evolving code assistant architecture named `nlx8_slo`.\nMust include: module layout, patch-safety policy, evaluation gates (tests/lint/types), versioned memory index.\n\nArchitecture: `nlx8_slo` (offline-first, self-evolving)\n\nModules\n- core/loop.py: evolve → validate → accept/reject (bounded iterations)\n- patching/: diff builder, safe apply, atomic writes, rollback points\n- policy/: allowlist paths, deny globs (.git/, __pycache__/, binaries), patch size caps\n- signals/: parse pytest/ruff/mypy into normalized findings\n- memory/index.jsonl: append-only snapshots (hashes, metrics, rationale)\n\nSafety gates\n- refuse path traversal/symlink escapes; never edit binaries\n- accept only if tests/lint/types stay green or improve", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Design and implement an algorithm for time series.\nRequirements: define inputs/outputs, implement solution with complexity analysis, and include tests.\nConstraints: must be easy to extend, must include docstrings, must avoid global state.\nDifficulty: easy. Handle empty inputs and malformed records gracefully.\n\nDeliverable: implementation + tests.\nProblem: compute rolling sums over events (ts:int,value:int) with window W seconds. Events may be out-of-order.\n\nComplexity: sorting O(n log n); window maintenance O(n); memory O(k).\n\n```python\nfrom __future__ import annotations\nfrom collections import deque\nfrom dataclasses import dataclass\nfrom typing import Iterable, List, Tuple\n\n@dataclass(frozen=True, slots=True)\nclass Event:\n ts: int\n value: int\n\ndef rolling_sum(events: Iterable[Event], window_s: int) -> List[Tuple[int,int]]:\n if window_s < 0:\n raise ValueError(\"window_s must be >= 0\")\n evs = sorted(events, key=lambda e: e.ts)\n q: deque[Event] = deque()\n s = 0\n out: List[Tuple[int,int]] = []\n for e in evs:\n q.append(e)\n s += e.value\n cutoff = e.ts - window_s\n while q and q[0].ts < cutoff:\n old = q.popleft()\n s -= old.value\n out.append((e.ts, s))\n return out\n```\n\n```python\nimport pytest\nfrom module_under_test import Event, rolling_sum\n\ndef test_rolling_sum():\n ev = [Event(10,1), Event(11,2), Event(20,5)]\n assert rolling_sum(ev, 5) == [(10,1),(11,3),(20,5)]\n```", "source": "WithinUsAI/python_GOD_coder_100k"} {"text": "Add a clear docstring and type hints to this function:\n\n```python\ndef f78450(s):\n return ''.join(x for x in s if x.isalnum()).lower()\n```\n\n```python\nfrom __future__ import annotations\n\ndef f78450(s: str) -> str:\n \"\"\"Normalize a string: keep only alphanumerics and lowercase the result.\"\"\"\n return \"\".join(ch for ch in s if ch.isalnum()).lower()\n```", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Fix a bug and add tests.\n\nFile: j0fcazm_.py\n```python\ndef ihgfeyt_muj(n: int) -> int:\n \"\"\"Sum 1..n inclusive.\"\"\"\n if n < 0:\n raise ValueError(\"n must be non-negative\")\n total = 0\n for k in range(n): # BUG: should include n\n total += k\n return total\n```\n\nReturn unified diffs for j0fcazm_.py and test_j0fcazm_.py (pytest).\n\n*** Begin Patch\n*** Update File: j0fcazm_.py\n@@\n def ihgfeyt_muj(n: int) -> int:\n@@\n total = 0\n- for k in range(n): # BUG: should include n\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_j0fcazm_.py\n+import pytest\n+from j0fcazm_ import ihgfeyt_muj\n+\n+def test_zero():\n+ assert ihgfeyt_muj(0) == 0\n+\n+def test_one():\n+ assert ihgfeyt_muj(1) == 1\n+\n+def test_small():\n+ assert ihgfeyt_muj(7) == 28\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ ihgfeyt_muj(-1)\n+\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Task type: static_analyzer\nScenario: payment ledger\nDomain focus: query planning\nPrimary language: sql\nDifficulty: hard\nScale/SLO: 1M msgs/min\nComponent: component_rjdppvxd\nConstraints: include security threat model (defensive only), include deterministic replay plan, include verification strategy, include failure modes and recovery, avoid data races and undefined behavior, assume adversarial inputs; validate everything\nAssume hostile inputs and targeted abuse patterns.\nDeliverable: Design a static analyzer for a safety property (e.g., taint/SQLi prevention); include rule set, false-positive strategy, and tests.\n\nOutput: elite engineering answer optimized for correctness, performance, and operability.\n**Contract**\n- Inputs validated at the boundary; explicit error taxonomy.\n- Idempotency for side effects via request_id; deterministic replay.\n- Backward compatibility: additive changes by default; versioned breaking changes.\n**Invariants**\n- Liveness: under bounded faults and stable network, progress occurs.\n- Isolation: tenant boundary enforced; no cross-tenant reads/writes.\n- Determinism: replay of the same event log yields identical outputs.\n**Failure modes & recovery**\n- Data corruption: checksums + scrubber; quarantine and rebuild from replicas/snapshots.\n- Crash during commit: WAL replay completes or transaction aborts; no torn writes.\n- Network partition: minority cannot commit; clients receive retriable errors.\n**Security posture (defensive)**\n- Threat model: auth/authz, injection, replay/abuse, supply chain.\n- Least privilege; secrets in managed store; audit logs for sensitive ops.\n- Input normalization, parameterized queries, path traversal protections.\n**Verification strategy**\n- Canary + shadow traffic; invariants checked in production via assertions/metrics.\n- Property tests against a pure reference model (state machine).\n- Deterministic simulation with fault injection (crash/partition/latency).\n\n**Snippet**\n```text\nImplementation sketch: factor pure state-machine core; adapters for I/O; add deterministic replay log.\n```\nHard checks: fault injection tests gate merges; perf thresholds enforced in CI.", "source": "WithinUsAI/Omega_Genesis_Coder_100k"} {"text": "Write a thorough test suite for a Python component used for parsing.\nRequirements: cover edge cases, invalid inputs, and behavior invariants.\nConstraints: must include tests, stdlib-only, must include type hints.\nDifficulty: medium. Provide helpful exceptions with actionable messages.\n\nDeliverable: corrected code and verification tests.\n```python\n# tests (pytest-style) for a module providing: normalize(), parse_lines(), compute_stats()\nimport math\nimport pytest\n\ndef test_normalize_idempotent(module_under_test):\n x = \" A\\tB \"\n assert module_under_test.normalize(module_under_test.normalize(x)) == module_under_test.normalize(x)\n\ndef test_parse_lines_rejects_invalid(module_under_test):\n with pytest.raises(ValueError):\n module_under_test.parse_lines([\"\", \"???\", None]) # type: ignore[arg-type]\n\ndef test_compute_stats_basic(module_under_test):\n data = [1, 2, 3, 4]\n s = module_under_test.compute_stats(data)\n assert s.count == 4\n assert s.total == 10\n assert math.isclose(s.mean, 2.5)\n```", "source": "WithinUsAI/python_GOD_coder_100k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Refactor to modern typed Python with immutability and tests.\n\nFile: zztdk2rz0x9.py\n```python\nclass Sdeq06T:\n def __init__(self, name, values):\n self.name = name\n self.values = list(values)\n def add(self, v):\n self.values.append(v)\n def mean(self):\n s = 0\n for x in self.values:\n s += x\n return s / len(self.values)\n```\n\nReturn full new zztdk2rz0x9.py and test_zztdk2rz0x9.py.\n\n# zztdk2rz0x9.py\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom typing import Iterable, Tuple\n\n@dataclass(frozen=True)\nclass Sdeq06T:\n name: str\n values: Tuple[float, ...]\n\n @staticmethod\n def create(name: str, values: Iterable[float]) -> \"Sdeq06T\":\n vals = tuple(float(v) for v in values)\n if not vals:\n raise ValueError(\"values must be non-empty\")\n return Sdeq06T(name=name, values=vals)\n\n def add(self, v: float) -> \"Sdeq06T\":\n return Sdeq06T(name=self.name, values=self.values + (float(v),))\n\n def mean(self) -> float:\n return sum(self.values) / len(self.values)\n\n# test_zztdk2rz0x9.py\nimport pytest\nfrom zztdk2rz0x9 import Sdeq06T\n\ndef test_mean_and_add():\n c = Sdeq06T.create(\"a\", [1, 2, 3])\n assert c.mean() == 2.0\n assert c.add(5).mean() == (1 + 2 + 3 + 5) / 4\n\ndef test_empty_raises():\n with pytest.raises(ValueError):\n Sdeq06T.create(\"x\", [])", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Build an elite-grade solution in the domain of gpu compute for scenario: job scheduler.\nPrimary language: rust.\nDifficulty: hard.\nConstraints: make the interface contract explicit, include invariants and failure modes, avoid undefined behavior and data races, provide rollout and rollback guidance, design for backward compatibility and migrations.\nComponent: component_vyzvtvy.\nAssume 50k RPS and p99 < 250ms.\nTask: Define a small DSL, implement tokenizer/parser, IR, and a codegen or interpreter. Include tests and complexity notes.\n\nOutput: rigorous solution with invariants, failure modes, and performance notes.\nOutput: DSL + parser + IR + interpreter/codegen + tests.\n\n**DSL**\n- Expressions: integers, identifiers, `+ - * /`, let-binding: `let x = expr in expr`\n- Example: `let x = 2+3 in x*10`\n\n**Pipeline**\n1. Tokenize\n2. Parse into AST\n3. Lower into IR (stack ops) or interpret AST directly\n\n**Reference (Rust-style outline)**\n- `enum Expr { Int(i64), Var(String), Bin(Op, Box, Box), Let(String, Box, Box) }`\n- Parser: Pratt or recursive descent.\n\n**Tests**\n- Golden tests for parse trees.\n- Property: pretty-print(parse(x)) round-trips for a corpus.\n- Eval tests for precedence and scoping.\n\n\nHard checks: failure injection tests and performance regressions gated.", "source": "WithinUsAI/Elite_GOD_Coder_100k"} {"text": "Write pytest tests for `f04336`.\n\n```python\ndef f04336(a: int, b: int) -> int:\n return a*a + b*b\n```\nInclude edge cases and a property-style check.\n\n```python\nimport random\nfrom m72048 import f04336\n\ndef test_known():\n assert f04336(3,4) == 25\n\ndef test_zero():\n assert f04336(0,0) == 0\n\ndef test_property_nonnegative():\n for _ in range(200):\n a=random.randint(-50,50)\n b=random.randint(-50,50)\n assert f04336(a,b) >= 0\n```", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Fix the bug and add pytest tests.\n\n```python\ndef f39887(n: int) -> int:\n # sum 1..n inclusive\n if n < 0: raise ValueError\n total = 0\n for k in range(n): # BUG\n total += k\n return total\n```\nReturn unified diffs for `m62841.py` and `test_m62841.py`.\n\n*** Begin Patch\n*** Update File: m62841.py\n@@\n def f39887(n: int) -> int:\n@@\n- for k in range(n): # BUG\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_m62841.py\n+import pytest\n+from m62841 import f39887\n+\n+def test_small():\n+ assert f39887(7) == 28\n+\n+def test_zero():\n+ assert f39887(0) == 0\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ f39887(-1)\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: Language: Bash\nFramework/tooling: awk\nDomain: reporting engine\nLogic challenge: partial checkpoint corruption\nTask type: backwards_compatible_redesign\nDifficulty: expert\n\nReturn a rigorous engineering answer:\n- identify the hidden root cause or logical failure\n- present the corrected implementation\n- add tests that prove the fix\n- list verification commands\n- explain why naive fixes are insufficient when relevant\n\nRepository sketch:\nrepo/\n scripts/\n run.sh\n deploy.sh\n tests/\n smoke.sh\n\nFocus: Focus on staff-level problem solving with multi-file patches, rollout implications, performance and security tradeoffs.\n\nassistant: Diagnosis:\n- Staff-level diagnosis: partial checkpoint corruption impacts correctness, operability, and future maintenance, so the fix must be minimal where possible but complete where necessary.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```bash\n#!/usr/bin/env bash\nset -euo pipefail\n\ninput=\"${1:-}\"\nif [[ -z \"$input\" ]]; then\n echo \"missing input\" >&2\n exit 1\nfi\n\nprintf '%s\n' \"$input\" | tr -d '\r'\n```\n\nTests:\n```bash\noutput=\"$(bash scripts/run.sh \"abc\")\"\ntest \"$output\" = \"abc\"\n```\n\nVerification:\n- `bash tests/smoke.sh`\n- `shellcheck scripts/*.sh`\n\nEngineering notes:\n- Language: Bash\n- Framework/tooling: awk\n- Stack context: FastAPI, PostgreSQL, Redis, Celery, pytest, Docker\n- Domain: reporting engine\n- Task type: backwards_compatible_redesign\n- Difficulty: expert\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "Design a small, production-grade Python API for time series.\nRequirements: define data models and interfaces, implement reference version, include tests.\nConstraints: must include docstrings, must be easy to extend, must avoid global state, must be memory-efficient.\nDifficulty: medium. Handle empty inputs and malformed records gracefully.\n\nDeliverable: production-ready reference solution.\nArchitecture:\n- Public facade class coordinating concerns (parsing, validation, persistence)\n- Small pure functions for testability\n- No global state; dependency injection for filesystem I/O\n\n```python\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom pathlib import Path\nfrom typing import Protocol, Iterable\nimport json\n\nclass Store(Protocol):\n def write_text(self, path: Path, data: str) -> None: ...\n\nclass FSStore:\n def write_text(self, path: Path, data: str) -> None:\n path.parent.mkdir(parents=True, exist_ok=True)\n path.write_text(data, encoding=\"utf-8\")\n\n@dataclass(frozen=True, slots=True)\nclass Item:\n name: str\n qty: int\n\ndef parse_items(lines: Iterable[str]) -> list[Item]:\n out: list[Item] = []\n for i, line in enumerate(lines, 1):\n s = line.strip()\n if not s:\n continue\n obj = json.loads(s)\n if not isinstance(obj, dict):\n raise ValueError(f\"line {i}: expected object\")\n name = obj.get(\"name\")\n qty = obj.get(\"qty\")\n if not isinstance(name, str) or not name:\n raise ValueError(f\"line {i}: name must be str\")\n if not isinstance(qty, int) or qty < 0:\n raise ValueError(f\"line {i}: qty must be non-negative int\")\n out.append(Item(name, qty))\n return out\n\nclass InventoryWriter:\n def __init__(self, base_dir: Path, store: Store | None = None) -> None:\n self._base = base_dir\n self._store: Store = store or FSStore()\n\n def write(self, rel_path: str, items: list[Item]) -> Path:\n dst = (self._base / rel_path).resolve()\n base = self._base.resolve()\n if dst != base and base not in dst.parents:\n raise ValueError(\"unsafe path traversal\")\n payload = json.dumps([item.__dict__ for item in items], ensure_ascii=False)\n self._store.write_text(dst, payload)\n return dst\n```\n\n```python\nimport json\nfrom pathlib import Path\nimport pytest\nfrom module_under_test import InventoryWriter, parse_items\n\ndef test_parse_items_valid():\n lines = [json.dumps({\"name\":\"x\",\"qty\":1})]\n assert parse_items(lines)[0].name == \"x\"\n\ndef test_writer_blocks_traversal(tmp_path: Path):\n w = InventoryWriter(tmp_path)\n with pytest.raises(ValueError):\n w.write(\"../evil.json\", [])\n```", "source": "WithinUsAI/python_GOD_coder_100k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Fix a bug and add tests.\n\nFile: tak03dil5.py\n```python\ndef b1jh733d(n: int) -> int:\n \"\"\"Sum 1..n inclusive.\"\"\"\n if n < 0:\n raise ValueError(\"n must be non-negative\")\n total = 0\n for k in range(n): # BUG: should include n\n total += k\n return total\n```\n\nReturn unified diffs for tak03dil5.py and test_tak03dil5.py (pytest).\n\n*** Begin Patch\n*** Update File: tak03dil5.py\n@@\n def b1jh733d(n: int) -> int:\n@@\n total = 0\n- for k in range(n): # BUG: should include n\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_tak03dil5.py\n+import pytest\n+from tak03dil5 import b1jh733d\n+\n+def test_zero():\n+ assert b1jh733d(0) == 0\n+\n+def test_one():\n+ assert b1jh733d(1) == 1\n+\n+def test_small():\n+ assert b1jh733d(7) == 28\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ b1jh733d(-1)\n+\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Build an elite-grade solution in the domain of networking for scenario: analytics pipeline.\nPrimary language: sql.\nDifficulty: medium.\nConstraints: include invariants and failure modes, design for backward compatibility and migrations, assume untrusted inputs; validate and sanitize.\nComponent: component_evmvsfg.\nAssume compliance requires data deletion with proofs.\nTask: Implement or outline a storage/indexing subsystem (LSM/B-Tree, WAL, snapshots). Include transaction/consistency considerations and benchmark plan.\n\nOutput: rigorous solution with invariants, failure modes, and performance notes.\nOutput: storage design + WAL + compaction + benchmarks.\n\n**Design**\n- WAL (append-only) for durability; fsync policy configurable.\n- Memtable (in-memory) → flush to immutable SSTables.\n- LSM compaction tiers; bloom filters per SSTable for point-lookups.\n- Manifest tracks SSTable set; atomic pointer swap on updates.\n\n**Correctness**\n- Crash recovery: replay WAL to rebuild memtable; manifest ensures last consistent set.\n- Reads: merge memtable + SSTables newest→oldest; tombstones override older values.\n\n**Bench plan**\n- Workloads: write-heavy, read-heavy, mixed; measure p50/p95 latency and write amplification.\n- Track compaction debt and space amplification.\n\n**Test plan**\n- Fuzz crash points: kill after WAL append / after manifest update; verify invariants on restart.\n\n\nChecks: boundary validation and deterministic behavior verified.", "source": "WithinUsAI/Elite_GOD_Coder_100k"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: Project domain: artifact registry\nImplementation stack: Next.js, Node.js, Prisma, PostgreSQL, Playwright, Docker\nSoftware delivery problem: streaming timeout handling\nTask type: test_strategy_implementation\nDifficulty: hard\n\nReturn a complete delivery-grade response with:\n- diagnosis or design reasoning\n- implementation\n- test plan or tests\n- rollout plan\n- rollback or compatibility note\n- verification commands\n\nRepository sketch:\nrepo/\n src/\n api.js\n service.js\n utils.js\n tests/\n api.test.js\n package.json\n\nFocus: Focus on shipping production software with rollout safety, acceptance criteria, telemetry, and maintenance quality.\n\nassistant: Diagnosis:\n- Root cause or delivery blocker: streaming timeout handling needs both implementation work and a safe shipping plan.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```javascript\ntype Payload = Record;\n\nexport function normalizePayload(payload: Payload): Payload {\n if (!payload || typeof payload !== \"object\" || Array.isArray(payload)) {\n throw new TypeError(\"payload must be a plain object\");\n }\n return Object.fromEntries(\n Object.entries(payload)\n .filter(([, value]) => value !== null && value !== undefined)\n .map(([key, value]) => [String(key).trim(), value])\n );\n}\n\nexport function handleStreamingTimeoutHandling(payload: Payload) {\n const clean = normalizePayload(payload);\n if (!(\"id\" in clean)) {\n return { ok: false, data: {}, error: \"missing id\" };\n }\n return { ok: true, data: clean, error: null };\n}\n```\n\nTests:\n```javascript\nimport { describe, it, expect } from \"vitest\";\nimport { handleStreamingTimeoutHandling } from \"../src/service\";\n\ndescribe(\"handler\", () => {\n it(\"accepts valid input\", () => {\n expect(handleStreamingTimeoutHandling({ id: 7, name: \"ok\", unused: null })).toEqual({\n ok: true,\n data: { id: 7, name: \"ok\" },\n error: null\n });\n });\n\n it(\"rejects missing id\", () => {\n expect(handleStreamingTimeoutHandling({ name: \"x\" }).error).toMatch(/missing id/);\n });\n});\n```\n\nVerification:\n- `npm test`\n- `npm run lint`\n\nEngineering notes:\n- Language: JavaScript\n- Framework/tooling: Express\n- Stack context: Next.js, Node.js, Prisma, PostgreSQL, Playwright, Docker\n- Domain: artifact registry\n- Task type: test_strategy_implementation\n- Difficulty: hard\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "Build an elite-grade solution in the domain of realtime systems for scenario: chat messaging.\nPrimary language: rust.\nDifficulty: expert.\nConstraints: assume untrusted inputs; validate and sanitize, avoid undefined behavior and data races, provide rollout and rollback guidance.\nComponent: component_gtfvqny.\nAssume partial network partitions occur weekly.\nTask: Define an API and evolving schema strategy (versioning, migrations, compatibility rules). Provide example schemas and validation tests.\n\nOutput: production blueprint plus correctness arguments and test strategy.\nOutput: GPU pipeline design for throughput and tail-latency.\n\n**Pipeline**\n- Request batching with max batch size + max wait (e.g., 5ms) to control p99.\n- Separate CPU pre/post-processing threads; pin memory for transfers if available.\n- Model warmup; cache weights in VRAM; use concurrency limits.\n\n**Monitoring**\n- GPU utilization, queue wait time, batch size distribution, OOM events.\n\n**Fallback**\n- Graceful degradation to smaller batch size; circuit breaker on repeated OOM.\n\n\nExpert checks: state-machine reasoning, concurrency stress, and upgrade/rollback validated.", "source": "WithinUsAI/Elite_GOD_Coder_100k"} {"text": "Provision infrastructure for a customer support workload providing offline-first sync.\nTarget platform: backend (Go).\nRequirements: IaC (Terraform or Kubernetes YAML), networking, secrets, autoscaling.\nConstraints: must be easy to extend, must avoid global state, must be production-ready, must include tests.\nDifficulty: medium. Assume PII must be protected.\n\nOutput: engineering-grade answer with edge cases covered.\nDeliverable: Kubernetes deployment + basic security posture.\n\n```yaml\napiVersion: apps/v1\nkind: Deployment\nmetadata:\n name: app\nspec:\n replicas: 3\n selector:\n matchLabels: { app: app }\n template:\n metadata:\n labels: { app: app }\n spec:\n containers:\n - name: app\n image: app:latest\n ports: [{ containerPort: 8080 }]\n readinessProbe:\n httpGet: { path: /healthz, port: 8080 }\n resources:\n requests: { cpu: \"200m\", memory: \"256Mi\" }\n limits: { cpu: \"1\", memory: \"1Gi\" }\n```\n\nAdditions:\n- NetworkPolicy to restrict egress/ingress.\n- Secrets via external secret store; rotate regularly.\n- HPA for autoscaling; PodDisruptionBudget for availability.\n\n\nChecks: input validation, tests, and safe defaults included.", "source": "WithinUsAI/GOD_Coder_100k"} {"text": "Fix the bug and add pytest tests.\n\n```python\ndef f56675(n: int) -> int:\n # sum 1..n inclusive\n if n < 0: raise ValueError\n total = 0\n for k in range(n): # BUG\n total += k\n return total\n```\nReturn unified diffs for `m79525.py` and `test_m79525.py`.\n\n*** Begin Patch\n*** Update File: m79525.py\n@@\n def f56675(n: int) -> int:\n@@\n- for k in range(n): # BUG\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_m79525.py\n+import pytest\n+from m79525 import f56675\n+\n+def test_small():\n+ assert f56675(7) == 28\n+\n+def test_zero():\n+ assert f56675(0) == 0\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ f56675(-1)\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Implement rate limiting for a healthtech product.\nTarget platform: ML (PyTorch + serving).\nRequirements: provide production-ready code, configuration, and tests.\nConstraints: must be easy to extend, must avoid global state, must be production-ready, must include type hints where applicable, must be performant under load.\nDifficulty: medium. Assume mobile clients are occasionally offline.\n\nOutput: actionable implementation and verification artifacts.\nDeliverable: production-grade reference implementation (FastAPI) + tests.\n\n```python\n# app.py\nfrom __future__ import annotations\n\nimport hashlib\nimport json\nfrom dataclasses import dataclass\nfrom datetime import datetime, timezone\nfrom typing import Any, Optional\n\nfrom fastapi import FastAPI, Header, HTTPException\nfrom pydantic import BaseModel, Field\n\napp = FastAPI(title=\"Idempotent API\")\n\nclass CreateReq(BaseModel):\n tenant_id: str = Field(min_length=1)\n amount_cents: int = Field(ge=0)\n currency: str = Field(min_length=3, max_length=3)\n\nclass CreateResp(BaseModel):\n id: str\n created_at: str\n echo: CreateReq\n\n@dataclass\nclass _IdempoEntry:\n request_hash: str\n response_json: str\n\n# In production: Postgres table with UNIQUE(tenant_id, key)\n_IDEMPO: dict[tuple[str, str], _IdempoEntry] = {}\n\ndef _hash_req(req: CreateReq) -> str:\n raw = req.model_dump_json()\n return hashlib.sha256(raw.encode(\"utf-8\")).hexdigest()\n\n@app.post(\"/v1/payments\", response_model=CreateResp)\ndef create_payment(\n req: CreateReq,\n idempotency_key: Optional[str] = Header(default=None, alias=\"Idempotency-Key\"),\n) -> Any:\n if not idempotency_key:\n raise HTTPException(status_code=400, detail=\"Missing Idempotency-Key\")\n if len(idempotency_key) > 128:\n raise HTTPException(status_code=400, detail=\"Idempotency-Key too long\")\n\n key = (req.tenant_id, idempotency_key)\n rh = _hash_req(req)\n\n existing = _IDEMPO.get(key)\n if existing:\n if existing.request_hash != rh:\n raise HTTPException(status_code=409, detail=\"Idempotency-Key reuse with different payload\")\n return json.loads(existing.response_json)\n\n # Create new payment (stubbed)\n pid = hashlib.md5(f\"{req.tenant_id}:{idempotency_key}\".encode()).hexdigest()\n resp = CreateResp(\n id=pid,\n created_at=datetime.now(timezone.utc).isoformat(),\n echo=req,\n )\n _IDEMPO[key] = _IdempoEntry(request_hash=rh, response_json=resp.model_dump_json())\n return resp\n```\n\n```python\n# test_app.py (pytest)\nfrom fastapi.testclient import TestClient\nfrom app import app\n\nclient = TestClient(app)\n\ndef test_idempotent_replay():\n headers = {\"Idempotency-Key\": \"abc\"}\n body = {\"tenant_id\":\"t1\",\"amount_cents\":100,\"currency\":\"USD\"}\n r1 = client.post(\"/v1/payments\", json=body, headers=headers)\n r2 = client.post(\"/v1/payments\", json=body, headers=headers)\n assert r1.status_code == 200 and r2.status_code == 200\n assert r1.json() == r2.json()\n\ndef test_payload_conflict():\n headers = {\"Idempotency-Key\": \"abc\"}\n b1 = {\"tenant_id\":\"t1\",\"amount_cents\":100,\"currency\":\"USD\"}\n b2 = {\"tenant_id\":\"t1\",\"amount_cents\":200,\"currency\":\"USD\"}\n assert client.post(\"/v1/payments\", json=b1, headers=headers).status_code == 200\n assert client.post(\"/v1/payments\", json=b2, headers=headers).status_code == 409\n```\n\nNotes:\n- Replace in-memory store with a DB table and transaction.\n- Store response + request hash to detect key reuse with different payload.\n\n\nChecks: input validation, tests, and safe defaults included.", "source": "WithinUsAI/GOD_Coder_100k"} {"text": "Refactor a Python module used for ETL pipelines into a clean, extensible design.\nRequirements: outline the new architecture briefly, then provide the refactored code and tests.\nConstraints: must include docstrings, must be streaming-friendly, must be memory-efficient.\nDifficulty: easy. Handle empty inputs and malformed records gracefully.\n\nDeliverable: production-ready reference solution.\nArchitecture:\n- Public facade class coordinating concerns (parsing, validation, persistence)\n- Small pure functions for testability\n- No global state; dependency injection for filesystem I/O\n\n```python\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom pathlib import Path\nfrom typing import Protocol, Iterable\nimport json\n\nclass Store(Protocol):\n def write_text(self, path: Path, data: str) -> None: ...\n\nclass FSStore:\n def write_text(self, path: Path, data: str) -> None:\n path.parent.mkdir(parents=True, exist_ok=True)\n path.write_text(data, encoding=\"utf-8\")\n\n@dataclass(frozen=True, slots=True)\nclass Item:\n name: str\n qty: int\n\ndef parse_items(lines: Iterable[str]) -> list[Item]:\n out: list[Item] = []\n for i, line in enumerate(lines, 1):\n s = line.strip()\n if not s:\n continue\n obj = json.loads(s)\n if not isinstance(obj, dict):\n raise ValueError(f\"line {i}: expected object\")\n name = obj.get(\"name\")\n qty = obj.get(\"qty\")\n if not isinstance(name, str) or not name:\n raise ValueError(f\"line {i}: name must be str\")\n if not isinstance(qty, int) or qty < 0:\n raise ValueError(f\"line {i}: qty must be non-negative int\")\n out.append(Item(name, qty))\n return out\n\nclass InventoryWriter:\n def __init__(self, base_dir: Path, store: Store | None = None) -> None:\n self._base = base_dir\n self._store: Store = store or FSStore()\n\n def write(self, rel_path: str, items: list[Item]) -> Path:\n dst = (self._base / rel_path).resolve()\n base = self._base.resolve()\n if dst != base and base not in dst.parents:\n raise ValueError(\"unsafe path traversal\")\n payload = json.dumps([item.__dict__ for item in items], ensure_ascii=False)\n self._store.write_text(dst, payload)\n return dst\n```\n\n```python\nimport json\nfrom pathlib import Path\nimport pytest\nfrom module_under_test import InventoryWriter, parse_items\n\ndef test_parse_items_valid():\n lines = [json.dumps({\"name\":\"x\",\"qty\":1})]\n assert parse_items(lines)[0].name == \"x\"\n\ndef test_writer_blocks_traversal(tmp_path: Path):\n w = InventoryWriter(tmp_path)\n with pytest.raises(ValueError):\n w.write(\"../evil.json\", [])\n```", "source": "WithinUsAI/python_GOD_coder_100k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Refactor to modern typed Python with immutability and tests.\n\nFile: ptvppy.py\n```python\nclass Uu2OnLai:\n def __init__(self, name, values):\n self.name = name\n self.values = list(values)\n def add(self, v):\n self.values.append(v)\n def mean(self):\n s = 0\n for x in self.values:\n s += x\n return s / len(self.values)\n```\n\nReturn full new ptvppy.py and test_ptvppy.py.\n\n# ptvppy.py\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom typing import Iterable, Tuple\n\n@dataclass(frozen=True)\nclass Uu2OnLai:\n name: str\n values: Tuple[float, ...]\n\n @staticmethod\n def create(name: str, values: Iterable[float]) -> \"Uu2OnLai\":\n vals = tuple(float(v) for v in values)\n if not vals:\n raise ValueError(\"values must be non-empty\")\n return Uu2OnLai(name=name, values=vals)\n\n def add(self, v: float) -> \"Uu2OnLai\":\n return Uu2OnLai(name=self.name, values=self.values + (float(v),))\n\n def mean(self) -> float:\n return sum(self.values) / len(self.values)\n\n# test_ptvppy.py\nimport pytest\nfrom ptvppy import Uu2OnLai\n\ndef test_mean_and_add():\n c = Uu2OnLai.create(\"a\", [1, 2, 3])\n assert c.mean() == 2.0\n assert c.add(5).mean() == (1 + 2 + 3 + 5) / 4\n\ndef test_empty_raises():\n with pytest.raises(ValueError):\n Uu2OnLai.create(\"x\", [])", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Fix a subtle bug in a Python module used for telemetry ingestion.\nRequirements: explain root cause briefly, provide corrected code, and add regression tests.\nConstraints: must avoid global state, must include tests, must include type hints.\nDifficulty: hard. Ensure the API is testable via dependency injection.\n\nDeliverable: corrected code and verification tests.\n```python\nfrom __future__ import annotations\n\nfrom dataclasses import dataclass\nfrom pathlib import Path\nfrom typing import Iterable\nimport json\n\n\nclass ValidationError(ValueError):\n \"\"\"Raised when input validation fails.\"\"\"\n\n\ndef safe_join(base: Path, *parts: str) -> Path:\n \"\"\"Join paths while preventing traversal outside base.\"\"\"\n b = base.resolve()\n p = (b / Path(*parts)).resolve()\n if p != b and b not in p.parents:\n raise ValidationError(f\"unsafe path: {p}\")\n return p\n\n\n@dataclass(frozen=True, slots=True)\nclass Record:\n key: str\n value: int\n\n\ndef parse_jsonl(lines: Iterable[str]) -> list[Record]:\n out: list[Record] = []\n for idx, line in enumerate(lines, 1):\n s = line.strip()\n if not s:\n continue\n try:\n obj = json.loads(s)\n except json.JSONDecodeError as e:\n raise ValidationError(f\"line {idx}: invalid json\") from e\n if not isinstance(obj, dict):\n raise ValidationError(f\"line {idx}: expected object\")\n key = obj.get(\"key\")\n val = obj.get(\"value\")\n if not isinstance(key, str) or not key:\n raise ValidationError(f\"line {idx}: key must be non-empty str\")\n if not isinstance(val, int):\n raise ValidationError(f\"line {idx}: value must be int\")\n out.append(Record(key, val))\n return out\n\n\ndef write_jsonl(base: Path, rel: str, records: Iterable[Record]) -> Path:\n base.mkdir(parents=True, exist_ok=True)\n dst = safe_join(base, rel)\n dst.parent.mkdir(parents=True, exist_ok=True)\n with dst.open(\"w\", encoding=\"utf-8\", newline=\"\\n\") as f:\n for r in records:\n f.write(json.dumps({\"key\": r.key, \"value\": r.value}, ensure_ascii=False) + \"\\n\")\n return dst\n```\n\n```python\n# tests (pytest-style)\nimport json\nfrom pathlib import Path\nimport pytest\nfrom module_under_test import ValidationError, Record, parse_jsonl, write_jsonl\n\ndef test_parse_ok():\n lines = [json.dumps({\"key\":\"a\",\"value\":1}), json.dumps({\"key\":\"b\",\"value\":2})]\n assert parse_jsonl(lines) == [Record(\"a\",1), Record(\"b\",2)]\n\ndef test_parse_rejects_bad_json():\n with pytest.raises(ValidationError):\n parse_jsonl([\"{not json}\"])\n\ndef test_safe_join_blocks_traversal(tmp_path: Path):\n with pytest.raises(ValidationError):\n write_jsonl(tmp_path, \"../x.jsonl\", [Record(\"a\",1)])\n```", "source": "WithinUsAI/python_GOD_coder_100k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Produce an offline-first self-evolving code assistant architecture named `pn55pr78`.\nMust include: module layout, patch-safety policy, evaluation gates (tests/lint/types), versioned memory index.\n\nArchitecture: `pn55pr78` (offline-first, self-evolving)\n\nModules\n- core/loop.py: evolve → validate → accept/reject (bounded iterations)\n- patching/: diff builder, safe apply, atomic writes, rollback points\n- policy/: allowlist paths, deny globs (.git/, __pycache__/, binaries), patch size caps\n- signals/: parse pytest/ruff/mypy into normalized findings\n- memory/index.jsonl: append-only snapshots (hashes, metrics, rationale)\n\nSafety gates\n- refuse path traversal/symlink escapes; never edit binaries\n- accept only if tests/lint/types stay green or improve", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: System domain: document processing API\nStack: Rust, Axum, SQLx, Redis, Tokio, Docker\nCross-layer incident: memory leak in AST cache\nTask type: schema_contract_alignment\nDifficulty: hard\n\nSolve this as a complete-project engineer.\nOutput must include:\n- root cause across layers\n- final implementation patch\n- tests touching at least two layers\n- deployment or observability note\n- verification commands\n\nRepository sketch:\nrepo/\n src/main/java/com/acme/App.java\n src/main/java/com/acme/Service.java\n src/test/java/com/acme/AppTest.java\n pom.xml\n\nFocus: Focus on multi-layer debugging across frontend, backend, database, CI, caching, and deployment.\n\nassistant: Diagnosis:\n- Root cause: memory leak in AST cache crosses service boundaries, so the fix must align code, contracts, tests, and deployment behavior.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```java\nimport java.util.HashMap;\nimport java.util.Map;\n\npublic final class RequestHandler {\n public static Map handleRequest(Map payload) {\n Map clean = new HashMap<>();\n for (Map.Entry entry : payload.entrySet()) {\n if (entry.getValue() != null) clean.put(entry.getKey().trim(), entry.getValue());\n }\n if (!clean.containsKey(\"id\")) throw new IllegalArgumentException(\"missing id\");\n return Map.of(\"ok\", true, \"data\", clean);\n }\n}\n```\n\nTests:\n```java\nimport static org.junit.jupiter.api.Assertions.*;\nimport java.util.Map;\nimport org.junit.jupiter.api.Test;\n\nclass RequestHandlerTest {\n @Test\n void requiresId() {\n assertThrows(IllegalArgumentException.class, () -> RequestHandler.handleRequest(Map.of(\"name\", \"x\")));\n }\n}\n```\n\nVerification:\n- `./gradlew test`\n- `mvn test`\n\nEngineering notes:\n- Language: Java\n- Framework/tooling: Gradle\n- Stack context: Rust, Axum, SQLx, Redis, Tokio, Docker\n- Domain: document processing API\n- Task type: schema_contract_alignment\n- Difficulty: hard\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "Design CI/CD for a e-commerce service delivering audit logs.\nTarget platform: infra (Terraform).\nRequirements: pipelines, checks, artifact strategy, deployments, and rollbacks.\nConstraints: must include type hints where applicable, must include tests, must be production-ready, must avoid global state, must include clear error handling.\nDifficulty: expert. Include rollback strategy.\n\nOutput: design + implementation guidance suitable for shipping.\nDeliverable: CI/CD pipeline (GitHub Actions) with quality gates.\n\n```yaml\nname: ci\non:\n pull_request:\n push:\n branches: [main]\n\njobs:\n test:\n runs-on: ubuntu-latest\n steps:\n - uses: actions/checkout@v4\n - uses: actions/setup-python@v5\n with:\n python-version: \"3.11\"\n - run: python -m pip install -U pip\n - run: pip install -r requirements.txt\n - run: pip install -r requirements-dev.txt\n - run: ruff check .\n - run: mypy .\n - run: pytest -q --maxfail=1 --disable-warnings\n\n docker:\n needs: test\n runs-on: ubuntu-latest\n steps:\n - uses: actions/checkout@v4\n - uses: docker/setup-buildx-action@v3\n - run: docker build -t app:${{ github.sha }} .\n```\n\nDeployment strategy:\n- main → build → deploy to staging → smoke tests → canary to prod.\n- Rollback: redeploy previous image + DB migration rollback plan.\n\n\nHard-mode checks: concurrency safety, idempotency, and rollback validated; add chaos tests where feasible.", "source": "WithinUsAI/GOD_Coder_100k"} {"text": "Task type: lockfree_primitive\nScenario: job scheduler\nDomain focus: cryptography engineering (defensive)\nPrimary language: rust\nDifficulty: expert\nScale/SLO: multi-region active-active\nComponent: component_mopydnhy\nConstraints: include deterministic replay plan, include verification strategy, include failure modes and recovery, include backward compatibility and migration plan, explicit contracts and invariants\nAssume tight memory budget and cold-start constraints.\nDeliverable: Design a lock-free primitive with memory ordering reasoning and stress tests (no UB).\n\nOutput: rigorous design + invariants + verification plan + implementation sketch.\n**Contract**\n- Inputs validated at the boundary; explicit error taxonomy.\n- Idempotency for side effects via request_id; deterministic replay.\n- Backward compatibility: additive changes by default; versioned breaking changes.\n**Invariants**\n- Liveness: under bounded faults and stable network, progress occurs.\n- Isolation: tenant boundary enforced; no cross-tenant reads/writes.\n- Safety: state transitions preserve invariants; no partial commit leaks.\n**Failure modes & recovery**\n- Crash during commit: WAL replay completes or transaction aborts; no torn writes.\n- Duplicate requests: de-duplicate by (tenant, request_id) returning cached response.\n- Data corruption: checksums + scrubber; quarantine and rebuild from replicas/snapshots.\n**Security posture (defensive)**\n- Threat model: auth/authz, injection, replay/abuse, supply chain.\n- Least privilege; secrets in managed store; audit logs for sensitive ops.\n- Input normalization, parameterized queries, path traversal protections.\n**Verification strategy**\n- Fuzzing of parsers/framers/validators with corpus seeds.\n- Property tests against a pure reference model (state machine).\n- Deterministic simulation with fault injection (crash/partition/latency).\n\n**Snippet**\n```rust\n// Skeleton: SPSC ring buffer with acquire/release (outline)\nuse std::sync::atomic::{AtomicUsize, Ordering};\n\npub struct Ring {\n buf: Vec>,\n head: AtomicUsize,\n tail: AtomicUsize,\n cap: usize,\n}\n\n// Correctness sketch: producer uses Release on tail store, consumer uses Acquire on tail load.\n```\n\nExpert checks: state-machine proof sketch + model checking; upgrade/rollback rehearsed.", "source": "WithinUsAI/Omega_Genesis_Coder_100k"} {"text": "Perform a code review for a e-commerce PR implementing role-based access control.\nTarget platform: web (React + TypeScript).\nRequirements: list critical issues, improvements, and provide an improved patch excerpt.\nConstraints: must be easy to extend, must avoid global state, must include clear error handling, must include type hints where applicable, must be performant under load.\nDifficulty: easy. Assume untrusted input; validate everything.\n\nOutput: actionable implementation and verification artifacts.\nDeliverable: code review findings + improved patch excerpt.\n\n**Critical issues**\n1. Missing input validation at boundary; potential unexpected exceptions.\n2. No idempotency / retry safety for side-effecting endpoint.\n3. No tests for edge cases (empty input, duplicates, timeouts).\n4. Observability gaps: no request_id correlation, no metrics.\n\n**Improvements**\n- Add strict validation and explicit error responses.\n- Add idempotency key support for create endpoints.\n- Add unit + integration tests with CI gating.\n- Add structured logs and basic metrics.\n\nPatch excerpt (illustrative):\n```python\nif not idem_key:\n raise HTTPException(400, \"Missing Idempotency-Key\")\n```\n\n\nChecks: input validation, tests, and safe defaults included.", "source": "WithinUsAI/GOD_Coder_100k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Optimize while preserving behavior.\n\nFile: kmbztvkatdi.py\n```python\ndef itxsckdh_0(xs):\n out = []\n for x in xs:\n if x not in out:\n out.append(x)\n return out\n```\n\nRequirements: preserve first-seen order; O(n) average; add types + docstring.\n\n# kmbztvkatdi.py\nfrom __future__ import annotations\nfrom typing import Iterable, List, Set, TypeVar\n\nT = TypeVar(\"T\")\n\ndef itxsckdh_0(xs: Iterable[T]) -> List[T]:\n \"\"\"Return unique items preserving first-seen order.\"\"\"\n seen: Set[T] = set()\n out: List[T] = []\n for x in xs:\n if x in seen:\n continue\n seen.add(x)\n out.append(x)\n return out", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Produce an offline-first self-evolving code assistant architecture named `wyfxwi`.\nMust include: module layout, patch-safety policy, evaluation gates (tests/lint/types), versioned memory index.\n\nArchitecture: `wyfxwi` (offline-first, self-evolving)\n\nModules\n- core/loop.py: evolve → validate → accept/reject (bounded iterations)\n- patching/: diff builder, safe apply, atomic writes, rollback points\n- policy/: allowlist paths, deny globs (.git/, __pycache__/, binaries), patch size caps\n- signals/: parse pytest/ruff/mypy into normalized findings\n- memory/index.jsonl: append-only snapshots (hashes, metrics, rationale)\n\nSafety gates\n- refuse path traversal/symlink escapes; never edit binaries\n- accept only if tests/lint/types stay green or improve", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Task type: query_optimizer\nScenario: identity and access\nDomain focus: runtime systems\nPrimary language: rust\nDifficulty: expert\nScale/SLO: 1M msgs/min\nComponent: component_resvwklv\nConstraints: include deterministic replay plan, include test vectors and fuzz strategy, include performance model and limits, include verification strategy, include security threat model (defensive only)\nAssume tight memory budget and cold-start constraints.\nDeliverable: Design a cost-based optimizer slice: logical rules, physical operators, and cost model. Include regression tests and query-plan explain examples.\n\nOutput: elite engineering answer optimized for correctness, performance, and operability.\n**Contract**\n- Inputs validated at the boundary; explicit error taxonomy.\n- Idempotency for side effects via request_id; deterministic replay.\n- Backward compatibility: additive changes by default; versioned breaking changes.\n**Invariants**\n- Safety: state transitions preserve invariants; no partial commit leaks.\n- Isolation: tenant boundary enforced; no cross-tenant reads/writes.\n- Liveness: under bounded faults and stable network, progress occurs.\n**Failure modes & recovery**\n- Duplicate requests: de-duplicate by (tenant, request_id) returning cached response.\n- Network partition: minority cannot commit; clients receive retriable errors.\n- Data corruption: checksums + scrubber; quarantine and rebuild from replicas/snapshots.\n**Security posture (defensive)**\n- Threat model: auth/authz, injection, replay/abuse, supply chain.\n- Least privilege; secrets in managed store; audit logs for sensitive ops.\n- Input normalization, parameterized queries, path traversal protections.\n**Verification strategy**\n- Canary + shadow traffic; invariants checked in production via assertions/metrics.\n- Property tests against a pure reference model (state machine).\n- Fuzzing of parsers/framers/validators with corpus seeds.\n\n**Snippet**\n```python\n# Minimal cost model skeleton\nfrom dataclasses import dataclass\n\n@dataclass(frozen=True)\nclass Plan:\n op: str\n cost: float\n children: tuple[\"Plan\", ...] = ()\n\ndef choose_best(plans: list[Plan]) -> Plan:\n return min(plans, key=lambda p: p.cost)\n```\n\nExpert checks: state-machine proof sketch + model checking; upgrade/rollback rehearsed.", "source": "WithinUsAI/Omega_Genesis_Coder_100k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Fix a bug and add tests.\n\nFile: dqd1iovmrgf.py\n```python\ndef kd44ziv(n: int) -> int:\n \"\"\"Sum 1..n inclusive.\"\"\"\n if n < 0:\n raise ValueError(\"n must be non-negative\")\n total = 0\n for k in range(n): # BUG: should include n\n total += k\n return total\n```\n\nReturn unified diffs for dqd1iovmrgf.py and test_dqd1iovmrgf.py (pytest).\n\n*** Begin Patch\n*** Update File: dqd1iovmrgf.py\n@@\n def kd44ziv(n: int) -> int:\n@@\n total = 0\n- for k in range(n): # BUG: should include n\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_dqd1iovmrgf.py\n+import pytest\n+from dqd1iovmrgf import kd44ziv\n+\n+def test_zero():\n+ assert kd44ziv(0) == 0\n+\n+def test_one():\n+ assert kd44ziv(1) == 1\n+\n+def test_small():\n+ assert kd44ziv(7) == 28\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ kd44ziv(-1)\n+\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Implement a concurrent Python solution for telemetry ingestion.\nRequirements: choose appropriate concurrency model, handle cancellation/timeouts, include tests.\nConstraints: must be streaming-friendly, must be easy to extend, must avoid global state.\nDifficulty: hard. Provide helpful exceptions with actionable messages.\n\nDeliverable: corrected code and verification tests.\n```python\nfrom __future__ import annotations\nimport asyncio\nfrom dataclasses import dataclass\nfrom typing import Awaitable, Callable, Iterable, Optional\n\n@dataclass(frozen=True, slots=True)\nclass JobResult:\n ok: bool\n value: Optional[int]\n error: Optional[str]\n\nasync def run_bounded(\n factories: Iterable[Callable[[], Awaitable[int]]],\n *,\n limit: int = 10,\n timeout_s: float = 5.0,\n) -> list[JobResult]:\n if limit <= 0:\n raise ValueError(\"limit must be > 0\")\n sem = asyncio.Semaphore(limit)\n results: list[JobResult] = []\n\n async def one(factory: Callable[[], Awaitable[int]]) -> None:\n async with sem:\n try:\n v = await asyncio.wait_for(factory(), timeout=timeout_s)\n results.append(JobResult(True, v, None))\n except Exception as e:\n results.append(JobResult(False, None, str(e)))\n\n tasks = [asyncio.create_task(one(f)) for f in factories]\n try:\n await asyncio.gather(*tasks)\n finally:\n for t in tasks:\n if not t.done():\n t.cancel()\n return results\n```\n\n```python\nimport asyncio\nimport pytest\nfrom module_under_test import run_bounded\n\n@pytest.mark.asyncio\nasync def test_run_bounded_collects():\n async def work(x: int) -> int:\n await asyncio.sleep(0.01)\n return x\n fs = [(lambda i=i: work(i)) for i in range(30)]\n out = await run_bounded(fs, limit=5, timeout_s=1.0)\n assert len(out) == 30\n assert all(r.ok for r in out)\n```", "source": "WithinUsAI/python_GOD_coder_100k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Fix a bug and add tests.\n\nFile: ql7cj2h9.py\n```python\ndef hp4h72l6(n: int) -> int:\n \"\"\"Sum 1..n inclusive.\"\"\"\n if n < 0:\n raise ValueError(\"n must be non-negative\")\n total = 0\n for k in range(n): # BUG: should include n\n total += k\n return total\n```\n\nReturn unified diffs for ql7cj2h9.py and test_ql7cj2h9.py (pytest).\n\n*** Begin Patch\n*** Update File: ql7cj2h9.py\n@@\n def hp4h72l6(n: int) -> int:\n@@\n total = 0\n- for k in range(n): # BUG: should include n\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_ql7cj2h9.py\n+import pytest\n+from ql7cj2h9 import hp4h72l6\n+\n+def test_zero():\n+ assert hp4h72l6(0) == 0\n+\n+def test_one():\n+ assert hp4h72l6(1) == 1\n+\n+def test_small():\n+ assert hp4h72l6(7) == 28\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ hp4h72l6(-1)\n+\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: Language: TypeScript\nFramework/tooling: React\nDomain: feature flag service\nLogic challenge: gRPC retry storm\nTask type: backwards_compatible_redesign\nDifficulty: expert\n\nReturn a rigorous engineering answer:\n- identify the hidden root cause or logical failure\n- present the corrected implementation\n- add tests that prove the fix\n- list verification commands\n- explain why naive fixes are insufficient when relevant\n\nRepository sketch:\nrepo/\n src/\n api.ts\n service.ts\n schema.ts\n tests/\n api.test.ts\n package.json\n\nFocus: Focus on staff-level problem solving with multi-file patches, rollout implications, performance and security tradeoffs.\n\nassistant: Diagnosis:\n- Staff-level diagnosis: gRPC retry storm impacts correctness, operability, and future maintenance, so the fix must be minimal where possible but complete where necessary.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```ts\ntype Payload = Record;\n\nexport function normalizePayload(payload: Payload): Payload {\n if (!payload || typeof payload !== \"object\" || Array.isArray(payload)) {\n throw new TypeError(\"payload must be a plain object\");\n }\n return Object.fromEntries(\n Object.entries(payload)\n .filter(([, value]) => value !== null && value !== undefined)\n .map(([key, value]) => [String(key).trim(), value])\n );\n}\n\nexport function handleGrpcRetryStorm(payload: Payload) {\n const clean = normalizePayload(payload);\n if (!(\"id\" in clean)) {\n return { ok: false, data: {}, error: \"missing id\" };\n }\n return { ok: true, data: clean, error: null };\n}\n```\n\nTests:\n```ts\nimport { describe, it, expect } from \"vitest\";\nimport { handleGrpcRetryStorm } from \"../src/service\";\n\ndescribe(\"handler\", () => {\n it(\"accepts valid input\", () => {\n expect(handleGrpcRetryStorm({ id: 7, name: \"ok\", unused: null })).toEqual({\n ok: true,\n data: { id: 7, name: \"ok\" },\n error: null\n });\n });\n\n it(\"rejects missing id\", () => {\n expect(handleGrpcRetryStorm({ name: \"x\" }).error).toMatch(/missing id/);\n });\n});\n```\n\nVerification:\n- `npm test`\n- `npm run typecheck`\n- `npm run lint`\n\nEngineering notes:\n- Language: TypeScript\n- Framework/tooling: React\n- Stack context: Rust, Axum, SQLx, Redis, Tokio, Docker\n- Domain: feature flag service\n- Task type: backwards_compatible_redesign\n- Difficulty: expert\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Fix a bug and add tests.\n\nFile: tcp06h.py\n```python\ndef ufyj1v83(n: int) -> int:\n \"\"\"Sum 1..n inclusive.\"\"\"\n if n < 0:\n raise ValueError(\"n must be non-negative\")\n total = 0\n for k in range(n): # BUG: should include n\n total += k\n return total\n```\n\nReturn unified diffs for tcp06h.py and test_tcp06h.py (pytest).\n\n*** Begin Patch\n*** Update File: tcp06h.py\n@@\n def ufyj1v83(n: int) -> int:\n@@\n total = 0\n- for k in range(n): # BUG: should include n\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_tcp06h.py\n+import pytest\n+from tcp06h import ufyj1v83\n+\n+def test_zero():\n+ assert ufyj1v83(0) == 0\n+\n+def test_one():\n+ assert ufyj1v83(1) == 1\n+\n+def test_small():\n+ assert ufyj1v83(7) == 28\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ ufyj1v83(-1)\n+\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Fix a bug and add tests.\n\nFile: hy8mv_25_.py\n```python\ndef bsravxqvrfi7(n: int) -> int:\n \"\"\"Sum 1..n inclusive.\"\"\"\n if n < 0:\n raise ValueError(\"n must be non-negative\")\n total = 0\n for k in range(n): # BUG: should include n\n total += k\n return total\n```\n\nReturn unified diffs for hy8mv_25_.py and test_hy8mv_25_.py (pytest).\n\n*** Begin Patch\n*** Update File: hy8mv_25_.py\n@@\n def bsravxqvrfi7(n: int) -> int:\n@@\n total = 0\n- for k in range(n): # BUG: should include n\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_hy8mv_25_.py\n+import pytest\n+from hy8mv_25_ import bsravxqvrfi7\n+\n+def test_zero():\n+ assert bsravxqvrfi7(0) == 0\n+\n+def test_one():\n+ assert bsravxqvrfi7(1) == 1\n+\n+def test_small():\n+ assert bsravxqvrfi7(7) == 28\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ bsravxqvrfi7(-1)\n+\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Optimize while preserving behavior and order.\n\n```python\ndef f77860(xs):\n out=[]\n for x in xs:\n if x not in out: out.append(x)\n return out\n```\nReturn `m53980.py` with types and O(n) average.\n\n```python\n# m53980.py\nfrom __future__ import annotations\nfrom typing import Iterable, List, Set, TypeVar\nT=TypeVar(\"T\")\n\ndef f77860(xs: Iterable[T]) -> List[T]:\n \"\"\"Unique items preserving first-seen order.\"\"\"\n seen: Set[T]=set()\n out: List[T]=[]\n for x in xs:\n if x in seen: continue\n seen.add(x); out.append(x)\n return out\n```", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Optimize while preserving behavior and order.\n\n```python\ndef f78924(xs):\n out=[]\n for x in xs:\n if x not in out: out.append(x)\n return out\n```\nReturn `m54132.py` with types and O(n) average.\n\n```python\n# m54132.py\nfrom __future__ import annotations\nfrom typing import Iterable, List, Set, TypeVar\nT=TypeVar(\"T\")\n\ndef f78924(xs: Iterable[T]) -> List[T]:\n \"\"\"Unique items preserving first-seen order.\"\"\"\n seen: Set[T]=set()\n out: List[T]=[]\n for x in xs:\n if x in seen: continue\n seen.add(x); out.append(x)\n return out\n```", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Fix the bug and add pytest tests.\n\n```python\ndef f84496(n: int) -> int:\n # sum 1..n inclusive\n if n < 0: raise ValueError\n total = 0\n for k in range(n): # BUG\n total += k\n return total\n```\nReturn unified diffs for `m54928.py` and `test_m54928.py`.\n\n*** Begin Patch\n*** Update File: m54928.py\n@@\n def f84496(n: int) -> int:\n@@\n- for k in range(n): # BUG\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_m54928.py\n+import pytest\n+from m54928 import f84496\n+\n+def test_small():\n+ assert f84496(7) == 28\n+\n+def test_zero():\n+ assert f84496(0) == 0\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ f84496(-1)\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Implement an ML engineering workflow for gaming focusing on multi-tenant isolation.\nTarget platform: ML (training + serving).\nRequirements: data contract, training loop, evaluation, model registry, serving API, monitoring.\nConstraints: must be performant under load, must avoid global state, must be production-ready, must be observable (logs/metrics/traces), must include clear error handling.\nDifficulty: hard. Assume schema evolves frequently; design for migrations.\n\nOutput: design + implementation guidance suitable for shipping.\nDeliverable: ML engineering blueprint (training + serving + monitoring), safe and production-oriented.\n\n**Data contract**\n- Define feature schema + ranges; validate at training and serving.\n\n**Training**\n- Deterministic split; baseline model; track metrics (AUC/F1/latency).\n- Store artifacts: model, config, feature stats.\n\n**Registry**\n- Promote models via approval gates; record lineage.\n\n**Serving**\n- Separate inference service with `/predict`.\n- Input validation + default handling; timeouts.\n\n**Monitoring**\n- Data drift: feature distribution checks.\n- Performance: online metrics + periodic labels; alert on regression.\n\nMinimal serving skeleton (FastAPI-ish):\n```python\n# validate input -> vectorize -> model.predict_proba -> return\n```\n\n\nHard-mode checks: concurrency safety, idempotency, and rollback validated; add chaos tests where feasible.", "source": "WithinUsAI/GOD_Coder_100k"} {"text": "Write a thorough test suite for a Python component used for rate limiting.\nRequirements: cover edge cases, invalid inputs, and behavior invariants.\nConstraints: must be easy to extend, must avoid global state, must be streaming-friendly.\nDifficulty: expert. Provide helpful exceptions with actionable messages.\n\nDeliverable: implementation + tests.\n```python\n# tests (pytest-style) for a module providing: normalize(), parse_lines(), compute_stats()\nimport math\nimport pytest\n\ndef test_normalize_idempotent(module_under_test):\n x = \" A\\tB \"\n assert module_under_test.normalize(module_under_test.normalize(x)) == module_under_test.normalize(x)\n\ndef test_parse_lines_rejects_invalid(module_under_test):\n with pytest.raises(ValueError):\n module_under_test.parse_lines([\"\", \"???\", None]) # type: ignore[arg-type]\n\ndef test_compute_stats_basic(module_under_test):\n data = [1, 2, 3, 4]\n s = module_under_test.compute_stats(data)\n assert s.count == 4\n assert s.total == 10\n assert math.isclose(s.mean, 2.5)\n```", "source": "WithinUsAI/python_GOD_coder_100k"} {"text": "Fix the bug and add pytest tests.\n\n```python\ndef f63330(n: int) -> int:\n # sum 1..n inclusive\n if n < 0: raise ValueError\n total = 0\n for k in range(n): # BUG\n total += k\n return total\n```\nReturn unified diffs for `m66190.py` and `test_m66190.py`.\n\n*** Begin Patch\n*** Update File: m66190.py\n@@\n def f63330(n: int) -> int:\n@@\n- for k in range(n): # BUG\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_m66190.py\n+import pytest\n+from m66190 import f63330\n+\n+def test_small():\n+ assert f63330(7) == 28\n+\n+def test_zero():\n+ assert f63330(0) == 0\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ f63330(-1)\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: Language: Java\nFramework/tooling: Maven\nDomain: search service\nLogic challenge: rate-limit bypass\nTask type: edge_case_hardening\nDifficulty: hard\n\nReturn a rigorous engineering answer:\n- identify the hidden root cause or logical failure\n- present the corrected implementation\n- add tests that prove the fix\n- list verification commands\n- explain why naive fixes are insufficient when relevant\n\nRepository sketch:\nrepo/\n src/main/java/com/acme/App.java\n src/main/java/com/acme/Service.java\n src/test/java/com/acme/AppTest.java\n pom.xml\n\nFocus: Focus on strong structured logic with edge cases, data validation, and concurrency safety.\n\nassistant: Diagnosis:\n- Root cause: the failure around rate-limit bypass is caused by missing validation, weak edge-case handling, or unsafe lifecycle behavior in the current implementation.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```java\nimport java.util.HashMap;\nimport java.util.Map;\n\npublic final class RequestHandler {\n public static Map handleRequest(Map payload) {\n Map clean = new HashMap<>();\n for (Map.Entry entry : payload.entrySet()) {\n if (entry.getValue() != null) clean.put(entry.getKey().trim(), entry.getValue());\n }\n if (!clean.containsKey(\"id\")) throw new IllegalArgumentException(\"missing id\");\n return Map.of(\"ok\", true, \"data\", clean);\n }\n}\n```\n\nTests:\n```java\nimport static org.junit.jupiter.api.Assertions.*;\nimport java.util.Map;\nimport org.junit.jupiter.api.Test;\n\nclass RequestHandlerTest {\n @Test\n void requiresId() {\n assertThrows(IllegalArgumentException.class, () -> RequestHandler.handleRequest(Map.of(\"name\", \"x\")));\n }\n}\n```\n\nVerification:\n- `./gradlew test`\n- `mvn test`\n\nEngineering notes:\n- Language: Java\n- Framework/tooling: Maven\n- Stack context: Rust, Axum, SQLx, Redis, Tokio, Docker\n- Domain: search service\n- Task type: edge_case_hardening\n- Difficulty: hard\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Refactor to modern typed Python with immutability and tests.\n\nFile: kcutm8_g3tsz.py\n```python\nclass Vo58I6Lum:\n def __init__(self, name, values):\n self.name = name\n self.values = list(values)\n def add(self, v):\n self.values.append(v)\n def mean(self):\n s = 0\n for x in self.values:\n s += x\n return s / len(self.values)\n```\n\nReturn full new kcutm8_g3tsz.py and test_kcutm8_g3tsz.py.\n\n# kcutm8_g3tsz.py\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom typing import Iterable, Tuple\n\n@dataclass(frozen=True)\nclass Vo58I6Lum:\n name: str\n values: Tuple[float, ...]\n\n @staticmethod\n def create(name: str, values: Iterable[float]) -> \"Vo58I6Lum\":\n vals = tuple(float(v) for v in values)\n if not vals:\n raise ValueError(\"values must be non-empty\")\n return Vo58I6Lum(name=name, values=vals)\n\n def add(self, v: float) -> \"Vo58I6Lum\":\n return Vo58I6Lum(name=self.name, values=self.values + (float(v),))\n\n def mean(self) -> float:\n return sum(self.values) / len(self.values)\n\n# test_kcutm8_g3tsz.py\nimport pytest\nfrom kcutm8_g3tsz import Vo58I6Lum\n\ndef test_mean_and_add():\n c = Vo58I6Lum.create(\"a\", [1, 2, 3])\n assert c.mean() == 2.0\n assert c.add(5).mean() == (1 + 2 + 3 + 5) / 4\n\ndef test_empty_raises():\n with pytest.raises(ValueError):\n Vo58I6Lum.create(\"x\", [])", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Add a clear docstring and type hints to this function:\n\n```python\ndef f43524(s):\n return ''.join(x for x in s if x.isalnum()).lower()\n```\n\n```python\nfrom __future__ import annotations\n\ndef f43524(s: str) -> str:\n \"\"\"Normalize a string: keep only alphanumerics and lowercase the result.\"\"\"\n return \"\".join(ch for ch in s if ch.isalnum()).lower()\n```", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Refactor to modern typed Python with immutability and tests.\n\nFile: c2k80k5ltitz.py\n```python\nclass G0Niu9:\n def __init__(self, name, values):\n self.name = name\n self.values = list(values)\n def add(self, v):\n self.values.append(v)\n def mean(self):\n s = 0\n for x in self.values:\n s += x\n return s / len(self.values)\n```\n\nReturn full new c2k80k5ltitz.py and test_c2k80k5ltitz.py.\n\n# c2k80k5ltitz.py\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom typing import Iterable, Tuple\n\n@dataclass(frozen=True)\nclass G0Niu9:\n name: str\n values: Tuple[float, ...]\n\n @staticmethod\n def create(name: str, values: Iterable[float]) -> \"G0Niu9\":\n vals = tuple(float(v) for v in values)\n if not vals:\n raise ValueError(\"values must be non-empty\")\n return G0Niu9(name=name, values=vals)\n\n def add(self, v: float) -> \"G0Niu9\":\n return G0Niu9(name=self.name, values=self.values + (float(v),))\n\n def mean(self) -> float:\n return sum(self.values) / len(self.values)\n\n# test_c2k80k5ltitz.py\nimport pytest\nfrom c2k80k5ltitz import G0Niu9\n\ndef test_mean_and_add():\n c = G0Niu9.create(\"a\", [1, 2, 3])\n assert c.mean() == 2.0\n assert c.add(5).mean() == (1 + 2 + 3 + 5) / 4\n\ndef test_empty_raises():\n with pytest.raises(ValueError):\n G0Niu9.create(\"x\", [])", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Add observability for file uploads in a social media system.\nTarget platform: ML (scikit + batch).\nRequirements: structured logs, metrics, tracing, dashboards, and alerting rules.\nConstraints: must avoid global state, must be secure-by-default, must include clear error handling.\nDifficulty: expert. Assume mobile clients are occasionally offline.\n\nOutput: production-oriented blueprint with code where appropriate.\nDeliverable: observability plan + example instrumentation.\n\n**Logs**\n- JSON logs with: request_id, tenant_id, route, status, latency_ms, error_code.\n\n**Metrics**\n- Counters: requests_total{route,status}, errors_total{code}\n- Histograms: request_latency_ms{route}\n- Gauges: queue_depth, db_pool_in_use\n\n**Tracing**\n- Trace ID propagated via headers; spans around DB, cache, external calls.\n\n**Alerts**\n- p95 latency breach, error rate spike, saturation (CPU/mem), queue backlog.\n\nExample (Python structured logging pseudo):\n```python\nlog.info(\"request_done\", extra={\"route\": route, \"status\": status, \"latency_ms\": ms, \"request_id\": rid})\n```\n\n\nHard-mode checks: concurrency safety, idempotency, and rollback validated; add chaos tests where feasible.", "source": "WithinUsAI/GOD_Coder_100k"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: Language: Python\nFramework/tooling: Airflow\nDomain: search service\nLogic challenge: websocket reconnect storm\nTask type: misleading_symptom_debug\nDifficulty: hard\n\nReturn a rigorous engineering answer:\n- identify the hidden root cause or logical failure\n- present the corrected implementation\n- add tests that prove the fix\n- list verification commands\n- explain why naive fixes are insufficient when relevant\n\nRepository sketch:\nrepo/\n app/\n api.py\n service.py\n models.py\n tests/\n test_api.py\n pyproject.toml\n\nFocus: Focus on ambiguity, misleading symptoms, hidden root causes, and high-stakes debugging.\n\nassistant: Diagnosis:\n- Hidden root cause: websocket reconnect storm presents misleading symptoms, so the patch must target the actual logic boundary rather than the first visible failure.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```python\nfrom __future__ import annotations\n\nfrom dataclasses import dataclass\nfrom typing import Any\n\n@dataclass\nclass ServiceResult:\n ok: bool\n data: dict[str, Any]\n error: str | None = None\n\ndef normalize_payload(payload: dict[str, Any]) -> dict[str, Any]:\n if not isinstance(payload, dict):\n raise TypeError(\"payload must be a dict\")\n clean: dict[str, Any] = {}\n for key, value in payload.items():\n if value is None:\n continue\n clean[str(key).strip()] = value\n return clean\n\ndef handle_websocket_reconnect_storm(payload: dict[str, Any]) -> ServiceResult:\n clean = normalize_payload(payload)\n if \"id\" not in clean:\n return ServiceResult(ok=False, data={}, error=\"missing id\")\n return ServiceResult(ok=True, data=clean)\n```\n\nTests:\n```python\nimport pytest\nfrom app.service import handle_jwt_refresh_token_rotation as handler\n\ndef test_handler_accepts_valid_payload():\n result = handler({\"id\": 7, \"name\": \"ok\", \"unused\": None})\n assert result.ok is True\n assert result.data == {\"id\": 7, \"name\": \"ok\"}\n\ndef test_handler_rejects_missing_id():\n result = handler({\"name\": \"x\"})\n assert result.ok is False\n assert result.error == \"missing id\"\n```\n\nVerification:\n- `pytest -q`\n- `ruff check .`\n- `python -m compileall .`\n\nEngineering notes:\n- Language: Python\n- Framework/tooling: Airflow\n- Stack context: Rust, Axum, SQLx, Redis, Tokio, Docker\n- Domain: search service\n- Task type: misleading_symptom_debug\n- Difficulty: hard\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: Language: SQL\nFramework/tooling: DuckDB\nDomain: feature flag service\nLogic challenge: slow cold start\nTask type: monorepo_toolchain_recovery\nDifficulty: expert\n\nReturn a rigorous engineering answer:\n- identify the hidden root cause or logical failure\n- present the corrected implementation\n- add tests that prove the fix\n- list verification commands\n- explain why naive fixes are insufficient when relevant\n\nRepository sketch:\nrepo/\n migrations/\n 001_init.sql\n 002_add_index.sql\n queries/\n report.sql\n tests/\n report_cases.md\n\nFocus: Focus on staff-level problem solving with multi-file patches, rollout implications, performance and security tradeoffs.\n\nassistant: Diagnosis:\n- Staff-level diagnosis: slow cold start impacts correctness, operability, and future maintenance, so the fix must be minimal where possible but complete where necessary.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```sql\nWITH ranked AS (\n SELECT\n user_id,\n created_at,\n amount,\n ROW_NUMBER() OVER (PARTITION BY user_id ORDER BY created_at DESC, id DESC) AS rn\n FROM orders\n)\nSELECT user_id, created_at, amount\nFROM ranked\nWHERE rn = 1;\n```\n\nTests:\n```sql\n-- Correctness checks:\n-- 1) multiple rows per user\n-- 2) identical timestamps require deterministic tie-breaker\n-- 3) null values handled by business rules\n```\n\nVerification:\n- `run migration checks`\n- `run query correctness cases`\n\nEngineering notes:\n- Language: SQL\n- Framework/tooling: DuckDB\n- Stack context: FastAPI, PostgreSQL, Redis, Celery, pytest, Docker\n- Domain: feature flag service\n- Task type: monorepo_toolchain_recovery\n- Difficulty: expert\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "Task type: smt_constraint_model\nScenario: real-time notification hub\nDomain focus: real-time scheduling\nPrimary language: smtlib\nDifficulty: hard\nScale/SLO: 100k RPS peak\nComponent: component_agpspniz\nConstraints: include verification strategy, include security threat model (defensive only), include failure modes and recovery, include backward compatibility and migration plan, avoid data races and undefined behavior, include performance model and limits, assume adversarial inputs; validate everything\nAssume weekly network partitions.\nDeliverable: Provide an SMT constraint model (or Python-to-SMT) for correctness/optimization; include sample instances and how to validate solutions.\n\nOutput: rigorous design + invariants + verification plan + implementation sketch.\n**Contract**\n- Inputs validated at the boundary; explicit error taxonomy.\n- Idempotency for side effects via request_id; deterministic replay.\n- Backward compatibility: additive changes by default; versioned breaking changes.\n**Invariants**\n- Determinism: replay of the same event log yields identical outputs.\n- Safety: state transitions preserve invariants; no partial commit leaks.\n- Liveness: under bounded faults and stable network, progress occurs.\n**Failure modes & recovery**\n- Network partition: minority cannot commit; clients receive retriable errors.\n- Crash during commit: WAL replay completes or transaction aborts; no torn writes.\n- Data corruption: checksums + scrubber; quarantine and rebuild from replicas/snapshots.\n**Security posture (defensive)**\n- Threat model: auth/authz, injection, replay/abuse, supply chain.\n- Least privilege; secrets in managed store; audit logs for sensitive ops.\n- Input normalization, parameterized queries, path traversal protections.\n**Verification strategy**\n- Property tests against a pure reference model (state machine).\n- Canary + shadow traffic; invariants checked in production via assertions/metrics.\n- Deterministic simulation with fault injection (crash/partition/latency).\n\n**Snippet**\n```smtlib\n; Find an assignment minimizing cost while satisfying constraints\n(declare-const x Int)\n(declare-const y Int)\n(assert (and (>= x 0) (>= y 0) (<= (+ x y) 10)))\n(minimize (+ (* 3 x) (* 2 y)))\n(check-sat)\n(get-model)\n```\n\nHard checks: fault injection tests gate merges; perf thresholds enforced in CI.", "source": "WithinUsAI/Omega_Genesis_Coder_100k"} {"text": "Write secure, defensive Python code for log processing.\nRequirements: input validation, safe file handling, prevent path traversal, include tests.\nConstraints: must include docstrings, must be streaming-friendly.\nDifficulty: expert. Avoid quadratic behavior on large inputs.\n\nDeliverable: corrected code and verification tests.\n```python\nfrom __future__ import annotations\n\nfrom dataclasses import dataclass\nfrom pathlib import Path\nfrom typing import Iterable\nimport json\n\n\nclass ValidationError(ValueError):\n \"\"\"Raised when input validation fails.\"\"\"\n\n\ndef safe_join(base: Path, *parts: str) -> Path:\n \"\"\"Join paths while preventing traversal outside base.\"\"\"\n b = base.resolve()\n p = (b / Path(*parts)).resolve()\n if p != b and b not in p.parents:\n raise ValidationError(f\"unsafe path: {p}\")\n return p\n\n\n@dataclass(frozen=True, slots=True)\nclass Record:\n key: str\n value: int\n\n\ndef parse_jsonl(lines: Iterable[str]) -> list[Record]:\n out: list[Record] = []\n for idx, line in enumerate(lines, 1):\n s = line.strip()\n if not s:\n continue\n try:\n obj = json.loads(s)\n except json.JSONDecodeError as e:\n raise ValidationError(f\"line {idx}: invalid json\") from e\n if not isinstance(obj, dict):\n raise ValidationError(f\"line {idx}: expected object\")\n key = obj.get(\"key\")\n val = obj.get(\"value\")\n if not isinstance(key, str) or not key:\n raise ValidationError(f\"line {idx}: key must be non-empty str\")\n if not isinstance(val, int):\n raise ValidationError(f\"line {idx}: value must be int\")\n out.append(Record(key, val))\n return out\n\n\ndef write_jsonl(base: Path, rel: str, records: Iterable[Record]) -> Path:\n base.mkdir(parents=True, exist_ok=True)\n dst = safe_join(base, rel)\n dst.parent.mkdir(parents=True, exist_ok=True)\n with dst.open(\"w\", encoding=\"utf-8\", newline=\"\\n\") as f:\n for r in records:\n f.write(json.dumps({\"key\": r.key, \"value\": r.value}, ensure_ascii=False) + \"\\n\")\n return dst\n```\n\n```python\n# tests (pytest-style)\nimport json\nfrom pathlib import Path\nimport pytest\nfrom module_under_test import ValidationError, Record, parse_jsonl, write_jsonl\n\ndef test_parse_ok():\n lines = [json.dumps({\"key\":\"a\",\"value\":1}), json.dumps({\"key\":\"b\",\"value\":2})]\n assert parse_jsonl(lines) == [Record(\"a\",1), Record(\"b\",2)]\n\ndef test_parse_rejects_bad_json():\n with pytest.raises(ValidationError):\n parse_jsonl([\"{not json}\"])\n\ndef test_safe_join_blocks_traversal(tmp_path: Path):\n with pytest.raises(ValidationError):\n write_jsonl(tmp_path, \"../x.jsonl\", [Record(\"a\",1)])\n```", "source": "WithinUsAI/python_GOD_coder_100k"} {"text": "Build an elite-grade solution in the domain of databases for scenario: payment processing.\nPrimary language: python.\nDifficulty: expert.\nConstraints: include tests or verification strategy, avoid undefined behavior and data races, document performance characteristics, provide rollout and rollback guidance.\nComponent: component_lqkoypr.\nAssume strict auditability and replayable history.\nTask: Implement a concurrency primitive or subsystem (lock-free queue, thread pool, async runtime component). Explain memory ordering and correctness arguments; include stress tests.\n\nOutput: rigorous solution with invariants, failure modes, and performance notes.\nOutput: correctness-focused concurrency primitive + stress tests.\n\n**Primitive**\n- Bounded MPMC queue with backpressure (blocking push/pop) OR lock-free SPSC ring buffer.\n\n**Correctness notes**\n- For lock-free: use acquire/release semantics on head/tail indices.\n- Avoid ABA by monotonic counters; ring index = counter % capacity.\n\n**Stress tests**\n- Multi-thread producers/consumers; assert item multiset preserved.\n- Use time-bounded randomized schedules; detect deadlocks.\n\n\nExpert checks: state-machine reasoning, concurrency stress, and upgrade/rollback validated.", "source": "WithinUsAI/Elite_GOD_Coder_100k"} {"text": "Design and implement an algorithm for task scheduling.\nRequirements: define inputs/outputs, implement solution with complexity analysis, and include tests.\nConstraints: must include type hints, must provide clear error messages, must include tests.\nDifficulty: easy. Provide helpful exceptions with actionable messages.\n\nDeliverable: corrected code and verification tests.\nProblem: compute rolling sums over events (ts:int,value:int) with window W seconds. Events may be out-of-order.\n\nComplexity: sorting O(n log n); window maintenance O(n); memory O(k).\n\n```python\nfrom __future__ import annotations\nfrom collections import deque\nfrom dataclasses import dataclass\nfrom typing import Iterable, List, Tuple\n\n@dataclass(frozen=True, slots=True)\nclass Event:\n ts: int\n value: int\n\ndef rolling_sum(events: Iterable[Event], window_s: int) -> List[Tuple[int,int]]:\n if window_s < 0:\n raise ValueError(\"window_s must be >= 0\")\n evs = sorted(events, key=lambda e: e.ts)\n q: deque[Event] = deque()\n s = 0\n out: List[Tuple[int,int]] = []\n for e in evs:\n q.append(e)\n s += e.value\n cutoff = e.ts - window_s\n while q and q[0].ts < cutoff:\n old = q.popleft()\n s -= old.value\n out.append((e.ts, s))\n return out\n```\n\n```python\nimport pytest\nfrom module_under_test import Event, rolling_sum\n\ndef test_rolling_sum():\n ev = [Event(10,1), Event(11,2), Event(20,5)]\n assert rolling_sum(ev, 5) == [(10,1),(11,3),(20,5)]\n```", "source": "WithinUsAI/python_GOD_coder_100k"} {"text": "Build an elite-grade solution in the domain of high-performance services for scenario: chat messaging.\nPrimary language: rust.\nDifficulty: hard.\nConstraints: avoid undefined behavior and data races, assume untrusted inputs; validate and sanitize, include tests or verification strategy, include invariants and failure modes, provide rollout and rollback guidance.\nComponent: component_uqphqom.\nAssume crash-only design; recovery must be deterministic.\nTask: Implement or outline a storage/indexing subsystem (LSM/B-Tree, WAL, snapshots). Include transaction/consistency considerations and benchmark plan.\n\nOutput: production blueprint plus correctness arguments and test strategy.\nOutput: storage design + WAL + compaction + benchmarks.\n\n**Design**\n- WAL (append-only) for durability; fsync policy configurable.\n- Memtable (in-memory) → flush to immutable SSTables.\n- LSM compaction tiers; bloom filters per SSTable for point-lookups.\n- Manifest tracks SSTable set; atomic pointer swap on updates.\n\n**Correctness**\n- Crash recovery: replay WAL to rebuild memtable; manifest ensures last consistent set.\n- Reads: merge memtable + SSTables newest→oldest; tombstones override older values.\n\n**Bench plan**\n- Workloads: write-heavy, read-heavy, mixed; measure p50/p95 latency and write amplification.\n- Track compaction debt and space amplification.\n\n**Test plan**\n- Fuzz crash points: kill after WAL append / after manifest update; verify invariants on restart.\n\n\nHard checks: failure injection tests and performance regressions gated.", "source": "WithinUsAI/Elite_GOD_Coder_100k"} {"text": "Optimize while preserving behavior and order.\n\n```python\ndef f60452(xs):\n out=[]\n for x in xs:\n if x not in out: out.append(x)\n return out\n```\nReturn `m08636.py` with types and O(n) average.\n\n```python\n# m08636.py\nfrom __future__ import annotations\nfrom typing import Iterable, List, Set, TypeVar\nT=TypeVar(\"T\")\n\ndef f60452(xs: Iterable[T]) -> List[T]:\n \"\"\"Unique items preserving first-seen order.\"\"\"\n seen: Set[T]=set()\n out: List[T]=[]\n for x in xs:\n if x in seen: continue\n seen.add(x); out.append(x)\n return out\n```", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Optimize while preserving behavior.\n\nFile: yas8itb.py\n```python\ndef rpdtyvz(xs):\n out = []\n for x in xs:\n if x not in out:\n out.append(x)\n return out\n```\n\nRequirements: preserve first-seen order; O(n) average; add types + docstring.\n\n# yas8itb.py\nfrom __future__ import annotations\nfrom typing import Iterable, List, Set, TypeVar\n\nT = TypeVar(\"T\")\n\ndef rpdtyvz(xs: Iterable[T]) -> List[T]:\n \"\"\"Return unique items preserving first-seen order.\"\"\"\n seen: Set[T] = set()\n out: List[T] = []\n for x in xs:\n if x in seen:\n continue\n seen.add(x)\n out.append(x)\n return out", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Refactor to modern typed Python with immutability and tests.\n\nFile: jp_5t6hg3.py\n```python\nclass Ak316Cnke:\n def __init__(self, name, values):\n self.name = name\n self.values = list(values)\n def add(self, v):\n self.values.append(v)\n def mean(self):\n s = 0\n for x in self.values:\n s += x\n return s / len(self.values)\n```\n\nReturn full new jp_5t6hg3.py and test_jp_5t6hg3.py.\n\n# jp_5t6hg3.py\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom typing import Iterable, Tuple\n\n@dataclass(frozen=True)\nclass Ak316Cnke:\n name: str\n values: Tuple[float, ...]\n\n @staticmethod\n def create(name: str, values: Iterable[float]) -> \"Ak316Cnke\":\n vals = tuple(float(v) for v in values)\n if not vals:\n raise ValueError(\"values must be non-empty\")\n return Ak316Cnke(name=name, values=vals)\n\n def add(self, v: float) -> \"Ak316Cnke\":\n return Ak316Cnke(name=self.name, values=self.values + (float(v),))\n\n def mean(self) -> float:\n return sum(self.values) / len(self.values)\n\n# test_jp_5t6hg3.py\nimport pytest\nfrom jp_5t6hg3 import Ak316Cnke\n\ndef test_mean_and_add():\n c = Ak316Cnke.create(\"a\", [1, 2, 3])\n assert c.mean() == 2.0\n assert c.add(5).mean() == (1 + 2 + 3 + 5) / 4\n\ndef test_empty_raises():\n with pytest.raises(ValueError):\n Ak316Cnke.create(\"x\", [])", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Task type: storage_engine\nScenario: streaming ETL\nDomain focus: query planning\nPrimary language: typescript\nDifficulty: expert+\nScale/SLO: 50 TB/day ingestion\nComponent: component_siyswvok\nConstraints: include deterministic replay plan, assume adversarial inputs; validate everything, include backward compatibility and migration plan, include test vectors and fuzz strategy, explicit contracts and invariants, include security threat model (defensive only)\nAssume hostile inputs and targeted abuse patterns.\nDeliverable: Design a storage engine subsystem (WAL, snapshots, compaction). Include crash recovery invariants and a benchmark plan.\n\nOutput: elite engineering answer optimized for correctness, performance, and operability.\n**Contract**\n- Inputs validated at the boundary; explicit error taxonomy.\n- Idempotency for side effects via request_id; deterministic replay.\n- Backward compatibility: additive changes by default; versioned breaking changes.\n**Invariants**\n- Determinism: replay of the same event log yields identical outputs.\n- Isolation: tenant boundary enforced; no cross-tenant reads/writes.\n- Liveness: under bounded faults and stable network, progress occurs.\n**Failure modes & recovery**\n- Data corruption: checksums + scrubber; quarantine and rebuild from replicas/snapshots.\n- Network partition: minority cannot commit; clients receive retriable errors.\n- Duplicate requests: de-duplicate by (tenant, request_id) returning cached response.\n**Security posture (defensive)**\n- Threat model: auth/authz, injection, replay/abuse, supply chain.\n- Least privilege; secrets in managed store; audit logs for sensitive ops.\n- Input normalization, parameterized queries, path traversal protections.\n**Verification strategy**\n- Deterministic simulation with fault injection (crash/partition/latency).\n- Canary + shadow traffic; invariants checked in production via assertions/metrics.\n- Fuzzing of parsers/framers/validators with corpus seeds.\n\n**Snippet**\n```text\nImplementation sketch: factor pure state-machine core; adapters for I/O; add deterministic replay log.\n```\nExpert+ checks: mechanized invariants (or exhaustive model checking), adversarial fuzzing, and multi-region failure drills.", "source": "WithinUsAI/Omega_Genesis_Coder_100k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Refactor to modern typed Python with immutability and tests.\n\nFile: ht3prxeh.py\n```python\nclass C1Q1Ky:\n def __init__(self, name, values):\n self.name = name\n self.values = list(values)\n def add(self, v):\n self.values.append(v)\n def mean(self):\n s = 0\n for x in self.values:\n s += x\n return s / len(self.values)\n```\n\nReturn full new ht3prxeh.py and test_ht3prxeh.py.\n\n# ht3prxeh.py\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom typing import Iterable, Tuple\n\n@dataclass(frozen=True)\nclass C1Q1Ky:\n name: str\n values: Tuple[float, ...]\n\n @staticmethod\n def create(name: str, values: Iterable[float]) -> \"C1Q1Ky\":\n vals = tuple(float(v) for v in values)\n if not vals:\n raise ValueError(\"values must be non-empty\")\n return C1Q1Ky(name=name, values=vals)\n\n def add(self, v: float) -> \"C1Q1Ky\":\n return C1Q1Ky(name=self.name, values=self.values + (float(v),))\n\n def mean(self) -> float:\n return sum(self.values) / len(self.values)\n\n# test_ht3prxeh.py\nimport pytest\nfrom ht3prxeh import C1Q1Ky\n\ndef test_mean_and_add():\n c = C1Q1Ky.create(\"a\", [1, 2, 3])\n assert c.mean() == 2.0\n assert c.add(5).mean() == (1 + 2 + 3 + 5) / 4\n\ndef test_empty_raises():\n with pytest.raises(ValueError):\n C1Q1Ky.create(\"x\", [])", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Fix a bug and add tests.\n\nFile: j0zgqbzgaa7.py\n```python\ndef uhnn8cne(n: int) -> int:\n \"\"\"Sum 1..n inclusive.\"\"\"\n if n < 0:\n raise ValueError(\"n must be non-negative\")\n total = 0\n for k in range(n): # BUG: should include n\n total += k\n return total\n```\n\nReturn unified diffs for j0zgqbzgaa7.py and test_j0zgqbzgaa7.py (pytest).\n\n*** Begin Patch\n*** Update File: j0zgqbzgaa7.py\n@@\n def uhnn8cne(n: int) -> int:\n@@\n total = 0\n- for k in range(n): # BUG: should include n\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_j0zgqbzgaa7.py\n+import pytest\n+from j0zgqbzgaa7 import uhnn8cne\n+\n+def test_zero():\n+ assert uhnn8cne(0) == 0\n+\n+def test_one():\n+ assert uhnn8cne(1) == 1\n+\n+def test_small():\n+ assert uhnn8cne(7) == 28\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ uhnn8cne(-1)\n+\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: Project domain: notification service\nImplementation stack: Spring Boot, PostgreSQL, JUnit, Gradle, Docker, GitHub Actions\nSoftware delivery problem: slow cold start\nTask type: prd_to_patch\nDifficulty: hard\n\nReturn a complete delivery-grade response with:\n- diagnosis or design reasoning\n- implementation\n- test plan or tests\n- rollout plan\n- rollback or compatibility note\n- verification commands\n\nRepository sketch:\nrepo/\n scripts/\n run.sh\n deploy.sh\n tests/\n smoke.sh\n\nFocus: Focus on shipping production software with rollout safety, acceptance criteria, telemetry, and maintenance quality.\n\nassistant: Diagnosis:\n- Root cause or delivery blocker: slow cold start needs both implementation work and a safe shipping plan.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```bash\n#!/usr/bin/env bash\nset -euo pipefail\n\ninput=\"${1:-}\"\nif [[ -z \"$input\" ]]; then\n echo \"missing input\" >&2\n exit 1\nfi\n\nprintf '%s\n' \"$input\" | tr -d '\r'\n```\n\nTests:\n```bash\noutput=\"$(bash scripts/run.sh \"abc\")\"\ntest \"$output\" = \"abc\"\n```\n\nVerification:\n- `bash tests/smoke.sh`\n- `shellcheck scripts/*.sh`\n\nEngineering notes:\n- Language: Bash\n- Framework/tooling: sed\n- Stack context: Spring Boot, PostgreSQL, JUnit, Gradle, Docker, GitHub Actions\n- Domain: notification service\n- Task type: prd_to_patch\n- Difficulty: hard\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: System domain: document processing API\nStack: Go, Gin, PostgreSQL, gRPC, Prometheus, Docker\nCross-layer incident: gRPC retry storm\nTask type: cache_consistency_patch\nDifficulty: hard\n\nSolve this as a complete-project engineer.\nOutput must include:\n- root cause across layers\n- final implementation patch\n- tests touching at least two layers\n- deployment or observability note\n- verification commands\n\nRepository sketch:\nrepo/\n src/main.rs\n src/lib.rs\n src/service.rs\n src/store.rs\n tests/integration.rs\n Cargo.toml\n\nFocus: Focus on multi-layer debugging across frontend, backend, database, CI, caching, and deployment.\n\nassistant: Diagnosis:\n- Root cause: gRPC retry storm crosses service boundaries, so the fix must align code, contracts, tests, and deployment behavior.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```rust\nuse std::collections::HashMap;\n\npub fn normalize_payload(payload: HashMap) -> HashMap {\n payload\n .into_iter()\n .filter(|(_, v)| !v.trim().is_empty())\n .collect()\n}\n```\n\nTests:\n```rust\n#[test]\nfn normalize_payload_filters_empty_values() {\n use std::collections::HashMap;\n let mut payload = HashMap::new();\n payload.insert(\"id\".to_string(), \"7\".to_string());\n payload.insert(\"name\".to_string(), \"\".to_string());\n let out = normalize_payload(payload);\n assert!(out.contains_key(\"id\"));\n assert!(!out.contains_key(\"name\"));\n}\n```\n\nVerification:\n- `cargo test`\n- `cargo clippy -- -D warnings`\n\nEngineering notes:\n- Language: Rust\n- Framework/tooling: Tokio\n- Stack context: Go, Gin, PostgreSQL, gRPC, Prometheus, Docker\n- Domain: document processing API\n- Task type: cache_consistency_patch\n- Difficulty: hard\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "Add a clear docstring and type hints to this function:\n\n```python\ndef f96335(s):\n return ''.join(x for x in s if x.isalnum()).lower()\n```\n\n```python\nfrom __future__ import annotations\n\ndef f96335(s: str) -> str:\n \"\"\"Normalize a string: keep only alphanumerics and lowercase the result.\"\"\"\n return \"\".join(ch for ch in s if ch.isalnum()).lower()\n```", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Fix the bug and add pytest tests.\n\n```python\ndef f40184(n: int) -> int:\n # sum 1..n inclusive\n if n < 0: raise ValueError\n total = 0\n for k in range(n): # BUG\n total += k\n return total\n```\nReturn unified diffs for `m34312.py` and `test_m34312.py`.\n\n*** Begin Patch\n*** Update File: m34312.py\n@@\n def f40184(n: int) -> int:\n@@\n- for k in range(n): # BUG\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_m34312.py\n+import pytest\n+from m34312 import f40184\n+\n+def test_small():\n+ assert f40184(7) == 28\n+\n+def test_zero():\n+ assert f40184(0) == 0\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ f40184(-1)\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Fix the bug and add pytest tests.\n\n```python\ndef f24318(n: int) -> int:\n # sum 1..n inclusive\n if n < 0: raise ValueError\n total = 0\n for k in range(n): # BUG\n total += k\n return total\n```\nReturn unified diffs for `m03474.py` and `test_m03474.py`.\n\n*** Begin Patch\n*** Update File: m03474.py\n@@\n def f24318(n: int) -> int:\n@@\n- for k in range(n): # BUG\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_m03474.py\n+import pytest\n+from m03474 import f24318\n+\n+def test_small():\n+ assert f24318(7) == 28\n+\n+def test_zero():\n+ assert f24318(0) == 0\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ f24318(-1)\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Optimize while preserving behavior.\n\nFile: qmattkmluw.py\n```python\ndef hwdw9n(xs):\n out = []\n for x in xs:\n if x not in out:\n out.append(x)\n return out\n```\n\nRequirements: preserve first-seen order; O(n) average; add types + docstring.\n\n# qmattkmluw.py\nfrom __future__ import annotations\nfrom typing import Iterable, List, Set, TypeVar\n\nT = TypeVar(\"T\")\n\ndef hwdw9n(xs: Iterable[T]) -> List[T]:\n \"\"\"Return unique items preserving first-seen order.\"\"\"\n seen: Set[T] = set()\n out: List[T] = []\n for x in xs:\n if x in seen:\n continue\n seen.add(x)\n out.append(x)\n return out", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Design a production system for fintech supporting idempotent payments.\nTarget platform: mobile (iOS Swift).\nRequirements: APIs, data model, scaling strategy, failure modes, and security.\nConstraints: must be easy to extend, must include tests, must be performant under load, must avoid global state.\nDifficulty: medium. Assume PII must be protected.\n\nOutput: engineering-grade answer with edge cases covered.\nDeliverable: system design with APIs, data model, and operational plan.\n\n**High-level architecture**\n- Edge: API Gateway + WAF\n- Core service: stateless app pods behind L7 LB\n- Data: Postgres (primary), Redis (cache + rate limit tokens), Object storage (uploads if needed)\n- Async: message queue (e.g., SQS/Rabbit) + worker pool for background jobs\n- Observability: structured logs + metrics + tracing\n\n**APIs (example)**\n- `POST /v1/{resource}` create (idempotent via `Idempotency-Key`)\n- `GET /v1/{resource}/{id}` read\n- `POST /v1/{resource}/{id}:action` command endpoint when side effects exist\n\n**Data model (Postgres)**\n- `resources(id UUID PK, tenant_id UUID, status TEXT, payload JSONB, created_at, updated_at)`\n- Unique constraint for idempotency: `(tenant_id, idempotency_key)` in a separate table:\n - `idempotency(tenant_id, key TEXT, request_hash TEXT, response JSONB, created_at, PRIMARY KEY(tenant_id,key))`\n\n**Scaling**\n- App layer scales horizontally; keep sessions out of process.\n- Cache reads in Redis; write-through invalidation on mutations.\n- Use connection pooling; consider read replicas for heavy reads.\n\n**Failure modes**\n- Retries: only for safe/ idempotent operations; exponential backoff + jitter.\n- Partial failures: background jobs must be idempotent; use a de-dup key.\n\n**Security**\n- AuthN: JWT/OIDC; AuthZ: RBAC/ABAC with tenant isolation\n- Validate all inputs; enforce per-tenant quotas/rate limits.\n\n**Rollout**\n- Dark launch + feature flags; canary; rapid rollback by toggling flags.\n\n\nChecks: input validation, tests, and safe defaults included.", "source": "WithinUsAI/GOD_Coder_100k"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: Language: Java\nFramework/tooling: JUnit\nDomain: notification service\nLogic challenge: unsafe deserialization\nTask type: multi_file_migration_repair\nDifficulty: hard\n\nReturn a rigorous engineering answer:\n- identify the hidden root cause or logical failure\n- present the corrected implementation\n- add tests that prove the fix\n- list verification commands\n- explain why naive fixes are insufficient when relevant\n\nRepository sketch:\nrepo/\n src/main/java/com/acme/App.java\n src/main/java/com/acme/Service.java\n src/test/java/com/acme/AppTest.java\n pom.xml\n\nFocus: Focus on staff-level problem solving with multi-file patches, rollout implications, performance and security tradeoffs.\n\nassistant: Diagnosis:\n- Staff-level diagnosis: unsafe deserialization impacts correctness, operability, and future maintenance, so the fix must be minimal where possible but complete where necessary.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```java\nimport java.util.HashMap;\nimport java.util.Map;\n\npublic final class RequestHandler {\n public static Map handleRequest(Map payload) {\n Map clean = new HashMap<>();\n for (Map.Entry entry : payload.entrySet()) {\n if (entry.getValue() != null) clean.put(entry.getKey().trim(), entry.getValue());\n }\n if (!clean.containsKey(\"id\")) throw new IllegalArgumentException(\"missing id\");\n return Map.of(\"ok\", true, \"data\", clean);\n }\n}\n```\n\nTests:\n```java\nimport static org.junit.jupiter.api.Assertions.*;\nimport java.util.Map;\nimport org.junit.jupiter.api.Test;\n\nclass RequestHandlerTest {\n @Test\n void requiresId() {\n assertThrows(IllegalArgumentException.class, () -> RequestHandler.handleRequest(Map.of(\"name\", \"x\")));\n }\n}\n```\n\nVerification:\n- `./gradlew test`\n- `mvn test`\n\nEngineering notes:\n- Language: Java\n- Framework/tooling: JUnit\n- Stack context: Go, Gin, PostgreSQL, gRPC, Prometheus, Docker\n- Domain: notification service\n- Task type: multi_file_migration_repair\n- Difficulty: hard\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "Create a comprehensive test plan and automated tests for A/B experimentation in a content moderation product.\nTarget platform: mobile (Android Kotlin).\nRequirements: unit/integration tests, edge cases, load tests strategy, and CI gates.\nConstraints: must include documentation/comments, must avoid global state, must be easy to extend, must be observable (logs/metrics/traces), must be production-ready.\nDifficulty: hard. Assume untrusted input; validate everything.\n\nOutput: production-oriented blueprint with code where appropriate.\nDeliverable: test plan + automation guidance.\n\n**Unit tests**\n- Validation: malformed payloads rejected with correct codes.\n- AuthZ: tenant boundary enforced.\n- Idempotency: replay returns same response; conflicting reuse yields 409.\n\n**Integration tests**\n- DB transaction behavior; unique constraints.\n- Cache behavior: correctness under concurrent requests.\n\n**Load tests**\n- 10k RPS target: measure p95 latency, error rate, saturation.\n\n**CI gates**\n- Lint + typecheck + unit tests required.\n- Coverage threshold for critical modules.\n- Block merge on flaky test detection.\n\n\nHard-mode checks: concurrency safety, idempotency, and rollback validated; add chaos tests where feasible.", "source": "WithinUsAI/GOD_Coder_100k"} {"text": "Build an elite-grade solution in the domain of networking for scenario: payment processing.\nPrimary language: go.\nDifficulty: hard.\nConstraints: assume untrusted inputs; validate and sanitize, include tests or verification strategy, include invariants and failure modes.\nComponent: component_ovdjzcq.\nAssume strict auditability and replayable history.\nTask: Optimize a hot path with profiling-driven approach; propose micro/meso optimizations, and supply a benchmark harness with acceptance thresholds.\n\nOutput: rigorous solution with invariants, failure modes, and performance notes.\nOutput: profiling-first optimization + benchmark harness.\n\n**Plan**\n1. Establish baseline with microbench + representative dataset.\n2. Profile (CPU, allocations, syscalls).\n3. Apply optimizations: reduce allocations, reuse buffers, batch I/O, vectorize parsing where safe.\n4. Validate with regression suite and perf thresholds.\n\n**Benchmark guidance**\n- Use p50/p95 and throughput; pin CPU frequency if possible.\n- Acceptance: p95 improves ≥ X% with no correctness regressions.\n\n\nHard checks: failure injection tests and performance regressions gated.", "source": "WithinUsAI/Elite_GOD_Coder_100k"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: Project domain: artifact registry\nImplementation stack: ASP.NET Core, SQL Server, EF Core, xUnit, Docker\nSoftware delivery problem: mismatched API contract\nTask type: test_strategy_implementation\nDifficulty: medium\n\nReturn a complete delivery-grade response with:\n- diagnosis or design reasoning\n- implementation\n- test plan or tests\n- rollout plan\n- rollback or compatibility note\n- verification commands\n\nRepository sketch:\nrepo/\n src/main/java/com/acme/App.java\n src/main/java/com/acme/Service.java\n src/test/java/com/acme/AppTest.java\n pom.xml\n\nFocus: Focus on shipping production software with rollout safety, acceptance criteria, telemetry, and maintenance quality.\n\nassistant: Diagnosis:\n- Root cause or delivery blocker: mismatched API contract needs both implementation work and a safe shipping plan.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```java\nimport java.util.HashMap;\nimport java.util.Map;\n\npublic final class RequestHandler {\n public static Map handleRequest(Map payload) {\n Map clean = new HashMap<>();\n for (Map.Entry entry : payload.entrySet()) {\n if (entry.getValue() != null) clean.put(entry.getKey().trim(), entry.getValue());\n }\n if (!clean.containsKey(\"id\")) throw new IllegalArgumentException(\"missing id\");\n return Map.of(\"ok\", true, \"data\", clean);\n }\n}\n```\n\nTests:\n```java\nimport static org.junit.jupiter.api.Assertions.*;\nimport java.util.Map;\nimport org.junit.jupiter.api.Test;\n\nclass RequestHandlerTest {\n @Test\n void requiresId() {\n assertThrows(IllegalArgumentException.class, () -> RequestHandler.handleRequest(Map.of(\"name\", \"x\")));\n }\n}\n```\n\nVerification:\n- `./gradlew test`\n- `mvn test`\n\nEngineering notes:\n- Language: Java\n- Framework/tooling: Spring Boot\n- Stack context: ASP.NET Core, SQL Server, EF Core, xUnit, Docker\n- Domain: artifact registry\n- Task type: test_strategy_implementation\n- Difficulty: medium\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "Optimize a Python workflow for data modeling.\nRequirements: provide an optimized implementation and a small benchmark harness.\nConstraints: must handle Windows paths safely, must avoid global state, must be memory-efficient, must include type hints.\nDifficulty: easy. Provide helpful exceptions with actionable messages.\n\nDeliverable: API + reference implementation + tests.\nStrategy:\n- Avoid repeated parsing; precompile regex if needed; use local variables; stream processing.\n\n```python\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom typing import Iterable\nimport time\n\n@dataclass(frozen=True, slots=True)\nclass Stats:\n count: int\n total: int\n\ndef compute_stats_stream(values: Iterable[int]) -> Stats:\n c = 0\n t = 0\n for v in values:\n c += 1\n t += v\n return Stats(c, t)\n\ndef bench(n: int = 1_000_00) -> float:\n data = range(n)\n t0 = time.perf_counter()\n _ = compute_stats_stream(data)\n return time.perf_counter() - t0\n```\n\n```python\nfrom module_under_test import bench\ndef test_bench_runs_fast_enough():\n # Sanity: should run quickly on typical machines; adjust threshold for CI.\n assert bench(50_000) < 0.5\n```", "source": "WithinUsAI/python_GOD_coder_100k"} {"text": "Secure-by-default implementation for idempotent payments in a enterprise SaaS product.\nTarget platform: ML (PyTorch + serving).\nRequirements: threat model, input validation, authz/authn guidance, safe storage, tests.\nConstraints: must be performant under load, must include clear error handling, must be observable (logs/metrics/traces), must be secure-by-default, must avoid global state.\nDifficulty: medium. Assume GDPR-style deletion requests must be supported.\n\nOutput: engineering-grade answer with edge cases covered.\nDeliverable: threat model + secure patterns (no offensive content).\n\n**Threat model**\n- Input: untrusted clients → validation required\n- Auth: token theft / privilege escalation → short-lived tokens + RBAC checks\n- Data: PII exposure → encryption at rest + access logging + least privilege\n- Webhooks/callbacks: SSRF → allowlist destinations + timeouts + egress controls\n\n**Secure implementation patterns**\n- Validate and normalize inputs at boundaries (API/CLI/file).\n- Use parameterized SQL; never string interpolate.\n- Prevent path traversal when writing files (resolve + base containment).\n- Use idempotency keys for side-effecting endpoints; safe retries.\n- Centralize authorization checks in one layer; test them.\n\n**Test checklist**\n- Invalid inputs rejected with clear error messages.\n- AuthZ tests for tenant boundary violations.\n- Replay/idempotency conflict test.\n\n\nChecks: input validation, tests, and safe defaults included.", "source": "WithinUsAI/GOD_Coder_100k"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: Language: Bash\nFramework/tooling: GNU coreutils\nDomain: artifact registry\nLogic challenge: CI failures after dependency upgrade\nTask type: monorepo_toolchain_recovery\nDifficulty: hard\n\nReturn a rigorous engineering answer:\n- identify the hidden root cause or logical failure\n- present the corrected implementation\n- add tests that prove the fix\n- list verification commands\n- explain why naive fixes are insufficient when relevant\n\nRepository sketch:\nrepo/\n scripts/\n run.sh\n deploy.sh\n tests/\n smoke.sh\n\nFocus: Focus on staff-level problem solving with multi-file patches, rollout implications, performance and security tradeoffs.\n\nassistant: Diagnosis:\n- Staff-level diagnosis: CI failures after dependency upgrade impacts correctness, operability, and future maintenance, so the fix must be minimal where possible but complete where necessary.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```bash\n#!/usr/bin/env bash\nset -euo pipefail\n\ninput=\"${1:-}\"\nif [[ -z \"$input\" ]]; then\n echo \"missing input\" >&2\n exit 1\nfi\n\nprintf '%s\n' \"$input\" | tr -d '\r'\n```\n\nTests:\n```bash\noutput=\"$(bash scripts/run.sh \"abc\")\"\ntest \"$output\" = \"abc\"\n```\n\nVerification:\n- `bash tests/smoke.sh`\n- `shellcheck scripts/*.sh`\n\nEngineering notes:\n- Language: Bash\n- Framework/tooling: GNU coreutils\n- Stack context: Go, Gin, PostgreSQL, gRPC, Prometheus, Docker\n- Domain: artifact registry\n- Task type: monorepo_toolchain_recovery\n- Difficulty: hard\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "Write pytest tests for `f26289`.\n\n```python\ndef f26289(a: int, b: int) -> int:\n return a*a + b*b\n```\nInclude edge cases and a property-style check.\n\n```python\nimport random\nfrom m32327 import f26289\n\ndef test_known():\n assert f26289(3,4) == 25\n\ndef test_zero():\n assert f26289(0,0) == 0\n\ndef test_property_nonnegative():\n for _ in range(200):\n a=random.randint(-50,50)\n b=random.randint(-50,50)\n assert f26289(a,b) >= 0\n```", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Produce an offline-first self-evolving code assistant architecture named `ux2wj3xw5v1`.\nMust include: module layout, patch-safety policy, evaluation gates (tests/lint/types), versioned memory index.\n\nArchitecture: `ux2wj3xw5v1` (offline-first, self-evolving)\n\nModules\n- core/loop.py: evolve → validate → accept/reject (bounded iterations)\n- patching/: diff builder, safe apply, atomic writes, rollback points\n- policy/: allowlist paths, deny globs (.git/, __pycache__/, binaries), patch size caps\n- signals/: parse pytest/ruff/mypy into normalized findings\n- memory/index.jsonl: append-only snapshots (hashes, metrics, rationale)\n\nSafety gates\n- refuse path traversal/symlink escapes; never edit binaries\n- accept only if tests/lint/types stay green or improve", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Secure-by-default implementation for audit logs in a education product.\nTarget platform: mobile (Android Kotlin).\nRequirements: threat model, input validation, authz/authn guidance, safe storage, tests.\nConstraints: must be production-ready, must include type hints where applicable, must avoid global state.\nDifficulty: expert. Assume untrusted input; validate everything.\n\nOutput: production-oriented blueprint with code where appropriate.\nDeliverable: threat model + secure patterns (no offensive content).\n\n**Threat model**\n- Input: untrusted clients → validation required\n- Auth: token theft / privilege escalation → short-lived tokens + RBAC checks\n- Data: PII exposure → encryption at rest + access logging + least privilege\n- Webhooks/callbacks: SSRF → allowlist destinations + timeouts + egress controls\n\n**Secure implementation patterns**\n- Validate and normalize inputs at boundaries (API/CLI/file).\n- Use parameterized SQL; never string interpolate.\n- Prevent path traversal when writing files (resolve + base containment).\n- Use idempotency keys for side-effecting endpoints; safe retries.\n- Centralize authorization checks in one layer; test them.\n\n**Test checklist**\n- Invalid inputs rejected with clear error messages.\n- AuthZ tests for tenant boundary violations.\n- Replay/idempotency conflict test.\n\n\nHard-mode checks: concurrency safety, idempotency, and rollback validated; add chaos tests where feasible.", "source": "WithinUsAI/GOD_Coder_100k"} {"text": "Optimize a Python workflow for metrics aggregation.\nRequirements: provide an optimized implementation and a small benchmark harness.\nConstraints: must handle Windows paths safely, must be memory-efficient.\nDifficulty: medium. Ensure the API is testable via dependency injection.\n\nDeliverable: corrected code and verification tests.\nStrategy:\n- Avoid repeated parsing; precompile regex if needed; use local variables; stream processing.\n\n```python\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom typing import Iterable\nimport time\n\n@dataclass(frozen=True, slots=True)\nclass Stats:\n count: int\n total: int\n\ndef compute_stats_stream(values: Iterable[int]) -> Stats:\n c = 0\n t = 0\n for v in values:\n c += 1\n t += v\n return Stats(c, t)\n\ndef bench(n: int = 1_000_00) -> float:\n data = range(n)\n t0 = time.perf_counter()\n _ = compute_stats_stream(data)\n return time.perf_counter() - t0\n```\n\n```python\nfrom module_under_test import bench\ndef test_bench_runs_fast_enough():\n # Sanity: should run quickly on typical machines; adjust threshold for CI.\n assert bench(50_000) < 0.5\n```", "source": "WithinUsAI/python_GOD_coder_100k"} {"text": "Refactor a Python module used for metrics aggregation into a clean, extensible design.\nRequirements: outline the new architecture briefly, then provide the refactored code and tests.\nConstraints: must be streaming-friendly, must include tests, must be easy to extend, must avoid global state.\nDifficulty: expert. Support both Windows and POSIX paths correctly.\n\nDeliverable: production-ready reference solution.\nArchitecture:\n- Public facade class coordinating concerns (parsing, validation, persistence)\n- Small pure functions for testability\n- No global state; dependency injection for filesystem I/O\n\n```python\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom pathlib import Path\nfrom typing import Protocol, Iterable\nimport json\n\nclass Store(Protocol):\n def write_text(self, path: Path, data: str) -> None: ...\n\nclass FSStore:\n def write_text(self, path: Path, data: str) -> None:\n path.parent.mkdir(parents=True, exist_ok=True)\n path.write_text(data, encoding=\"utf-8\")\n\n@dataclass(frozen=True, slots=True)\nclass Item:\n name: str\n qty: int\n\ndef parse_items(lines: Iterable[str]) -> list[Item]:\n out: list[Item] = []\n for i, line in enumerate(lines, 1):\n s = line.strip()\n if not s:\n continue\n obj = json.loads(s)\n if not isinstance(obj, dict):\n raise ValueError(f\"line {i}: expected object\")\n name = obj.get(\"name\")\n qty = obj.get(\"qty\")\n if not isinstance(name, str) or not name:\n raise ValueError(f\"line {i}: name must be str\")\n if not isinstance(qty, int) or qty < 0:\n raise ValueError(f\"line {i}: qty must be non-negative int\")\n out.append(Item(name, qty))\n return out\n\nclass InventoryWriter:\n def __init__(self, base_dir: Path, store: Store | None = None) -> None:\n self._base = base_dir\n self._store: Store = store or FSStore()\n\n def write(self, rel_path: str, items: list[Item]) -> Path:\n dst = (self._base / rel_path).resolve()\n base = self._base.resolve()\n if dst != base and base not in dst.parents:\n raise ValueError(\"unsafe path traversal\")\n payload = json.dumps([item.__dict__ for item in items], ensure_ascii=False)\n self._store.write_text(dst, payload)\n return dst\n```\n\n```python\nimport json\nfrom pathlib import Path\nimport pytest\nfrom module_under_test import InventoryWriter, parse_items\n\ndef test_parse_items_valid():\n lines = [json.dumps({\"name\":\"x\",\"qty\":1})]\n assert parse_items(lines)[0].name == \"x\"\n\ndef test_writer_blocks_traversal(tmp_path: Path):\n w = InventoryWriter(tmp_path)\n with pytest.raises(ValueError):\n w.write(\"../evil.json\", [])\n```", "source": "WithinUsAI/python_GOD_coder_100k"} {"text": "Improve typing and robustness of a Python module used for file synchronization.\nRequirements: provide type-safe APIs (generics/protocols where appropriate) and include tests.\nConstraints: must include type hints, must provide clear error messages, must include tests.\nDifficulty: hard. Provide helpful exceptions with actionable messages.\n\nDeliverable: corrected code and verification tests.\n```python\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom typing import Callable, Generic, Iterable, Protocol, TypeVar\n\nT = TypeVar(\"T\")\nR = TypeVar(\"R\")\n\nclass Mapper(Protocol[T, R]):\n def __call__(self, x: T) -> R: ...\n\n@dataclass(frozen=True, slots=True)\nclass Batch(Generic[T]):\n items: tuple[T, ...]\n\ndef map_batch(batch: Batch[T], fn: Mapper[T, R]) -> Batch[R]:\n return Batch(items=tuple(fn(x) for x in batch.items))\n\ndef chunked(xs: Iterable[T], size: int) -> Iterable[Batch[T]]:\n if size <= 0:\n raise ValueError(\"size must be > 0\")\n buf: list[T] = []\n for x in xs:\n buf.append(x)\n if len(buf) == size:\n yield Batch(items=tuple(buf))\n buf.clear()\n if buf:\n yield Batch(items=tuple(buf))\n```\n\n```python\nimport pytest\nfrom module_under_test import Batch, map_batch, chunked\n\ndef test_map_batch():\n b = Batch(items=(1,2,3))\n assert map_batch(b, lambda x: x*2).items == (2,4,6)\n\ndef test_chunked():\n out = list(chunked([1,2,3,4,5], 2))\n assert [b.items for b in out] == [(1,2),(3,4),(5,)]\n```", "source": "WithinUsAI/python_GOD_coder_100k"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: Language: Java\nFramework/tooling: Gradle\nDomain: team dashboard\nLogic challenge: streaming timeout handling\nTask type: performance_bottleneck_patch\nDifficulty: hard\n\nReturn a rigorous engineering answer:\n- identify the hidden root cause or logical failure\n- present the corrected implementation\n- add tests that prove the fix\n- list verification commands\n- explain why naive fixes are insufficient when relevant\n\nRepository sketch:\nrepo/\n src/main/java/com/acme/App.java\n src/main/java/com/acme/Service.java\n src/test/java/com/acme/AppTest.java\n pom.xml\n\nFocus: Focus on ambiguity, misleading symptoms, hidden root causes, and high-stakes debugging.\n\nassistant: Diagnosis:\n- Hidden root cause: streaming timeout handling presents misleading symptoms, so the patch must target the actual logic boundary rather than the first visible failure.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```java\nimport java.util.HashMap;\nimport java.util.Map;\n\npublic final class RequestHandler {\n public static Map handleRequest(Map payload) {\n Map clean = new HashMap<>();\n for (Map.Entry entry : payload.entrySet()) {\n if (entry.getValue() != null) clean.put(entry.getKey().trim(), entry.getValue());\n }\n if (!clean.containsKey(\"id\")) throw new IllegalArgumentException(\"missing id\");\n return Map.of(\"ok\", true, \"data\", clean);\n }\n}\n```\n\nTests:\n```java\nimport static org.junit.jupiter.api.Assertions.*;\nimport java.util.Map;\nimport org.junit.jupiter.api.Test;\n\nclass RequestHandlerTest {\n @Test\n void requiresId() {\n assertThrows(IllegalArgumentException.class, () -> RequestHandler.handleRequest(Map.of(\"name\", \"x\")));\n }\n}\n```\n\nVerification:\n- `./gradlew test`\n- `mvn test`\n\nEngineering notes:\n- Language: Java\n- Framework/tooling: Gradle\n- Stack context: Rust, Axum, SQLx, Redis, Tokio, Docker\n- Domain: team dashboard\n- Task type: performance_bottleneck_patch\n- Difficulty: hard\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: System domain: feature flag service\nStack: ASP.NET Core, SQL Server, EF Core, xUnit, Docker\nCross-layer incident: race condition on worker shutdown\nTask type: deploy_runtime_patch\nDifficulty: hard\n\nSolve this as a complete-project engineer.\nOutput must include:\n- root cause across layers\n- final implementation patch\n- tests touching at least two layers\n- deployment or observability note\n- verification commands\n\nRepository sketch:\nrepo/\n app/\n api.py\n service.py\n models.py\n tests/\n test_api.py\n pyproject.toml\n\nFocus: Focus on multi-layer debugging across frontend, backend, database, CI, caching, and deployment.\n\nassistant: Diagnosis:\n- Root cause: race condition on worker shutdown crosses service boundaries, so the fix must align code, contracts, tests, and deployment behavior.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```python\nfrom __future__ import annotations\n\nfrom dataclasses import dataclass\nfrom typing import Any\n\n@dataclass\nclass ServiceResult:\n ok: bool\n data: dict[str, Any]\n error: str | None = None\n\ndef normalize_payload(payload: dict[str, Any]) -> dict[str, Any]:\n if not isinstance(payload, dict):\n raise TypeError(\"payload must be a dict\")\n clean: dict[str, Any] = {}\n for key, value in payload.items():\n if value is None:\n continue\n clean[str(key).strip()] = value\n return clean\n\ndef handle_race_condition_on_worker_shutdown(payload: dict[str, Any]) -> ServiceResult:\n clean = normalize_payload(payload)\n if \"id\" not in clean:\n return ServiceResult(ok=False, data={}, error=\"missing id\")\n return ServiceResult(ok=True, data=clean)\n```\n\nTests:\n```python\nimport pytest\nfrom app.service import handle_jwt_refresh_token_rotation as handler\n\ndef test_handler_accepts_valid_payload():\n result = handler({\"id\": 7, \"name\": \"ok\", \"unused\": None})\n assert result.ok is True\n assert result.data == {\"id\": 7, \"name\": \"ok\"}\n\ndef test_handler_rejects_missing_id():\n result = handler({\"name\": \"x\"})\n assert result.ok is False\n assert result.error == \"missing id\"\n```\n\nVerification:\n- `pytest -q`\n- `ruff check .`\n- `python -m compileall .`\n\nEngineering notes:\n- Language: Python\n- Framework/tooling: Pydantic\n- Stack context: ASP.NET Core, SQL Server, EF Core, xUnit, Docker\n- Domain: feature flag service\n- Task type: deploy_runtime_patch\n- Difficulty: hard\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "Improve typing and robustness of a Python module used for parsing.\nRequirements: provide type-safe APIs (generics/protocols where appropriate) and include tests.\nConstraints: must be memory-efficient, stdlib-only.\nDifficulty: medium. Handle empty inputs and malformed records gracefully.\n\nDeliverable: API + reference implementation + tests.\n```python\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom typing import Callable, Generic, Iterable, Protocol, TypeVar\n\nT = TypeVar(\"T\")\nR = TypeVar(\"R\")\n\nclass Mapper(Protocol[T, R]):\n def __call__(self, x: T) -> R: ...\n\n@dataclass(frozen=True, slots=True)\nclass Batch(Generic[T]):\n items: tuple[T, ...]\n\ndef map_batch(batch: Batch[T], fn: Mapper[T, R]) -> Batch[R]:\n return Batch(items=tuple(fn(x) for x in batch.items))\n\ndef chunked(xs: Iterable[T], size: int) -> Iterable[Batch[T]]:\n if size <= 0:\n raise ValueError(\"size must be > 0\")\n buf: list[T] = []\n for x in xs:\n buf.append(x)\n if len(buf) == size:\n yield Batch(items=tuple(buf))\n buf.clear()\n if buf:\n yield Batch(items=tuple(buf))\n```\n\n```python\nimport pytest\nfrom module_under_test import Batch, map_batch, chunked\n\ndef test_map_batch():\n b = Batch(items=(1,2,3))\n assert map_batch(b, lambda x: x*2).items == (2,4,6)\n\ndef test_chunked():\n out = list(chunked([1,2,3,4,5], 2))\n assert [b.items for b in out] == [(1,2),(3,4),(5,)]\n```", "source": "WithinUsAI/python_GOD_coder_100k"} {"text": "Create a comprehensive test plan and automated tests for background jobs in a fintech product.\nTarget platform: mobile (Android Kotlin).\nRequirements: unit/integration tests, edge cases, load tests strategy, and CI gates.\nConstraints: must include type hints where applicable, must avoid global state, must be performant under load, must include clear error handling.\nDifficulty: hard. Assume PII must be protected.\n\nOutput: engineering-grade answer with edge cases covered.\nDeliverable: test plan + automation guidance.\n\n**Unit tests**\n- Validation: malformed payloads rejected with correct codes.\n- AuthZ: tenant boundary enforced.\n- Idempotency: replay returns same response; conflicting reuse yields 409.\n\n**Integration tests**\n- DB transaction behavior; unique constraints.\n- Cache behavior: correctness under concurrent requests.\n\n**Load tests**\n- 10k RPS target: measure p95 latency, error rate, saturation.\n\n**CI gates**\n- Lint + typecheck + unit tests required.\n- Coverage threshold for critical modules.\n- Block merge on flaky test detection.\n\n\nHard-mode checks: concurrency safety, idempotency, and rollback validated; add chaos tests where feasible.", "source": "WithinUsAI/GOD_Coder_100k"} {"text": "Refactor to typed, mostly-immutable Python and add minimal tests.\n\n```python\nclass C90059:\n def __init__(self, values): self.values=list(values)\n def mean(self): return sum(self.values)/len(self.values)\n```\nReturn `m91543.py` and `test_m91543.py`.\n\n```python\n# m91543.py\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom typing import Iterable, Tuple\n\n@dataclass(frozen=True)\nclass C90059:\n values: Tuple[float, ...]\n\n @staticmethod\n def create(values: Iterable[float]) -> \"C90059\":\n vals = tuple(float(v) for v in values)\n if not vals: raise ValueError(\"empty\")\n return C90059(vals)\n\n def mean(self) -> float:\n return sum(self.values)/len(self.values)\n```\n\n```python\n# test_m91543.py\nimport pytest\nfrom m91543 import C90059\n\ndef test_mean():\n assert C90059.create([1,2,3]).mean() == 2.0\ndef test_empty():\n with pytest.raises(ValueError):\n C90059.create([])\n```", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Fix the bug and add pytest tests.\n\n```python\ndef f06401(n: int) -> int:\n # sum 1..n inclusive\n if n < 0: raise ValueError\n total = 0\n for k in range(n): # BUG\n total += k\n return total\n```\nReturn unified diffs for `m72343.py` and `test_m72343.py`.\n\n*** Begin Patch\n*** Update File: m72343.py\n@@\n def f06401(n: int) -> int:\n@@\n- for k in range(n): # BUG\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_m72343.py\n+import pytest\n+from m72343 import f06401\n+\n+def test_small():\n+ assert f06401(7) == 28\n+\n+def test_zero():\n+ assert f06401(0) == 0\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ f06401(-1)\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: System domain: repo automation\nStack: ASP.NET Core, SQL Server, EF Core, xUnit, Docker\nCross-layer incident: stale cache invalidation\nTask type: auth_session_repair\nDifficulty: hard\n\nSolve this as a complete-project engineer.\nOutput must include:\n- root cause across layers\n- final implementation patch\n- tests touching at least two layers\n- deployment or observability note\n- verification commands\n\nRepository sketch:\nrepo/\n migrations/\n 001_init.sql\n 002_add_index.sql\n queries/\n report.sql\n tests/\n report_cases.md\n\nFocus: Focus on multi-layer debugging across frontend, backend, database, CI, caching, and deployment.\n\nassistant: Diagnosis:\n- Root cause: stale cache invalidation crosses service boundaries, so the fix must align code, contracts, tests, and deployment behavior.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```sql\nWITH ranked AS (\n SELECT\n user_id,\n created_at,\n amount,\n ROW_NUMBER() OVER (PARTITION BY user_id ORDER BY created_at DESC, id DESC) AS rn\n FROM orders\n)\nSELECT user_id, created_at, amount\nFROM ranked\nWHERE rn = 1;\n```\n\nTests:\n```sql\n-- Correctness checks:\n-- 1) multiple rows per user\n-- 2) identical timestamps require deterministic tie-breaker\n-- 3) null values handled by business rules\n```\n\nVerification:\n- `run migration checks`\n- `run query correctness cases`\n\nEngineering notes:\n- Language: SQL\n- Framework/tooling: SQLite\n- Stack context: ASP.NET Core, SQL Server, EF Core, xUnit, Docker\n- Domain: repo automation\n- Task type: auth_session_repair\n- Difficulty: hard\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: Language: Rust\nFramework/tooling: Serde\nDomain: document processing API\nLogic challenge: optimistic locking conflict\nTask type: misleading_symptom_debug\nDifficulty: hard\n\nReturn a rigorous engineering answer:\n- identify the hidden root cause or logical failure\n- present the corrected implementation\n- add tests that prove the fix\n- list verification commands\n- explain why naive fixes are insufficient when relevant\n\nRepository sketch:\nrepo/\n src/main.rs\n src/lib.rs\n src/service.rs\n src/store.rs\n tests/integration.rs\n Cargo.toml\n\nFocus: Focus on ambiguity, misleading symptoms, hidden root causes, and high-stakes debugging.\n\nassistant: Diagnosis:\n- Hidden root cause: optimistic locking conflict presents misleading symptoms, so the patch must target the actual logic boundary rather than the first visible failure.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```rust\nuse std::collections::HashMap;\n\npub fn normalize_payload(payload: HashMap) -> HashMap {\n payload\n .into_iter()\n .filter(|(_, v)| !v.trim().is_empty())\n .collect()\n}\n```\n\nTests:\n```rust\n#[test]\nfn normalize_payload_filters_empty_values() {\n use std::collections::HashMap;\n let mut payload = HashMap::new();\n payload.insert(\"id\".to_string(), \"7\".to_string());\n payload.insert(\"name\".to_string(), \"\".to_string());\n let out = normalize_payload(payload);\n assert!(out.contains_key(\"id\"));\n assert!(!out.contains_key(\"name\"));\n}\n```\n\nVerification:\n- `cargo test`\n- `cargo clippy -- -D warnings`\n\nEngineering notes:\n- Language: Rust\n- Framework/tooling: Serde\n- Stack context: Airflow, dbt, DuckDB, MinIO, pytest\n- Domain: document processing API\n- Task type: misleading_symptom_debug\n- Difficulty: hard\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "Build an elite-grade solution in the domain of stream processing for scenario: event ingestion.\nPrimary language: rust.\nDifficulty: hard.\nConstraints: provide rollout and rollback guidance, document performance characteristics, include tests or verification strategy, avoid undefined behavior and data races.\nComponent: component_twunqos.\nAssume cold-start and memory limits are tight.\nTask: Implement or outline a storage/indexing subsystem (LSM/B-Tree, WAL, snapshots). Include transaction/consistency considerations and benchmark plan.\n\nOutput: elite-grade engineering answer with contracts, edge cases, and verification.\nOutput: storage design + WAL + compaction + benchmarks.\n\n**Design**\n- WAL (append-only) for durability; fsync policy configurable.\n- Memtable (in-memory) → flush to immutable SSTables.\n- LSM compaction tiers; bloom filters per SSTable for point-lookups.\n- Manifest tracks SSTable set; atomic pointer swap on updates.\n\n**Correctness**\n- Crash recovery: replay WAL to rebuild memtable; manifest ensures last consistent set.\n- Reads: merge memtable + SSTables newest→oldest; tombstones override older values.\n\n**Bench plan**\n- Workloads: write-heavy, read-heavy, mixed; measure p50/p95 latency and write amplification.\n- Track compaction debt and space amplification.\n\n**Test plan**\n- Fuzz crash points: kill after WAL append / after manifest update; verify invariants on restart.\n\n\nHard checks: failure injection tests and performance regressions gated.", "source": "WithinUsAI/Elite_GOD_Coder_100k"} {"text": "Task type: formal_proof_sketch\nScenario: rate limit gateway\nDomain focus: observability platforms\nPrimary language: bash\nDifficulty: expert\nScale/SLO: multi-region active-active\nComponent: component_dhvwdljl\nConstraints: include deterministic replay plan, include test vectors and fuzz strategy, include verification strategy, assume adversarial inputs; validate everything, avoid data races and undefined behavior, include security threat model (defensive only)\nAssume tight memory budget and cold-start constraints.\nDeliverable: Provide a rigorous proof sketch for key invariants and show how to test/verify them in practice.\n\nOutput: elite engineering answer optimized for correctness, performance, and operability.\n**Contract**\n- Inputs validated at the boundary; explicit error taxonomy.\n- Idempotency for side effects via request_id; deterministic replay.\n- Backward compatibility: additive changes by default; versioned breaking changes.\n**Invariants**\n- Determinism: replay of the same event log yields identical outputs.\n- Safety: state transitions preserve invariants; no partial commit leaks.\n- Isolation: tenant boundary enforced; no cross-tenant reads/writes.\n**Failure modes & recovery**\n- Crash during commit: WAL replay completes or transaction aborts; no torn writes.\n- Duplicate requests: de-duplicate by (tenant, request_id) returning cached response.\n- Data corruption: checksums + scrubber; quarantine and rebuild from replicas/snapshots.\n**Security posture (defensive)**\n- Threat model: auth/authz, injection, replay/abuse, supply chain.\n- Least privilege; secrets in managed store; audit logs for sensitive ops.\n- Input normalization, parameterized queries, path traversal protections.\n**Verification strategy**\n- Deterministic simulation with fault injection (crash/partition/latency).\n- Property tests against a pure reference model (state machine).\n- Canary + shadow traffic; invariants checked in production via assertions/metrics.\n\n**Snippet**\n```text\nImplementation sketch: factor pure state-machine core; adapters for I/O; add deterministic replay log.\n```\nExpert checks: state-machine proof sketch + model checking; upgrade/rollback rehearsed.", "source": "WithinUsAI/Omega_Genesis_Coder_100k"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: Language: C#\nFramework/tooling: xUnit\nDomain: data pipeline\nLogic challenge: dead-letter queue replay\nTask type: performance_bottleneck_patch\nDifficulty: hard\n\nReturn a rigorous engineering answer:\n- identify the hidden root cause or logical failure\n- present the corrected implementation\n- add tests that prove the fix\n- list verification commands\n- explain why naive fixes are insufficient when relevant\n\nRepository sketch:\nrepo/\n src/App/Program.cs\n src/App/Service.cs\n tests/App.Tests/ServiceTests.cs\n App.sln\n\nFocus: Focus on ambiguity, misleading symptoms, hidden root causes, and high-stakes debugging.\n\nassistant: Diagnosis:\n- Hidden root cause: dead-letter queue replay presents misleading symptoms, so the patch must target the actual logic boundary rather than the first visible failure.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```csharp\nusing System;\nusing System.Collections.Generic;\n\npublic static class RequestHandler\n{\n public static Dictionary HandleRequest(Dictionary payload)\n {\n var clean = new Dictionary();\n foreach (var entry in payload)\n {\n if (entry.Value != null)\n clean[entry.Key.Trim()] = entry.Value;\n }\n if (!clean.ContainsKey(\"id\"))\n throw new ArgumentException(\"missing id\");\n return new Dictionary\n {\n [\"ok\"] = true,\n [\"data\"] = clean\n };\n }\n}\n```\n\nTests:\n```csharp\nusing System;\nusing System.Collections.Generic;\nusing Xunit;\n\npublic class RequestHandlerTests\n{\n [Fact]\n public void RequiresId()\n {\n Assert.Throws(() => RequestHandler.HandleRequest(new Dictionary { [\"name\"] = \"x\" }));\n }\n}\n```\n\nVerification:\n- `dotnet test`\n- `dotnet build`\n\nEngineering notes:\n- Language: C#\n- Framework/tooling: xUnit\n- Stack context: Go, Gin, PostgreSQL, gRPC, Prometheus, Docker\n- Domain: data pipeline\n- Task type: performance_bottleneck_patch\n- Difficulty: hard\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Refactor to modern typed Python with immutability and tests.\n\nFile: ea34jwwjlnpk.py\n```python\nclass P10Iam:\n def __init__(self, name, values):\n self.name = name\n self.values = list(values)\n def add(self, v):\n self.values.append(v)\n def mean(self):\n s = 0\n for x in self.values:\n s += x\n return s / len(self.values)\n```\n\nReturn full new ea34jwwjlnpk.py and test_ea34jwwjlnpk.py.\n\n# ea34jwwjlnpk.py\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom typing import Iterable, Tuple\n\n@dataclass(frozen=True)\nclass P10Iam:\n name: str\n values: Tuple[float, ...]\n\n @staticmethod\n def create(name: str, values: Iterable[float]) -> \"P10Iam\":\n vals = tuple(float(v) for v in values)\n if not vals:\n raise ValueError(\"values must be non-empty\")\n return P10Iam(name=name, values=vals)\n\n def add(self, v: float) -> \"P10Iam\":\n return P10Iam(name=self.name, values=self.values + (float(v),))\n\n def mean(self) -> float:\n return sum(self.values) / len(self.values)\n\n# test_ea34jwwjlnpk.py\nimport pytest\nfrom ea34jwwjlnpk import P10Iam\n\ndef test_mean_and_add():\n c = P10Iam.create(\"a\", [1, 2, 3])\n assert c.mean() == 2.0\n assert c.add(5).mean() == (1 + 2 + 3 + 5) / 4\n\ndef test_empty_raises():\n with pytest.raises(ValueError):\n P10Iam.create(\"x\", [])", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Design and implement an algorithm for parsing.\nRequirements: define inputs/outputs, implement solution with complexity analysis, and include tests.\nConstraints: must be memory-efficient, must be easy to extend, must be streaming-friendly.\nDifficulty: medium. Avoid quadratic behavior on large inputs.\n\nDeliverable: production-ready reference solution.\nProblem: compute rolling sums over events (ts:int,value:int) with window W seconds. Events may be out-of-order.\n\nComplexity: sorting O(n log n); window maintenance O(n); memory O(k).\n\n```python\nfrom __future__ import annotations\nfrom collections import deque\nfrom dataclasses import dataclass\nfrom typing import Iterable, List, Tuple\n\n@dataclass(frozen=True, slots=True)\nclass Event:\n ts: int\n value: int\n\ndef rolling_sum(events: Iterable[Event], window_s: int) -> List[Tuple[int,int]]:\n if window_s < 0:\n raise ValueError(\"window_s must be >= 0\")\n evs = sorted(events, key=lambda e: e.ts)\n q: deque[Event] = deque()\n s = 0\n out: List[Tuple[int,int]] = []\n for e in evs:\n q.append(e)\n s += e.value\n cutoff = e.ts - window_s\n while q and q[0].ts < cutoff:\n old = q.popleft()\n s -= old.value\n out.append((e.ts, s))\n return out\n```\n\n```python\nimport pytest\nfrom module_under_test import Event, rolling_sum\n\ndef test_rolling_sum():\n ev = [Event(10,1), Event(11,2), Event(20,5)]\n assert rolling_sum(ev, 5) == [(10,1),(11,3),(20,5)]\n```", "source": "WithinUsAI/python_GOD_coder_100k"} {"text": "Build a data pipeline for a fintech product around role-based access control.\nTarget platform: data (SQL + Python).\nRequirements: schema, ingestion, validation, backfills, and tests.\nConstraints: must be observable (logs/metrics/traces), must include type hints where applicable, must include clear error handling, must be secure-by-default.\nDifficulty: medium. Assume schema evolves frequently; design for migrations.\n\nOutput: actionable implementation and verification artifacts.\nDeliverable: schema + ingestion + validation + backfill strategy.\n\n**Schema (example)**\n- events(event_id TEXT PK, tenant_id TEXT, ts TIMESTAMP, type TEXT, payload JSONB)\n\n**Ingestion**\n- Write to raw table first; validate; then materialize to curated tables.\n- Idempotency by event_id; enforce uniqueness.\n\n**Validation**\n- Reject missing tenant_id/type/ts.\n- Quarantine bad records with reason.\n\n**Backfills**\n- Re-run deterministic transforms from raw → curated.\n- Version transformations; store transform_version with outputs.\n\n**Tests**\n- Unit tests for validators and transforms.\n- Integration test: sample raw batch produces expected curated rows.\n\n\nChecks: input validation, tests, and safe defaults included.", "source": "WithinUsAI/GOD_Coder_100k"} {"text": "Implement a concurrent Python solution for caching layer.\nRequirements: choose appropriate concurrency model, handle cancellation/timeouts, include tests.\nConstraints: must handle Windows paths safely, stdlib-only.\nDifficulty: medium. Ensure the API is testable via dependency injection.\n\nDeliverable: corrected code and verification tests.\n```python\nfrom __future__ import annotations\nimport asyncio\nfrom dataclasses import dataclass\nfrom typing import Awaitable, Callable, Iterable, Optional\n\n@dataclass(frozen=True, slots=True)\nclass JobResult:\n ok: bool\n value: Optional[int]\n error: Optional[str]\n\nasync def run_bounded(\n factories: Iterable[Callable[[], Awaitable[int]]],\n *,\n limit: int = 10,\n timeout_s: float = 5.0,\n) -> list[JobResult]:\n if limit <= 0:\n raise ValueError(\"limit must be > 0\")\n sem = asyncio.Semaphore(limit)\n results: list[JobResult] = []\n\n async def one(factory: Callable[[], Awaitable[int]]) -> None:\n async with sem:\n try:\n v = await asyncio.wait_for(factory(), timeout=timeout_s)\n results.append(JobResult(True, v, None))\n except Exception as e:\n results.append(JobResult(False, None, str(e)))\n\n tasks = [asyncio.create_task(one(f)) for f in factories]\n try:\n await asyncio.gather(*tasks)\n finally:\n for t in tasks:\n if not t.done():\n t.cancel()\n return results\n```\n\n```python\nimport asyncio\nimport pytest\nfrom module_under_test import run_bounded\n\n@pytest.mark.asyncio\nasync def test_run_bounded_collects():\n async def work(x: int) -> int:\n await asyncio.sleep(0.01)\n return x\n fs = [(lambda i=i: work(i)) for i in range(30)]\n out = await run_bounded(fs, limit=5, timeout_s=1.0)\n assert len(out) == 30\n assert all(r.ok for r in out)\n```", "source": "WithinUsAI/python_GOD_coder_100k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Fix a bug and add tests.\n\nFile: vn3ucz5hq25o.py\n```python\ndef wiwlf17hf(n: int) -> int:\n \"\"\"Sum 1..n inclusive.\"\"\"\n if n < 0:\n raise ValueError(\"n must be non-negative\")\n total = 0\n for k in range(n): # BUG: should include n\n total += k\n return total\n```\n\nReturn unified diffs for vn3ucz5hq25o.py and test_vn3ucz5hq25o.py (pytest).\n\n*** Begin Patch\n*** Update File: vn3ucz5hq25o.py\n@@\n def wiwlf17hf(n: int) -> int:\n@@\n total = 0\n- for k in range(n): # BUG: should include n\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_vn3ucz5hq25o.py\n+import pytest\n+from vn3ucz5hq25o import wiwlf17hf\n+\n+def test_zero():\n+ assert wiwlf17hf(0) == 0\n+\n+def test_one():\n+ assert wiwlf17hf(1) == 1\n+\n+def test_small():\n+ assert wiwlf17hf(7) == 28\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ wiwlf17hf(-1)\n+\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: Language: Rust\nFramework/tooling: Tokio\nDomain: document processing API\nLogic challenge: schema drift during deployment\nTask type: performance_bottleneck_patch\nDifficulty: hard\n\nReturn a rigorous engineering answer:\n- identify the hidden root cause or logical failure\n- present the corrected implementation\n- add tests that prove the fix\n- list verification commands\n- explain why naive fixes are insufficient when relevant\n\nRepository sketch:\nrepo/\n src/main.rs\n src/lib.rs\n src/service.rs\n src/store.rs\n tests/integration.rs\n Cargo.toml\n\nFocus: Focus on ambiguity, misleading symptoms, hidden root causes, and high-stakes debugging.\n\nassistant: Diagnosis:\n- Hidden root cause: schema drift during deployment presents misleading symptoms, so the patch must target the actual logic boundary rather than the first visible failure.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```rust\nuse std::collections::HashMap;\n\npub fn normalize_payload(payload: HashMap) -> HashMap {\n payload\n .into_iter()\n .filter(|(_, v)| !v.trim().is_empty())\n .collect()\n}\n```\n\nTests:\n```rust\n#[test]\nfn normalize_payload_filters_empty_values() {\n use std::collections::HashMap;\n let mut payload = HashMap::new();\n payload.insert(\"id\".to_string(), \"7\".to_string());\n payload.insert(\"name\".to_string(), \"\".to_string());\n let out = normalize_payload(payload);\n assert!(out.contains_key(\"id\"));\n assert!(!out.contains_key(\"name\"));\n}\n```\n\nVerification:\n- `cargo test`\n- `cargo clippy -- -D warnings`\n\nEngineering notes:\n- Language: Rust\n- Framework/tooling: Tokio\n- Stack context: Rust, Axum, SQLx, Redis, Tokio, Docker\n- Domain: document processing API\n- Task type: performance_bottleneck_patch\n- Difficulty: hard\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "Write pytest tests for `f82209`.\n\n```python\ndef f82209(a: int, b: int) -> int:\n return a*a + b*b\n```\nInclude edge cases and a property-style check.\n\n```python\nimport random\nfrom m68887 import f82209\n\ndef test_known():\n assert f82209(3,4) == 25\n\ndef test_zero():\n assert f82209(0,0) == 0\n\ndef test_property_nonnegative():\n for _ in range(200):\n a=random.randint(-50,50)\n b=random.randint(-50,50)\n assert f82209(a,b) >= 0\n```", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Task type: kernel_syscall_design\nScenario: rate limit gateway\nDomain focus: query planning\nPrimary language: cpp\nDifficulty: expert\nScale/SLO: 99.99% availability\nComponent: component_ywlzobvv\nConstraints: assume adversarial inputs; validate everything, include verification strategy, include failure modes and recovery, include performance model and limits, include backward compatibility and migration plan, avoid data races and undefined behavior\nAssume strict auditability and replayable history.\nDeliverable: Design a safe syscall/API boundary: ABI, validation, error codes, and compatibility; include tests and fuzz plan.\n\nOutput: elite engineering answer optimized for correctness, performance, and operability.\n**Contract**\n- Inputs validated at the boundary; explicit error taxonomy.\n- Idempotency for side effects via request_id; deterministic replay.\n- Backward compatibility: additive changes by default; versioned breaking changes.\n**Invariants**\n- Isolation: tenant boundary enforced; no cross-tenant reads/writes.\n- Liveness: under bounded faults and stable network, progress occurs.\n- Determinism: replay of the same event log yields identical outputs.\n**Failure modes & recovery**\n- Crash during commit: WAL replay completes or transaction aborts; no torn writes.\n- Data corruption: checksums + scrubber; quarantine and rebuild from replicas/snapshots.\n- Duplicate requests: de-duplicate by (tenant, request_id) returning cached response.\n**Security posture (defensive)**\n- Threat model: auth/authz, injection, replay/abuse, supply chain.\n- Least privilege; secrets in managed store; audit logs for sensitive ops.\n- Input normalization, parameterized queries, path traversal protections.\n**Verification strategy**\n- Property tests against a pure reference model (state machine).\n- Fuzzing of parsers/framers/validators with corpus seeds.\n- Deterministic simulation with fault injection (crash/partition/latency).\n\n**Snippet**\n```text\nImplementation sketch: factor pure state-machine core; adapters for I/O; add deterministic replay log.\n```\nExpert checks: state-machine proof sketch + model checking; upgrade/rollback rehearsed.", "source": "WithinUsAI/Omega_Genesis_Coder_100k"} {"text": "Optimize a Python workflow for CLI tooling.\nRequirements: provide an optimized implementation and a small benchmark harness.\nConstraints: must include tests, must provide clear error messages, must include type hints.\nDifficulty: hard. Handle empty inputs and malformed records gracefully.\n\nDeliverable: implementation + tests.\nStrategy:\n- Avoid repeated parsing; precompile regex if needed; use local variables; stream processing.\n\n```python\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom typing import Iterable\nimport time\n\n@dataclass(frozen=True, slots=True)\nclass Stats:\n count: int\n total: int\n\ndef compute_stats_stream(values: Iterable[int]) -> Stats:\n c = 0\n t = 0\n for v in values:\n c += 1\n t += v\n return Stats(c, t)\n\ndef bench(n: int = 1_000_00) -> float:\n data = range(n)\n t0 = time.perf_counter()\n _ = compute_stats_stream(data)\n return time.perf_counter() - t0\n```\n\n```python\nfrom module_under_test import bench\ndef test_bench_runs_fast_enough():\n # Sanity: should run quickly on typical machines; adjust threshold for CI.\n assert bench(50_000) < 0.5\n```", "source": "WithinUsAI/python_GOD_coder_100k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Produce an offline-first self-evolving code assistant architecture named `cbx094g2`.\nMust include: module layout, patch-safety policy, evaluation gates (tests/lint/types), versioned memory index.\n\nArchitecture: `cbx094g2` (offline-first, self-evolving)\n\nModules\n- core/loop.py: evolve → validate → accept/reject (bounded iterations)\n- patching/: diff builder, safe apply, atomic writes, rollback points\n- policy/: allowlist paths, deny globs (.git/, __pycache__/, binaries), patch size caps\n- signals/: parse pytest/ruff/mypy into normalized findings\n- memory/index.jsonl: append-only snapshots (hashes, metrics, rationale)\n\nSafety gates\n- refuse path traversal/symlink escapes; never edit binaries\n- accept only if tests/lint/types stay green or improve", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: Language: C#\nFramework/tooling: xUnit\nDomain: data pipeline\nLogic challenge: N+1 query explosion\nTask type: multi_file_migration_repair\nDifficulty: hard\n\nReturn a rigorous engineering answer:\n- identify the hidden root cause or logical failure\n- present the corrected implementation\n- add tests that prove the fix\n- list verification commands\n- explain why naive fixes are insufficient when relevant\n\nRepository sketch:\nrepo/\n src/App/Program.cs\n src/App/Service.cs\n tests/App.Tests/ServiceTests.cs\n App.sln\n\nFocus: Focus on staff-level problem solving with multi-file patches, rollout implications, performance and security tradeoffs.\n\nassistant: Diagnosis:\n- Staff-level diagnosis: N+1 query explosion impacts correctness, operability, and future maintenance, so the fix must be minimal where possible but complete where necessary.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```csharp\nusing System;\nusing System.Collections.Generic;\n\npublic static class RequestHandler\n{\n public static Dictionary HandleRequest(Dictionary payload)\n {\n var clean = new Dictionary();\n foreach (var entry in payload)\n {\n if (entry.Value != null)\n clean[entry.Key.Trim()] = entry.Value;\n }\n if (!clean.ContainsKey(\"id\"))\n throw new ArgumentException(\"missing id\");\n return new Dictionary\n {\n [\"ok\"] = true,\n [\"data\"] = clean\n };\n }\n}\n```\n\nTests:\n```csharp\nusing System;\nusing System.Collections.Generic;\nusing Xunit;\n\npublic class RequestHandlerTests\n{\n [Fact]\n public void RequiresId()\n {\n Assert.Throws(() => RequestHandler.HandleRequest(new Dictionary { [\"name\"] = \"x\" }));\n }\n}\n```\n\nVerification:\n- `dotnet test`\n- `dotnet build`\n\nEngineering notes:\n- Language: C#\n- Framework/tooling: xUnit\n- Stack context: Airflow, dbt, DuckDB, MinIO, pytest\n- Domain: data pipeline\n- Task type: multi_file_migration_repair\n- Difficulty: hard\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "Task type: tla_state_machine\nScenario: document indexing pipeline\nDomain focus: static analysis\nPrimary language: tla+\nDifficulty: expert\nScale/SLO: p99 < 50ms\nComponent: component_ighxexfg\nConstraints: assume adversarial inputs; validate everything, include backward compatibility and migration plan, include failure modes and recovery, include test vectors and fuzz strategy, include deterministic replay plan\nAssume tight memory budget and cold-start constraints.\nDeliverable: Provide a TLA+-style state machine (pseudo), safety/liveness properties, and a model-checking strategy. Include an implementation sketch and test vectors.\n\nOutput: rigorous design + invariants + verification plan + implementation sketch.\n**Contract**\n- Inputs validated at the boundary; explicit error taxonomy.\n- Idempotency for side effects via request_id; deterministic replay.\n- Backward compatibility: additive changes by default; versioned breaking changes.\n**Invariants**\n- Liveness: under bounded faults and stable network, progress occurs.\n- Isolation: tenant boundary enforced; no cross-tenant reads/writes.\n- Safety: state transitions preserve invariants; no partial commit leaks.\n**Failure modes & recovery**\n- Duplicate requests: de-duplicate by (tenant, request_id) returning cached response.\n- Data corruption: checksums + scrubber; quarantine and rebuild from replicas/snapshots.\n- Crash during commit: WAL replay completes or transaction aborts; no torn writes.\n**Security posture (defensive)**\n- Threat model: auth/authz, injection, replay/abuse, supply chain.\n- Least privilege; secrets in managed store; audit logs for sensitive ops.\n- Input normalization, parameterized queries, path traversal protections.\n**Verification strategy**\n- Fuzzing of parsers/framers/validators with corpus seeds.\n- Deterministic simulation with fault injection (crash/partition/latency).\n- Property tests against a pure reference model (state machine).\n\n**Snippet**\n```tla\nVARIABLES state, log, seen\n\nInit == state = [k \\in Keys |-> <<0, NULL>>] /\\ log = << >> /\\ seen = [r \\in ReqIds |-> NULL]\n\nPut(req, k, v) ==\n IF seen[req] # NULL THEN UNCHANGED <>\n ELSE\n LET ver == state[k][1] + 1 IN\n /\\ state' = [state EXCEPT ![k] = <>]\n /\\ log' = Append(log, <>)\n /\\ seen' = [seen EXCEPT ![req] = <<\"ok\", ver>>]\n\nSafety == \\A k \\in Keys: state[k][1] >= 0\n```\n\nExpert checks: state-machine proof sketch + model checking; upgrade/rollback rehearsed.", "source": "WithinUsAI/Omega_Genesis_Coder_100k"} {"text": "Refactor to typed, mostly-immutable Python and add minimal tests.\n\n```python\nclass C94033:\n def __init__(self, values): self.values=list(values)\n def mean(self): return sum(self.values)/len(self.values)\n```\nReturn `m99541.py` and `test_m99541.py`.\n\n```python\n# m99541.py\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom typing import Iterable, Tuple\n\n@dataclass(frozen=True)\nclass C94033:\n values: Tuple[float, ...]\n\n @staticmethod\n def create(values: Iterable[float]) -> \"C94033\":\n vals = tuple(float(v) for v in values)\n if not vals: raise ValueError(\"empty\")\n return C94033(vals)\n\n def mean(self) -> float:\n return sum(self.values)/len(self.values)\n```\n\n```python\n# test_m99541.py\nimport pytest\nfrom m99541 import C94033\n\ndef test_mean():\n assert C94033.create([1,2,3]).mean() == 2.0\ndef test_empty():\n with pytest.raises(ValueError):\n C94033.create([])\n```", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Optimize while preserving behavior.\n\nFile: cjne7s.py\n```python\ndef pji1n_5epory(xs):\n out = []\n for x in xs:\n if x not in out:\n out.append(x)\n return out\n```\n\nRequirements: preserve first-seen order; O(n) average; add types + docstring.\n\n# cjne7s.py\nfrom __future__ import annotations\nfrom typing import Iterable, List, Set, TypeVar\n\nT = TypeVar(\"T\")\n\ndef pji1n_5epory(xs: Iterable[T]) -> List[T]:\n \"\"\"Return unique items preserving first-seen order.\"\"\"\n seen: Set[T] = set()\n out: List[T] = []\n for x in xs:\n if x in seen:\n continue\n seen.add(x)\n out.append(x)\n return out", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Fix a bug and add tests.\n\nFile: iglclb.py\n```python\ndef u0d7pqlpmp9(n: int) -> int:\n \"\"\"Sum 1..n inclusive.\"\"\"\n if n < 0:\n raise ValueError(\"n must be non-negative\")\n total = 0\n for k in range(n): # BUG: should include n\n total += k\n return total\n```\n\nReturn unified diffs for iglclb.py and test_iglclb.py (pytest).\n\n*** Begin Patch\n*** Update File: iglclb.py\n@@\n def u0d7pqlpmp9(n: int) -> int:\n@@\n total = 0\n- for k in range(n): # BUG: should include n\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_iglclb.py\n+import pytest\n+from iglclb import u0d7pqlpmp9\n+\n+def test_zero():\n+ assert u0d7pqlpmp9(0) == 0\n+\n+def test_one():\n+ assert u0d7pqlpmp9(1) == 1\n+\n+def test_small():\n+ assert u0d7pqlpmp9(7) == 28\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ u0d7pqlpmp9(-1)\n+\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Write pytest tests for `f08911`.\n\n```python\ndef f08911(a: int, b: int) -> int:\n return a*a + b*b\n```\nInclude edge cases and a property-style check.\n\n```python\nimport random\nfrom m01273 import f08911\n\ndef test_known():\n assert f08911(3,4) == 25\n\ndef test_zero():\n assert f08911(0,0) == 0\n\ndef test_property_nonnegative():\n for _ in range(200):\n a=random.randint(-50,50)\n b=random.randint(-50,50)\n assert f08911(a,b) >= 0\n```", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Improve typing and robustness of a Python module used for log processing.\nRequirements: provide type-safe APIs (generics/protocols where appropriate) and include tests.\nConstraints: must avoid global state, must provide clear error messages.\nDifficulty: easy. Guarantee deterministic output ordering.\n\nDeliverable: production-ready reference solution.\n```python\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom typing import Callable, Generic, Iterable, Protocol, TypeVar\n\nT = TypeVar(\"T\")\nR = TypeVar(\"R\")\n\nclass Mapper(Protocol[T, R]):\n def __call__(self, x: T) -> R: ...\n\n@dataclass(frozen=True, slots=True)\nclass Batch(Generic[T]):\n items: tuple[T, ...]\n\ndef map_batch(batch: Batch[T], fn: Mapper[T, R]) -> Batch[R]:\n return Batch(items=tuple(fn(x) for x in batch.items))\n\ndef chunked(xs: Iterable[T], size: int) -> Iterable[Batch[T]]:\n if size <= 0:\n raise ValueError(\"size must be > 0\")\n buf: list[T] = []\n for x in xs:\n buf.append(x)\n if len(buf) == size:\n yield Batch(items=tuple(buf))\n buf.clear()\n if buf:\n yield Batch(items=tuple(buf))\n```\n\n```python\nimport pytest\nfrom module_under_test import Batch, map_batch, chunked\n\ndef test_map_batch():\n b = Batch(items=(1,2,3))\n assert map_batch(b, lambda x: x*2).items == (2,4,6)\n\ndef test_chunked():\n out = list(chunked([1,2,3,4,5], 2))\n assert [b.items for b in out] == [(1,2),(3,4),(5,)]\n```", "source": "WithinUsAI/python_GOD_coder_100k"} {"text": "Optimize while preserving behavior and order.\n\n```python\ndef f55010(xs):\n out=[]\n for x in xs:\n if x not in out: out.append(x)\n return out\n```\nReturn `m36430.py` with types and O(n) average.\n\n```python\n# m36430.py\nfrom __future__ import annotations\nfrom typing import Iterable, List, Set, TypeVar\nT=TypeVar(\"T\")\n\ndef f55010(xs: Iterable[T]) -> List[T]:\n \"\"\"Unique items preserving first-seen order.\"\"\"\n seen: Set[T]=set()\n out: List[T]=[]\n for x in xs:\n if x in seen: continue\n seen.add(x); out.append(x)\n return out\n```", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Build an elite-grade solution in the domain of sre/observability for scenario: edge sync.\nPrimary language: python.\nDifficulty: medium.\nConstraints: design for backward compatibility and migrations, include invariants and failure modes, include tests or verification strategy, provide rollout and rollback guidance.\nComponent: component_ditlqhw.\nAssume compliance requires data deletion with proofs.\nTask: Implement a concurrency primitive or subsystem (lock-free queue, thread pool, async runtime component). Explain memory ordering and correctness arguments; include stress tests.\n\nOutput: production blueprint plus correctness arguments and test strategy.\nOutput: correctness-focused concurrency primitive + stress tests.\n\n**Primitive**\n- Bounded MPMC queue with backpressure (blocking push/pop) OR lock-free SPSC ring buffer.\n\n**Correctness notes**\n- For lock-free: use acquire/release semantics on head/tail indices.\n- Avoid ABA by monotonic counters; ring index = counter % capacity.\n\n**Stress tests**\n- Multi-thread producers/consumers; assert item multiset preserved.\n- Use time-bounded randomized schedules; detect deadlocks.\n\n\nChecks: boundary validation and deterministic behavior verified.", "source": "WithinUsAI/Elite_GOD_Coder_100k"} {"text": "Improve typing and robustness of a Python module used for data modeling.\nRequirements: provide type-safe APIs (generics/protocols where appropriate) and include tests.\nConstraints: must include tests, must include type hints, must avoid global state.\nDifficulty: easy. Support both Windows and POSIX paths correctly.\n\nDeliverable: production-ready reference solution.\n```python\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom typing import Callable, Generic, Iterable, Protocol, TypeVar\n\nT = TypeVar(\"T\")\nR = TypeVar(\"R\")\n\nclass Mapper(Protocol[T, R]):\n def __call__(self, x: T) -> R: ...\n\n@dataclass(frozen=True, slots=True)\nclass Batch(Generic[T]):\n items: tuple[T, ...]\n\ndef map_batch(batch: Batch[T], fn: Mapper[T, R]) -> Batch[R]:\n return Batch(items=tuple(fn(x) for x in batch.items))\n\ndef chunked(xs: Iterable[T], size: int) -> Iterable[Batch[T]]:\n if size <= 0:\n raise ValueError(\"size must be > 0\")\n buf: list[T] = []\n for x in xs:\n buf.append(x)\n if len(buf) == size:\n yield Batch(items=tuple(buf))\n buf.clear()\n if buf:\n yield Batch(items=tuple(buf))\n```\n\n```python\nimport pytest\nfrom module_under_test import Batch, map_batch, chunked\n\ndef test_map_batch():\n b = Batch(items=(1,2,3))\n assert map_batch(b, lambda x: x*2).items == (2,4,6)\n\ndef test_chunked():\n out = list(chunked([1,2,3,4,5], 2))\n assert [b.items for b in out] == [(1,2),(3,4),(5,)]\n```", "source": "WithinUsAI/python_GOD_coder_100k"} {"text": "Build an elite-grade solution in the domain of stream processing for scenario: event ingestion.\nPrimary language: sql.\nDifficulty: medium.\nConstraints: assume untrusted inputs; validate and sanitize, design for backward compatibility and migrations, include invariants and failure modes.\nComponent: component_awbgmyi.\nAssume schema changes every sprint; must be backward compatible.\nTask: Implement or outline a storage/indexing subsystem (LSM/B-Tree, WAL, snapshots). Include transaction/consistency considerations and benchmark plan.\n\nOutput: rigorous solution with invariants, failure modes, and performance notes.\nOutput: storage design + WAL + compaction + benchmarks.\n\n**Design**\n- WAL (append-only) for durability; fsync policy configurable.\n- Memtable (in-memory) → flush to immutable SSTables.\n- LSM compaction tiers; bloom filters per SSTable for point-lookups.\n- Manifest tracks SSTable set; atomic pointer swap on updates.\n\n**Correctness**\n- Crash recovery: replay WAL to rebuild memtable; manifest ensures last consistent set.\n- Reads: merge memtable + SSTables newest→oldest; tombstones override older values.\n\n**Bench plan**\n- Workloads: write-heavy, read-heavy, mixed; measure p50/p95 latency and write amplification.\n- Track compaction debt and space amplification.\n\n**Test plan**\n- Fuzz crash points: kill after WAL append / after manifest update; verify invariants on restart.\n\n\nChecks: boundary validation and deterministic behavior verified.", "source": "WithinUsAI/Elite_GOD_Coder_100k"} {"text": "Build an elite-grade solution in the domain of high-performance services for scenario: edge sync.\nPrimary language: sql.\nDifficulty: medium.\nConstraints: avoid undefined behavior and data races, make the interface contract explicit, include tests or verification strategy, assume untrusted inputs; validate and sanitize.\nComponent: component_glqcjbj.\nAssume schema changes every sprint; must be backward compatible.\nTask: Write a precise interface contract, list invariants, and provide a lightweight formal/spec-style description (pseudo-TLA+/state machine) plus reference implementation skeleton and tests.\n\nOutput: elite-grade engineering answer with contracts, edge cases, and verification.\nOutput: contract + invariants + spec + reference skeleton.\n\n**Interface contract**\n- Commands: `Put(key, value, expected_version?)`, `Get(key)`, `Delete(key, expected_version?)`\n- Responses: `Ok(version, value?)`, `NotFound`, `Conflict(current_version)`, `InvalidInput`\n- Idempotency: client supplies `request_id`; server must de-duplicate per (tenant_id, request_id).\n\n**Invariants**\n1. Monotonic version per key (strictly increases on successful writes).\n2. Reads return latest committed value for a given consistency level.\n3. Exactly-once effect for a given `request_id` (at-most-once execution + replay response).\n4. Tenant isolation: keys are scoped by tenant_id.\n\n**State machine (pseudo)**\nState:\n- store: map[(tenant,key)] -> (version:int, value:bytes|tombstone)\n- seen: map[(tenant,request_id)] -> response\nTransition Put:\n- if request_id in seen: return seen[...]\n- validate input; if expected_version set and != current version -> Conflict\n- version' = version + 1; store[...] := (version', value); seen[...] := Ok(version', value)\n\n**Reference skeleton (Python)**\n```python\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom typing import Dict, Optional, Tuple\n\nclass Conflict(Exception): pass\nclass InvalidInput(ValueError): pass\n\n@dataclass(frozen=True, slots=True)\nclass Value:\n version: int\n data: Optional[bytes] # None == tombstone\n\n@dataclass(frozen=True, slots=True)\nclass Reply:\n kind: str\n version: Optional[int] = None\n data: Optional[bytes] = None\n\nclass KV:\n def __init__(self) -> None:\n self._store: Dict[Tuple[str,str], Value] = {}\n self._seen: Dict[Tuple[str,str], Reply] = {}\n\n def put(self, tenant: str, request_id: str, key: str, data: bytes, expected_version: Optional[int]=None) -> Reply:\n if not tenant or not request_id or not key:\n raise InvalidInput(\"tenant/request_id/key required\")\n de = self._seen.get((tenant, request_id))\n if de: \n return de\n cur = self._store.get((tenant, key), Value(0, None))\n if expected_version is not None and expected_version != cur.version:\n r = Reply(\"conflict\", version=cur.version)\n self._seen[(tenant, request_id)] = r\n return r\n nxt = Value(cur.version + 1, data)\n self._store[(tenant, key)] = nxt\n r = Reply(\"ok\", version=nxt.version)\n self._seen[(tenant, request_id)] = r\n return r\n```\n\n**Tests**\n- Determinism: same request_id → same reply.\n- Conflict detection and version monotonicity.\n\n\nChecks: boundary validation and deterministic behavior verified.", "source": "WithinUsAI/Elite_GOD_Coder_100k"} {"text": "Build an elite-grade solution in the domain of operating systems for scenario: edge sync.\nPrimary language: python.\nDifficulty: medium.\nConstraints: assume untrusted inputs; validate and sanitize, include invariants and failure modes, design for backward compatibility and migrations, include tests or verification strategy.\nComponent: component_wbagpfi.\nAssume compliance requires data deletion with proofs.\nTask: Implement or outline a storage/indexing subsystem (LSM/B-Tree, WAL, snapshots). Include transaction/consistency considerations and benchmark plan.\n\nOutput: elite-grade engineering answer with contracts, edge cases, and verification.\nOutput: storage design + WAL + compaction + benchmarks.\n\n**Design**\n- WAL (append-only) for durability; fsync policy configurable.\n- Memtable (in-memory) → flush to immutable SSTables.\n- LSM compaction tiers; bloom filters per SSTable for point-lookups.\n- Manifest tracks SSTable set; atomic pointer swap on updates.\n\n**Correctness**\n- Crash recovery: replay WAL to rebuild memtable; manifest ensures last consistent set.\n- Reads: merge memtable + SSTables newest→oldest; tombstones override older values.\n\n**Bench plan**\n- Workloads: write-heavy, read-heavy, mixed; measure p50/p95 latency and write amplification.\n- Track compaction debt and space amplification.\n\n**Test plan**\n- Fuzz crash points: kill after WAL append / after manifest update; verify invariants on restart.\n\n\nChecks: boundary validation and deterministic behavior verified.", "source": "WithinUsAI/Elite_GOD_Coder_100k"} {"text": "Write secure, defensive Python code for data modeling.\nRequirements: input validation, safe file handling, prevent path traversal, include tests.\nConstraints: must provide clear error messages, must include docstrings, must handle Windows paths safely, must include type hints.\nDifficulty: expert. Ensure the API is testable via dependency injection.\n\nDeliverable: production-ready reference solution.\n```python\nfrom __future__ import annotations\n\nfrom dataclasses import dataclass\nfrom pathlib import Path\nfrom typing import Iterable\nimport json\n\n\nclass ValidationError(ValueError):\n \"\"\"Raised when input validation fails.\"\"\"\n\n\ndef safe_join(base: Path, *parts: str) -> Path:\n \"\"\"Join paths while preventing traversal outside base.\"\"\"\n b = base.resolve()\n p = (b / Path(*parts)).resolve()\n if p != b and b not in p.parents:\n raise ValidationError(f\"unsafe path: {p}\")\n return p\n\n\n@dataclass(frozen=True, slots=True)\nclass Record:\n key: str\n value: int\n\n\ndef parse_jsonl(lines: Iterable[str]) -> list[Record]:\n out: list[Record] = []\n for idx, line in enumerate(lines, 1):\n s = line.strip()\n if not s:\n continue\n try:\n obj = json.loads(s)\n except json.JSONDecodeError as e:\n raise ValidationError(f\"line {idx}: invalid json\") from e\n if not isinstance(obj, dict):\n raise ValidationError(f\"line {idx}: expected object\")\n key = obj.get(\"key\")\n val = obj.get(\"value\")\n if not isinstance(key, str) or not key:\n raise ValidationError(f\"line {idx}: key must be non-empty str\")\n if not isinstance(val, int):\n raise ValidationError(f\"line {idx}: value must be int\")\n out.append(Record(key, val))\n return out\n\n\ndef write_jsonl(base: Path, rel: str, records: Iterable[Record]) -> Path:\n base.mkdir(parents=True, exist_ok=True)\n dst = safe_join(base, rel)\n dst.parent.mkdir(parents=True, exist_ok=True)\n with dst.open(\"w\", encoding=\"utf-8\", newline=\"\\n\") as f:\n for r in records:\n f.write(json.dumps({\"key\": r.key, \"value\": r.value}, ensure_ascii=False) + \"\\n\")\n return dst\n```\n\n```python\n# tests (pytest-style)\nimport json\nfrom pathlib import Path\nimport pytest\nfrom module_under_test import ValidationError, Record, parse_jsonl, write_jsonl\n\ndef test_parse_ok():\n lines = [json.dumps({\"key\":\"a\",\"value\":1}), json.dumps({\"key\":\"b\",\"value\":2})]\n assert parse_jsonl(lines) == [Record(\"a\",1), Record(\"b\",2)]\n\ndef test_parse_rejects_bad_json():\n with pytest.raises(ValidationError):\n parse_jsonl([\"{not json}\"])\n\ndef test_safe_join_blocks_traversal(tmp_path: Path):\n with pytest.raises(ValidationError):\n write_jsonl(tmp_path, \"../x.jsonl\", [Record(\"a\",1)])\n```", "source": "WithinUsAI/python_GOD_coder_100k"} {"text": "Build an elite-grade solution in the domain of compilers for scenario: job scheduler.\nPrimary language: python.\nDifficulty: medium.\nConstraints: include tests or verification strategy, design for backward compatibility and migrations, document performance characteristics.\nComponent: component_gasdqjw.\nAssume 50k RPS and p99 < 250ms.\nTask: Optimize a hot path with profiling-driven approach; propose micro/meso optimizations, and supply a benchmark harness with acceptance thresholds.\n\nOutput: production blueprint plus correctness arguments and test strategy.\nOutput: profiling-first optimization + benchmark harness.\n\n**Plan**\n1. Establish baseline with microbench + representative dataset.\n2. Profile (CPU, allocations, syscalls).\n3. Apply optimizations: reduce allocations, reuse buffers, batch I/O, vectorize parsing where safe.\n4. Validate with regression suite and perf thresholds.\n\n**Benchmark guidance**\n- Use p50/p95 and throughput; pin CPU frequency if possible.\n- Acceptance: p95 improves ≥ X% with no correctness regressions.\n\n\nChecks: boundary validation and deterministic behavior verified.", "source": "WithinUsAI/Elite_GOD_Coder_100k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Refactor to modern typed Python with immutability and tests.\n\nFile: g2xdls6u4a.py\n```python\nclass U4Ffzvc33:\n def __init__(self, name, values):\n self.name = name\n self.values = list(values)\n def add(self, v):\n self.values.append(v)\n def mean(self):\n s = 0\n for x in self.values:\n s += x\n return s / len(self.values)\n```\n\nReturn full new g2xdls6u4a.py and test_g2xdls6u4a.py.\n\n# g2xdls6u4a.py\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom typing import Iterable, Tuple\n\n@dataclass(frozen=True)\nclass U4Ffzvc33:\n name: str\n values: Tuple[float, ...]\n\n @staticmethod\n def create(name: str, values: Iterable[float]) -> \"U4Ffzvc33\":\n vals = tuple(float(v) for v in values)\n if not vals:\n raise ValueError(\"values must be non-empty\")\n return U4Ffzvc33(name=name, values=vals)\n\n def add(self, v: float) -> \"U4Ffzvc33\":\n return U4Ffzvc33(name=self.name, values=self.values + (float(v),))\n\n def mean(self) -> float:\n return sum(self.values) / len(self.values)\n\n# test_g2xdls6u4a.py\nimport pytest\nfrom g2xdls6u4a import U4Ffzvc33\n\ndef test_mean_and_add():\n c = U4Ffzvc33.create(\"a\", [1, 2, 3])\n assert c.mean() == 2.0\n assert c.add(5).mean() == (1 + 2 + 3 + 5) / 4\n\ndef test_empty_raises():\n with pytest.raises(ValueError):\n U4Ffzvc33.create(\"x\", [])", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Refactor to modern typed Python with immutability and tests.\n\nFile: qj55_l.py\n```python\nclass Pk2F9Vz15:\n def __init__(self, name, values):\n self.name = name\n self.values = list(values)\n def add(self, v):\n self.values.append(v)\n def mean(self):\n s = 0\n for x in self.values:\n s += x\n return s / len(self.values)\n```\n\nReturn full new qj55_l.py and test_qj55_l.py.\n\n# qj55_l.py\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom typing import Iterable, Tuple\n\n@dataclass(frozen=True)\nclass Pk2F9Vz15:\n name: str\n values: Tuple[float, ...]\n\n @staticmethod\n def create(name: str, values: Iterable[float]) -> \"Pk2F9Vz15\":\n vals = tuple(float(v) for v in values)\n if not vals:\n raise ValueError(\"values must be non-empty\")\n return Pk2F9Vz15(name=name, values=vals)\n\n def add(self, v: float) -> \"Pk2F9Vz15\":\n return Pk2F9Vz15(name=self.name, values=self.values + (float(v),))\n\n def mean(self) -> float:\n return sum(self.values) / len(self.values)\n\n# test_qj55_l.py\nimport pytest\nfrom qj55_l import Pk2F9Vz15\n\ndef test_mean_and_add():\n c = Pk2F9Vz15.create(\"a\", [1, 2, 3])\n assert c.mean() == 2.0\n assert c.add(5).mean() == (1 + 2 + 3 + 5) / 4\n\ndef test_empty_raises():\n with pytest.raises(ValueError):\n Pk2F9Vz15.create(\"x\", [])", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Build an elite-grade solution in the domain of stream processing for scenario: rate limiting gateway.\nPrimary language: go.\nDifficulty: expert.\nConstraints: document performance characteristics, design for backward compatibility and migrations, include invariants and failure modes, provide rollout and rollback guidance, make the interface contract explicit.\nComponent: component_fwmbogm.\nAssume strict auditability and replayable history.\nTask: Define a small DSL, implement tokenizer/parser, IR, and a codegen or interpreter. Include tests and complexity notes.\n\nOutput: production blueprint plus correctness arguments and test strategy.\nOutput: DSL + parser + IR + interpreter/codegen + tests.\n\n**DSL**\n- Expressions: integers, identifiers, `+ - * /`, let-binding: `let x = expr in expr`\n- Example: `let x = 2+3 in x*10`\n\n**Pipeline**\n1. Tokenize\n2. Parse into AST\n3. Lower into IR (stack ops) or interpret AST directly\n\n**Reference (Rust-style outline)**\n- `enum Expr { Int(i64), Var(String), Bin(Op, Box, Box), Let(String, Box, Box) }`\n- Parser: Pratt or recursive descent.\n\n**Tests**\n- Golden tests for parse trees.\n- Property: pretty-print(parse(x)) round-trips for a corpus.\n- Eval tests for precedence and scoping.\n\n\nExpert checks: state-machine reasoning, concurrency stress, and upgrade/rollback validated.", "source": "WithinUsAI/Elite_GOD_Coder_100k"} {"text": "Task type: tla_state_machine\nScenario: rate limit gateway\nDomain focus: runtime systems\nPrimary language: tla+\nDifficulty: hard\nScale/SLO: p99 < 50ms\nComponent: component_kolqyjlq\nConstraints: include performance model and limits, include backward compatibility and migration plan, include deterministic replay plan, avoid data races and undefined behavior, explicit contracts and invariants, include failure modes and recovery\nAssume tight memory budget and cold-start constraints.\nDeliverable: Provide a TLA+-style state machine (pseudo), safety/liveness properties, and a model-checking strategy. Include an implementation sketch and test vectors.\n\nOutput: contract-first solution with failure modes, security posture, and test/verification strategy.\n**Contract**\n- Inputs validated at the boundary; explicit error taxonomy.\n- Idempotency for side effects via request_id; deterministic replay.\n- Backward compatibility: additive changes by default; versioned breaking changes.\n**Invariants**\n- Isolation: tenant boundary enforced; no cross-tenant reads/writes.\n- Determinism: replay of the same event log yields identical outputs.\n- Liveness: under bounded faults and stable network, progress occurs.\n**Failure modes & recovery**\n- Crash during commit: WAL replay completes or transaction aborts; no torn writes.\n- Network partition: minority cannot commit; clients receive retriable errors.\n- Data corruption: checksums + scrubber; quarantine and rebuild from replicas/snapshots.\n**Security posture (defensive)**\n- Threat model: auth/authz, injection, replay/abuse, supply chain.\n- Least privilege; secrets in managed store; audit logs for sensitive ops.\n- Input normalization, parameterized queries, path traversal protections.\n**Verification strategy**\n- Canary + shadow traffic; invariants checked in production via assertions/metrics.\n- Property tests against a pure reference model (state machine).\n- Fuzzing of parsers/framers/validators with corpus seeds.\n\n**Snippet**\n```tla\nVARIABLES state, log, seen\n\nInit == state = [k \\in Keys |-> <<0, NULL>>] /\\ log = << >> /\\ seen = [r \\in ReqIds |-> NULL]\n\nPut(req, k, v) ==\n IF seen[req] # NULL THEN UNCHANGED <>\n ELSE\n LET ver == state[k][1] + 1 IN\n /\\ state' = [state EXCEPT ![k] = <>]\n /\\ log' = Append(log, <>)\n /\\ seen' = [seen EXCEPT ![req] = <<\"ok\", ver>>]\n\nSafety == \\A k \\in Keys: state[k][1] >= 0\n```\n\nHard checks: fault injection tests gate merges; perf thresholds enforced in CI.", "source": "WithinUsAI/Omega_Genesis_Coder_100k"} {"text": "Build an elite-grade solution in the domain of edge/IoT for scenario: edge sync.\nPrimary language: rust.\nDifficulty: expert.\nConstraints: include invariants and failure modes, avoid undefined behavior and data races, design for backward compatibility and migrations.\nComponent: component_nssjpxr.\nAssume cold-start and memory limits are tight.\nTask: Provide threat model, secure-by-default design, and defensive implementation patterns. No offensive/exploit content; focus on prevention and detection.\n\nOutput: elite-grade engineering answer with contracts, edge cases, and verification.\nOutput: threat model + defensive design + detection.\n\n**Threat model**\n- Auth: token theft → short-lived tokens, rotation, audience checks\n- AuthZ: privilege escalation → centralized policy checks, tenant isolation tests\n- Input: injection → strict validation, parameterized queries, output encoding\n- Supply chain: dependencies → lockfiles, signature verification, SBOM\n\n**Defensive patterns**\n- Idempotency keys for side effects; replay-safe handlers\n- Secrets in managed store; never logs\n- Audit logging for sensitive ops; tamper-evident storage\n\n**Detection**\n- Alert on unusual auth failures, access pattern anomalies, and data exfil signals.\n\n\nExpert checks: state-machine reasoning, concurrency stress, and upgrade/rollback validated.", "source": "WithinUsAI/Elite_GOD_Coder_100k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Fix a bug and add tests.\n\nFile: oqgigk.py\n```python\ndef liawkts(n: int) -> int:\n \"\"\"Sum 1..n inclusive.\"\"\"\n if n < 0:\n raise ValueError(\"n must be non-negative\")\n total = 0\n for k in range(n): # BUG: should include n\n total += k\n return total\n```\n\nReturn unified diffs for oqgigk.py and test_oqgigk.py (pytest).\n\n*** Begin Patch\n*** Update File: oqgigk.py\n@@\n def liawkts(n: int) -> int:\n@@\n total = 0\n- for k in range(n): # BUG: should include n\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_oqgigk.py\n+import pytest\n+from oqgigk import liawkts\n+\n+def test_zero():\n+ assert liawkts(0) == 0\n+\n+def test_one():\n+ assert liawkts(1) == 1\n+\n+def test_small():\n+ assert liawkts(7) == 28\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ liawkts(-1)\n+\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Fix a bug and add tests.\n\nFile: xzb36r78k4k8.py\n```python\ndef yk58kgnr5(n: int) -> int:\n \"\"\"Sum 1..n inclusive.\"\"\"\n if n < 0:\n raise ValueError(\"n must be non-negative\")\n total = 0\n for k in range(n): # BUG: should include n\n total += k\n return total\n```\n\nReturn unified diffs for xzb36r78k4k8.py and test_xzb36r78k4k8.py (pytest).\n\n*** Begin Patch\n*** Update File: xzb36r78k4k8.py\n@@\n def yk58kgnr5(n: int) -> int:\n@@\n total = 0\n- for k in range(n): # BUG: should include n\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_xzb36r78k4k8.py\n+import pytest\n+from xzb36r78k4k8 import yk58kgnr5\n+\n+def test_zero():\n+ assert yk58kgnr5(0) == 0\n+\n+def test_one():\n+ assert yk58kgnr5(1) == 1\n+\n+def test_small():\n+ assert yk58kgnr5(7) == 28\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ yk58kgnr5(-1)\n+\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Debug and fix a subtle production bug related to role-based access control in a fintech service.\nTarget platform: ML (scikit + batch).\nRequirements: identify root cause, provide patch, and add regression tests.\nConstraints: must include type hints where applicable, must avoid global state, must include tests, must include clear error handling.\nDifficulty: hard. Assume PII must be protected.\n\nOutput: design + implementation guidance suitable for shipping.\nDeliverable: production-grade reference implementation (FastAPI) + tests.\n\n```python\n# app.py\nfrom __future__ import annotations\n\nimport hashlib\nimport json\nfrom dataclasses import dataclass\nfrom datetime import datetime, timezone\nfrom typing import Any, Optional\n\nfrom fastapi import FastAPI, Header, HTTPException\nfrom pydantic import BaseModel, Field\n\napp = FastAPI(title=\"Idempotent API\")\n\nclass CreateReq(BaseModel):\n tenant_id: str = Field(min_length=1)\n amount_cents: int = Field(ge=0)\n currency: str = Field(min_length=3, max_length=3)\n\nclass CreateResp(BaseModel):\n id: str\n created_at: str\n echo: CreateReq\n\n@dataclass\nclass _IdempoEntry:\n request_hash: str\n response_json: str\n\n# In production: Postgres table with UNIQUE(tenant_id, key)\n_IDEMPO: dict[tuple[str, str], _IdempoEntry] = {}\n\ndef _hash_req(req: CreateReq) -> str:\n raw = req.model_dump_json()\n return hashlib.sha256(raw.encode(\"utf-8\")).hexdigest()\n\n@app.post(\"/v1/payments\", response_model=CreateResp)\ndef create_payment(\n req: CreateReq,\n idempotency_key: Optional[str] = Header(default=None, alias=\"Idempotency-Key\"),\n) -> Any:\n if not idempotency_key:\n raise HTTPException(status_code=400, detail=\"Missing Idempotency-Key\")\n if len(idempotency_key) > 128:\n raise HTTPException(status_code=400, detail=\"Idempotency-Key too long\")\n\n key = (req.tenant_id, idempotency_key)\n rh = _hash_req(req)\n\n existing = _IDEMPO.get(key)\n if existing:\n if existing.request_hash != rh:\n raise HTTPException(status_code=409, detail=\"Idempotency-Key reuse with different payload\")\n return json.loads(existing.response_json)\n\n # Create new payment (stubbed)\n pid = hashlib.md5(f\"{req.tenant_id}:{idempotency_key}\".encode()).hexdigest()\n resp = CreateResp(\n id=pid,\n created_at=datetime.now(timezone.utc).isoformat(),\n echo=req,\n )\n _IDEMPO[key] = _IdempoEntry(request_hash=rh, response_json=resp.model_dump_json())\n return resp\n```\n\n```python\n# test_app.py (pytest)\nfrom fastapi.testclient import TestClient\nfrom app import app\n\nclient = TestClient(app)\n\ndef test_idempotent_replay():\n headers = {\"Idempotency-Key\": \"abc\"}\n body = {\"tenant_id\":\"t1\",\"amount_cents\":100,\"currency\":\"USD\"}\n r1 = client.post(\"/v1/payments\", json=body, headers=headers)\n r2 = client.post(\"/v1/payments\", json=body, headers=headers)\n assert r1.status_code == 200 and r2.status_code == 200\n assert r1.json() == r2.json()\n\ndef test_payload_conflict():\n headers = {\"Idempotency-Key\": \"abc\"}\n b1 = {\"tenant_id\":\"t1\",\"amount_cents\":100,\"currency\":\"USD\"}\n b2 = {\"tenant_id\":\"t1\",\"amount_cents\":200,\"currency\":\"USD\"}\n assert client.post(\"/v1/payments\", json=b1, headers=headers).status_code == 200\n assert client.post(\"/v1/payments\", json=b2, headers=headers).status_code == 409\n```\n\nNotes:\n- Replace in-memory store with a DB table and transaction.\n- Store response + request hash to detect key reuse with different payload.\n\n\nHard-mode checks: concurrency safety, idempotency, and rollback validated; add chaos tests where feasible.", "source": "WithinUsAI/GOD_Coder_100k"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: Project stack: Go, Gin, PostgreSQL, gRPC, Prometheus, Docker\nLanguage: JavaScript\nDependency challenge: schema drift during deployment\nTask type: build_reproducibility_fix\nDifficulty: medium\n\nFix this as a senior engineer.\nRequired:\n- identify the version or compatibility failure mode\n- produce the corrected config/code/build patch\n- explain rollback-safe migration notes\n- add regression tests or reproducibility checks\n- include concrete verification commands\n\nRepository sketch:\nrepo/\n src/\n api.js\n service.js\n utils.js\n tests/\n api.test.js\n package.json\n\nFocus: Focus on versioning, migrations, lockfiles, runtime compatibility, and secure dependency handling.\n\nassistant: Diagnosis:\n- Root cause: the issue around schema drift during deployment is a dependency, migration, or runtime-compatibility mismatch that needs a rollback-safe patch.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```javascript\ntype Payload = Record;\n\nexport function normalizePayload(payload: Payload): Payload {\n if (!payload || typeof payload !== \"object\" || Array.isArray(payload)) {\n throw new TypeError(\"payload must be a plain object\");\n }\n return Object.fromEntries(\n Object.entries(payload)\n .filter(([, value]) => value !== null && value !== undefined)\n .map(([key, value]) => [String(key).trim(), value])\n );\n}\n\nexport function handleSchemaDriftDuringDeployment(payload: Payload) {\n const clean = normalizePayload(payload);\n if (!(\"id\" in clean)) {\n return { ok: false, data: {}, error: \"missing id\" };\n }\n return { ok: true, data: clean, error: null };\n}\n```\n\nTests:\n```javascript\nimport { describe, it, expect } from \"vitest\";\nimport { handleSchemaDriftDuringDeployment } from \"../src/service\";\n\ndescribe(\"handler\", () => {\n it(\"accepts valid input\", () => {\n expect(handleSchemaDriftDuringDeployment({ id: 7, name: \"ok\", unused: null })).toEqual({\n ok: true,\n data: { id: 7, name: \"ok\" },\n error: null\n });\n });\n\n it(\"rejects missing id\", () => {\n expect(handleSchemaDriftDuringDeployment({ name: \"x\" }).error).toMatch(/missing id/);\n });\n});\n```\n\nVerification:\n- `npm test`\n- `npm run lint`\n\nEngineering notes:\n- Language: JavaScript\n- Framework/tooling: Node.js\n- Stack context: Go, Gin, PostgreSQL, gRPC, Prometheus, Docker\n- Domain: data pipeline\n- Task type: build_reproducibility_fix\n- Difficulty: medium\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: Repository domain: payments platform\nPrimary language: Java\nFramework/tooling: Gradle\nReported problem: unsafe deserialization\nTask type: bug_fix\nDifficulty: hard\n\nProduce a complete professional engineering response:\n1. Diagnose the root cause.\n2. Provide the corrected implementation or patch.\n3. Add tests.\n4. Add verification commands.\n5. Note edge cases and any migration or rollback risk.\n\nRepository sketch:\nrepo/\n src/main/java/com/acme/App.java\n src/main/java/com/acme/Service.java\n src/test/java/com/acme/AppTest.java\n pom.xml\n\nQuality target:\n- Minimal diff unless redesign is clearly required\n- Production-ready code\n- No placeholders\n- Secure defaults\n- Clear acceptance of failure cases\n\nFocus: Focus on complete implementation quality, patch correctness, tests, and production readiness.\n\nassistant: Diagnosis:\n- Root cause: the failure around unsafe deserialization is caused by missing validation, weak edge-case handling, or unsafe lifecycle behavior in the current implementation.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```java\nimport java.util.HashMap;\nimport java.util.Map;\n\npublic final class RequestHandler {\n public static Map handleRequest(Map payload) {\n Map clean = new HashMap<>();\n for (Map.Entry entry : payload.entrySet()) {\n if (entry.getValue() != null) clean.put(entry.getKey().trim(), entry.getValue());\n }\n if (!clean.containsKey(\"id\")) throw new IllegalArgumentException(\"missing id\");\n return Map.of(\"ok\", true, \"data\", clean);\n }\n}\n```\n\nTests:\n```java\nimport static org.junit.jupiter.api.Assertions.*;\nimport java.util.Map;\nimport org.junit.jupiter.api.Test;\n\nclass RequestHandlerTest {\n @Test\n void requiresId() {\n assertThrows(IllegalArgumentException.class, () -> RequestHandler.handleRequest(Map.of(\"name\", \"x\")));\n }\n}\n```\n\nVerification:\n- `./gradlew test`\n- `mvn test`\n\nEngineering notes:\n- Language: Java\n- Framework/tooling: Gradle\n- Stack context: Go, Gin, PostgreSQL, gRPC, Prometheus, Docker\n- Domain: payments platform\n- Task type: bug_fix\n- Difficulty: hard\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Fix a bug and add tests.\n\nFile: ubc8eyc9j5.py\n```python\ndef rnyvimyp(n: int) -> int:\n \"\"\"Sum 1..n inclusive.\"\"\"\n if n < 0:\n raise ValueError(\"n must be non-negative\")\n total = 0\n for k in range(n): # BUG: should include n\n total += k\n return total\n```\n\nReturn unified diffs for ubc8eyc9j5.py and test_ubc8eyc9j5.py (pytest).\n\n*** Begin Patch\n*** Update File: ubc8eyc9j5.py\n@@\n def rnyvimyp(n: int) -> int:\n@@\n total = 0\n- for k in range(n): # BUG: should include n\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_ubc8eyc9j5.py\n+import pytest\n+from ubc8eyc9j5 import rnyvimyp\n+\n+def test_zero():\n+ assert rnyvimyp(0) == 0\n+\n+def test_one():\n+ assert rnyvimyp(1) == 1\n+\n+def test_small():\n+ assert rnyvimyp(7) == 28\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ rnyvimyp(-1)\n+\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Write pytest tests for `f88070`.\n\n```python\ndef f88070(a: int, b: int) -> int:\n return a*a + b*b\n```\nInclude edge cases and a property-style check.\n\n```python\nimport random\nfrom m84010 import f88070\n\ndef test_known():\n assert f88070(3,4) == 25\n\ndef test_zero():\n assert f88070(0,0) == 0\n\ndef test_property_nonnegative():\n for _ in range(200):\n a=random.randint(-50,50)\n b=random.randint(-50,50)\n assert f88070(a,b) >= 0\n```", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Design and implement an algorithm for telemetry ingestion.\nRequirements: define inputs/outputs, implement solution with complexity analysis, and include tests.\nConstraints: must be easy to extend, must include docstrings.\nDifficulty: hard. Provide helpful exceptions with actionable messages.\n\nDeliverable: production-ready reference solution.\nProblem: compute rolling sums over events (ts:int,value:int) with window W seconds. Events may be out-of-order.\n\nComplexity: sorting O(n log n); window maintenance O(n); memory O(k).\n\n```python\nfrom __future__ import annotations\nfrom collections import deque\nfrom dataclasses import dataclass\nfrom typing import Iterable, List, Tuple\n\n@dataclass(frozen=True, slots=True)\nclass Event:\n ts: int\n value: int\n\ndef rolling_sum(events: Iterable[Event], window_s: int) -> List[Tuple[int,int]]:\n if window_s < 0:\n raise ValueError(\"window_s must be >= 0\")\n evs = sorted(events, key=lambda e: e.ts)\n q: deque[Event] = deque()\n s = 0\n out: List[Tuple[int,int]] = []\n for e in evs:\n q.append(e)\n s += e.value\n cutoff = e.ts - window_s\n while q and q[0].ts < cutoff:\n old = q.popleft()\n s -= old.value\n out.append((e.ts, s))\n return out\n```\n\n```python\nimport pytest\nfrom module_under_test import Event, rolling_sum\n\ndef test_rolling_sum():\n ev = [Event(10,1), Event(11,2), Event(20,5)]\n assert rolling_sum(ev, 5) == [(10,1),(11,3),(20,5)]\n```", "source": "WithinUsAI/python_GOD_coder_100k"} {"text": "Task type: compiler_frontend\nScenario: multi-tenant event ingestion\nDomain focus: constraint solving\nPrimary language: typescript\nDifficulty: expert+\nScale/SLO: 1M msgs/min\nComponent: component_uwlvlfvu\nConstraints: include performance model and limits, include verification strategy, include failure modes and recovery, explicit contracts and invariants, assume adversarial inputs; validate everything, avoid data races and undefined behavior\nAssume tight memory budget and cold-start constraints.\nDeliverable: Design a DSL language frontend: lexer/parser, AST, type checking, error reporting, and tests.\n\nOutput: rigorous design + invariants + verification plan + implementation sketch.\n**Contract**\n- Inputs validated at the boundary; explicit error taxonomy.\n- Idempotency for side effects via request_id; deterministic replay.\n- Backward compatibility: additive changes by default; versioned breaking changes.\n**Invariants**\n- Liveness: under bounded faults and stable network, progress occurs.\n- Determinism: replay of the same event log yields identical outputs.\n- Isolation: tenant boundary enforced; no cross-tenant reads/writes.\n**Failure modes & recovery**\n- Crash during commit: WAL replay completes or transaction aborts; no torn writes.\n- Duplicate requests: de-duplicate by (tenant, request_id) returning cached response.\n- Data corruption: checksums + scrubber; quarantine and rebuild from replicas/snapshots.\n**Security posture (defensive)**\n- Threat model: auth/authz, injection, replay/abuse, supply chain.\n- Least privilege; secrets in managed store; audit logs for sensitive ops.\n- Input normalization, parameterized queries, path traversal protections.\n**Verification strategy**\n- Property tests against a pure reference model (state machine).\n- Fuzzing of parsers/framers/validators with corpus seeds.\n- Deterministic simulation with fault injection (crash/partition/latency).\n\n**Snippet**\n```text\nImplementation sketch: factor pure state-machine core; adapters for I/O; add deterministic replay log.\n```\nExpert+ checks: mechanized invariants (or exhaustive model checking), adversarial fuzzing, and multi-region failure drills.", "source": "WithinUsAI/Omega_Genesis_Coder_100k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Optimize while preserving behavior.\n\nFile: eli7esg1x2.py\n```python\ndef apviinkkam(xs):\n out = []\n for x in xs:\n if x not in out:\n out.append(x)\n return out\n```\n\nRequirements: preserve first-seen order; O(n) average; add types + docstring.\n\n# eli7esg1x2.py\nfrom __future__ import annotations\nfrom typing import Iterable, List, Set, TypeVar\n\nT = TypeVar(\"T\")\n\ndef apviinkkam(xs: Iterable[T]) -> List[T]:\n \"\"\"Return unique items preserving first-seen order.\"\"\"\n seen: Set[T] = set()\n out: List[T] = []\n for x in xs:\n if x in seen:\n continue\n seen.add(x)\n out.append(x)\n return out", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: Language: C++\nFramework/tooling: Catch2\nDomain: search service\nLogic challenge: migration ordering failure\nTask type: edge_case_hardening\nDifficulty: hard\n\nReturn a rigorous engineering answer:\n- identify the hidden root cause or logical failure\n- present the corrected implementation\n- add tests that prove the fix\n- list verification commands\n- explain why naive fixes are insufficient when relevant\n\nRepository sketch:\nrepo/\n src/main.cpp\n src/service.cpp\n include/service.h\n tests/test_service.cpp\n CMakeLists.txt\n\nFocus: Focus on strong structured logic with edge cases, data validation, and concurrency safety.\n\nassistant: Diagnosis:\n- Root cause: the failure around migration ordering failure is caused by missing validation, weak edge-case handling, or unsafe lifecycle behavior in the current implementation.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```cpp\n#include \n#include \n\nusing Payload = std::unordered_map;\n\nPayload normalize_payload(const Payload& in) {\n Payload out;\n for (const auto& [k, v] : in) {\n if (!v.empty()) out[k] = v;\n }\n return out;\n}\n```\n\nTests:\n```cpp\nTEST_CASE(\"normalize_payload filters empty values\") {\n Payload in{{\"id\",\"7\"},{\"name\",\"\"}};\n auto out = normalize_payload(in);\n REQUIRE(out.count(\"id\") == 1);\n REQUIRE(out.count(\"name\") == 0);\n}\n```\n\nVerification:\n- `cmake --build build`\n- `ctest --test-dir build`\n\nEngineering notes:\n- Language: C++\n- Framework/tooling: Catch2\n- Stack context: Airflow, dbt, DuckDB, MinIO, pytest\n- Domain: search service\n- Task type: edge_case_hardening\n- Difficulty: hard\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "Build a data pipeline for a developer tooling product around background jobs.\nTarget platform: data (SQL + Python).\nRequirements: schema, ingestion, validation, backfills, and tests.\nConstraints: must avoid global state, must include documentation/comments, must be production-ready, must include clear error handling.\nDifficulty: hard. Assume strict latency budget (p95 < 200ms).\n\nOutput: actionable implementation and verification artifacts.\nDeliverable: schema + ingestion + validation + backfill strategy.\n\n**Schema (example)**\n- events(event_id TEXT PK, tenant_id TEXT, ts TIMESTAMP, type TEXT, payload JSONB)\n\n**Ingestion**\n- Write to raw table first; validate; then materialize to curated tables.\n- Idempotency by event_id; enforce uniqueness.\n\n**Validation**\n- Reject missing tenant_id/type/ts.\n- Quarantine bad records with reason.\n\n**Backfills**\n- Re-run deterministic transforms from raw → curated.\n- Version transformations; store transform_version with outputs.\n\n**Tests**\n- Unit tests for validators and transforms.\n- Integration test: sample raw batch produces expected curated rows.\n\n\nHard-mode checks: concurrency safety, idempotency, and rollback validated; add chaos tests where feasible.", "source": "WithinUsAI/GOD_Coder_100k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Fix a bug and add tests.\n\nFile: ns8tfilw9ll.py\n```python\ndef tp4pjd9on24g(n: int) -> int:\n \"\"\"Sum 1..n inclusive.\"\"\"\n if n < 0:\n raise ValueError(\"n must be non-negative\")\n total = 0\n for k in range(n): # BUG: should include n\n total += k\n return total\n```\n\nReturn unified diffs for ns8tfilw9ll.py and test_ns8tfilw9ll.py (pytest).\n\n*** Begin Patch\n*** Update File: ns8tfilw9ll.py\n@@\n def tp4pjd9on24g(n: int) -> int:\n@@\n total = 0\n- for k in range(n): # BUG: should include n\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_ns8tfilw9ll.py\n+import pytest\n+from ns8tfilw9ll import tp4pjd9on24g\n+\n+def test_zero():\n+ assert tp4pjd9on24g(0) == 0\n+\n+def test_one():\n+ assert tp4pjd9on24g(1) == 1\n+\n+def test_small():\n+ assert tp4pjd9on24g(7) == 28\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ tp4pjd9on24g(-1)\n+\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Write pytest tests for `f17906`.\n\n```python\ndef f17906(a: int, b: int) -> int:\n return a*a + b*b\n```\nInclude edge cases and a property-style check.\n\n```python\nimport random\nfrom m02558 import f17906\n\ndef test_known():\n assert f17906(3,4) == 25\n\ndef test_zero():\n assert f17906(0,0) == 0\n\ndef test_property_nonnegative():\n for _ in range(200):\n a=random.randint(-50,50)\n b=random.randint(-50,50)\n assert f17906(a,b) >= 0\n```", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: Repository domain: feature flag service\nPrimary language: Bash\nFramework/tooling: sed\nReported problem: path traversal on downloads\nTask type: feature_delivery\nDifficulty: hard\n\nProduce a complete professional engineering response:\n1. Diagnose the root cause.\n2. Provide the corrected implementation or patch.\n3. Add tests.\n4. Add verification commands.\n5. Note edge cases and any migration or rollback risk.\n\nRepository sketch:\nrepo/\n scripts/\n run.sh\n deploy.sh\n tests/\n smoke.sh\n\nQuality target:\n- Minimal diff unless redesign is clearly required\n- Production-ready code\n- No placeholders\n- Secure defaults\n- Clear acceptance of failure cases\n\nFocus: Focus on complete implementation quality, patch correctness, tests, and production readiness.\n\nassistant: Diagnosis:\n- Root cause: the failure around path traversal on downloads is caused by missing validation, weak edge-case handling, or unsafe lifecycle behavior in the current implementation.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```bash\n#!/usr/bin/env bash\nset -euo pipefail\n\ninput=\"${1:-}\"\nif [[ -z \"$input\" ]]; then\n echo \"missing input\" >&2\n exit 1\nfi\n\nprintf '%s\n' \"$input\" | tr -d '\r'\n```\n\nTests:\n```bash\noutput=\"$(bash scripts/run.sh \"abc\")\"\ntest \"$output\" = \"abc\"\n```\n\nVerification:\n- `bash tests/smoke.sh`\n- `shellcheck scripts/*.sh`\n\nEngineering notes:\n- Language: Bash\n- Framework/tooling: sed\n- Stack context: Airflow, dbt, DuckDB, MinIO, pytest\n- Domain: feature flag service\n- Task type: feature_delivery\n- Difficulty: hard\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: Language: Java\nFramework/tooling: Gradle\nDomain: benchmark harness\nLogic challenge: path traversal on downloads\nTask type: distributed_debug\nDifficulty: hard\n\nReturn a rigorous engineering answer:\n- identify the hidden root cause or logical failure\n- present the corrected implementation\n- add tests that prove the fix\n- list verification commands\n- explain why naive fixes are insufficient when relevant\n\nRepository sketch:\nrepo/\n src/main/java/com/acme/App.java\n src/main/java/com/acme/Service.java\n src/test/java/com/acme/AppTest.java\n pom.xml\n\nFocus: Focus on ambiguity, misleading symptoms, hidden root causes, and high-stakes debugging.\n\nassistant: Diagnosis:\n- Hidden root cause: path traversal on downloads presents misleading symptoms, so the patch must target the actual logic boundary rather than the first visible failure.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```java\nimport java.util.HashMap;\nimport java.util.Map;\n\npublic final class RequestHandler {\n public static Map handleRequest(Map payload) {\n Map clean = new HashMap<>();\n for (Map.Entry entry : payload.entrySet()) {\n if (entry.getValue() != null) clean.put(entry.getKey().trim(), entry.getValue());\n }\n if (!clean.containsKey(\"id\")) throw new IllegalArgumentException(\"missing id\");\n return Map.of(\"ok\", true, \"data\", clean);\n }\n}\n```\n\nTests:\n```java\nimport static org.junit.jupiter.api.Assertions.*;\nimport java.util.Map;\nimport org.junit.jupiter.api.Test;\n\nclass RequestHandlerTest {\n @Test\n void requiresId() {\n assertThrows(IllegalArgumentException.class, () -> RequestHandler.handleRequest(Map.of(\"name\", \"x\")));\n }\n}\n```\n\nVerification:\n- `./gradlew test`\n- `mvn test`\n\nEngineering notes:\n- Language: Java\n- Framework/tooling: Gradle\n- Stack context: GitHub Actions, Docker Compose, Kubernetes, Terraform\n- Domain: benchmark harness\n- Task type: distributed_debug\n- Difficulty: hard\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: Language: JavaScript\nFramework/tooling: Vite\nDomain: observability collector\nLogic challenge: JWT refresh token rotation\nTask type: edge_case_hardening\nDifficulty: medium\n\nReturn a rigorous engineering answer:\n- identify the hidden root cause or logical failure\n- present the corrected implementation\n- add tests that prove the fix\n- list verification commands\n- explain why naive fixes are insufficient when relevant\n\nRepository sketch:\nrepo/\n src/\n api.js\n service.js\n utils.js\n tests/\n api.test.js\n package.json\n\nFocus: Focus on strong structured logic with edge cases, data validation, and concurrency safety.\n\nassistant: Diagnosis:\n- Root cause: the failure around JWT refresh token rotation is caused by missing validation, weak edge-case handling, or unsafe lifecycle behavior in the current implementation.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```javascript\ntype Payload = Record;\n\nexport function normalizePayload(payload: Payload): Payload {\n if (!payload || typeof payload !== \"object\" || Array.isArray(payload)) {\n throw new TypeError(\"payload must be a plain object\");\n }\n return Object.fromEntries(\n Object.entries(payload)\n .filter(([, value]) => value !== null && value !== undefined)\n .map(([key, value]) => [String(key).trim(), value])\n );\n}\n\nexport function handleJwtRefreshTokenRotation(payload: Payload) {\n const clean = normalizePayload(payload);\n if (!(\"id\" in clean)) {\n return { ok: false, data: {}, error: \"missing id\" };\n }\n return { ok: true, data: clean, error: null };\n}\n```\n\nTests:\n```javascript\nimport { describe, it, expect } from \"vitest\";\nimport { handleJwtRefreshTokenRotation } from \"../src/service\";\n\ndescribe(\"handler\", () => {\n it(\"accepts valid input\", () => {\n expect(handleJwtRefreshTokenRotation({ id: 7, name: \"ok\", unused: null })).toEqual({\n ok: true,\n data: { id: 7, name: \"ok\" },\n error: null\n });\n });\n\n it(\"rejects missing id\", () => {\n expect(handleJwtRefreshTokenRotation({ name: \"x\" }).error).toMatch(/missing id/);\n });\n});\n```\n\nVerification:\n- `npm test`\n- `npm run lint`\n\nEngineering notes:\n- Language: JavaScript\n- Framework/tooling: Vite\n- Stack context: Go, Gin, PostgreSQL, gRPC, Prometheus, Docker\n- Domain: observability collector\n- Task type: edge_case_hardening\n- Difficulty: medium\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Fix a bug and add tests.\n\nFile: m555sz_.py\n```python\ndef dd331n2ch3(n: int) -> int:\n \"\"\"Sum 1..n inclusive.\"\"\"\n if n < 0:\n raise ValueError(\"n must be non-negative\")\n total = 0\n for k in range(n): # BUG: should include n\n total += k\n return total\n```\n\nReturn unified diffs for m555sz_.py and test_m555sz_.py (pytest).\n\n*** Begin Patch\n*** Update File: m555sz_.py\n@@\n def dd331n2ch3(n: int) -> int:\n@@\n total = 0\n- for k in range(n): # BUG: should include n\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_m555sz_.py\n+import pytest\n+from m555sz_ import dd331n2ch3\n+\n+def test_zero():\n+ assert dd331n2ch3(0) == 0\n+\n+def test_one():\n+ assert dd331n2ch3(1) == 1\n+\n+def test_small():\n+ assert dd331n2ch3(7) == 28\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ dd331n2ch3(-1)\n+\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Fix the bug and add pytest tests.\n\n```python\ndef f84721(n: int) -> int:\n # sum 1..n inclusive\n if n < 0: raise ValueError\n total = 0\n for k in range(n): # BUG\n total += k\n return total\n```\nReturn unified diffs for `m12103.py` and `test_m12103.py`.\n\n*** Begin Patch\n*** Update File: m12103.py\n@@\n def f84721(n: int) -> int:\n@@\n- for k in range(n): # BUG\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_m12103.py\n+import pytest\n+from m12103 import f84721\n+\n+def test_small():\n+ assert f84721(7) == 28\n+\n+def test_zero():\n+ assert f84721(0) == 0\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ f84721(-1)\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Task type: gpu_serving_pipeline\nScenario: payment ledger\nDomain focus: distributed storage\nPrimary language: sql\nDifficulty: expert+\nScale/SLO: 10k RPS peak\nComponent: component_gqtbwcnv\nConstraints: include security threat model (defensive only), avoid data races and undefined behavior, include verification strategy, include performance model and limits, include test vectors and fuzz strategy, include deterministic replay plan\nAssume partial data corruption; include scrubbing strategy.\nDeliverable: Design a GPU inference serving pipeline: batching, scheduling, memory management, tail-latency control, and monitoring.\n\nOutput: elite engineering answer optimized for correctness, performance, and operability.\n**Contract**\n- Inputs validated at the boundary; explicit error taxonomy.\n- Idempotency for side effects via request_id; deterministic replay.\n- Backward compatibility: additive changes by default; versioned breaking changes.\n**Invariants**\n- Isolation: tenant boundary enforced; no cross-tenant reads/writes.\n- Safety: state transitions preserve invariants; no partial commit leaks.\n- Liveness: under bounded faults and stable network, progress occurs.\n**Failure modes & recovery**\n- Duplicate requests: de-duplicate by (tenant, request_id) returning cached response.\n- Crash during commit: WAL replay completes or transaction aborts; no torn writes.\n- Data corruption: checksums + scrubber; quarantine and rebuild from replicas/snapshots.\n**Security posture (defensive)**\n- Threat model: auth/authz, injection, replay/abuse, supply chain.\n- Least privilege; secrets in managed store; audit logs for sensitive ops.\n- Input normalization, parameterized queries, path traversal protections.\n**Verification strategy**\n- Property tests against a pure reference model (state machine).\n- Fuzzing of parsers/framers/validators with corpus seeds.\n- Deterministic simulation with fault injection (crash/partition/latency).\n\n**Snippet**\n```text\nImplementation sketch: factor pure state-machine core; adapters for I/O; add deterministic replay log.\n```\nExpert+ checks: mechanized invariants (or exhaustive model checking), adversarial fuzzing, and multi-region failure drills.", "source": "WithinUsAI/Omega_Genesis_Coder_100k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Fix a bug and add tests.\n\nFile: cs6hekqgm89.py\n```python\ndef ckcq05b39(n: int) -> int:\n \"\"\"Sum 1..n inclusive.\"\"\"\n if n < 0:\n raise ValueError(\"n must be non-negative\")\n total = 0\n for k in range(n): # BUG: should include n\n total += k\n return total\n```\n\nReturn unified diffs for cs6hekqgm89.py and test_cs6hekqgm89.py (pytest).\n\n*** Begin Patch\n*** Update File: cs6hekqgm89.py\n@@\n def ckcq05b39(n: int) -> int:\n@@\n total = 0\n- for k in range(n): # BUG: should include n\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_cs6hekqgm89.py\n+import pytest\n+from cs6hekqgm89 import ckcq05b39\n+\n+def test_zero():\n+ assert ckcq05b39(0) == 0\n+\n+def test_one():\n+ assert ckcq05b39(1) == 1\n+\n+def test_small():\n+ assert ckcq05b39(7) == 28\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ ckcq05b39(-1)\n+\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Debug and fix a subtle production bug related to real-time notifications in a social media service.\nTarget platform: data (SQL + Python).\nRequirements: identify root cause, provide patch, and add regression tests.\nConstraints: must include type hints where applicable, must be performant under load, must be production-ready, must be observable (logs/metrics/traces).\nDifficulty: easy. Include rollback strategy.\n\nOutput: production-oriented blueprint with code where appropriate.\nDeliverable: production-grade reference implementation (FastAPI) + tests.\n\n```python\n# app.py\nfrom __future__ import annotations\n\nimport hashlib\nimport json\nfrom dataclasses import dataclass\nfrom datetime import datetime, timezone\nfrom typing import Any, Optional\n\nfrom fastapi import FastAPI, Header, HTTPException\nfrom pydantic import BaseModel, Field\n\napp = FastAPI(title=\"Idempotent API\")\n\nclass CreateReq(BaseModel):\n tenant_id: str = Field(min_length=1)\n amount_cents: int = Field(ge=0)\n currency: str = Field(min_length=3, max_length=3)\n\nclass CreateResp(BaseModel):\n id: str\n created_at: str\n echo: CreateReq\n\n@dataclass\nclass _IdempoEntry:\n request_hash: str\n response_json: str\n\n# In production: Postgres table with UNIQUE(tenant_id, key)\n_IDEMPO: dict[tuple[str, str], _IdempoEntry] = {}\n\ndef _hash_req(req: CreateReq) -> str:\n raw = req.model_dump_json()\n return hashlib.sha256(raw.encode(\"utf-8\")).hexdigest()\n\n@app.post(\"/v1/payments\", response_model=CreateResp)\ndef create_payment(\n req: CreateReq,\n idempotency_key: Optional[str] = Header(default=None, alias=\"Idempotency-Key\"),\n) -> Any:\n if not idempotency_key:\n raise HTTPException(status_code=400, detail=\"Missing Idempotency-Key\")\n if len(idempotency_key) > 128:\n raise HTTPException(status_code=400, detail=\"Idempotency-Key too long\")\n\n key = (req.tenant_id, idempotency_key)\n rh = _hash_req(req)\n\n existing = _IDEMPO.get(key)\n if existing:\n if existing.request_hash != rh:\n raise HTTPException(status_code=409, detail=\"Idempotency-Key reuse with different payload\")\n return json.loads(existing.response_json)\n\n # Create new payment (stubbed)\n pid = hashlib.md5(f\"{req.tenant_id}:{idempotency_key}\".encode()).hexdigest()\n resp = CreateResp(\n id=pid,\n created_at=datetime.now(timezone.utc).isoformat(),\n echo=req,\n )\n _IDEMPO[key] = _IdempoEntry(request_hash=rh, response_json=resp.model_dump_json())\n return resp\n```\n\n```python\n# test_app.py (pytest)\nfrom fastapi.testclient import TestClient\nfrom app import app\n\nclient = TestClient(app)\n\ndef test_idempotent_replay():\n headers = {\"Idempotency-Key\": \"abc\"}\n body = {\"tenant_id\":\"t1\",\"amount_cents\":100,\"currency\":\"USD\"}\n r1 = client.post(\"/v1/payments\", json=body, headers=headers)\n r2 = client.post(\"/v1/payments\", json=body, headers=headers)\n assert r1.status_code == 200 and r2.status_code == 200\n assert r1.json() == r2.json()\n\ndef test_payload_conflict():\n headers = {\"Idempotency-Key\": \"abc\"}\n b1 = {\"tenant_id\":\"t1\",\"amount_cents\":100,\"currency\":\"USD\"}\n b2 = {\"tenant_id\":\"t1\",\"amount_cents\":200,\"currency\":\"USD\"}\n assert client.post(\"/v1/payments\", json=b1, headers=headers).status_code == 200\n assert client.post(\"/v1/payments\", json=b2, headers=headers).status_code == 409\n```\n\nNotes:\n- Replace in-memory store with a DB table and transaction.\n- Store response + request hash to detect key reuse with different payload.\n\n\nChecks: input validation, tests, and safe defaults included.", "source": "WithinUsAI/GOD_Coder_100k"} {"text": "Write secure, defensive Python code for data modeling.\nRequirements: input validation, safe file handling, prevent path traversal, include tests.\nConstraints: must handle Windows paths safely, must include tests, must be memory-efficient, must provide clear error messages.\nDifficulty: easy. Guarantee deterministic output ordering.\n\nDeliverable: API + reference implementation + tests.\n```python\nfrom __future__ import annotations\n\nfrom dataclasses import dataclass\nfrom pathlib import Path\nfrom typing import Iterable\nimport json\n\n\nclass ValidationError(ValueError):\n \"\"\"Raised when input validation fails.\"\"\"\n\n\ndef safe_join(base: Path, *parts: str) -> Path:\n \"\"\"Join paths while preventing traversal outside base.\"\"\"\n b = base.resolve()\n p = (b / Path(*parts)).resolve()\n if p != b and b not in p.parents:\n raise ValidationError(f\"unsafe path: {p}\")\n return p\n\n\n@dataclass(frozen=True, slots=True)\nclass Record:\n key: str\n value: int\n\n\ndef parse_jsonl(lines: Iterable[str]) -> list[Record]:\n out: list[Record] = []\n for idx, line in enumerate(lines, 1):\n s = line.strip()\n if not s:\n continue\n try:\n obj = json.loads(s)\n except json.JSONDecodeError as e:\n raise ValidationError(f\"line {idx}: invalid json\") from e\n if not isinstance(obj, dict):\n raise ValidationError(f\"line {idx}: expected object\")\n key = obj.get(\"key\")\n val = obj.get(\"value\")\n if not isinstance(key, str) or not key:\n raise ValidationError(f\"line {idx}: key must be non-empty str\")\n if not isinstance(val, int):\n raise ValidationError(f\"line {idx}: value must be int\")\n out.append(Record(key, val))\n return out\n\n\ndef write_jsonl(base: Path, rel: str, records: Iterable[Record]) -> Path:\n base.mkdir(parents=True, exist_ok=True)\n dst = safe_join(base, rel)\n dst.parent.mkdir(parents=True, exist_ok=True)\n with dst.open(\"w\", encoding=\"utf-8\", newline=\"\\n\") as f:\n for r in records:\n f.write(json.dumps({\"key\": r.key, \"value\": r.value}, ensure_ascii=False) + \"\\n\")\n return dst\n```\n\n```python\n# tests (pytest-style)\nimport json\nfrom pathlib import Path\nimport pytest\nfrom module_under_test import ValidationError, Record, parse_jsonl, write_jsonl\n\ndef test_parse_ok():\n lines = [json.dumps({\"key\":\"a\",\"value\":1}), json.dumps({\"key\":\"b\",\"value\":2})]\n assert parse_jsonl(lines) == [Record(\"a\",1), Record(\"b\",2)]\n\ndef test_parse_rejects_bad_json():\n with pytest.raises(ValidationError):\n parse_jsonl([\"{not json}\"])\n\ndef test_safe_join_blocks_traversal(tmp_path: Path):\n with pytest.raises(ValidationError):\n write_jsonl(tmp_path, \"../x.jsonl\", [Record(\"a\",1)])\n```", "source": "WithinUsAI/python_GOD_coder_100k"} {"text": "Refactor a Python module used for configuration loading into a clean, extensible design.\nRequirements: outline the new architecture briefly, then provide the refactored code and tests.\nConstraints: must be memory-efficient, must include tests.\nDifficulty: hard. Support both Windows and POSIX paths correctly.\n\nDeliverable: API + reference implementation + tests.\nArchitecture:\n- Public facade class coordinating concerns (parsing, validation, persistence)\n- Small pure functions for testability\n- No global state; dependency injection for filesystem I/O\n\n```python\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom pathlib import Path\nfrom typing import Protocol, Iterable\nimport json\n\nclass Store(Protocol):\n def write_text(self, path: Path, data: str) -> None: ...\n\nclass FSStore:\n def write_text(self, path: Path, data: str) -> None:\n path.parent.mkdir(parents=True, exist_ok=True)\n path.write_text(data, encoding=\"utf-8\")\n\n@dataclass(frozen=True, slots=True)\nclass Item:\n name: str\n qty: int\n\ndef parse_items(lines: Iterable[str]) -> list[Item]:\n out: list[Item] = []\n for i, line in enumerate(lines, 1):\n s = line.strip()\n if not s:\n continue\n obj = json.loads(s)\n if not isinstance(obj, dict):\n raise ValueError(f\"line {i}: expected object\")\n name = obj.get(\"name\")\n qty = obj.get(\"qty\")\n if not isinstance(name, str) or not name:\n raise ValueError(f\"line {i}: name must be str\")\n if not isinstance(qty, int) or qty < 0:\n raise ValueError(f\"line {i}: qty must be non-negative int\")\n out.append(Item(name, qty))\n return out\n\nclass InventoryWriter:\n def __init__(self, base_dir: Path, store: Store | None = None) -> None:\n self._base = base_dir\n self._store: Store = store or FSStore()\n\n def write(self, rel_path: str, items: list[Item]) -> Path:\n dst = (self._base / rel_path).resolve()\n base = self._base.resolve()\n if dst != base and base not in dst.parents:\n raise ValueError(\"unsafe path traversal\")\n payload = json.dumps([item.__dict__ for item in items], ensure_ascii=False)\n self._store.write_text(dst, payload)\n return dst\n```\n\n```python\nimport json\nfrom pathlib import Path\nimport pytest\nfrom module_under_test import InventoryWriter, parse_items\n\ndef test_parse_items_valid():\n lines = [json.dumps({\"name\":\"x\",\"qty\":1})]\n assert parse_items(lines)[0].name == \"x\"\n\ndef test_writer_blocks_traversal(tmp_path: Path):\n w = InventoryWriter(tmp_path)\n with pytest.raises(ValueError):\n w.write(\"../evil.json\", [])\n```", "source": "WithinUsAI/python_GOD_coder_100k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Optimize while preserving behavior.\n\nFile: vtxqic_.py\n```python\ndef q0ro2jdad(xs):\n out = []\n for x in xs:\n if x not in out:\n out.append(x)\n return out\n```\n\nRequirements: preserve first-seen order; O(n) average; add types + docstring.\n\n# vtxqic_.py\nfrom __future__ import annotations\nfrom typing import Iterable, List, Set, TypeVar\n\nT = TypeVar(\"T\")\n\ndef q0ro2jdad(xs: Iterable[T]) -> List[T]:\n \"\"\"Return unique items preserving first-seen order.\"\"\"\n seen: Set[T] = set()\n out: List[T] = []\n for x in xs:\n if x in seen:\n continue\n seen.add(x)\n out.append(x)\n return out", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Produce an offline-first self-evolving code assistant architecture named `vdzi351yed`.\nMust include: module layout, patch-safety policy, evaluation gates (tests/lint/types), versioned memory index.\n\nArchitecture: `vdzi351yed` (offline-first, self-evolving)\n\nModules\n- core/loop.py: evolve → validate → accept/reject (bounded iterations)\n- patching/: diff builder, safe apply, atomic writes, rollback points\n- policy/: allowlist paths, deny globs (.git/, __pycache__/, binaries), patch size caps\n- signals/: parse pytest/ruff/mypy into normalized findings\n- memory/index.jsonl: append-only snapshots (hashes, metrics, rationale)\n\nSafety gates\n- refuse path traversal/symlink escapes; never edit binaries\n- accept only if tests/lint/types stay green or improve", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Refactor to modern typed Python with immutability and tests.\n\nFile: v3p41ud2jw6.py\n```python\nclass Of58Q:\n def __init__(self, name, values):\n self.name = name\n self.values = list(values)\n def add(self, v):\n self.values.append(v)\n def mean(self):\n s = 0\n for x in self.values:\n s += x\n return s / len(self.values)\n```\n\nReturn full new v3p41ud2jw6.py and test_v3p41ud2jw6.py.\n\n# v3p41ud2jw6.py\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom typing import Iterable, Tuple\n\n@dataclass(frozen=True)\nclass Of58Q:\n name: str\n values: Tuple[float, ...]\n\n @staticmethod\n def create(name: str, values: Iterable[float]) -> \"Of58Q\":\n vals = tuple(float(v) for v in values)\n if not vals:\n raise ValueError(\"values must be non-empty\")\n return Of58Q(name=name, values=vals)\n\n def add(self, v: float) -> \"Of58Q\":\n return Of58Q(name=self.name, values=self.values + (float(v),))\n\n def mean(self) -> float:\n return sum(self.values) / len(self.values)\n\n# test_v3p41ud2jw6.py\nimport pytest\nfrom v3p41ud2jw6 import Of58Q\n\ndef test_mean_and_add():\n c = Of58Q.create(\"a\", [1, 2, 3])\n assert c.mean() == 2.0\n assert c.add(5).mean() == (1 + 2 + 3 + 5) / 4\n\ndef test_empty_raises():\n with pytest.raises(ValueError):\n Of58Q.create(\"x\", [])", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Write a thorough test suite for a Python component used for task scheduling.\nRequirements: cover edge cases, invalid inputs, and behavior invariants.\nConstraints: must include docstrings, must include type hints, must handle Windows paths safely, stdlib-only.\nDifficulty: expert. Avoid quadratic behavior on large inputs.\n\nDeliverable: API + reference implementation + tests.\n```python\n# tests (pytest-style) for a module providing: normalize(), parse_lines(), compute_stats()\nimport math\nimport pytest\n\ndef test_normalize_idempotent(module_under_test):\n x = \" A\\tB \"\n assert module_under_test.normalize(module_under_test.normalize(x)) == module_under_test.normalize(x)\n\ndef test_parse_lines_rejects_invalid(module_under_test):\n with pytest.raises(ValueError):\n module_under_test.parse_lines([\"\", \"???\", None]) # type: ignore[arg-type]\n\ndef test_compute_stats_basic(module_under_test):\n data = [1, 2, 3, 4]\n s = module_under_test.compute_stats(data)\n assert s.count == 4\n assert s.total == 10\n assert math.isclose(s.mean, 2.5)\n```", "source": "WithinUsAI/python_GOD_coder_100k"} {"text": "Task type: network_protocol\nScenario: identity and access\nDomain focus: GPU serving\nPrimary language: python\nDifficulty: expert\nScale/SLO: 1M msgs/min\nComponent: component_pfzkwthw\nConstraints: include verification strategy, include failure modes and recovery, include deterministic replay plan, avoid data races and undefined behavior, include performance model and limits\nAssume crash-only processes; recovery must be deterministic.\nDeliverable: Design an application protocol: framing, retries, backpressure, timeouts; include client/server skeleton and test vectors.\n\nOutput: contract-first solution with failure modes, security posture, and test/verification strategy.\n**Contract**\n- Inputs validated at the boundary; explicit error taxonomy.\n- Idempotency for side effects via request_id; deterministic replay.\n- Backward compatibility: additive changes by default; versioned breaking changes.\n**Invariants**\n- Determinism: replay of the same event log yields identical outputs.\n- Isolation: tenant boundary enforced; no cross-tenant reads/writes.\n- Liveness: under bounded faults and stable network, progress occurs.\n**Failure modes & recovery**\n- Data corruption: checksums + scrubber; quarantine and rebuild from replicas/snapshots.\n- Duplicate requests: de-duplicate by (tenant, request_id) returning cached response.\n- Network partition: minority cannot commit; clients receive retriable errors.\n**Security posture (defensive)**\n- Threat model: auth/authz, injection, replay/abuse, supply chain.\n- Least privilege; secrets in managed store; audit logs for sensitive ops.\n- Input normalization, parameterized queries, path traversal protections.\n**Verification strategy**\n- Canary + shadow traffic; invariants checked in production via assertions/metrics.\n- Fuzzing of parsers/framers/validators with corpus seeds.\n- Deterministic simulation with fault injection (crash/partition/latency).\n\n**Snippet**\n```text\nImplementation sketch: factor pure state-machine core; adapters for I/O; add deterministic replay log.\n```\nExpert checks: state-machine proof sketch + model checking; upgrade/rollback rehearsed.", "source": "WithinUsAI/Omega_Genesis_Coder_100k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Produce an offline-first self-evolving code assistant architecture named `x1ej41xn`.\nMust include: module layout, patch-safety policy, evaluation gates (tests/lint/types), versioned memory index.\n\nArchitecture: `x1ej41xn` (offline-first, self-evolving)\n\nModules\n- core/loop.py: evolve → validate → accept/reject (bounded iterations)\n- patching/: diff builder, safe apply, atomic writes, rollback points\n- policy/: allowlist paths, deny globs (.git/, __pycache__/, binaries), patch size caps\n- signals/: parse pytest/ruff/mypy into normalized findings\n- memory/index.jsonl: append-only snapshots (hashes, metrics, rationale)\n\nSafety gates\n- refuse path traversal/symlink escapes; never edit binaries\n- accept only if tests/lint/types stay green or improve", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Build an elite-grade solution in the domain of high-performance services for scenario: document indexing.\nPrimary language: bash.\nDifficulty: medium.\nConstraints: design for backward compatibility and migrations, make the interface contract explicit, include tests or verification strategy, document performance characteristics, assume untrusted inputs; validate and sanitize.\nComponent: component_hgfondb.\nAssume strict auditability and replayable history.\nTask: Provide threat model, secure-by-default design, and defensive implementation patterns. No offensive/exploit content; focus on prevention and detection.\n\nOutput: rigorous solution with invariants, failure modes, and performance notes.\nOutput: threat model + defensive design + detection.\n\n**Threat model**\n- Auth: token theft → short-lived tokens, rotation, audience checks\n- AuthZ: privilege escalation → centralized policy checks, tenant isolation tests\n- Input: injection → strict validation, parameterized queries, output encoding\n- Supply chain: dependencies → lockfiles, signature verification, SBOM\n\n**Defensive patterns**\n- Idempotency keys for side effects; replay-safe handlers\n- Secrets in managed store; never logs\n- Audit logging for sensitive ops; tamper-evident storage\n\n**Detection**\n- Alert on unusual auth failures, access pattern anomalies, and data exfil signals.\n\n\nChecks: boundary validation and deterministic behavior verified.", "source": "WithinUsAI/Elite_GOD_Coder_100k"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: Language: Go\nFramework/tooling: sqlc\nDomain: repo automation\nLogic challenge: transaction boundary bug\nTask type: edge_case_hardening\nDifficulty: hard\n\nReturn a rigorous engineering answer:\n- identify the hidden root cause or logical failure\n- present the corrected implementation\n- add tests that prove the fix\n- list verification commands\n- explain why naive fixes are insufficient when relevant\n\nRepository sketch:\nrepo/\n cmd/server/main.go\n internal/service/service.go\n internal/store/store.go\n internal/api/api.go\n service_test.go\n go.mod\n\nFocus: Focus on strong structured logic with edge cases, data validation, and concurrency safety.\n\nassistant: Diagnosis:\n- Root cause: the failure around transaction boundary bug is caused by missing validation, weak edge-case handling, or unsafe lifecycle behavior in the current implementation.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```go\npackage service\n\nimport \"fmt\"\n\nfunc NormalizePayload(payload map[string]any) map[string]any {\n\tout := make(map[string]any)\n\tfor k, v := range payload {\n\t\tif v == nil {\n\t\t\tcontinue\n\t\t}\n\t\tout[k] = v\n\t}\n\treturn out\n}\n\nfunc Handle(payload map[string]any) (map[string]any, error) {\n\tclean := NormalizePayload(payload)\n\tif _, ok := clean[\"id\"]; !ok {\n\t\treturn nil, fmt.Errorf(\"missing id\")\n\t}\n\treturn map[string]any{\"ok\": true, \"data\": clean}, nil\n}\n```\n\nTests:\n```go\npackage service\n\nimport \"testing\"\n\nfunc TestHandle(t *testing.T) {\n\tgot, err := Handle(map[string]any{\"id\": 7, \"name\": \"ok\", \"unused\": nil})\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tif got[\"ok\"] != true {\n\t\tt.Fatalf(\"expected ok=true\")\n\t}\n\tif _, err := Handle(map[string]any{\"name\": \"x\"}); err == nil {\n\t\tt.Fatalf(\"expected missing id error\")\n\t}\n}\n```\n\nVerification:\n- `go test ./...`\n- `go vet ./...`\n\nEngineering notes:\n- Language: Go\n- Framework/tooling: sqlc\n- Stack context: ASP.NET Core, SQL Server, EF Core, xUnit, Docker\n- Domain: repo automation\n- Task type: edge_case_hardening\n- Difficulty: hard\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Produce an offline-first self-evolving code assistant architecture named `zjl6hnpxv58j`.\nMust include: module layout, patch-safety policy, evaluation gates (tests/lint/types), versioned memory index.\n\nArchitecture: `zjl6hnpxv58j` (offline-first, self-evolving)\n\nModules\n- core/loop.py: evolve → validate → accept/reject (bounded iterations)\n- patching/: diff builder, safe apply, atomic writes, rollback points\n- policy/: allowlist paths, deny globs (.git/, __pycache__/, binaries), patch size caps\n- signals/: parse pytest/ruff/mypy into normalized findings\n- memory/index.jsonl: append-only snapshots (hashes, metrics, rationale)\n\nSafety gates\n- refuse path traversal/symlink escapes; never edit binaries\n- accept only if tests/lint/types stay green or improve", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Fix a bug and add tests.\n\nFile: jf8x2tjfz_h.py\n```python\ndef rac1droa3y(n: int) -> int:\n \"\"\"Sum 1..n inclusive.\"\"\"\n if n < 0:\n raise ValueError(\"n must be non-negative\")\n total = 0\n for k in range(n): # BUG: should include n\n total += k\n return total\n```\n\nReturn unified diffs for jf8x2tjfz_h.py and test_jf8x2tjfz_h.py (pytest).\n\n*** Begin Patch\n*** Update File: jf8x2tjfz_h.py\n@@\n def rac1droa3y(n: int) -> int:\n@@\n total = 0\n- for k in range(n): # BUG: should include n\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_jf8x2tjfz_h.py\n+import pytest\n+from jf8x2tjfz_h import rac1droa3y\n+\n+def test_zero():\n+ assert rac1droa3y(0) == 0\n+\n+def test_one():\n+ assert rac1droa3y(1) == 1\n+\n+def test_small():\n+ assert rac1droa3y(7) == 28\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ rac1droa3y(-1)\n+\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Fix a bug and add tests.\n\nFile: hx2qgqihgo.py\n```python\ndef ns0blwmodv6(n: int) -> int:\n \"\"\"Sum 1..n inclusive.\"\"\"\n if n < 0:\n raise ValueError(\"n must be non-negative\")\n total = 0\n for k in range(n): # BUG: should include n\n total += k\n return total\n```\n\nReturn unified diffs for hx2qgqihgo.py and test_hx2qgqihgo.py (pytest).\n\n*** Begin Patch\n*** Update File: hx2qgqihgo.py\n@@\n def ns0blwmodv6(n: int) -> int:\n@@\n total = 0\n- for k in range(n): # BUG: should include n\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_hx2qgqihgo.py\n+import pytest\n+from hx2qgqihgo import ns0blwmodv6\n+\n+def test_zero():\n+ assert ns0blwmodv6(0) == 0\n+\n+def test_one():\n+ assert ns0blwmodv6(1) == 1\n+\n+def test_small():\n+ assert ns0blwmodv6(7) == 28\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ ns0blwmodv6(-1)\n+\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Fix the bug and add pytest tests.\n\n```python\ndef f86023(n: int) -> int:\n # sum 1..n inclusive\n if n < 0: raise ValueError\n total = 0\n for k in range(n): # BUG\n total += k\n return total\n```\nReturn unified diffs for `m12289.py` and `test_m12289.py`.\n\n*** Begin Patch\n*** Update File: m12289.py\n@@\n def f86023(n: int) -> int:\n@@\n- for k in range(n): # BUG\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_m12289.py\n+import pytest\n+from m12289 import f86023\n+\n+def test_small():\n+ assert f86023(7) == 28\n+\n+def test_zero():\n+ assert f86023(0) == 0\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ f86023(-1)\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Task type: static_analyzer\nScenario: payment ledger\nDomain focus: high-frequency trading systems (safe engineering)\nPrimary language: go\nDifficulty: hard\nScale/SLO: 99.99% availability\nComponent: component_bafbwczu\nConstraints: include backward compatibility and migration plan, avoid data races and undefined behavior, include deterministic replay plan, include test vectors and fuzz strategy, assume adversarial inputs; validate everything, include performance model and limits\nAssume weekly network partitions.\nDeliverable: Design a static analyzer for a safety property (e.g., taint/SQLi prevention); include rule set, false-positive strategy, and tests.\n\nOutput: elite engineering answer optimized for correctness, performance, and operability.\n**Contract**\n- Inputs validated at the boundary; explicit error taxonomy.\n- Idempotency for side effects via request_id; deterministic replay.\n- Backward compatibility: additive changes by default; versioned breaking changes.\n**Invariants**\n- Safety: state transitions preserve invariants; no partial commit leaks.\n- Liveness: under bounded faults and stable network, progress occurs.\n- Determinism: replay of the same event log yields identical outputs.\n**Failure modes & recovery**\n- Data corruption: checksums + scrubber; quarantine and rebuild from replicas/snapshots.\n- Crash during commit: WAL replay completes or transaction aborts; no torn writes.\n- Network partition: minority cannot commit; clients receive retriable errors.\n**Security posture (defensive)**\n- Threat model: auth/authz, injection, replay/abuse, supply chain.\n- Least privilege; secrets in managed store; audit logs for sensitive ops.\n- Input normalization, parameterized queries, path traversal protections.\n**Verification strategy**\n- Canary + shadow traffic; invariants checked in production via assertions/metrics.\n- Property tests against a pure reference model (state machine).\n- Deterministic simulation with fault injection (crash/partition/latency).\n\n**Snippet**\n```text\nImplementation sketch: factor pure state-machine core; adapters for I/O; add deterministic replay log.\n```\nHard checks: fault injection tests gate merges; perf thresholds enforced in CI.", "source": "WithinUsAI/Omega_Genesis_Coder_100k"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: Project stack: Airflow, dbt, DuckDB, MinIO, pytest\nLanguage: Java\nDependency challenge: invalid rollback sequence\nTask type: build_reproducibility_fix\nDifficulty: hard\n\nFix this as a senior engineer.\nRequired:\n- identify the version or compatibility failure mode\n- produce the corrected config/code/build patch\n- explain rollback-safe migration notes\n- add regression tests or reproducibility checks\n- include concrete verification commands\n\nRepository sketch:\nrepo/\n src/main/java/com/acme/App.java\n src/main/java/com/acme/Service.java\n src/test/java/com/acme/AppTest.java\n pom.xml\n\nFocus: Focus on versioning, migrations, lockfiles, runtime compatibility, and secure dependency handling.\n\nassistant: Diagnosis:\n- Root cause: the issue around invalid rollback sequence is a dependency, migration, or runtime-compatibility mismatch that needs a rollback-safe patch.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```java\nimport java.util.HashMap;\nimport java.util.Map;\n\npublic final class RequestHandler {\n public static Map handleRequest(Map payload) {\n Map clean = new HashMap<>();\n for (Map.Entry entry : payload.entrySet()) {\n if (entry.getValue() != null) clean.put(entry.getKey().trim(), entry.getValue());\n }\n if (!clean.containsKey(\"id\")) throw new IllegalArgumentException(\"missing id\");\n return Map.of(\"ok\", true, \"data\", clean);\n }\n}\n```\n\nTests:\n```java\nimport static org.junit.jupiter.api.Assertions.*;\nimport java.util.Map;\nimport org.junit.jupiter.api.Test;\n\nclass RequestHandlerTest {\n @Test\n void requiresId() {\n assertThrows(IllegalArgumentException.class, () -> RequestHandler.handleRequest(Map.of(\"name\", \"x\")));\n }\n}\n```\n\nVerification:\n- `./gradlew test`\n- `mvn test`\n\nEngineering notes:\n- Language: Java\n- Framework/tooling: JUnit\n- Stack context: Airflow, dbt, DuckDB, MinIO, pytest\n- Domain: document processing API\n- Task type: build_reproducibility_fix\n- Difficulty: hard\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "Write a thorough test suite for a Python component used for metrics aggregation.\nRequirements: cover edge cases, invalid inputs, and behavior invariants.\nConstraints: must include tests, stdlib-only, must avoid global state.\nDifficulty: easy. Include a small CLI example if relevant.\n\nDeliverable: production-ready reference solution.\n```python\n# tests (pytest-style) for a module providing: normalize(), parse_lines(), compute_stats()\nimport math\nimport pytest\n\ndef test_normalize_idempotent(module_under_test):\n x = \" A\\tB \"\n assert module_under_test.normalize(module_under_test.normalize(x)) == module_under_test.normalize(x)\n\ndef test_parse_lines_rejects_invalid(module_under_test):\n with pytest.raises(ValueError):\n module_under_test.parse_lines([\"\", \"???\", None]) # type: ignore[arg-type]\n\ndef test_compute_stats_basic(module_under_test):\n data = [1, 2, 3, 4]\n s = module_under_test.compute_stats(data)\n assert s.count == 4\n assert s.total == 10\n assert math.isclose(s.mean, 2.5)\n```", "source": "WithinUsAI/python_GOD_coder_100k"} {"text": "Provision infrastructure for a enterprise SaaS workload providing audit logs.\nTarget platform: backend (Node.js).\nRequirements: IaC (Terraform or Kubernetes YAML), networking, secrets, autoscaling.\nConstraints: must be production-ready, must include documentation/comments, must include tests, must include clear error handling.\nDifficulty: easy. Assume strict latency budget (p95 < 200ms).\n\nOutput: engineering-grade answer with edge cases covered.\nDeliverable: Kubernetes deployment + basic security posture.\n\n```yaml\napiVersion: apps/v1\nkind: Deployment\nmetadata:\n name: app\nspec:\n replicas: 3\n selector:\n matchLabels: { app: app }\n template:\n metadata:\n labels: { app: app }\n spec:\n containers:\n - name: app\n image: app:latest\n ports: [{ containerPort: 8080 }]\n readinessProbe:\n httpGet: { path: /healthz, port: 8080 }\n resources:\n requests: { cpu: \"200m\", memory: \"256Mi\" }\n limits: { cpu: \"1\", memory: \"1Gi\" }\n```\n\nAdditions:\n- NetworkPolicy to restrict egress/ingress.\n- Secrets via external secret store; rotate regularly.\n- HPA for autoscaling; PodDisruptionBudget for availability.\n\n\nChecks: input validation, tests, and safe defaults included.", "source": "WithinUsAI/GOD_Coder_100k"} {"text": "Add a clear docstring and type hints to this function:\n\n```python\ndef f63273(s):\n return ''.join(x for x in s if x.isalnum()).lower()\n```\n\n```python\nfrom __future__ import annotations\n\ndef f63273(s: str) -> str:\n \"\"\"Normalize a string: keep only alphanumerics and lowercase the result.\"\"\"\n return \"\".join(ch for ch in s if ch.isalnum()).lower()\n```", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Secure-by-default implementation for rate limiting in a IoT telemetry product.\nTarget platform: infra (Docker + Kubernetes).\nRequirements: threat model, input validation, authz/authn guidance, safe storage, tests.\nConstraints: must be easy to extend, must include tests, must avoid global state, must be performant under load, must include type hints where applicable.\nDifficulty: expert. Include rollback strategy.\n\nOutput: production-oriented blueprint with code where appropriate.\nDeliverable: threat model + secure patterns (no offensive content).\n\n**Threat model**\n- Input: untrusted clients → validation required\n- Auth: token theft / privilege escalation → short-lived tokens + RBAC checks\n- Data: PII exposure → encryption at rest + access logging + least privilege\n- Webhooks/callbacks: SSRF → allowlist destinations + timeouts + egress controls\n\n**Secure implementation patterns**\n- Validate and normalize inputs at boundaries (API/CLI/file).\n- Use parameterized SQL; never string interpolate.\n- Prevent path traversal when writing files (resolve + base containment).\n- Use idempotency keys for side-effecting endpoints; safe retries.\n- Centralize authorization checks in one layer; test them.\n\n**Test checklist**\n- Invalid inputs rejected with clear error messages.\n- AuthZ tests for tenant boundary violations.\n- Replay/idempotency conflict test.\n\n\nHard-mode checks: concurrency safety, idempotency, and rollback validated; add chaos tests where feasible.", "source": "WithinUsAI/GOD_Coder_100k"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: Language: Python\nFramework/tooling: Celery\nDomain: document processing API\nLogic challenge: monorepo toolchain skew\nTask type: parser_validation_logic\nDifficulty: hard\n\nReturn a rigorous engineering answer:\n- identify the hidden root cause or logical failure\n- present the corrected implementation\n- add tests that prove the fix\n- list verification commands\n- explain why naive fixes are insufficient when relevant\n\nRepository sketch:\nrepo/\n app/\n api.py\n service.py\n models.py\n tests/\n test_api.py\n pyproject.toml\n\nFocus: Focus on strong structured logic with edge cases, data validation, and concurrency safety.\n\nassistant: Diagnosis:\n- Root cause: the failure around monorepo toolchain skew is caused by missing validation, weak edge-case handling, or unsafe lifecycle behavior in the current implementation.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```python\nfrom __future__ import annotations\n\nfrom dataclasses import dataclass\nfrom typing import Any\n\n@dataclass\nclass ServiceResult:\n ok: bool\n data: dict[str, Any]\n error: str | None = None\n\ndef normalize_payload(payload: dict[str, Any]) -> dict[str, Any]:\n if not isinstance(payload, dict):\n raise TypeError(\"payload must be a dict\")\n clean: dict[str, Any] = {}\n for key, value in payload.items():\n if value is None:\n continue\n clean[str(key).strip()] = value\n return clean\n\ndef handle_monorepo_toolchain_skew(payload: dict[str, Any]) -> ServiceResult:\n clean = normalize_payload(payload)\n if \"id\" not in clean:\n return ServiceResult(ok=False, data={}, error=\"missing id\")\n return ServiceResult(ok=True, data=clean)\n```\n\nTests:\n```python\nimport pytest\nfrom app.service import handle_jwt_refresh_token_rotation as handler\n\ndef test_handler_accepts_valid_payload():\n result = handler({\"id\": 7, \"name\": \"ok\", \"unused\": None})\n assert result.ok is True\n assert result.data == {\"id\": 7, \"name\": \"ok\"}\n\ndef test_handler_rejects_missing_id():\n result = handler({\"name\": \"x\"})\n assert result.ok is False\n assert result.error == \"missing id\"\n```\n\nVerification:\n- `pytest -q`\n- `ruff check .`\n- `python -m compileall .`\n\nEngineering notes:\n- Language: Python\n- Framework/tooling: Celery\n- Stack context: GitHub Actions, Docker Compose, Kubernetes, Terraform\n- Domain: document processing API\n- Task type: parser_validation_logic\n- Difficulty: hard\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Fix a bug and add tests.\n\nFile: h2flvxj.py\n```python\ndef po_jfljp(n: int) -> int:\n \"\"\"Sum 1..n inclusive.\"\"\"\n if n < 0:\n raise ValueError(\"n must be non-negative\")\n total = 0\n for k in range(n): # BUG: should include n\n total += k\n return total\n```\n\nReturn unified diffs for h2flvxj.py and test_h2flvxj.py (pytest).\n\n*** Begin Patch\n*** Update File: h2flvxj.py\n@@\n def po_jfljp(n: int) -> int:\n@@\n total = 0\n- for k in range(n): # BUG: should include n\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_h2flvxj.py\n+import pytest\n+from h2flvxj import po_jfljp\n+\n+def test_zero():\n+ assert po_jfljp(0) == 0\n+\n+def test_one():\n+ assert po_jfljp(1) == 1\n+\n+def test_small():\n+ assert po_jfljp(7) == 28\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ po_jfljp(-1)\n+\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Task type: secure_architecture\nScenario: identity and access\nDomain focus: data lineage & governance\nPrimary language: go\nDifficulty: hard\nScale/SLO: 99.99% availability\nComponent: component_xlxisjdr\nConstraints: include verification strategy, include backward compatibility and migration plan, include test vectors and fuzz strategy, include performance model and limits, include failure modes and recovery\nAssume tight memory budget and cold-start constraints.\nDeliverable: Provide a defensive threat model and secure-by-default architecture; include monitoring/detection and tests (no offensive content).\n\nOutput: elite engineering answer optimized for correctness, performance, and operability.\n**Contract**\n- Inputs validated at the boundary; explicit error taxonomy.\n- Idempotency for side effects via request_id; deterministic replay.\n- Backward compatibility: additive changes by default; versioned breaking changes.\n**Invariants**\n- Liveness: under bounded faults and stable network, progress occurs.\n- Isolation: tenant boundary enforced; no cross-tenant reads/writes.\n- Determinism: replay of the same event log yields identical outputs.\n**Failure modes & recovery**\n- Duplicate requests: de-duplicate by (tenant, request_id) returning cached response.\n- Network partition: minority cannot commit; clients receive retriable errors.\n- Crash during commit: WAL replay completes or transaction aborts; no torn writes.\n**Security posture (defensive)**\n- Threat model: auth/authz, injection, replay/abuse, supply chain.\n- Least privilege; secrets in managed store; audit logs for sensitive ops.\n- Input normalization, parameterized queries, path traversal protections.\n**Verification strategy**\n- Fuzzing of parsers/framers/validators with corpus seeds.\n- Property tests against a pure reference model (state machine).\n- Canary + shadow traffic; invariants checked in production via assertions/metrics.\n\n**Snippet**\n```text\nImplementation sketch: factor pure state-machine core; adapters for I/O; add deterministic replay log.\n```\nHard checks: fault injection tests gate merges; perf thresholds enforced in CI.", "source": "WithinUsAI/Omega_Genesis_Coder_100k"} {"text": "Build an elite-grade solution in the domain of databases for scenario: document indexing.\nPrimary language: sql.\nDifficulty: expert.\nConstraints: include tests or verification strategy, design for backward compatibility and migrations, assume untrusted inputs; validate and sanitize, document performance characteristics.\nComponent: component_syqgvil.\nAssume 50k RPS and p99 < 250ms.\nTask: Implement or outline a storage/indexing subsystem (LSM/B-Tree, WAL, snapshots). Include transaction/consistency considerations and benchmark plan.\n\nOutput: rigorous solution with invariants, failure modes, and performance notes.\nOutput: storage design + WAL + compaction + benchmarks.\n\n**Design**\n- WAL (append-only) for durability; fsync policy configurable.\n- Memtable (in-memory) → flush to immutable SSTables.\n- LSM compaction tiers; bloom filters per SSTable for point-lookups.\n- Manifest tracks SSTable set; atomic pointer swap on updates.\n\n**Correctness**\n- Crash recovery: replay WAL to rebuild memtable; manifest ensures last consistent set.\n- Reads: merge memtable + SSTables newest→oldest; tombstones override older values.\n\n**Bench plan**\n- Workloads: write-heavy, read-heavy, mixed; measure p50/p95 latency and write amplification.\n- Track compaction debt and space amplification.\n\n**Test plan**\n- Fuzz crash points: kill after WAL append / after manifest update; verify invariants on restart.\n\n\nExpert checks: state-machine reasoning, concurrency stress, and upgrade/rollback validated.", "source": "WithinUsAI/Elite_GOD_Coder_100k"} {"text": "Build an elite-grade solution in the domain of edge/IoT for scenario: document indexing.\nPrimary language: go.\nDifficulty: expert.\nConstraints: include tests or verification strategy, make the interface contract explicit, assume untrusted inputs; validate and sanitize.\nComponent: component_wltpzrh.\nAssume strict auditability and replayable history.\nTask: Design a replication/consistency approach (e.g., leader-based, quorum reads/writes). Provide message flows, failure handling, and a minimal reference implementation skeleton.\n\nOutput: production blueprint plus correctness arguments and test strategy.\nOutput: replication design + failure handling + minimal skeleton.\n\n**Model**\n- Leader-based replication with term + log index.\n- Quorum acks for durability: write committed when majority acks.\n- Read options: leader-read (linearizable) or quorum-read (monotonic if using read-index).\n\n**Message flow (write)**\n1. Client → Leader: Put(request_id, payload)\n2. Leader appends to log, sends AppendEntries to followers\n3. Followers append + ack\n4. On majority ack: commit index advances; apply to state machine; respond to client\n\n**Failure modes**\n- Leader crash: new election; uncommitted entries may be rolled back.\n- Partition: minority side cannot commit.\n- Duplicate requests: deduplicate by request_id stored in state.\n\n**Skeleton (Go pseudo)**\n```go\ntype Entry struct { Term uint64; Index uint64; Cmd []byte }\ntype Node struct {\n id int\n term uint64\n log []Entry\n commit uint64\n seen map[string][]byte // request_id -> response\n}\n```\n\n**Verification**\n- Invariant: committed index never decreases.\n- Property: if a write is committed, all future leaders contain it.\n- Test with simulated partitions and crash/restart.\n\n\nExpert checks: state-machine reasoning, concurrency stress, and upgrade/rollback validated.", "source": "WithinUsAI/Elite_GOD_Coder_100k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Optimize while preserving behavior.\n\nFile: rtrrdtr_4.py\n```python\ndef g1am3h8g(xs):\n out = []\n for x in xs:\n if x not in out:\n out.append(x)\n return out\n```\n\nRequirements: preserve first-seen order; O(n) average; add types + docstring.\n\n# rtrrdtr_4.py\nfrom __future__ import annotations\nfrom typing import Iterable, List, Set, TypeVar\n\nT = TypeVar(\"T\")\n\ndef g1am3h8g(xs: Iterable[T]) -> List[T]:\n \"\"\"Return unique items preserving first-seen order.\"\"\"\n seen: Set[T] = set()\n out: List[T] = []\n for x in xs:\n if x in seen:\n continue\n seen.add(x)\n out.append(x)\n return out", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Build an elite-grade solution in the domain of databases for scenario: job scheduler.\nPrimary language: go.\nDifficulty: medium.\nConstraints: provide rollout and rollback guidance, include tests or verification strategy, design for backward compatibility and migrations, make the interface contract explicit, document performance characteristics.\nComponent: component_uouydgz.\nAssume compliance requires data deletion with proofs.\nTask: Implement or outline a storage/indexing subsystem (LSM/B-Tree, WAL, snapshots). Include transaction/consistency considerations and benchmark plan.\n\nOutput: production blueprint plus correctness arguments and test strategy.\nOutput: storage design + WAL + compaction + benchmarks.\n\n**Design**\n- WAL (append-only) for durability; fsync policy configurable.\n- Memtable (in-memory) → flush to immutable SSTables.\n- LSM compaction tiers; bloom filters per SSTable for point-lookups.\n- Manifest tracks SSTable set; atomic pointer swap on updates.\n\n**Correctness**\n- Crash recovery: replay WAL to rebuild memtable; manifest ensures last consistent set.\n- Reads: merge memtable + SSTables newest→oldest; tombstones override older values.\n\n**Bench plan**\n- Workloads: write-heavy, read-heavy, mixed; measure p50/p95 latency and write amplification.\n- Track compaction debt and space amplification.\n\n**Test plan**\n- Fuzz crash points: kill after WAL append / after manifest update; verify invariants on restart.\n\n\nChecks: boundary validation and deterministic behavior verified.", "source": "WithinUsAI/Elite_GOD_Coder_100k"} {"text": "Task type: distributed_algorithm\nScenario: document indexing pipeline\nDomain focus: kernel primitives\nPrimary language: python\nDifficulty: expert+\nScale/SLO: 100k RPS peak\nComponent: component_qjklmfbm\nConstraints: include backward compatibility and migration plan, explicit contracts and invariants, include test vectors and fuzz strategy, include deterministic replay plan, include security threat model (defensive only), avoid data races and undefined behavior\nAssume crash-only processes; recovery must be deterministic.\nDeliverable: Design an algorithm with message flows and correctness arguments (safety + liveness). Include failure handling and a minimal reference implementation skeleton.\n\nOutput: contract-first solution with failure modes, security posture, and test/verification strategy.\n**Contract**\n- Inputs validated at the boundary; explicit error taxonomy.\n- Idempotency for side effects via request_id; deterministic replay.\n- Backward compatibility: additive changes by default; versioned breaking changes.\n**Invariants**\n- Isolation: tenant boundary enforced; no cross-tenant reads/writes.\n- Determinism: replay of the same event log yields identical outputs.\n- Safety: state transitions preserve invariants; no partial commit leaks.\n**Failure modes & recovery**\n- Data corruption: checksums + scrubber; quarantine and rebuild from replicas/snapshots.\n- Crash during commit: WAL replay completes or transaction aborts; no torn writes.\n- Network partition: minority cannot commit; clients receive retriable errors.\n**Security posture (defensive)**\n- Threat model: auth/authz, injection, replay/abuse, supply chain.\n- Least privilege; secrets in managed store; audit logs for sensitive ops.\n- Input normalization, parameterized queries, path traversal protections.\n**Verification strategy**\n- Fuzzing of parsers/framers/validators with corpus seeds.\n- Property tests against a pure reference model (state machine).\n- Canary + shadow traffic; invariants checked in production via assertions/metrics.\n\n**Snippet**\n```text\nImplementation sketch: factor pure state-machine core; adapters for I/O; add deterministic replay log.\n```\nExpert+ checks: mechanized invariants (or exhaustive model checking), adversarial fuzzing, and multi-region failure drills.", "source": "WithinUsAI/Omega_Genesis_Coder_100k"} {"text": "Add a clear docstring and type hints to this function:\n\n```python\ndef f52853(s):\n return ''.join(x for x in s if x.isalnum()).lower()\n```\n\n```python\nfrom __future__ import annotations\n\ndef f52853(s: str) -> str:\n \"\"\"Normalize a string: keep only alphanumerics and lowercase the result.\"\"\"\n return \"\".join(ch for ch in s if ch.isalnum()).lower()\n```", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Create a comprehensive test plan and automated tests for A/B experimentation in a calendar/scheduling product.\nTarget platform: data (SQL + Python).\nRequirements: unit/integration tests, edge cases, load tests strategy, and CI gates.\nConstraints: must include type hints where applicable, must be secure-by-default, must include clear error handling, must be performant under load.\nDifficulty: medium. Assume untrusted input; validate everything.\n\nOutput: actionable implementation and verification artifacts.\nDeliverable: test plan + automation guidance.\n\n**Unit tests**\n- Validation: malformed payloads rejected with correct codes.\n- AuthZ: tenant boundary enforced.\n- Idempotency: replay returns same response; conflicting reuse yields 409.\n\n**Integration tests**\n- DB transaction behavior; unique constraints.\n- Cache behavior: correctness under concurrent requests.\n\n**Load tests**\n- 10k RPS target: measure p95 latency, error rate, saturation.\n\n**CI gates**\n- Lint + typecheck + unit tests required.\n- Coverage threshold for critical modules.\n- Block merge on flaky test detection.\n\n\nChecks: input validation, tests, and safe defaults included.", "source": "WithinUsAI/GOD_Coder_100k"} {"text": "Fix a subtle bug in a Python module used for time series.\nRequirements: explain root cause briefly, provide corrected code, and add regression tests.\nConstraints: must be streaming-friendly, must include type hints, stdlib-only.\nDifficulty: hard. Ensure the API is testable via dependency injection.\n\nDeliverable: corrected code and verification tests.\n```python\nfrom __future__ import annotations\n\nfrom dataclasses import dataclass\nfrom pathlib import Path\nfrom typing import Iterable\nimport json\n\n\nclass ValidationError(ValueError):\n \"\"\"Raised when input validation fails.\"\"\"\n\n\ndef safe_join(base: Path, *parts: str) -> Path:\n \"\"\"Join paths while preventing traversal outside base.\"\"\"\n b = base.resolve()\n p = (b / Path(*parts)).resolve()\n if p != b and b not in p.parents:\n raise ValidationError(f\"unsafe path: {p}\")\n return p\n\n\n@dataclass(frozen=True, slots=True)\nclass Record:\n key: str\n value: int\n\n\ndef parse_jsonl(lines: Iterable[str]) -> list[Record]:\n out: list[Record] = []\n for idx, line in enumerate(lines, 1):\n s = line.strip()\n if not s:\n continue\n try:\n obj = json.loads(s)\n except json.JSONDecodeError as e:\n raise ValidationError(f\"line {idx}: invalid json\") from e\n if not isinstance(obj, dict):\n raise ValidationError(f\"line {idx}: expected object\")\n key = obj.get(\"key\")\n val = obj.get(\"value\")\n if not isinstance(key, str) or not key:\n raise ValidationError(f\"line {idx}: key must be non-empty str\")\n if not isinstance(val, int):\n raise ValidationError(f\"line {idx}: value must be int\")\n out.append(Record(key, val))\n return out\n\n\ndef write_jsonl(base: Path, rel: str, records: Iterable[Record]) -> Path:\n base.mkdir(parents=True, exist_ok=True)\n dst = safe_join(base, rel)\n dst.parent.mkdir(parents=True, exist_ok=True)\n with dst.open(\"w\", encoding=\"utf-8\", newline=\"\\n\") as f:\n for r in records:\n f.write(json.dumps({\"key\": r.key, \"value\": r.value}, ensure_ascii=False) + \"\\n\")\n return dst\n```\n\n```python\n# tests (pytest-style)\nimport json\nfrom pathlib import Path\nimport pytest\nfrom module_under_test import ValidationError, Record, parse_jsonl, write_jsonl\n\ndef test_parse_ok():\n lines = [json.dumps({\"key\":\"a\",\"value\":1}), json.dumps({\"key\":\"b\",\"value\":2})]\n assert parse_jsonl(lines) == [Record(\"a\",1), Record(\"b\",2)]\n\ndef test_parse_rejects_bad_json():\n with pytest.raises(ValidationError):\n parse_jsonl([\"{not json}\"])\n\ndef test_safe_join_blocks_traversal(tmp_path: Path):\n with pytest.raises(ValidationError):\n write_jsonl(tmp_path, \"../x.jsonl\", [Record(\"a\",1)])\n```", "source": "WithinUsAI/python_GOD_coder_100k"} {"text": "Fix the bug and add pytest tests.\n\n```python\ndef f70658(n: int) -> int:\n # sum 1..n inclusive\n if n < 0: raise ValueError\n total = 0\n for k in range(n): # BUG\n total += k\n return total\n```\nReturn unified diffs for `m10094.py` and `test_m10094.py`.\n\n*** Begin Patch\n*** Update File: m10094.py\n@@\n def f70658(n: int) -> int:\n@@\n- for k in range(n): # BUG\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_m10094.py\n+import pytest\n+from m10094 import f70658\n+\n+def test_small():\n+ assert f70658(7) == 28\n+\n+def test_zero():\n+ assert f70658(0) == 0\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ f70658(-1)\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Fix the bug and add pytest tests.\n\n```python\ndef f67223(n: int) -> int:\n # sum 1..n inclusive\n if n < 0: raise ValueError\n total = 0\n for k in range(n): # BUG\n total += k\n return total\n```\nReturn unified diffs for `m23889.py` and `test_m23889.py`.\n\n*** Begin Patch\n*** Update File: m23889.py\n@@\n def f67223(n: int) -> int:\n@@\n- for k in range(n): # BUG\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_m23889.py\n+import pytest\n+from m23889 import f67223\n+\n+def test_small():\n+ assert f67223(7) == 28\n+\n+def test_zero():\n+ assert f67223(0) == 0\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ f67223(-1)\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Fix a subtle bug in a Python module used for file synchronization.\nRequirements: explain root cause briefly, provide corrected code, and add regression tests.\nConstraints: must be memory-efficient, must be easy to extend.\nDifficulty: expert. Avoid quadratic behavior on large inputs.\n\nDeliverable: corrected code and verification tests.\n```python\nfrom __future__ import annotations\n\nfrom dataclasses import dataclass\nfrom pathlib import Path\nfrom typing import Iterable\nimport json\n\n\nclass ValidationError(ValueError):\n \"\"\"Raised when input validation fails.\"\"\"\n\n\ndef safe_join(base: Path, *parts: str) -> Path:\n \"\"\"Join paths while preventing traversal outside base.\"\"\"\n b = base.resolve()\n p = (b / Path(*parts)).resolve()\n if p != b and b not in p.parents:\n raise ValidationError(f\"unsafe path: {p}\")\n return p\n\n\n@dataclass(frozen=True, slots=True)\nclass Record:\n key: str\n value: int\n\n\ndef parse_jsonl(lines: Iterable[str]) -> list[Record]:\n out: list[Record] = []\n for idx, line in enumerate(lines, 1):\n s = line.strip()\n if not s:\n continue\n try:\n obj = json.loads(s)\n except json.JSONDecodeError as e:\n raise ValidationError(f\"line {idx}: invalid json\") from e\n if not isinstance(obj, dict):\n raise ValidationError(f\"line {idx}: expected object\")\n key = obj.get(\"key\")\n val = obj.get(\"value\")\n if not isinstance(key, str) or not key:\n raise ValidationError(f\"line {idx}: key must be non-empty str\")\n if not isinstance(val, int):\n raise ValidationError(f\"line {idx}: value must be int\")\n out.append(Record(key, val))\n return out\n\n\ndef write_jsonl(base: Path, rel: str, records: Iterable[Record]) -> Path:\n base.mkdir(parents=True, exist_ok=True)\n dst = safe_join(base, rel)\n dst.parent.mkdir(parents=True, exist_ok=True)\n with dst.open(\"w\", encoding=\"utf-8\", newline=\"\\n\") as f:\n for r in records:\n f.write(json.dumps({\"key\": r.key, \"value\": r.value}, ensure_ascii=False) + \"\\n\")\n return dst\n```\n\n```python\n# tests (pytest-style)\nimport json\nfrom pathlib import Path\nimport pytest\nfrom module_under_test import ValidationError, Record, parse_jsonl, write_jsonl\n\ndef test_parse_ok():\n lines = [json.dumps({\"key\":\"a\",\"value\":1}), json.dumps({\"key\":\"b\",\"value\":2})]\n assert parse_jsonl(lines) == [Record(\"a\",1), Record(\"b\",2)]\n\ndef test_parse_rejects_bad_json():\n with pytest.raises(ValidationError):\n parse_jsonl([\"{not json}\"])\n\ndef test_safe_join_blocks_traversal(tmp_path: Path):\n with pytest.raises(ValidationError):\n write_jsonl(tmp_path, \"../x.jsonl\", [Record(\"a\",1)])\n```", "source": "WithinUsAI/python_GOD_coder_100k"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: Language: C++\nFramework/tooling: Boost\nDomain: notification service\nLogic challenge: build reproducibility failure\nTask type: performance_bottleneck_patch\nDifficulty: hard\n\nReturn a rigorous engineering answer:\n- identify the hidden root cause or logical failure\n- present the corrected implementation\n- add tests that prove the fix\n- list verification commands\n- explain why naive fixes are insufficient when relevant\n\nRepository sketch:\nrepo/\n src/main.cpp\n src/service.cpp\n include/service.h\n tests/test_service.cpp\n CMakeLists.txt\n\nFocus: Focus on ambiguity, misleading symptoms, hidden root causes, and high-stakes debugging.\n\nassistant: Diagnosis:\n- Hidden root cause: build reproducibility failure presents misleading symptoms, so the patch must target the actual logic boundary rather than the first visible failure.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```cpp\n#include \n#include \n\nusing Payload = std::unordered_map;\n\nPayload normalize_payload(const Payload& in) {\n Payload out;\n for (const auto& [k, v] : in) {\n if (!v.empty()) out[k] = v;\n }\n return out;\n}\n```\n\nTests:\n```cpp\nTEST_CASE(\"normalize_payload filters empty values\") {\n Payload in{{\"id\",\"7\"},{\"name\",\"\"}};\n auto out = normalize_payload(in);\n REQUIRE(out.count(\"id\") == 1);\n REQUIRE(out.count(\"name\") == 0);\n}\n```\n\nVerification:\n- `cmake --build build`\n- `ctest --test-dir build`\n\nEngineering notes:\n- Language: C++\n- Framework/tooling: Boost\n- Stack context: Airflow, dbt, DuckDB, MinIO, pytest\n- Domain: notification service\n- Task type: performance_bottleneck_patch\n- Difficulty: hard\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "Build an elite-grade solution in the domain of stream processing for scenario: time-series metrics.\nPrimary language: python.\nDifficulty: hard.\nConstraints: design for backward compatibility and migrations, assume untrusted inputs; validate and sanitize, provide rollout and rollback guidance, make the interface contract explicit.\nComponent: component_vsulqwd.\nAssume partial network partitions occur weekly.\nTask: Define an API and evolving schema strategy (versioning, migrations, compatibility rules). Provide example schemas and validation tests.\n\nOutput: rigorous solution with invariants, failure modes, and performance notes.\nOutput: GPU pipeline design for throughput and tail-latency.\n\n**Pipeline**\n- Request batching with max batch size + max wait (e.g., 5ms) to control p99.\n- Separate CPU pre/post-processing threads; pin memory for transfers if available.\n- Model warmup; cache weights in VRAM; use concurrency limits.\n\n**Monitoring**\n- GPU utilization, queue wait time, batch size distribution, OOM events.\n\n**Fallback**\n- Graceful degradation to smaller batch size; circuit breaker on repeated OOM.\n\n\nHard checks: failure injection tests and performance regressions gated.", "source": "WithinUsAI/Elite_GOD_Coder_100k"} {"text": "Refactor to typed, mostly-immutable Python and add minimal tests.\n\n```python\nclass C80747:\n def __init__(self, values): self.values=list(values)\n def mean(self): return sum(self.values)/len(self.values)\n```\nReturn `m98519.py` and `test_m98519.py`.\n\n```python\n# m98519.py\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom typing import Iterable, Tuple\n\n@dataclass(frozen=True)\nclass C80747:\n values: Tuple[float, ...]\n\n @staticmethod\n def create(values: Iterable[float]) -> \"C80747\":\n vals = tuple(float(v) for v in values)\n if not vals: raise ValueError(\"empty\")\n return C80747(vals)\n\n def mean(self) -> float:\n return sum(self.values)/len(self.values)\n```\n\n```python\n# test_m98519.py\nimport pytest\nfrom m98519 import C80747\n\ndef test_mean():\n assert C80747.create([1,2,3]).mean() == 2.0\ndef test_empty():\n with pytest.raises(ValueError):\n C80747.create([])\n```", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Fix the bug and add pytest tests.\n\n```python\ndef f13740(n: int) -> int:\n # sum 1..n inclusive\n if n < 0: raise ValueError\n total = 0\n for k in range(n): # BUG\n total += k\n return total\n```\nReturn unified diffs for `m44820.py` and `test_m44820.py`.\n\n*** Begin Patch\n*** Update File: m44820.py\n@@\n def f13740(n: int) -> int:\n@@\n- for k in range(n): # BUG\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_m44820.py\n+import pytest\n+from m44820 import f13740\n+\n+def test_small():\n+ assert f13740(7) == 28\n+\n+def test_zero():\n+ assert f13740(0) == 0\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ f13740(-1)\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Refactor to modern typed Python with immutability and tests.\n\nFile: z6rl7n62qaz.py\n```python\nclass AdffltCa:\n def __init__(self, name, values):\n self.name = name\n self.values = list(values)\n def add(self, v):\n self.values.append(v)\n def mean(self):\n s = 0\n for x in self.values:\n s += x\n return s / len(self.values)\n```\n\nReturn full new z6rl7n62qaz.py and test_z6rl7n62qaz.py.\n\n# z6rl7n62qaz.py\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom typing import Iterable, Tuple\n\n@dataclass(frozen=True)\nclass AdffltCa:\n name: str\n values: Tuple[float, ...]\n\n @staticmethod\n def create(name: str, values: Iterable[float]) -> \"AdffltCa\":\n vals = tuple(float(v) for v in values)\n if not vals:\n raise ValueError(\"values must be non-empty\")\n return AdffltCa(name=name, values=vals)\n\n def add(self, v: float) -> \"AdffltCa\":\n return AdffltCa(name=self.name, values=self.values + (float(v),))\n\n def mean(self) -> float:\n return sum(self.values) / len(self.values)\n\n# test_z6rl7n62qaz.py\nimport pytest\nfrom z6rl7n62qaz import AdffltCa\n\ndef test_mean_and_add():\n c = AdffltCa.create(\"a\", [1, 2, 3])\n assert c.mean() == 2.0\n assert c.add(5).mean() == (1 + 2 + 3 + 5) / 4\n\ndef test_empty_raises():\n with pytest.raises(ValueError):\n AdffltCa.create(\"x\", [])", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Refactor to modern typed Python with immutability and tests.\n\nFile: q7ms0c8.py\n```python\nclass Ox0Ew2:\n def __init__(self, name, values):\n self.name = name\n self.values = list(values)\n def add(self, v):\n self.values.append(v)\n def mean(self):\n s = 0\n for x in self.values:\n s += x\n return s / len(self.values)\n```\n\nReturn full new q7ms0c8.py and test_q7ms0c8.py.\n\n# q7ms0c8.py\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom typing import Iterable, Tuple\n\n@dataclass(frozen=True)\nclass Ox0Ew2:\n name: str\n values: Tuple[float, ...]\n\n @staticmethod\n def create(name: str, values: Iterable[float]) -> \"Ox0Ew2\":\n vals = tuple(float(v) for v in values)\n if not vals:\n raise ValueError(\"values must be non-empty\")\n return Ox0Ew2(name=name, values=vals)\n\n def add(self, v: float) -> \"Ox0Ew2\":\n return Ox0Ew2(name=self.name, values=self.values + (float(v),))\n\n def mean(self) -> float:\n return sum(self.values) / len(self.values)\n\n# test_q7ms0c8.py\nimport pytest\nfrom q7ms0c8 import Ox0Ew2\n\ndef test_mean_and_add():\n c = Ox0Ew2.create(\"a\", [1, 2, 3])\n assert c.mean() == 2.0\n assert c.add(5).mean() == (1 + 2 + 3 + 5) / 4\n\ndef test_empty_raises():\n with pytest.raises(ValueError):\n Ox0Ew2.create(\"x\", [])", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Optimize while preserving behavior.\n\nFile: nk6otbze_2.py\n```python\ndef nye28uwx(xs):\n out = []\n for x in xs:\n if x not in out:\n out.append(x)\n return out\n```\n\nRequirements: preserve first-seen order; O(n) average; add types + docstring.\n\n# nk6otbze_2.py\nfrom __future__ import annotations\nfrom typing import Iterable, List, Set, TypeVar\n\nT = TypeVar(\"T\")\n\ndef nye28uwx(xs: Iterable[T]) -> List[T]:\n \"\"\"Return unique items preserving first-seen order.\"\"\"\n seen: Set[T] = set()\n out: List[T] = []\n for x in xs:\n if x in seen:\n continue\n seen.add(x)\n out.append(x)\n return out", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Task type: compiler_backend_ir\nScenario: feature-flag evaluation\nDomain focus: distributed storage\nPrimary language: rust\nDifficulty: hard\nScale/SLO: 10k RPS peak\nComponent: component_istctimy\nConstraints: include verification strategy, include failure modes and recovery, avoid data races and undefined behavior, include backward compatibility and migration plan, include performance model and limits\nAssume hostile inputs and targeted abuse patterns.\nDeliverable: Design an IR and lowering pipeline; include an optimization pass and correctness checks. Provide minimal code skeleton and tests.\n\nOutput: elite engineering answer optimized for correctness, performance, and operability.\n**Contract**\n- Inputs validated at the boundary; explicit error taxonomy.\n- Idempotency for side effects via request_id; deterministic replay.\n- Backward compatibility: additive changes by default; versioned breaking changes.\n**Invariants**\n- Liveness: under bounded faults and stable network, progress occurs.\n- Safety: state transitions preserve invariants; no partial commit leaks.\n- Determinism: replay of the same event log yields identical outputs.\n**Failure modes & recovery**\n- Duplicate requests: de-duplicate by (tenant, request_id) returning cached response.\n- Data corruption: checksums + scrubber; quarantine and rebuild from replicas/snapshots.\n- Crash during commit: WAL replay completes or transaction aborts; no torn writes.\n**Security posture (defensive)**\n- Threat model: auth/authz, injection, replay/abuse, supply chain.\n- Least privilege; secrets in managed store; audit logs for sensitive ops.\n- Input normalization, parameterized queries, path traversal protections.\n**Verification strategy**\n- Canary + shadow traffic; invariants checked in production via assertions/metrics.\n- Deterministic simulation with fault injection (crash/partition/latency).\n- Property tests against a pure reference model (state machine).\n\n**Snippet**\n```text\nImplementation sketch: factor pure state-machine core; adapters for I/O; add deterministic replay log.\n```\nHard checks: fault injection tests gate merges; perf thresholds enforced in CI.", "source": "WithinUsAI/Omega_Genesis_Coder_100k"} {"text": "Fix a subtle bug in a Python module used for event dispatching.\nRequirements: explain root cause briefly, provide corrected code, and add regression tests.\nConstraints: must include docstrings, must include type hints.\nDifficulty: expert. Support both Windows and POSIX paths correctly.\n\nDeliverable: implementation + tests.\n```python\nfrom __future__ import annotations\n\nfrom dataclasses import dataclass\nfrom pathlib import Path\nfrom typing import Iterable\nimport json\n\n\nclass ValidationError(ValueError):\n \"\"\"Raised when input validation fails.\"\"\"\n\n\ndef safe_join(base: Path, *parts: str) -> Path:\n \"\"\"Join paths while preventing traversal outside base.\"\"\"\n b = base.resolve()\n p = (b / Path(*parts)).resolve()\n if p != b and b not in p.parents:\n raise ValidationError(f\"unsafe path: {p}\")\n return p\n\n\n@dataclass(frozen=True, slots=True)\nclass Record:\n key: str\n value: int\n\n\ndef parse_jsonl(lines: Iterable[str]) -> list[Record]:\n out: list[Record] = []\n for idx, line in enumerate(lines, 1):\n s = line.strip()\n if not s:\n continue\n try:\n obj = json.loads(s)\n except json.JSONDecodeError as e:\n raise ValidationError(f\"line {idx}: invalid json\") from e\n if not isinstance(obj, dict):\n raise ValidationError(f\"line {idx}: expected object\")\n key = obj.get(\"key\")\n val = obj.get(\"value\")\n if not isinstance(key, str) or not key:\n raise ValidationError(f\"line {idx}: key must be non-empty str\")\n if not isinstance(val, int):\n raise ValidationError(f\"line {idx}: value must be int\")\n out.append(Record(key, val))\n return out\n\n\ndef write_jsonl(base: Path, rel: str, records: Iterable[Record]) -> Path:\n base.mkdir(parents=True, exist_ok=True)\n dst = safe_join(base, rel)\n dst.parent.mkdir(parents=True, exist_ok=True)\n with dst.open(\"w\", encoding=\"utf-8\", newline=\"\\n\") as f:\n for r in records:\n f.write(json.dumps({\"key\": r.key, \"value\": r.value}, ensure_ascii=False) + \"\\n\")\n return dst\n```\n\n```python\n# tests (pytest-style)\nimport json\nfrom pathlib import Path\nimport pytest\nfrom module_under_test import ValidationError, Record, parse_jsonl, write_jsonl\n\ndef test_parse_ok():\n lines = [json.dumps({\"key\":\"a\",\"value\":1}), json.dumps({\"key\":\"b\",\"value\":2})]\n assert parse_jsonl(lines) == [Record(\"a\",1), Record(\"b\",2)]\n\ndef test_parse_rejects_bad_json():\n with pytest.raises(ValidationError):\n parse_jsonl([\"{not json}\"])\n\ndef test_safe_join_blocks_traversal(tmp_path: Path):\n with pytest.raises(ValidationError):\n write_jsonl(tmp_path, \"../x.jsonl\", [Record(\"a\",1)])\n```", "source": "WithinUsAI/python_GOD_coder_100k"} {"text": "Task type: runtime_gc\nScenario: identity and access\nDomain focus: large-scale ML systems\nPrimary language: rust\nDifficulty: expert\nScale/SLO: multi-region active-active\nComponent: component_hxkswlrd\nConstraints: include deterministic replay plan, include backward compatibility and migration plan, explicit contracts and invariants, include performance model and limits, include test vectors and fuzz strategy, avoid data races and undefined behavior, include security threat model (defensive only)\nAssume weekly network partitions.\nDeliverable: Design a GC/runtime component (mark-sweep/arena/RC hybrid); include pause-time strategy and tests.\n\nOutput: rigorous design + invariants + verification plan + implementation sketch.\n**Contract**\n- Inputs validated at the boundary; explicit error taxonomy.\n- Idempotency for side effects via request_id; deterministic replay.\n- Backward compatibility: additive changes by default; versioned breaking changes.\n**Invariants**\n- Safety: state transitions preserve invariants; no partial commit leaks.\n- Determinism: replay of the same event log yields identical outputs.\n- Liveness: under bounded faults and stable network, progress occurs.\n**Failure modes & recovery**\n- Data corruption: checksums + scrubber; quarantine and rebuild from replicas/snapshots.\n- Crash during commit: WAL replay completes or transaction aborts; no torn writes.\n- Network partition: minority cannot commit; clients receive retriable errors.\n**Security posture (defensive)**\n- Threat model: auth/authz, injection, replay/abuse, supply chain.\n- Least privilege; secrets in managed store; audit logs for sensitive ops.\n- Input normalization, parameterized queries, path traversal protections.\n**Verification strategy**\n- Property tests against a pure reference model (state machine).\n- Deterministic simulation with fault injection (crash/partition/latency).\n- Canary + shadow traffic; invariants checked in production via assertions/metrics.\n\n**Snippet**\n```text\nImplementation sketch: factor pure state-machine core; adapters for I/O; add deterministic replay log.\n```\nExpert checks: state-machine proof sketch + model checking; upgrade/rollback rehearsed.", "source": "WithinUsAI/Omega_Genesis_Coder_100k"} {"text": "Fix the bug and add pytest tests.\n\n```python\ndef f87704(n: int) -> int:\n # sum 1..n inclusive\n if n < 0: raise ValueError\n total = 0\n for k in range(n): # BUG\n total += k\n return total\n```\nReturn unified diffs for `m69672.py` and `test_m69672.py`.\n\n*** Begin Patch\n*** Update File: m69672.py\n@@\n def f87704(n: int) -> int:\n@@\n- for k in range(n): # BUG\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_m69672.py\n+import pytest\n+from m69672 import f87704\n+\n+def test_small():\n+ assert f87704(7) == 28\n+\n+def test_zero():\n+ assert f87704(0) == 0\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ f87704(-1)\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Create a comprehensive test plan and automated tests for audit logs in a gaming product.\nTarget platform: mobile (Android Kotlin).\nRequirements: unit/integration tests, edge cases, load tests strategy, and CI gates.\nConstraints: must include clear error handling, must be observable (logs/metrics/traces), must be production-ready, must be secure-by-default, must include type hints where applicable.\nDifficulty: medium. Assume schema evolves frequently; design for migrations.\n\nOutput: production-oriented blueprint with code where appropriate.\nDeliverable: test plan + automation guidance.\n\n**Unit tests**\n- Validation: malformed payloads rejected with correct codes.\n- AuthZ: tenant boundary enforced.\n- Idempotency: replay returns same response; conflicting reuse yields 409.\n\n**Integration tests**\n- DB transaction behavior; unique constraints.\n- Cache behavior: correctness under concurrent requests.\n\n**Load tests**\n- 10k RPS target: measure p95 latency, error rate, saturation.\n\n**CI gates**\n- Lint + typecheck + unit tests required.\n- Coverage threshold for critical modules.\n- Block merge on flaky test detection.\n\n\nChecks: input validation, tests, and safe defaults included.", "source": "WithinUsAI/GOD_Coder_100k"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: Language: C#\nFramework/tooling: xUnit\nDomain: notification service\nLogic challenge: N+1 query explosion\nTask type: multi_service_security_patch\nDifficulty: expert\n\nReturn a rigorous engineering answer:\n- identify the hidden root cause or logical failure\n- present the corrected implementation\n- add tests that prove the fix\n- list verification commands\n- explain why naive fixes are insufficient when relevant\n\nRepository sketch:\nrepo/\n src/App/Program.cs\n src/App/Service.cs\n tests/App.Tests/ServiceTests.cs\n App.sln\n\nFocus: Focus on staff-level problem solving with multi-file patches, rollout implications, performance and security tradeoffs.\n\nassistant: Diagnosis:\n- Staff-level diagnosis: N+1 query explosion impacts correctness, operability, and future maintenance, so the fix must be minimal where possible but complete where necessary.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```csharp\nusing System;\nusing System.Collections.Generic;\n\npublic static class RequestHandler\n{\n public static Dictionary HandleRequest(Dictionary payload)\n {\n var clean = new Dictionary();\n foreach (var entry in payload)\n {\n if (entry.Value != null)\n clean[entry.Key.Trim()] = entry.Value;\n }\n if (!clean.ContainsKey(\"id\"))\n throw new ArgumentException(\"missing id\");\n return new Dictionary\n {\n [\"ok\"] = true,\n [\"data\"] = clean\n };\n }\n}\n```\n\nTests:\n```csharp\nusing System;\nusing System.Collections.Generic;\nusing Xunit;\n\npublic class RequestHandlerTests\n{\n [Fact]\n public void RequiresId()\n {\n Assert.Throws(() => RequestHandler.HandleRequest(new Dictionary { [\"name\"] = \"x\" }));\n }\n}\n```\n\nVerification:\n- `dotnet test`\n- `dotnet build`\n\nEngineering notes:\n- Language: C#\n- Framework/tooling: xUnit\n- Stack context: ASP.NET Core, SQL Server, EF Core, xUnit, Docker\n- Domain: notification service\n- Task type: multi_service_security_patch\n- Difficulty: expert\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "Create a comprehensive test plan and automated tests for real-time notifications in a gaming product.\nTarget platform: data (SQL + Python).\nRequirements: unit/integration tests, edge cases, load tests strategy, and CI gates.\nConstraints: must be observable (logs/metrics/traces), must avoid global state, must be secure-by-default, must include documentation/comments, must be production-ready.\nDifficulty: medium. Assume 10k RPS peak traffic.\n\nOutput: design + implementation guidance suitable for shipping.\nDeliverable: test plan + automation guidance.\n\n**Unit tests**\n- Validation: malformed payloads rejected with correct codes.\n- AuthZ: tenant boundary enforced.\n- Idempotency: replay returns same response; conflicting reuse yields 409.\n\n**Integration tests**\n- DB transaction behavior; unique constraints.\n- Cache behavior: correctness under concurrent requests.\n\n**Load tests**\n- 10k RPS target: measure p95 latency, error rate, saturation.\n\n**CI gates**\n- Lint + typecheck + unit tests required.\n- Coverage threshold for critical modules.\n- Block merge on flaky test detection.\n\n\nChecks: input validation, tests, and safe defaults included.", "source": "WithinUsAI/GOD_Coder_100k"} {"text": "Fix the bug and add pytest tests.\n\n```python\ndef f03639(n: int) -> int:\n # sum 1..n inclusive\n if n < 0: raise ValueError\n total = 0\n for k in range(n): # BUG\n total += k\n return total\n```\nReturn unified diffs for `m43377.py` and `test_m43377.py`.\n\n*** Begin Patch\n*** Update File: m43377.py\n@@\n def f03639(n: int) -> int:\n@@\n- for k in range(n): # BUG\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_m43377.py\n+import pytest\n+from m43377 import f03639\n+\n+def test_small():\n+ assert f03639(7) == 28\n+\n+def test_zero():\n+ assert f03639(0) == 0\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ f03639(-1)\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Optimize a Python workflow for ETL pipelines.\nRequirements: provide an optimized implementation and a small benchmark harness.\nConstraints: must handle Windows paths safely, stdlib-only.\nDifficulty: hard. Include a small CLI example if relevant.\n\nDeliverable: production-ready reference solution.\nStrategy:\n- Avoid repeated parsing; precompile regex if needed; use local variables; stream processing.\n\n```python\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom typing import Iterable\nimport time\n\n@dataclass(frozen=True, slots=True)\nclass Stats:\n count: int\n total: int\n\ndef compute_stats_stream(values: Iterable[int]) -> Stats:\n c = 0\n t = 0\n for v in values:\n c += 1\n t += v\n return Stats(c, t)\n\ndef bench(n: int = 1_000_00) -> float:\n data = range(n)\n t0 = time.perf_counter()\n _ = compute_stats_stream(data)\n return time.perf_counter() - t0\n```\n\n```python\nfrom module_under_test import bench\ndef test_bench_runs_fast_enough():\n # Sanity: should run quickly on typical machines; adjust threshold for CI.\n assert bench(50_000) < 0.5\n```", "source": "WithinUsAI/python_GOD_coder_100k"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: Language: YAML\nFramework/tooling: Helm\nDomain: benchmark harness\nLogic challenge: multi-tenant access leak\nTask type: state_machine_patch\nDifficulty: hard\n\nReturn a rigorous engineering answer:\n- identify the hidden root cause or logical failure\n- present the corrected implementation\n- add tests that prove the fix\n- list verification commands\n- explain why naive fixes are insufficient when relevant\n\nRepository sketch:\nrepo/\n .github/workflows/ci.yml\n docker-compose.yml\n deploy/\n app.yaml\n\nFocus: Focus on strong structured logic with edge cases, data validation, and concurrency safety.\n\nassistant: Diagnosis:\n- Root cause: the failure around multi-tenant access leak is caused by missing validation, weak edge-case handling, or unsafe lifecycle behavior in the current implementation.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```yaml\nname: ci\non: [push, pull_request]\njobs:\n test:\n runs-on: ubuntu-latest\n steps:\n - uses: actions/checkout@v4\n - name: Validate\n run: echo \"validated\"\n```\n\nTests:\n```yaml\n# Verification:\n# - validate syntax\n# - run smoke workflow\n# - fail fast on broken config\n```\n\nVerification:\n- `validate workflow syntax`\n- `run CI smoke job`\n\nEngineering notes:\n- Language: YAML\n- Framework/tooling: Helm\n- Stack context: Rust, Axum, SQLx, Redis, Tokio, Docker\n- Domain: benchmark harness\n- Task type: state_machine_patch\n- Difficulty: hard\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "Write pytest tests for `f57573`.\n\n```python\ndef f57573(a: int, b: int) -> int:\n return a*a + b*b\n```\nInclude edge cases and a property-style check.\n\n```python\nimport random\nfrom m93939 import f57573\n\ndef test_known():\n assert f57573(3,4) == 25\n\ndef test_zero():\n assert f57573(0,0) == 0\n\ndef test_property_nonnegative():\n for _ in range(200):\n a=random.randint(-50,50)\n b=random.randint(-50,50)\n assert f57573(a,b) >= 0\n```", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Task type: query_optimizer\nScenario: real-time notification hub\nDomain focus: cryptography engineering (defensive)\nPrimary language: rust\nDifficulty: expert+\nScale/SLO: p99 < 150ms\nComponent: component_jhaoctpu\nConstraints: include failure modes and recovery, include security threat model (defensive only), explicit contracts and invariants, assume adversarial inputs; validate everything, include deterministic replay plan, include verification strategy, avoid data races and undefined behavior\nAssume crash-only processes; recovery must be deterministic.\nDeliverable: Design a cost-based optimizer slice: logical rules, physical operators, and cost model. Include regression tests and query-plan explain examples.\n\nOutput: rigorous design + invariants + verification plan + implementation sketch.\n**Contract**\n- Inputs validated at the boundary; explicit error taxonomy.\n- Idempotency for side effects via request_id; deterministic replay.\n- Backward compatibility: additive changes by default; versioned breaking changes.\n**Invariants**\n- Determinism: replay of the same event log yields identical outputs.\n- Liveness: under bounded faults and stable network, progress occurs.\n- Safety: state transitions preserve invariants; no partial commit leaks.\n**Failure modes & recovery**\n- Network partition: minority cannot commit; clients receive retriable errors.\n- Crash during commit: WAL replay completes or transaction aborts; no torn writes.\n- Data corruption: checksums + scrubber; quarantine and rebuild from replicas/snapshots.\n**Security posture (defensive)**\n- Threat model: auth/authz, injection, replay/abuse, supply chain.\n- Least privilege; secrets in managed store; audit logs for sensitive ops.\n- Input normalization, parameterized queries, path traversal protections.\n**Verification strategy**\n- Canary + shadow traffic; invariants checked in production via assertions/metrics.\n- Fuzzing of parsers/framers/validators with corpus seeds.\n- Property tests against a pure reference model (state machine).\n\n**Snippet**\n```python\n# Minimal cost model skeleton\nfrom dataclasses import dataclass\n\n@dataclass(frozen=True)\nclass Plan:\n op: str\n cost: float\n children: tuple[\"Plan\", ...] = ()\n\ndef choose_best(plans: list[Plan]) -> Plan:\n return min(plans, key=lambda p: p.cost)\n```\n\nExpert+ checks: mechanized invariants (or exhaustive model checking), adversarial fuzzing, and multi-region failure drills.", "source": "WithinUsAI/Omega_Genesis_Coder_100k"} {"text": "Implement an ML engineering workflow for education focusing on role-based access control.\nTarget platform: ML (training + serving).\nRequirements: data contract, training loop, evaluation, model registry, serving API, monitoring.\nConstraints: must be observable (logs/metrics/traces), must include clear error handling, must be easy to extend, must include documentation/comments, must include type hints where applicable.\nDifficulty: easy. Assume strict latency budget (p95 < 200ms).\n\nOutput: production-oriented blueprint with code where appropriate.\nDeliverable: ML engineering blueprint (training + serving + monitoring), safe and production-oriented.\n\n**Data contract**\n- Define feature schema + ranges; validate at training and serving.\n\n**Training**\n- Deterministic split; baseline model; track metrics (AUC/F1/latency).\n- Store artifacts: model, config, feature stats.\n\n**Registry**\n- Promote models via approval gates; record lineage.\n\n**Serving**\n- Separate inference service with `/predict`.\n- Input validation + default handling; timeouts.\n\n**Monitoring**\n- Data drift: feature distribution checks.\n- Performance: online metrics + periodic labels; alert on regression.\n\nMinimal serving skeleton (FastAPI-ish):\n```python\n# validate input -> vectorize -> model.predict_proba -> return\n```\n\n\nChecks: input validation, tests, and safe defaults included.", "source": "WithinUsAI/GOD_Coder_100k"} {"text": "Fix the bug and add pytest tests.\n\n```python\ndef f81353(n: int) -> int:\n # sum 1..n inclusive\n if n < 0: raise ValueError\n total = 0\n for k in range(n): # BUG\n total += k\n return total\n```\nReturn unified diffs for `m54479.py` and `test_m54479.py`.\n\n*** Begin Patch\n*** Update File: m54479.py\n@@\n def f81353(n: int) -> int:\n@@\n- for k in range(n): # BUG\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_m54479.py\n+import pytest\n+from m54479 import f81353\n+\n+def test_small():\n+ assert f81353(7) == 28\n+\n+def test_zero():\n+ assert f81353(0) == 0\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ f81353(-1)\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Fix a bug and add tests.\n\nFile: yfpdh2pn.py\n```python\ndef ua1mdvrzh83(n: int) -> int:\n \"\"\"Sum 1..n inclusive.\"\"\"\n if n < 0:\n raise ValueError(\"n must be non-negative\")\n total = 0\n for k in range(n): # BUG: should include n\n total += k\n return total\n```\n\nReturn unified diffs for yfpdh2pn.py and test_yfpdh2pn.py (pytest).\n\n*** Begin Patch\n*** Update File: yfpdh2pn.py\n@@\n def ua1mdvrzh83(n: int) -> int:\n@@\n total = 0\n- for k in range(n): # BUG: should include n\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_yfpdh2pn.py\n+import pytest\n+from yfpdh2pn import ua1mdvrzh83\n+\n+def test_zero():\n+ assert ua1mdvrzh83(0) == 0\n+\n+def test_one():\n+ assert ua1mdvrzh83(1) == 1\n+\n+def test_small():\n+ assert ua1mdvrzh83(7) == 28\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ ua1mdvrzh83(-1)\n+\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Produce an offline-first self-evolving code assistant architecture named `g_nzcp`.\nMust include: module layout, patch-safety policy, evaluation gates (tests/lint/types), versioned memory index.\n\nArchitecture: `g_nzcp` (offline-first, self-evolving)\n\nModules\n- core/loop.py: evolve → validate → accept/reject (bounded iterations)\n- patching/: diff builder, safe apply, atomic writes, rollback points\n- policy/: allowlist paths, deny globs (.git/, __pycache__/, binaries), patch size caps\n- signals/: parse pytest/ruff/mypy into normalized findings\n- memory/index.jsonl: append-only snapshots (hashes, metrics, rationale)\n\nSafety gates\n- refuse path traversal/symlink escapes; never edit binaries\n- accept only if tests/lint/types stay green or improve", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: Language: C#\nFramework/tooling: NUnit\nDomain: reporting engine\nLogic challenge: broken pagination cursor\nTask type: concurrency_fix\nDifficulty: hard\n\nReturn a rigorous engineering answer:\n- identify the hidden root cause or logical failure\n- present the corrected implementation\n- add tests that prove the fix\n- list verification commands\n- explain why naive fixes are insufficient when relevant\n\nRepository sketch:\nrepo/\n src/App/Program.cs\n src/App/Service.cs\n tests/App.Tests/ServiceTests.cs\n App.sln\n\nFocus: Focus on strong structured logic with edge cases, data validation, and concurrency safety.\n\nassistant: Diagnosis:\n- Root cause: the failure around broken pagination cursor is caused by missing validation, weak edge-case handling, or unsafe lifecycle behavior in the current implementation.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```csharp\nusing System;\nusing System.Collections.Generic;\n\npublic static class RequestHandler\n{\n public static Dictionary HandleRequest(Dictionary payload)\n {\n var clean = new Dictionary();\n foreach (var entry in payload)\n {\n if (entry.Value != null)\n clean[entry.Key.Trim()] = entry.Value;\n }\n if (!clean.ContainsKey(\"id\"))\n throw new ArgumentException(\"missing id\");\n return new Dictionary\n {\n [\"ok\"] = true,\n [\"data\"] = clean\n };\n }\n}\n```\n\nTests:\n```csharp\nusing System;\nusing System.Collections.Generic;\nusing Xunit;\n\npublic class RequestHandlerTests\n{\n [Fact]\n public void RequiresId()\n {\n Assert.Throws(() => RequestHandler.HandleRequest(new Dictionary { [\"name\"] = \"x\" }));\n }\n}\n```\n\nVerification:\n- `dotnet test`\n- `dotnet build`\n\nEngineering notes:\n- Language: C#\n- Framework/tooling: NUnit\n- Stack context: Go, Gin, PostgreSQL, gRPC, Prometheus, Docker\n- Domain: reporting engine\n- Task type: concurrency_fix\n- Difficulty: hard\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Refactor to modern typed Python with immutability and tests.\n\nFile: alkq56u1ye.py\n```python\nclass S42L3Pd3Khhj:\n def __init__(self, name, values):\n self.name = name\n self.values = list(values)\n def add(self, v):\n self.values.append(v)\n def mean(self):\n s = 0\n for x in self.values:\n s += x\n return s / len(self.values)\n```\n\nReturn full new alkq56u1ye.py and test_alkq56u1ye.py.\n\n# alkq56u1ye.py\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom typing import Iterable, Tuple\n\n@dataclass(frozen=True)\nclass S42L3Pd3Khhj:\n name: str\n values: Tuple[float, ...]\n\n @staticmethod\n def create(name: str, values: Iterable[float]) -> \"S42L3Pd3Khhj\":\n vals = tuple(float(v) for v in values)\n if not vals:\n raise ValueError(\"values must be non-empty\")\n return S42L3Pd3Khhj(name=name, values=vals)\n\n def add(self, v: float) -> \"S42L3Pd3Khhj\":\n return S42L3Pd3Khhj(name=self.name, values=self.values + (float(v),))\n\n def mean(self) -> float:\n return sum(self.values) / len(self.values)\n\n# test_alkq56u1ye.py\nimport pytest\nfrom alkq56u1ye import S42L3Pd3Khhj\n\ndef test_mean_and_add():\n c = S42L3Pd3Khhj.create(\"a\", [1, 2, 3])\n assert c.mean() == 2.0\n assert c.add(5).mean() == (1 + 2 + 3 + 5) / 4\n\ndef test_empty_raises():\n with pytest.raises(ValueError):\n S42L3Pd3Khhj.create(\"x\", [])", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Fix the bug and add pytest tests.\n\n```python\ndef f01389(n: int) -> int:\n # sum 1..n inclusive\n if n < 0: raise ValueError\n total = 0\n for k in range(n): # BUG\n total += k\n return total\n```\nReturn unified diffs for `m71627.py` and `test_m71627.py`.\n\n*** Begin Patch\n*** Update File: m71627.py\n@@\n def f01389(n: int) -> int:\n@@\n- for k in range(n): # BUG\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_m71627.py\n+import pytest\n+from m71627 import f01389\n+\n+def test_small():\n+ assert f01389(7) == 28\n+\n+def test_zero():\n+ assert f01389(0) == 0\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ f01389(-1)\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Task type: runtime_gc\nScenario: graph query service\nDomain focus: cryptography engineering (defensive)\nPrimary language: sql\nDifficulty: expert+\nScale/SLO: 1M msgs/min\nComponent: component_unjgeumf\nConstraints: include verification strategy, include security threat model (defensive only), include failure modes and recovery, include test vectors and fuzz strategy, explicit contracts and invariants, include performance model and limits, assume adversarial inputs; validate everything\nAssume strict auditability and replayable history.\nDeliverable: Design a GC/runtime component (mark-sweep/arena/RC hybrid); include pause-time strategy and tests.\n\nOutput: elite engineering answer optimized for correctness, performance, and operability.\n**Contract**\n- Inputs validated at the boundary; explicit error taxonomy.\n- Idempotency for side effects via request_id; deterministic replay.\n- Backward compatibility: additive changes by default; versioned breaking changes.\n**Invariants**\n- Determinism: replay of the same event log yields identical outputs.\n- Safety: state transitions preserve invariants; no partial commit leaks.\n- Liveness: under bounded faults and stable network, progress occurs.\n**Failure modes & recovery**\n- Crash during commit: WAL replay completes or transaction aborts; no torn writes.\n- Duplicate requests: de-duplicate by (tenant, request_id) returning cached response.\n- Network partition: minority cannot commit; clients receive retriable errors.\n**Security posture (defensive)**\n- Threat model: auth/authz, injection, replay/abuse, supply chain.\n- Least privilege; secrets in managed store; audit logs for sensitive ops.\n- Input normalization, parameterized queries, path traversal protections.\n**Verification strategy**\n- Fuzzing of parsers/framers/validators with corpus seeds.\n- Property tests against a pure reference model (state machine).\n- Canary + shadow traffic; invariants checked in production via assertions/metrics.\n\n**Snippet**\n```text\nImplementation sketch: factor pure state-machine core; adapters for I/O; add deterministic replay log.\n```\nExpert+ checks: mechanized invariants (or exhaustive model checking), adversarial fuzzing, and multi-region failure drills.", "source": "WithinUsAI/Omega_Genesis_Coder_100k"} {"text": "Fix the bug and add pytest tests.\n\n```python\ndef f30033(n: int) -> int:\n # sum 1..n inclusive\n if n < 0: raise ValueError\n total = 0\n for k in range(n): # BUG\n total += k\n return total\n```\nReturn unified diffs for `m75719.py` and `test_m75719.py`.\n\n*** Begin Patch\n*** Update File: m75719.py\n@@\n def f30033(n: int) -> int:\n@@\n- for k in range(n): # BUG\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_m75719.py\n+import pytest\n+from m75719 import f30033\n+\n+def test_small():\n+ assert f30033(7) == 28\n+\n+def test_zero():\n+ assert f30033(0) == 0\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ f30033(-1)\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Add a clear docstring and type hints to this function:\n\n```python\ndef f51399(s):\n return ''.join(x for x in s if x.isalnum()).lower()\n```\n\n```python\nfrom __future__ import annotations\n\ndef f51399(s: str) -> str:\n \"\"\"Normalize a string: keep only alphanumerics and lowercase the result.\"\"\"\n return \"\".join(ch for ch in s if ch.isalnum()).lower()\n```", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Task type: distributed_algorithm\nScenario: job scheduler\nDomain focus: GPU serving\nPrimary language: python\nDifficulty: expert+\nScale/SLO: multi-region active-active\nComponent: component_jeowgtta\nConstraints: assume adversarial inputs; validate everything, include backward compatibility and migration plan, include security threat model (defensive only), include deterministic replay plan, avoid data races and undefined behavior, include test vectors and fuzz strategy, include verification strategy\nAssume weekly network partitions.\nDeliverable: Design an algorithm with message flows and correctness arguments (safety + liveness). Include failure handling and a minimal reference implementation skeleton.\n\nOutput: elite engineering answer optimized for correctness, performance, and operability.\n**Contract**\n- Inputs validated at the boundary; explicit error taxonomy.\n- Idempotency for side effects via request_id; deterministic replay.\n- Backward compatibility: additive changes by default; versioned breaking changes.\n**Invariants**\n- Safety: state transitions preserve invariants; no partial commit leaks.\n- Isolation: tenant boundary enforced; no cross-tenant reads/writes.\n- Liveness: under bounded faults and stable network, progress occurs.\n**Failure modes & recovery**\n- Crash during commit: WAL replay completes or transaction aborts; no torn writes.\n- Network partition: minority cannot commit; clients receive retriable errors.\n- Data corruption: checksums + scrubber; quarantine and rebuild from replicas/snapshots.\n**Security posture (defensive)**\n- Threat model: auth/authz, injection, replay/abuse, supply chain.\n- Least privilege; secrets in managed store; audit logs for sensitive ops.\n- Input normalization, parameterized queries, path traversal protections.\n**Verification strategy**\n- Deterministic simulation with fault injection (crash/partition/latency).\n- Fuzzing of parsers/framers/validators with corpus seeds.\n- Canary + shadow traffic; invariants checked in production via assertions/metrics.\n\n**Snippet**\n```text\nImplementation sketch: factor pure state-machine core; adapters for I/O; add deterministic replay log.\n```\nExpert+ checks: mechanized invariants (or exhaustive model checking), adversarial fuzzing, and multi-region failure drills.", "source": "WithinUsAI/Omega_Genesis_Coder_100k"} {"text": "Fix the bug and add pytest tests.\n\n```python\ndef f70785(n: int) -> int:\n # sum 1..n inclusive\n if n < 0: raise ValueError\n total = 0\n for k in range(n): # BUG\n total += k\n return total\n```\nReturn unified diffs for `m67255.py` and `test_m67255.py`.\n\n*** Begin Patch\n*** Update File: m67255.py\n@@\n def f70785(n: int) -> int:\n@@\n- for k in range(n): # BUG\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_m67255.py\n+import pytest\n+from m67255 import f70785\n+\n+def test_small():\n+ assert f70785(7) == 28\n+\n+def test_zero():\n+ assert f70785(0) == 0\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ f70785(-1)\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Optimize while preserving behavior.\n\nFile: mv0j5ucr.py\n```python\ndef x_jyop9lt0(xs):\n out = []\n for x in xs:\n if x not in out:\n out.append(x)\n return out\n```\n\nRequirements: preserve first-seen order; O(n) average; add types + docstring.\n\n# mv0j5ucr.py\nfrom __future__ import annotations\nfrom typing import Iterable, List, Set, TypeVar\n\nT = TypeVar(\"T\")\n\ndef x_jyop9lt0(xs: Iterable[T]) -> List[T]:\n \"\"\"Return unique items preserving first-seen order.\"\"\"\n seen: Set[T] = set()\n out: List[T] = []\n for x in xs:\n if x in seen:\n continue\n seen.add(x)\n out.append(x)\n return out", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Create a small, production-ready Python package for parsing.\nRequirements: include module code, CLI entrypoint, logging, and a minimal pyproject.toml.\nConstraints: must include type hints, must be streaming-friendly.\nDifficulty: easy. Support both Windows and POSIX paths correctly.\n\nDeliverable: implementation + tests.\nPackage layout:\n- mypkg/core.py\n- mypkg/cli.py\n- pyproject.toml\n\n```python\n# mypkg/core.py\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom typing import Iterable\nimport logging\n\nlog = logging.getLogger(__name__)\n\n@dataclass(frozen=True, slots=True)\nclass Result:\n total: int\n count: int\n\ndef aggregate(values: Iterable[int]) -> Result:\n total = 0\n count = 0\n for v in values:\n if not isinstance(v, int):\n raise TypeError(\"values must be ints\")\n total += v\n count += 1\n log.debug(\"aggregate count=%s total=%s\", count, total)\n return Result(total, count)\n```\n\n```python\n# mypkg/cli.py\nfrom __future__ import annotations\nimport argparse\nimport logging\nimport sys\nfrom .core import aggregate\n\ndef main(argv: list[str] | None = None) -> int:\n p = argparse.ArgumentParser(prog=\"mypkg\")\n p.add_argument(\"--log-level\", default=\"WARNING\")\n args = p.parse_args(argv)\n logging.basicConfig(level=getattr(logging, args.log_level.upper(), logging.WARNING))\n data: list[int] = []\n for line in sys.stdin:\n line = line.strip()\n if line:\n data.append(int(line))\n r = aggregate(data)\n print(f\"count={r.count} total={r.total}\")\n return 0\n```\n\n```toml\n# pyproject.toml\n[project]\nname = \"mypkg\"\nversion = \"0.1.0\"\nrequires-python = \">=3.10\"\n\n[project.scripts]\nmypkg = \"mypkg.cli:main\"\n```", "source": "WithinUsAI/python_GOD_coder_100k"} {"text": "Task type: perf_microarchitecture\nScenario: edge sync\nDomain focus: cryptography engineering (defensive)\nPrimary language: sql\nDifficulty: expert\nScale/SLO: 1M msgs/min\nComponent: component_teplymeh\nConstraints: include failure modes and recovery, include verification strategy, include deterministic replay plan, explicit contracts and invariants, include backward compatibility and migration plan, include performance model and limits\nAssume schema changes every sprint; must be backward compatible.\nDeliverable: Provide performance engineering plan: profiling, hot-path redesign, cache behavior assumptions, and microbench harness.\n\nOutput: rigorous design + invariants + verification plan + implementation sketch.\n**Contract**\n- Inputs validated at the boundary; explicit error taxonomy.\n- Idempotency for side effects via request_id; deterministic replay.\n- Backward compatibility: additive changes by default; versioned breaking changes.\n**Invariants**\n- Liveness: under bounded faults and stable network, progress occurs.\n- Determinism: replay of the same event log yields identical outputs.\n- Isolation: tenant boundary enforced; no cross-tenant reads/writes.\n**Failure modes & recovery**\n- Crash during commit: WAL replay completes or transaction aborts; no torn writes.\n- Network partition: minority cannot commit; clients receive retriable errors.\n- Data corruption: checksums + scrubber; quarantine and rebuild from replicas/snapshots.\n**Security posture (defensive)**\n- Threat model: auth/authz, injection, replay/abuse, supply chain.\n- Least privilege; secrets in managed store; audit logs for sensitive ops.\n- Input normalization, parameterized queries, path traversal protections.\n**Verification strategy**\n- Canary + shadow traffic; invariants checked in production via assertions/metrics.\n- Deterministic simulation with fault injection (crash/partition/latency).\n- Fuzzing of parsers/framers/validators with corpus seeds.\n\n**Snippet**\n```text\nImplementation sketch: factor pure state-machine core; adapters for I/O; add deterministic replay log.\n```\nExpert checks: state-machine proof sketch + model checking; upgrade/rollback rehearsed.", "source": "WithinUsAI/Omega_Genesis_Coder_100k"} {"text": "Fix the bug and add pytest tests.\n\n```python\ndef f43688(n: int) -> int:\n # sum 1..n inclusive\n if n < 0: raise ValueError\n total = 0\n for k in range(n): # BUG\n total += k\n return total\n```\nReturn unified diffs for `m63384.py` and `test_m63384.py`.\n\n*** Begin Patch\n*** Update File: m63384.py\n@@\n def f43688(n: int) -> int:\n@@\n- for k in range(n): # BUG\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_m63384.py\n+import pytest\n+from m63384 import f43688\n+\n+def test_small():\n+ assert f43688(7) == 28\n+\n+def test_zero():\n+ assert f43688(0) == 0\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ f43688(-1)\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Optimize a Python workflow for task scheduling.\nRequirements: provide an optimized implementation and a small benchmark harness.\nConstraints: must be streaming-friendly, must be memory-efficient, must be easy to extend, must avoid global state.\nDifficulty: expert. Include a small CLI example if relevant.\n\nDeliverable: implementation + tests.\nStrategy:\n- Avoid repeated parsing; precompile regex if needed; use local variables; stream processing.\n\n```python\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom typing import Iterable\nimport time\n\n@dataclass(frozen=True, slots=True)\nclass Stats:\n count: int\n total: int\n\ndef compute_stats_stream(values: Iterable[int]) -> Stats:\n c = 0\n t = 0\n for v in values:\n c += 1\n t += v\n return Stats(c, t)\n\ndef bench(n: int = 1_000_00) -> float:\n data = range(n)\n t0 = time.perf_counter()\n _ = compute_stats_stream(data)\n return time.perf_counter() - t0\n```\n\n```python\nfrom module_under_test import bench\ndef test_bench_runs_fast_enough():\n # Sanity: should run quickly on typical machines; adjust threshold for CI.\n assert bench(50_000) < 0.5\n```", "source": "WithinUsAI/python_GOD_coder_100k"} {"text": "Refactor a Python module used for validation into a clean, extensible design.\nRequirements: outline the new architecture briefly, then provide the refactored code and tests.\nConstraints: must include type hints, must handle Windows paths safely.\nDifficulty: hard. Include a small CLI example if relevant.\n\nDeliverable: API + reference implementation + tests.\nArchitecture:\n- Public facade class coordinating concerns (parsing, validation, persistence)\n- Small pure functions for testability\n- No global state; dependency injection for filesystem I/O\n\n```python\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom pathlib import Path\nfrom typing import Protocol, Iterable\nimport json\n\nclass Store(Protocol):\n def write_text(self, path: Path, data: str) -> None: ...\n\nclass FSStore:\n def write_text(self, path: Path, data: str) -> None:\n path.parent.mkdir(parents=True, exist_ok=True)\n path.write_text(data, encoding=\"utf-8\")\n\n@dataclass(frozen=True, slots=True)\nclass Item:\n name: str\n qty: int\n\ndef parse_items(lines: Iterable[str]) -> list[Item]:\n out: list[Item] = []\n for i, line in enumerate(lines, 1):\n s = line.strip()\n if not s:\n continue\n obj = json.loads(s)\n if not isinstance(obj, dict):\n raise ValueError(f\"line {i}: expected object\")\n name = obj.get(\"name\")\n qty = obj.get(\"qty\")\n if not isinstance(name, str) or not name:\n raise ValueError(f\"line {i}: name must be str\")\n if not isinstance(qty, int) or qty < 0:\n raise ValueError(f\"line {i}: qty must be non-negative int\")\n out.append(Item(name, qty))\n return out\n\nclass InventoryWriter:\n def __init__(self, base_dir: Path, store: Store | None = None) -> None:\n self._base = base_dir\n self._store: Store = store or FSStore()\n\n def write(self, rel_path: str, items: list[Item]) -> Path:\n dst = (self._base / rel_path).resolve()\n base = self._base.resolve()\n if dst != base and base not in dst.parents:\n raise ValueError(\"unsafe path traversal\")\n payload = json.dumps([item.__dict__ for item in items], ensure_ascii=False)\n self._store.write_text(dst, payload)\n return dst\n```\n\n```python\nimport json\nfrom pathlib import Path\nimport pytest\nfrom module_under_test import InventoryWriter, parse_items\n\ndef test_parse_items_valid():\n lines = [json.dumps({\"name\":\"x\",\"qty\":1})]\n assert parse_items(lines)[0].name == \"x\"\n\ndef test_writer_blocks_traversal(tmp_path: Path):\n w = InventoryWriter(tmp_path)\n with pytest.raises(ValueError):\n w.write(\"../evil.json\", [])\n```", "source": "WithinUsAI/python_GOD_coder_100k"} {"text": "Refactor a Python module used for ETL pipelines into a clean, extensible design.\nRequirements: outline the new architecture briefly, then provide the refactored code and tests.\nConstraints: must be memory-efficient, must handle Windows paths safely, must include type hints, must avoid global state.\nDifficulty: hard. Avoid quadratic behavior on large inputs.\n\nDeliverable: production-ready reference solution.\nArchitecture:\n- Public facade class coordinating concerns (parsing, validation, persistence)\n- Small pure functions for testability\n- No global state; dependency injection for filesystem I/O\n\n```python\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom pathlib import Path\nfrom typing import Protocol, Iterable\nimport json\n\nclass Store(Protocol):\n def write_text(self, path: Path, data: str) -> None: ...\n\nclass FSStore:\n def write_text(self, path: Path, data: str) -> None:\n path.parent.mkdir(parents=True, exist_ok=True)\n path.write_text(data, encoding=\"utf-8\")\n\n@dataclass(frozen=True, slots=True)\nclass Item:\n name: str\n qty: int\n\ndef parse_items(lines: Iterable[str]) -> list[Item]:\n out: list[Item] = []\n for i, line in enumerate(lines, 1):\n s = line.strip()\n if not s:\n continue\n obj = json.loads(s)\n if not isinstance(obj, dict):\n raise ValueError(f\"line {i}: expected object\")\n name = obj.get(\"name\")\n qty = obj.get(\"qty\")\n if not isinstance(name, str) or not name:\n raise ValueError(f\"line {i}: name must be str\")\n if not isinstance(qty, int) or qty < 0:\n raise ValueError(f\"line {i}: qty must be non-negative int\")\n out.append(Item(name, qty))\n return out\n\nclass InventoryWriter:\n def __init__(self, base_dir: Path, store: Store | None = None) -> None:\n self._base = base_dir\n self._store: Store = store or FSStore()\n\n def write(self, rel_path: str, items: list[Item]) -> Path:\n dst = (self._base / rel_path).resolve()\n base = self._base.resolve()\n if dst != base and base not in dst.parents:\n raise ValueError(\"unsafe path traversal\")\n payload = json.dumps([item.__dict__ for item in items], ensure_ascii=False)\n self._store.write_text(dst, payload)\n return dst\n```\n\n```python\nimport json\nfrom pathlib import Path\nimport pytest\nfrom module_under_test import InventoryWriter, parse_items\n\ndef test_parse_items_valid():\n lines = [json.dumps({\"name\":\"x\",\"qty\":1})]\n assert parse_items(lines)[0].name == \"x\"\n\ndef test_writer_blocks_traversal(tmp_path: Path):\n w = InventoryWriter(tmp_path)\n with pytest.raises(ValueError):\n w.write(\"../evil.json\", [])\n```", "source": "WithinUsAI/python_GOD_coder_100k"} {"text": "Create a comprehensive test plan and automated tests for idempotent payments in a fintech product.\nTarget platform: web (React + TypeScript).\nRequirements: unit/integration tests, edge cases, load tests strategy, and CI gates.\nConstraints: must include documentation/comments, must include clear error handling, must be secure-by-default, must be observable (logs/metrics/traces).\nDifficulty: easy. Assume PII must be protected.\n\nOutput: design + implementation guidance suitable for shipping.\nDeliverable: test plan + automation guidance.\n\n**Unit tests**\n- Validation: malformed payloads rejected with correct codes.\n- AuthZ: tenant boundary enforced.\n- Idempotency: replay returns same response; conflicting reuse yields 409.\n\n**Integration tests**\n- DB transaction behavior; unique constraints.\n- Cache behavior: correctness under concurrent requests.\n\n**Load tests**\n- 10k RPS target: measure p95 latency, error rate, saturation.\n\n**CI gates**\n- Lint + typecheck + unit tests required.\n- Coverage threshold for critical modules.\n- Block merge on flaky test detection.\n\n\nChecks: input validation, tests, and safe defaults included.", "source": "WithinUsAI/GOD_Coder_100k"} {"text": "Task type: supply_chain_security\nScenario: edge sync\nDomain focus: observability platforms\nPrimary language: typescript\nDifficulty: hard\nScale/SLO: p99 < 150ms\nComponent: component_iwgrqzqn\nConstraints: include backward compatibility and migration plan, avoid data races and undefined behavior, include deterministic replay plan, assume adversarial inputs; validate everything, include verification strategy, explicit contracts and invariants\nAssume strict auditability and replayable history.\nDeliverable: Design a supply-chain security plan: SBOM, signing, provenance, dependency policy, and CI gates.\n\nOutput: rigorous design + invariants + verification plan + implementation sketch.\n**Contract**\n- Inputs validated at the boundary; explicit error taxonomy.\n- Idempotency for side effects via request_id; deterministic replay.\n- Backward compatibility: additive changes by default; versioned breaking changes.\n**Invariants**\n- Safety: state transitions preserve invariants; no partial commit leaks.\n- Isolation: tenant boundary enforced; no cross-tenant reads/writes.\n- Liveness: under bounded faults and stable network, progress occurs.\n**Failure modes & recovery**\n- Crash during commit: WAL replay completes or transaction aborts; no torn writes.\n- Duplicate requests: de-duplicate by (tenant, request_id) returning cached response.\n- Network partition: minority cannot commit; clients receive retriable errors.\n**Security posture (defensive)**\n- Threat model: auth/authz, injection, replay/abuse, supply chain.\n- Least privilege; secrets in managed store; audit logs for sensitive ops.\n- Input normalization, parameterized queries, path traversal protections.\n**Verification strategy**\n- Fuzzing of parsers/framers/validators with corpus seeds.\n- Property tests against a pure reference model (state machine).\n- Deterministic simulation with fault injection (crash/partition/latency).\n\n**Snippet**\n```text\nImplementation sketch: factor pure state-machine core; adapters for I/O; add deterministic replay log.\n```\nHard checks: fault injection tests gate merges; perf thresholds enforced in CI.", "source": "WithinUsAI/Omega_Genesis_Coder_100k"} {"text": "Task type: mechanized_spec\nScenario: rate limit gateway\nDomain focus: zero-downtime migrations\nPrimary language: lean\nDifficulty: hard\nScale/SLO: p99 < 150ms\nComponent: component_uozexkiq\nConstraints: include test vectors and fuzz strategy, assume adversarial inputs; validate everything, include security threat model (defensive only), explicit contracts and invariants, include verification strategy, include failure modes and recovery\nAssume hostile inputs and targeted abuse patterns.\nDeliverable: Provide a mechanized-style spec outline (Lean-like), key definitions, and a proof plan. Include executable reference code skeleton and tests.\n\nOutput: contract-first solution with failure modes, security posture, and test/verification strategy.\n**Contract**\n- Inputs validated at the boundary; explicit error taxonomy.\n- Idempotency for side effects via request_id; deterministic replay.\n- Backward compatibility: additive changes by default; versioned breaking changes.\n**Invariants**\n- Safety: state transitions preserve invariants; no partial commit leaks.\n- Determinism: replay of the same event log yields identical outputs.\n- Isolation: tenant boundary enforced; no cross-tenant reads/writes.\n**Failure modes & recovery**\n- Duplicate requests: de-duplicate by (tenant, request_id) returning cached response.\n- Network partition: minority cannot commit; clients receive retriable errors.\n- Data corruption: checksums + scrubber; quarantine and rebuild from replicas/snapshots.\n**Security posture (defensive)**\n- Threat model: auth/authz, injection, replay/abuse, supply chain.\n- Least privilege; secrets in managed store; audit logs for sensitive ops.\n- Input normalization, parameterized queries, path traversal protections.\n**Verification strategy**\n- Canary + shadow traffic; invariants checked in production via assertions/metrics.\n- Fuzzing of parsers/framers/validators with corpus seeds.\n- Deterministic simulation with fault injection (crash/partition/latency).\n\n**Snippet**\n```lean\n-- Pseudo-Lean outline\nstructure State where\n ver : Nat\n val : Option ByteArray\n\ndef invariant (s : State) : Prop := True\n\ntheorem step_preserves_invariant :\n ∀ s, invariant s → ∀ s', Step s s' → invariant s' := by\n intro s hs s' hstep\n -- proof plan: case analysis on transition; trivial here\n trivial\n```\n\nHard checks: fault injection tests gate merges; perf thresholds enforced in CI.", "source": "WithinUsAI/Omega_Genesis_Coder_100k"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: Language: SQL\nFramework/tooling: PostgreSQL\nDomain: payments platform\nLogic challenge: optimistic locking conflict\nTask type: algorithmic_correctness\nDifficulty: hard\n\nReturn a rigorous engineering answer:\n- identify the hidden root cause or logical failure\n- present the corrected implementation\n- add tests that prove the fix\n- list verification commands\n- explain why naive fixes are insufficient when relevant\n\nRepository sketch:\nrepo/\n migrations/\n 001_init.sql\n 002_add_index.sql\n queries/\n report.sql\n tests/\n report_cases.md\n\nFocus: Focus on strong structured logic with edge cases, data validation, and concurrency safety.\n\nassistant: Diagnosis:\n- Root cause: the failure around optimistic locking conflict is caused by missing validation, weak edge-case handling, or unsafe lifecycle behavior in the current implementation.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```sql\nWITH ranked AS (\n SELECT\n user_id,\n created_at,\n amount,\n ROW_NUMBER() OVER (PARTITION BY user_id ORDER BY created_at DESC, id DESC) AS rn\n FROM orders\n)\nSELECT user_id, created_at, amount\nFROM ranked\nWHERE rn = 1;\n```\n\nTests:\n```sql\n-- Correctness checks:\n-- 1) multiple rows per user\n-- 2) identical timestamps require deterministic tie-breaker\n-- 3) null values handled by business rules\n```\n\nVerification:\n- `run migration checks`\n- `run query correctness cases`\n\nEngineering notes:\n- Language: SQL\n- Framework/tooling: PostgreSQL\n- Stack context: FastAPI, PostgreSQL, Redis, Celery, pytest, Docker\n- Domain: payments platform\n- Task type: algorithmic_correctness\n- Difficulty: hard\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Fix a bug and add tests.\n\nFile: wvd69ie23jx.py\n```python\ndef tlg5xk3u(n: int) -> int:\n \"\"\"Sum 1..n inclusive.\"\"\"\n if n < 0:\n raise ValueError(\"n must be non-negative\")\n total = 0\n for k in range(n): # BUG: should include n\n total += k\n return total\n```\n\nReturn unified diffs for wvd69ie23jx.py and test_wvd69ie23jx.py (pytest).\n\n*** Begin Patch\n*** Update File: wvd69ie23jx.py\n@@\n def tlg5xk3u(n: int) -> int:\n@@\n total = 0\n- for k in range(n): # BUG: should include n\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_wvd69ie23jx.py\n+import pytest\n+from wvd69ie23jx import tlg5xk3u\n+\n+def test_zero():\n+ assert tlg5xk3u(0) == 0\n+\n+def test_one():\n+ assert tlg5xk3u(1) == 1\n+\n+def test_small():\n+ assert tlg5xk3u(7) == 28\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ tlg5xk3u(-1)\n+\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Add a clear docstring and type hints to this function:\n\n```python\ndef f99050(s):\n return ''.join(x for x in s if x.isalnum()).lower()\n```\n\n```python\nfrom __future__ import annotations\n\ndef f99050(s: str) -> str:\n \"\"\"Normalize a string: keep only alphanumerics and lowercase the result.\"\"\"\n return \"\".join(ch for ch in s if ch.isalnum()).lower()\n```", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Build an elite-grade solution in the domain of edge/IoT for scenario: time-series metrics.\nPrimary language: rust.\nDifficulty: expert.\nConstraints: provide rollout and rollback guidance, design for backward compatibility and migrations, include invariants and failure modes, make the interface contract explicit, document performance characteristics.\nComponent: component_xkhvvyc.\nAssume crash-only design; recovery must be deterministic.\nTask: Define a small DSL, implement tokenizer/parser, IR, and a codegen or interpreter. Include tests and complexity notes.\n\nOutput: elite-grade engineering answer with contracts, edge cases, and verification.\nOutput: DSL + parser + IR + interpreter/codegen + tests.\n\n**DSL**\n- Expressions: integers, identifiers, `+ - * /`, let-binding: `let x = expr in expr`\n- Example: `let x = 2+3 in x*10`\n\n**Pipeline**\n1. Tokenize\n2. Parse into AST\n3. Lower into IR (stack ops) or interpret AST directly\n\n**Reference (Rust-style outline)**\n- `enum Expr { Int(i64), Var(String), Bin(Op, Box, Box), Let(String, Box, Box) }`\n- Parser: Pratt or recursive descent.\n\n**Tests**\n- Golden tests for parse trees.\n- Property: pretty-print(parse(x)) round-trips for a corpus.\n- Eval tests for precedence and scoping.\n\n\nExpert checks: state-machine reasoning, concurrency stress, and upgrade/rollback validated.", "source": "WithinUsAI/Elite_GOD_Coder_100k"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: Language: SQL\nFramework/tooling: DuckDB\nDomain: developer platform\nLogic challenge: unsafe deserialization\nTask type: transaction_integrity_fix\nDifficulty: hard\n\nReturn a rigorous engineering answer:\n- identify the hidden root cause or logical failure\n- present the corrected implementation\n- add tests that prove the fix\n- list verification commands\n- explain why naive fixes are insufficient when relevant\n\nRepository sketch:\nrepo/\n migrations/\n 001_init.sql\n 002_add_index.sql\n queries/\n report.sql\n tests/\n report_cases.md\n\nFocus: Focus on ambiguity, misleading symptoms, hidden root causes, and high-stakes debugging.\n\nassistant: Diagnosis:\n- Hidden root cause: unsafe deserialization presents misleading symptoms, so the patch must target the actual logic boundary rather than the first visible failure.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```sql\nWITH ranked AS (\n SELECT\n user_id,\n created_at,\n amount,\n ROW_NUMBER() OVER (PARTITION BY user_id ORDER BY created_at DESC, id DESC) AS rn\n FROM orders\n)\nSELECT user_id, created_at, amount\nFROM ranked\nWHERE rn = 1;\n```\n\nTests:\n```sql\n-- Correctness checks:\n-- 1) multiple rows per user\n-- 2) identical timestamps require deterministic tie-breaker\n-- 3) null values handled by business rules\n```\n\nVerification:\n- `run migration checks`\n- `run query correctness cases`\n\nEngineering notes:\n- Language: SQL\n- Framework/tooling: DuckDB\n- Stack context: Airflow, dbt, DuckDB, MinIO, pytest\n- Domain: developer platform\n- Task type: transaction_integrity_fix\n- Difficulty: hard\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "Debug and fix a subtle production bug related to idempotent payments in a fraud detection service.\nTarget platform: mobile (iOS Swift).\nRequirements: identify root cause, provide patch, and add regression tests.\nConstraints: must avoid global state, must include documentation/comments, must be performant under load, must include clear error handling.\nDifficulty: hard. Assume strict latency budget (p95 < 200ms).\n\nOutput: engineering-grade answer with edge cases covered.\nDeliverable: production-grade reference implementation (FastAPI) + tests.\n\n```python\n# app.py\nfrom __future__ import annotations\n\nimport hashlib\nimport json\nfrom dataclasses import dataclass\nfrom datetime import datetime, timezone\nfrom typing import Any, Optional\n\nfrom fastapi import FastAPI, Header, HTTPException\nfrom pydantic import BaseModel, Field\n\napp = FastAPI(title=\"Idempotent API\")\n\nclass CreateReq(BaseModel):\n tenant_id: str = Field(min_length=1)\n amount_cents: int = Field(ge=0)\n currency: str = Field(min_length=3, max_length=3)\n\nclass CreateResp(BaseModel):\n id: str\n created_at: str\n echo: CreateReq\n\n@dataclass\nclass _IdempoEntry:\n request_hash: str\n response_json: str\n\n# In production: Postgres table with UNIQUE(tenant_id, key)\n_IDEMPO: dict[tuple[str, str], _IdempoEntry] = {}\n\ndef _hash_req(req: CreateReq) -> str:\n raw = req.model_dump_json()\n return hashlib.sha256(raw.encode(\"utf-8\")).hexdigest()\n\n@app.post(\"/v1/payments\", response_model=CreateResp)\ndef create_payment(\n req: CreateReq,\n idempotency_key: Optional[str] = Header(default=None, alias=\"Idempotency-Key\"),\n) -> Any:\n if not idempotency_key:\n raise HTTPException(status_code=400, detail=\"Missing Idempotency-Key\")\n if len(idempotency_key) > 128:\n raise HTTPException(status_code=400, detail=\"Idempotency-Key too long\")\n\n key = (req.tenant_id, idempotency_key)\n rh = _hash_req(req)\n\n existing = _IDEMPO.get(key)\n if existing:\n if existing.request_hash != rh:\n raise HTTPException(status_code=409, detail=\"Idempotency-Key reuse with different payload\")\n return json.loads(existing.response_json)\n\n # Create new payment (stubbed)\n pid = hashlib.md5(f\"{req.tenant_id}:{idempotency_key}\".encode()).hexdigest()\n resp = CreateResp(\n id=pid,\n created_at=datetime.now(timezone.utc).isoformat(),\n echo=req,\n )\n _IDEMPO[key] = _IdempoEntry(request_hash=rh, response_json=resp.model_dump_json())\n return resp\n```\n\n```python\n# test_app.py (pytest)\nfrom fastapi.testclient import TestClient\nfrom app import app\n\nclient = TestClient(app)\n\ndef test_idempotent_replay():\n headers = {\"Idempotency-Key\": \"abc\"}\n body = {\"tenant_id\":\"t1\",\"amount_cents\":100,\"currency\":\"USD\"}\n r1 = client.post(\"/v1/payments\", json=body, headers=headers)\n r2 = client.post(\"/v1/payments\", json=body, headers=headers)\n assert r1.status_code == 200 and r2.status_code == 200\n assert r1.json() == r2.json()\n\ndef test_payload_conflict():\n headers = {\"Idempotency-Key\": \"abc\"}\n b1 = {\"tenant_id\":\"t1\",\"amount_cents\":100,\"currency\":\"USD\"}\n b2 = {\"tenant_id\":\"t1\",\"amount_cents\":200,\"currency\":\"USD\"}\n assert client.post(\"/v1/payments\", json=b1, headers=headers).status_code == 200\n assert client.post(\"/v1/payments\", json=b2, headers=headers).status_code == 409\n```\n\nNotes:\n- Replace in-memory store with a DB table and transaction.\n- Store response + request hash to detect key reuse with different payload.\n\n\nHard-mode checks: concurrency safety, idempotency, and rollback validated; add chaos tests where feasible.", "source": "WithinUsAI/GOD_Coder_100k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Refactor to modern typed Python with immutability and tests.\n\nFile: fg97bqo6tapf.py\n```python\nclass Pik0C4A5:\n def __init__(self, name, values):\n self.name = name\n self.values = list(values)\n def add(self, v):\n self.values.append(v)\n def mean(self):\n s = 0\n for x in self.values:\n s += x\n return s / len(self.values)\n```\n\nReturn full new fg97bqo6tapf.py and test_fg97bqo6tapf.py.\n\n# fg97bqo6tapf.py\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom typing import Iterable, Tuple\n\n@dataclass(frozen=True)\nclass Pik0C4A5:\n name: str\n values: Tuple[float, ...]\n\n @staticmethod\n def create(name: str, values: Iterable[float]) -> \"Pik0C4A5\":\n vals = tuple(float(v) for v in values)\n if not vals:\n raise ValueError(\"values must be non-empty\")\n return Pik0C4A5(name=name, values=vals)\n\n def add(self, v: float) -> \"Pik0C4A5\":\n return Pik0C4A5(name=self.name, values=self.values + (float(v),))\n\n def mean(self) -> float:\n return sum(self.values) / len(self.values)\n\n# test_fg97bqo6tapf.py\nimport pytest\nfrom fg97bqo6tapf import Pik0C4A5\n\ndef test_mean_and_add():\n c = Pik0C4A5.create(\"a\", [1, 2, 3])\n assert c.mean() == 2.0\n assert c.add(5).mean() == (1 + 2 + 3 + 5) / 4\n\ndef test_empty_raises():\n with pytest.raises(ValueError):\n Pik0C4A5.create(\"x\", [])", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Fix the bug and add pytest tests.\n\n```python\ndef f95448(n: int) -> int:\n # sum 1..n inclusive\n if n < 0: raise ValueError\n total = 0\n for k in range(n): # BUG\n total += k\n return total\n```\nReturn unified diffs for `m85064.py` and `test_m85064.py`.\n\n*** Begin Patch\n*** Update File: m85064.py\n@@\n def f95448(n: int) -> int:\n@@\n- for k in range(n): # BUG\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_m85064.py\n+import pytest\n+from m85064 import f95448\n+\n+def test_small():\n+ assert f95448(7) == 28\n+\n+def test_zero():\n+ assert f95448(0) == 0\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ f95448(-1)\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Design and implement an algorithm for rate limiting.\nRequirements: define inputs/outputs, implement solution with complexity analysis, and include tests.\nConstraints: must be streaming-friendly, must be memory-efficient, must handle Windows paths safely, must avoid global state.\nDifficulty: easy. Guarantee deterministic output ordering.\n\nDeliverable: corrected code and verification tests.\nProblem: compute rolling sums over events (ts:int,value:int) with window W seconds. Events may be out-of-order.\n\nComplexity: sorting O(n log n); window maintenance O(n); memory O(k).\n\n```python\nfrom __future__ import annotations\nfrom collections import deque\nfrom dataclasses import dataclass\nfrom typing import Iterable, List, Tuple\n\n@dataclass(frozen=True, slots=True)\nclass Event:\n ts: int\n value: int\n\ndef rolling_sum(events: Iterable[Event], window_s: int) -> List[Tuple[int,int]]:\n if window_s < 0:\n raise ValueError(\"window_s must be >= 0\")\n evs = sorted(events, key=lambda e: e.ts)\n q: deque[Event] = deque()\n s = 0\n out: List[Tuple[int,int]] = []\n for e in evs:\n q.append(e)\n s += e.value\n cutoff = e.ts - window_s\n while q and q[0].ts < cutoff:\n old = q.popleft()\n s -= old.value\n out.append((e.ts, s))\n return out\n```\n\n```python\nimport pytest\nfrom module_under_test import Event, rolling_sum\n\ndef test_rolling_sum():\n ev = [Event(10,1), Event(11,2), Event(20,5)]\n assert rolling_sum(ev, 5) == [(10,1),(11,3),(20,5)]\n```", "source": "WithinUsAI/python_GOD_coder_100k"} {"text": "Build an elite-grade solution in the domain of sre/observability for scenario: edge sync.\nPrimary language: sql.\nDifficulty: medium.\nConstraints: include invariants and failure modes, avoid undefined behavior and data races, provide rollout and rollback guidance, include tests or verification strategy, design for backward compatibility and migrations.\nComponent: component_cgnpmwk.\nAssume schema changes every sprint; must be backward compatible.\nTask: Write a precise interface contract, list invariants, and provide a lightweight formal/spec-style description (pseudo-TLA+/state machine) plus reference implementation skeleton and tests.\n\nOutput: rigorous solution with invariants, failure modes, and performance notes.\nOutput: contract + invariants + spec + reference skeleton.\n\n**Interface contract**\n- Commands: `Put(key, value, expected_version?)`, `Get(key)`, `Delete(key, expected_version?)`\n- Responses: `Ok(version, value?)`, `NotFound`, `Conflict(current_version)`, `InvalidInput`\n- Idempotency: client supplies `request_id`; server must de-duplicate per (tenant_id, request_id).\n\n**Invariants**\n1. Monotonic version per key (strictly increases on successful writes).\n2. Reads return latest committed value for a given consistency level.\n3. Exactly-once effect for a given `request_id` (at-most-once execution + replay response).\n4. Tenant isolation: keys are scoped by tenant_id.\n\n**State machine (pseudo)**\nState:\n- store: map[(tenant,key)] -> (version:int, value:bytes|tombstone)\n- seen: map[(tenant,request_id)] -> response\nTransition Put:\n- if request_id in seen: return seen[...]\n- validate input; if expected_version set and != current version -> Conflict\n- version' = version + 1; store[...] := (version', value); seen[...] := Ok(version', value)\n\n**Reference skeleton (Python)**\n```python\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom typing import Dict, Optional, Tuple\n\nclass Conflict(Exception): pass\nclass InvalidInput(ValueError): pass\n\n@dataclass(frozen=True, slots=True)\nclass Value:\n version: int\n data: Optional[bytes] # None == tombstone\n\n@dataclass(frozen=True, slots=True)\nclass Reply:\n kind: str\n version: Optional[int] = None\n data: Optional[bytes] = None\n\nclass KV:\n def __init__(self) -> None:\n self._store: Dict[Tuple[str,str], Value] = {}\n self._seen: Dict[Tuple[str,str], Reply] = {}\n\n def put(self, tenant: str, request_id: str, key: str, data: bytes, expected_version: Optional[int]=None) -> Reply:\n if not tenant or not request_id or not key:\n raise InvalidInput(\"tenant/request_id/key required\")\n de = self._seen.get((tenant, request_id))\n if de: \n return de\n cur = self._store.get((tenant, key), Value(0, None))\n if expected_version is not None and expected_version != cur.version:\n r = Reply(\"conflict\", version=cur.version)\n self._seen[(tenant, request_id)] = r\n return r\n nxt = Value(cur.version + 1, data)\n self._store[(tenant, key)] = nxt\n r = Reply(\"ok\", version=nxt.version)\n self._seen[(tenant, request_id)] = r\n return r\n```\n\n**Tests**\n- Determinism: same request_id → same reply.\n- Conflict detection and version monotonicity.\n\n\nChecks: boundary validation and deterministic behavior verified.", "source": "WithinUsAI/Elite_GOD_Coder_100k"} {"text": "Design CI/CD for a IoT telemetry service delivering multi-tenant isolation.\nTarget platform: backend (Python FastAPI).\nRequirements: pipelines, checks, artifact strategy, deployments, and rollbacks.\nConstraints: must be secure-by-default, must be easy to extend, must include type hints where applicable, must be performant under load, must include tests.\nDifficulty: easy. Assume 10k RPS peak traffic.\n\nOutput: actionable implementation and verification artifacts.\nDeliverable: CI/CD pipeline (GitHub Actions) with quality gates.\n\n```yaml\nname: ci\non:\n pull_request:\n push:\n branches: [main]\n\njobs:\n test:\n runs-on: ubuntu-latest\n steps:\n - uses: actions/checkout@v4\n - uses: actions/setup-python@v5\n with:\n python-version: \"3.11\"\n - run: python -m pip install -U pip\n - run: pip install -r requirements.txt\n - run: pip install -r requirements-dev.txt\n - run: ruff check .\n - run: mypy .\n - run: pytest -q --maxfail=1 --disable-warnings\n\n docker:\n needs: test\n runs-on: ubuntu-latest\n steps:\n - uses: actions/checkout@v4\n - uses: docker/setup-buildx-action@v3\n - run: docker build -t app:${{ github.sha }} .\n```\n\nDeployment strategy:\n- main → build → deploy to staging → smoke tests → canary to prod.\n- Rollback: redeploy previous image + DB migration rollback plan.\n\n\nChecks: input validation, tests, and safe defaults included.", "source": "WithinUsAI/GOD_Coder_100k"} {"text": "Refactor to typed, mostly-immutable Python and add minimal tests.\n\n```python\nclass C60374:\n def __init__(self, values): self.values=list(values)\n def mean(self): return sum(self.values)/len(self.values)\n```\nReturn `m50798.py` and `test_m50798.py`.\n\n```python\n# m50798.py\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom typing import Iterable, Tuple\n\n@dataclass(frozen=True)\nclass C60374:\n values: Tuple[float, ...]\n\n @staticmethod\n def create(values: Iterable[float]) -> \"C60374\":\n vals = tuple(float(v) for v in values)\n if not vals: raise ValueError(\"empty\")\n return C60374(vals)\n\n def mean(self) -> float:\n return sum(self.values)/len(self.values)\n```\n\n```python\n# test_m50798.py\nimport pytest\nfrom m50798 import C60374\n\ndef test_mean():\n assert C60374.create([1,2,3]).mean() == 2.0\ndef test_empty():\n with pytest.raises(ValueError):\n C60374.create([])\n```", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Optimize while preserving behavior and order.\n\n```python\ndef f08899(xs):\n out=[]\n for x in xs:\n if x not in out: out.append(x)\n return out\n```\nReturn `m15557.py` with types and O(n) average.\n\n```python\n# m15557.py\nfrom __future__ import annotations\nfrom typing import Iterable, List, Set, TypeVar\nT=TypeVar(\"T\")\n\ndef f08899(xs: Iterable[T]) -> List[T]:\n \"\"\"Unique items preserving first-seen order.\"\"\"\n seen: Set[T]=set()\n out: List[T]=[]\n for x in xs:\n if x in seen: continue\n seen.add(x); out.append(x)\n return out\n```", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Build an elite-grade solution in the domain of databases for scenario: multi-tenant SaaS.\nPrimary language: python.\nDifficulty: expert.\nConstraints: make the interface contract explicit, provide rollout and rollback guidance, include invariants and failure modes.\nComponent: component_avhkhjv.\nAssume schema changes every sprint; must be backward compatible.\nTask: Design an application-level protocol (framing, retries, timeouts, backpressure). Provide client/server skeleton and test vectors.\n\nOutput: rigorous solution with invariants, failure modes, and performance notes.\nOutput: protocol framing + retry policy + client/server skeleton.\n\n**Framing**\n- Length-prefixed: uint32_be length + payload\n- Payload: msgpack/json; include request_id, type, and optional checksum\n\n**Reliability**\n- Retries only for idempotent ops; exponential backoff + jitter.\n- Timeouts: connect, read, overall; enforce max in-flight to provide backpressure.\n\n**Test vectors**\n- Corrupted length / truncated frame rejected\n- Duplicate request_id returns cached response\n- Slowloris protection by read deadlines\n\n\nExpert checks: state-machine reasoning, concurrency stress, and upgrade/rollback validated.", "source": "WithinUsAI/Elite_GOD_Coder_100k"} {"text": "Task type: static_analyzer\nScenario: time-series metrics store\nDomain focus: fault injection & chaos engineering\nPrimary language: rust\nDifficulty: expert+\nScale/SLO: p99 < 50ms\nComponent: component_fogtlwcu\nConstraints: include deterministic replay plan, include verification strategy, explicit contracts and invariants, assume adversarial inputs; validate everything, include failure modes and recovery\nAssume weekly network partitions.\nDeliverable: Design a static analyzer for a safety property (e.g., taint/SQLi prevention); include rule set, false-positive strategy, and tests.\n\nOutput: contract-first solution with failure modes, security posture, and test/verification strategy.\n**Contract**\n- Inputs validated at the boundary; explicit error taxonomy.\n- Idempotency for side effects via request_id; deterministic replay.\n- Backward compatibility: additive changes by default; versioned breaking changes.\n**Invariants**\n- Liveness: under bounded faults and stable network, progress occurs.\n- Isolation: tenant boundary enforced; no cross-tenant reads/writes.\n- Determinism: replay of the same event log yields identical outputs.\n**Failure modes & recovery**\n- Data corruption: checksums + scrubber; quarantine and rebuild from replicas/snapshots.\n- Network partition: minority cannot commit; clients receive retriable errors.\n- Duplicate requests: de-duplicate by (tenant, request_id) returning cached response.\n**Security posture (defensive)**\n- Threat model: auth/authz, injection, replay/abuse, supply chain.\n- Least privilege; secrets in managed store; audit logs for sensitive ops.\n- Input normalization, parameterized queries, path traversal protections.\n**Verification strategy**\n- Fuzzing of parsers/framers/validators with corpus seeds.\n- Canary + shadow traffic; invariants checked in production via assertions/metrics.\n- Property tests against a pure reference model (state machine).\n\n**Snippet**\n```text\nImplementation sketch: factor pure state-machine core; adapters for I/O; add deterministic replay log.\n```\nExpert+ checks: mechanized invariants (or exhaustive model checking), adversarial fuzzing, and multi-region failure drills.", "source": "WithinUsAI/Omega_Genesis_Coder_100k"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: Language: Java\nFramework/tooling: Maven\nDomain: reporting engine\nLogic challenge: partial checkpoint corruption\nTask type: multi_file_migration_repair\nDifficulty: hard\n\nReturn a rigorous engineering answer:\n- identify the hidden root cause or logical failure\n- present the corrected implementation\n- add tests that prove the fix\n- list verification commands\n- explain why naive fixes are insufficient when relevant\n\nRepository sketch:\nrepo/\n src/main/java/com/acme/App.java\n src/main/java/com/acme/Service.java\n src/test/java/com/acme/AppTest.java\n pom.xml\n\nFocus: Focus on staff-level problem solving with multi-file patches, rollout implications, performance and security tradeoffs.\n\nassistant: Diagnosis:\n- Staff-level diagnosis: partial checkpoint corruption impacts correctness, operability, and future maintenance, so the fix must be minimal where possible but complete where necessary.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```java\nimport java.util.HashMap;\nimport java.util.Map;\n\npublic final class RequestHandler {\n public static Map handleRequest(Map payload) {\n Map clean = new HashMap<>();\n for (Map.Entry entry : payload.entrySet()) {\n if (entry.getValue() != null) clean.put(entry.getKey().trim(), entry.getValue());\n }\n if (!clean.containsKey(\"id\")) throw new IllegalArgumentException(\"missing id\");\n return Map.of(\"ok\", true, \"data\", clean);\n }\n}\n```\n\nTests:\n```java\nimport static org.junit.jupiter.api.Assertions.*;\nimport java.util.Map;\nimport org.junit.jupiter.api.Test;\n\nclass RequestHandlerTest {\n @Test\n void requiresId() {\n assertThrows(IllegalArgumentException.class, () -> RequestHandler.handleRequest(Map.of(\"name\", \"x\")));\n }\n}\n```\n\nVerification:\n- `./gradlew test`\n- `mvn test`\n\nEngineering notes:\n- Language: Java\n- Framework/tooling: Maven\n- Stack context: ASP.NET Core, SQL Server, EF Core, xUnit, Docker\n- Domain: reporting engine\n- Task type: multi_file_migration_repair\n- Difficulty: hard\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: Project stack: FastAPI, PostgreSQL, Redis, Celery, pytest, Docker\nLanguage: C#\nDependency challenge: stale cache invalidation\nTask type: build_reproducibility_fix\nDifficulty: medium\n\nFix this as a senior engineer.\nRequired:\n- identify the version or compatibility failure mode\n- produce the corrected config/code/build patch\n- explain rollback-safe migration notes\n- add regression tests or reproducibility checks\n- include concrete verification commands\n\nRepository sketch:\nrepo/\n src/App/Program.cs\n src/App/Service.cs\n tests/App.Tests/ServiceTests.cs\n App.sln\n\nFocus: Focus on versioning, migrations, lockfiles, runtime compatibility, and secure dependency handling.\n\nassistant: Diagnosis:\n- Root cause: the issue around stale cache invalidation is a dependency, migration, or runtime-compatibility mismatch that needs a rollback-safe patch.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```csharp\nusing System;\nusing System.Collections.Generic;\n\npublic static class RequestHandler\n{\n public static Dictionary HandleRequest(Dictionary payload)\n {\n var clean = new Dictionary();\n foreach (var entry in payload)\n {\n if (entry.Value != null)\n clean[entry.Key.Trim()] = entry.Value;\n }\n if (!clean.ContainsKey(\"id\"))\n throw new ArgumentException(\"missing id\");\n return new Dictionary\n {\n [\"ok\"] = true,\n [\"data\"] = clean\n };\n }\n}\n```\n\nTests:\n```csharp\nusing System;\nusing System.Collections.Generic;\nusing Xunit;\n\npublic class RequestHandlerTests\n{\n [Fact]\n public void RequiresId()\n {\n Assert.Throws(() => RequestHandler.HandleRequest(new Dictionary { [\"name\"] = \"x\" }));\n }\n}\n```\n\nVerification:\n- `dotnet test`\n- `dotnet build`\n\nEngineering notes:\n- Language: C#\n- Framework/tooling: xUnit\n- Stack context: FastAPI, PostgreSQL, Redis, Celery, pytest, Docker\n- Domain: repo automation\n- Task type: build_reproducibility_fix\n- Difficulty: medium\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "Fix the bug and add pytest tests.\n\n```python\ndef f97650(n: int) -> int:\n # sum 1..n inclusive\n if n < 0: raise ValueError\n total = 0\n for k in range(n): # BUG\n total += k\n return total\n```\nReturn unified diffs for `m13950.py` and `test_m13950.py`.\n\n*** Begin Patch\n*** Update File: m13950.py\n@@\n def f97650(n: int) -> int:\n@@\n- for k in range(n): # BUG\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_m13950.py\n+import pytest\n+from m13950 import f97650\n+\n+def test_small():\n+ assert f97650(7) == 28\n+\n+def test_zero():\n+ assert f97650(0) == 0\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ f97650(-1)\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Implement a concurrent Python solution for metrics aggregation.\nRequirements: choose appropriate concurrency model, handle cancellation/timeouts, include tests.\nConstraints: must include docstrings, must be easy to extend.\nDifficulty: hard. Avoid quadratic behavior on large inputs.\n\nDeliverable: corrected code and verification tests.\n```python\nfrom __future__ import annotations\nimport asyncio\nfrom dataclasses import dataclass\nfrom typing import Awaitable, Callable, Iterable, Optional\n\n@dataclass(frozen=True, slots=True)\nclass JobResult:\n ok: bool\n value: Optional[int]\n error: Optional[str]\n\nasync def run_bounded(\n factories: Iterable[Callable[[], Awaitable[int]]],\n *,\n limit: int = 10,\n timeout_s: float = 5.0,\n) -> list[JobResult]:\n if limit <= 0:\n raise ValueError(\"limit must be > 0\")\n sem = asyncio.Semaphore(limit)\n results: list[JobResult] = []\n\n async def one(factory: Callable[[], Awaitable[int]]) -> None:\n async with sem:\n try:\n v = await asyncio.wait_for(factory(), timeout=timeout_s)\n results.append(JobResult(True, v, None))\n except Exception as e:\n results.append(JobResult(False, None, str(e)))\n\n tasks = [asyncio.create_task(one(f)) for f in factories]\n try:\n await asyncio.gather(*tasks)\n finally:\n for t in tasks:\n if not t.done():\n t.cancel()\n return results\n```\n\n```python\nimport asyncio\nimport pytest\nfrom module_under_test import run_bounded\n\n@pytest.mark.asyncio\nasync def test_run_bounded_collects():\n async def work(x: int) -> int:\n await asyncio.sleep(0.01)\n return x\n fs = [(lambda i=i: work(i)) for i in range(30)]\n out = await run_bounded(fs, limit=5, timeout_s=1.0)\n assert len(out) == 30\n assert all(r.ok for r in out)\n```", "source": "WithinUsAI/python_GOD_coder_100k"} {"text": "Build an elite-grade solution in the domain of distributed systems for scenario: inventory & ordering.\nPrimary language: python.\nDifficulty: hard.\nConstraints: design for backward compatibility and migrations, make the interface contract explicit, include tests or verification strategy, document performance characteristics.\nComponent: component_ztcqves.\nAssume cold-start and memory limits are tight.\nTask: Design an application-level protocol (framing, retries, timeouts, backpressure). Provide client/server skeleton and test vectors.\n\nOutput: production blueprint plus correctness arguments and test strategy.\nOutput: protocol framing + retry policy + client/server skeleton.\n\n**Framing**\n- Length-prefixed: uint32_be length + payload\n- Payload: msgpack/json; include request_id, type, and optional checksum\n\n**Reliability**\n- Retries only for idempotent ops; exponential backoff + jitter.\n- Timeouts: connect, read, overall; enforce max in-flight to provide backpressure.\n\n**Test vectors**\n- Corrupted length / truncated frame rejected\n- Duplicate request_id returns cached response\n- Slowloris protection by read deadlines\n\n\nHard checks: failure injection tests and performance regressions gated.", "source": "WithinUsAI/Elite_GOD_Coder_100k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Fix a bug and add tests.\n\nFile: p0ve62.py\n```python\ndef cv2havb23hxr(n: int) -> int:\n \"\"\"Sum 1..n inclusive.\"\"\"\n if n < 0:\n raise ValueError(\"n must be non-negative\")\n total = 0\n for k in range(n): # BUG: should include n\n total += k\n return total\n```\n\nReturn unified diffs for p0ve62.py and test_p0ve62.py (pytest).\n\n*** Begin Patch\n*** Update File: p0ve62.py\n@@\n def cv2havb23hxr(n: int) -> int:\n@@\n total = 0\n- for k in range(n): # BUG: should include n\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_p0ve62.py\n+import pytest\n+from p0ve62 import cv2havb23hxr\n+\n+def test_zero():\n+ assert cv2havb23hxr(0) == 0\n+\n+def test_one():\n+ assert cv2havb23hxr(1) == 1\n+\n+def test_small():\n+ assert cv2havb23hxr(7) == 28\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ cv2havb23hxr(-1)\n+\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Debug and fix a subtle production bug related to webhooks in a fraud detection service.\nTarget platform: ML (PyTorch + serving).\nRequirements: identify root cause, provide patch, and add regression tests.\nConstraints: must be production-ready, must include type hints where applicable, must include clear error handling, must be secure-by-default, must be easy to extend.\nDifficulty: easy. Assume schema evolves frequently; design for migrations.\n\nOutput: production-oriented blueprint with code where appropriate.\nDeliverable: production-grade reference implementation (FastAPI) + tests.\n\n```python\n# app.py\nfrom __future__ import annotations\n\nimport hashlib\nimport json\nfrom dataclasses import dataclass\nfrom datetime import datetime, timezone\nfrom typing import Any, Optional\n\nfrom fastapi import FastAPI, Header, HTTPException\nfrom pydantic import BaseModel, Field\n\napp = FastAPI(title=\"Idempotent API\")\n\nclass CreateReq(BaseModel):\n tenant_id: str = Field(min_length=1)\n amount_cents: int = Field(ge=0)\n currency: str = Field(min_length=3, max_length=3)\n\nclass CreateResp(BaseModel):\n id: str\n created_at: str\n echo: CreateReq\n\n@dataclass\nclass _IdempoEntry:\n request_hash: str\n response_json: str\n\n# In production: Postgres table with UNIQUE(tenant_id, key)\n_IDEMPO: dict[tuple[str, str], _IdempoEntry] = {}\n\ndef _hash_req(req: CreateReq) -> str:\n raw = req.model_dump_json()\n return hashlib.sha256(raw.encode(\"utf-8\")).hexdigest()\n\n@app.post(\"/v1/payments\", response_model=CreateResp)\ndef create_payment(\n req: CreateReq,\n idempotency_key: Optional[str] = Header(default=None, alias=\"Idempotency-Key\"),\n) -> Any:\n if not idempotency_key:\n raise HTTPException(status_code=400, detail=\"Missing Idempotency-Key\")\n if len(idempotency_key) > 128:\n raise HTTPException(status_code=400, detail=\"Idempotency-Key too long\")\n\n key = (req.tenant_id, idempotency_key)\n rh = _hash_req(req)\n\n existing = _IDEMPO.get(key)\n if existing:\n if existing.request_hash != rh:\n raise HTTPException(status_code=409, detail=\"Idempotency-Key reuse with different payload\")\n return json.loads(existing.response_json)\n\n # Create new payment (stubbed)\n pid = hashlib.md5(f\"{req.tenant_id}:{idempotency_key}\".encode()).hexdigest()\n resp = CreateResp(\n id=pid,\n created_at=datetime.now(timezone.utc).isoformat(),\n echo=req,\n )\n _IDEMPO[key] = _IdempoEntry(request_hash=rh, response_json=resp.model_dump_json())\n return resp\n```\n\n```python\n# test_app.py (pytest)\nfrom fastapi.testclient import TestClient\nfrom app import app\n\nclient = TestClient(app)\n\ndef test_idempotent_replay():\n headers = {\"Idempotency-Key\": \"abc\"}\n body = {\"tenant_id\":\"t1\",\"amount_cents\":100,\"currency\":\"USD\"}\n r1 = client.post(\"/v1/payments\", json=body, headers=headers)\n r2 = client.post(\"/v1/payments\", json=body, headers=headers)\n assert r1.status_code == 200 and r2.status_code == 200\n assert r1.json() == r2.json()\n\ndef test_payload_conflict():\n headers = {\"Idempotency-Key\": \"abc\"}\n b1 = {\"tenant_id\":\"t1\",\"amount_cents\":100,\"currency\":\"USD\"}\n b2 = {\"tenant_id\":\"t1\",\"amount_cents\":200,\"currency\":\"USD\"}\n assert client.post(\"/v1/payments\", json=b1, headers=headers).status_code == 200\n assert client.post(\"/v1/payments\", json=b2, headers=headers).status_code == 409\n```\n\nNotes:\n- Replace in-memory store with a DB table and transaction.\n- Store response + request hash to detect key reuse with different payload.\n\n\nChecks: input validation, tests, and safe defaults included.", "source": "WithinUsAI/GOD_Coder_100k"} {"text": "Build an elite-grade solution in the domain of sre/observability for scenario: edge sync.\nPrimary language: rust.\nDifficulty: medium.\nConstraints: provide rollout and rollback guidance, assume untrusted inputs; validate and sanitize, design for backward compatibility and migrations.\nComponent: component_zrhdaes.\nAssume compliance requires data deletion with proofs.\nTask: Define properties/invariants and implement property-based tests (or generative tests) with a reference model and edge-case generators.\n\nOutput: rigorous solution with invariants, failure modes, and performance notes.\nOutput: properties + reference model + generative tests.\n\n**Properties**\n- Idempotency: replayed command yields same result.\n- Monotonicity: versions only increase.\n- Conservation: for queues, produced items == consumed items (multiset) under no-loss assumption.\n\n**Approach**\n- Write a small reference model (pure function).\n- Generate random sequences of operations; compare implementation outputs to model.\n\n\nChecks: boundary validation and deterministic behavior verified.", "source": "WithinUsAI/Elite_GOD_Coder_100k"} {"text": "Refactor a Python module used for caching layer into a clean, extensible design.\nRequirements: outline the new architecture briefly, then provide the refactored code and tests.\nConstraints: must include type hints, must provide clear error messages, must avoid global state.\nDifficulty: easy. Handle empty inputs and malformed records gracefully.\n\nDeliverable: corrected code and verification tests.\nArchitecture:\n- Public facade class coordinating concerns (parsing, validation, persistence)\n- Small pure functions for testability\n- No global state; dependency injection for filesystem I/O\n\n```python\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom pathlib import Path\nfrom typing import Protocol, Iterable\nimport json\n\nclass Store(Protocol):\n def write_text(self, path: Path, data: str) -> None: ...\n\nclass FSStore:\n def write_text(self, path: Path, data: str) -> None:\n path.parent.mkdir(parents=True, exist_ok=True)\n path.write_text(data, encoding=\"utf-8\")\n\n@dataclass(frozen=True, slots=True)\nclass Item:\n name: str\n qty: int\n\ndef parse_items(lines: Iterable[str]) -> list[Item]:\n out: list[Item] = []\n for i, line in enumerate(lines, 1):\n s = line.strip()\n if not s:\n continue\n obj = json.loads(s)\n if not isinstance(obj, dict):\n raise ValueError(f\"line {i}: expected object\")\n name = obj.get(\"name\")\n qty = obj.get(\"qty\")\n if not isinstance(name, str) or not name:\n raise ValueError(f\"line {i}: name must be str\")\n if not isinstance(qty, int) or qty < 0:\n raise ValueError(f\"line {i}: qty must be non-negative int\")\n out.append(Item(name, qty))\n return out\n\nclass InventoryWriter:\n def __init__(self, base_dir: Path, store: Store | None = None) -> None:\n self._base = base_dir\n self._store: Store = store or FSStore()\n\n def write(self, rel_path: str, items: list[Item]) -> Path:\n dst = (self._base / rel_path).resolve()\n base = self._base.resolve()\n if dst != base and base not in dst.parents:\n raise ValueError(\"unsafe path traversal\")\n payload = json.dumps([item.__dict__ for item in items], ensure_ascii=False)\n self._store.write_text(dst, payload)\n return dst\n```\n\n```python\nimport json\nfrom pathlib import Path\nimport pytest\nfrom module_under_test import InventoryWriter, parse_items\n\ndef test_parse_items_valid():\n lines = [json.dumps({\"name\":\"x\",\"qty\":1})]\n assert parse_items(lines)[0].name == \"x\"\n\ndef test_writer_blocks_traversal(tmp_path: Path):\n w = InventoryWriter(tmp_path)\n with pytest.raises(ValueError):\n w.write(\"../evil.json\", [])\n```", "source": "WithinUsAI/python_GOD_coder_100k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Fix a bug and add tests.\n\nFile: w4h22rzmlx0.py\n```python\ndef bur85h(n: int) -> int:\n \"\"\"Sum 1..n inclusive.\"\"\"\n if n < 0:\n raise ValueError(\"n must be non-negative\")\n total = 0\n for k in range(n): # BUG: should include n\n total += k\n return total\n```\n\nReturn unified diffs for w4h22rzmlx0.py and test_w4h22rzmlx0.py (pytest).\n\n*** Begin Patch\n*** Update File: w4h22rzmlx0.py\n@@\n def bur85h(n: int) -> int:\n@@\n total = 0\n- for k in range(n): # BUG: should include n\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_w4h22rzmlx0.py\n+import pytest\n+from w4h22rzmlx0 import bur85h\n+\n+def test_zero():\n+ assert bur85h(0) == 0\n+\n+def test_one():\n+ assert bur85h(1) == 1\n+\n+def test_small():\n+ assert bur85h(7) == 28\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ bur85h(-1)\n+\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Task type: smt_constraint_model\nScenario: identity and access\nDomain focus: stream processing\nPrimary language: smtlib\nDifficulty: expert\nScale/SLO: multi-region active-active\nComponent: component_vxymoayt\nConstraints: avoid data races and undefined behavior, include security threat model (defensive only), include test vectors and fuzz strategy, include failure modes and recovery, include verification strategy, include backward compatibility and migration plan\nAssume tight memory budget and cold-start constraints.\nDeliverable: Provide an SMT constraint model (or Python-to-SMT) for correctness/optimization; include sample instances and how to validate solutions.\n\nOutput: rigorous design + invariants + verification plan + implementation sketch.\n**Contract**\n- Inputs validated at the boundary; explicit error taxonomy.\n- Idempotency for side effects via request_id; deterministic replay.\n- Backward compatibility: additive changes by default; versioned breaking changes.\n**Invariants**\n- Safety: state transitions preserve invariants; no partial commit leaks.\n- Liveness: under bounded faults and stable network, progress occurs.\n- Determinism: replay of the same event log yields identical outputs.\n**Failure modes & recovery**\n- Duplicate requests: de-duplicate by (tenant, request_id) returning cached response.\n- Network partition: minority cannot commit; clients receive retriable errors.\n- Crash during commit: WAL replay completes or transaction aborts; no torn writes.\n**Security posture (defensive)**\n- Threat model: auth/authz, injection, replay/abuse, supply chain.\n- Least privilege; secrets in managed store; audit logs for sensitive ops.\n- Input normalization, parameterized queries, path traversal protections.\n**Verification strategy**\n- Property tests against a pure reference model (state machine).\n- Deterministic simulation with fault injection (crash/partition/latency).\n- Fuzzing of parsers/framers/validators with corpus seeds.\n\n**Snippet**\n```smtlib\n; Find an assignment minimizing cost while satisfying constraints\n(declare-const x Int)\n(declare-const y Int)\n(assert (and (>= x 0) (>= y 0) (<= (+ x y) 10)))\n(minimize (+ (* 3 x) (* 2 y)))\n(check-sat)\n(get-model)\n```\n\nExpert checks: state-machine proof sketch + model checking; upgrade/rollback rehearsed.", "source": "WithinUsAI/Omega_Genesis_Coder_100k"} {"text": "Build an elite-grade solution in the domain of networking for scenario: feature flagging.\nPrimary language: rust.\nDifficulty: hard.\nConstraints: include tests or verification strategy, provide rollout and rollback guidance, make the interface contract explicit.\nComponent: component_dixwpvb.\nAssume crash-only design; recovery must be deterministic.\nTask: Design a replication/consistency approach (e.g., leader-based, quorum reads/writes). Provide message flows, failure handling, and a minimal reference implementation skeleton.\n\nOutput: production blueprint plus correctness arguments and test strategy.\nOutput: replication design + failure handling + minimal skeleton.\n\n**Model**\n- Leader-based replication with term + log index.\n- Quorum acks for durability: write committed when majority acks.\n- Read options: leader-read (linearizable) or quorum-read (monotonic if using read-index).\n\n**Message flow (write)**\n1. Client → Leader: Put(request_id, payload)\n2. Leader appends to log, sends AppendEntries to followers\n3. Followers append + ack\n4. On majority ack: commit index advances; apply to state machine; respond to client\n\n**Failure modes**\n- Leader crash: new election; uncommitted entries may be rolled back.\n- Partition: minority side cannot commit.\n- Duplicate requests: deduplicate by request_id stored in state.\n\n**Skeleton (Go pseudo)**\n```go\ntype Entry struct { Term uint64; Index uint64; Cmd []byte }\ntype Node struct {\n id int\n term uint64\n log []Entry\n commit uint64\n seen map[string][]byte // request_id -> response\n}\n```\n\n**Verification**\n- Invariant: committed index never decreases.\n- Property: if a write is committed, all future leaders contain it.\n- Test with simulated partitions and crash/restart.\n\n\nHard checks: failure injection tests and performance regressions gated.", "source": "WithinUsAI/Elite_GOD_Coder_100k"} {"text": "Refactor to typed, mostly-immutable Python and add minimal tests.\n\n```python\nclass C64796:\n def __init__(self, values): self.values=list(values)\n def mean(self): return sum(self.values)/len(self.values)\n```\nReturn `m97292.py` and `test_m97292.py`.\n\n```python\n# m97292.py\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom typing import Iterable, Tuple\n\n@dataclass(frozen=True)\nclass C64796:\n values: Tuple[float, ...]\n\n @staticmethod\n def create(values: Iterable[float]) -> \"C64796\":\n vals = tuple(float(v) for v in values)\n if not vals: raise ValueError(\"empty\")\n return C64796(vals)\n\n def mean(self) -> float:\n return sum(self.values)/len(self.values)\n```\n\n```python\n# test_m97292.py\nimport pytest\nfrom m97292 import C64796\n\ndef test_mean():\n assert C64796.create([1,2,3]).mean() == 2.0\ndef test_empty():\n with pytest.raises(ValueError):\n C64796.create([])\n```", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Design a production system for document processing supporting role-based access control.\nTarget platform: web (React + TypeScript).\nRequirements: APIs, data model, scaling strategy, failure modes, and security.\nConstraints: must include clear error handling, must be easy to extend, must be production-ready, must include documentation/comments, must include type hints where applicable.\nDifficulty: easy. Assume GDPR-style deletion requests must be supported.\n\nOutput: design + implementation guidance suitable for shipping.\nDeliverable: system design with APIs, data model, and operational plan.\n\n**High-level architecture**\n- Edge: API Gateway + WAF\n- Core service: stateless app pods behind L7 LB\n- Data: Postgres (primary), Redis (cache + rate limit tokens), Object storage (uploads if needed)\n- Async: message queue (e.g., SQS/Rabbit) + worker pool for background jobs\n- Observability: structured logs + metrics + tracing\n\n**APIs (example)**\n- `POST /v1/{resource}` create (idempotent via `Idempotency-Key`)\n- `GET /v1/{resource}/{id}` read\n- `POST /v1/{resource}/{id}:action` command endpoint when side effects exist\n\n**Data model (Postgres)**\n- `resources(id UUID PK, tenant_id UUID, status TEXT, payload JSONB, created_at, updated_at)`\n- Unique constraint for idempotency: `(tenant_id, idempotency_key)` in a separate table:\n - `idempotency(tenant_id, key TEXT, request_hash TEXT, response JSONB, created_at, PRIMARY KEY(tenant_id,key))`\n\n**Scaling**\n- App layer scales horizontally; keep sessions out of process.\n- Cache reads in Redis; write-through invalidation on mutations.\n- Use connection pooling; consider read replicas for heavy reads.\n\n**Failure modes**\n- Retries: only for safe/ idempotent operations; exponential backoff + jitter.\n- Partial failures: background jobs must be idempotent; use a de-dup key.\n\n**Security**\n- AuthN: JWT/OIDC; AuthZ: RBAC/ABAC with tenant isolation\n- Validate all inputs; enforce per-tenant quotas/rate limits.\n\n**Rollout**\n- Dark launch + feature flags; canary; rapid rollback by toggling flags.\n\n\nChecks: input validation, tests, and safe defaults included.", "source": "WithinUsAI/GOD_Coder_100k"} {"text": "Design CI/CD for a fintech service delivering background jobs.\nTarget platform: backend (Node.js).\nRequirements: pipelines, checks, artifact strategy, deployments, and rollbacks.\nConstraints: must be production-ready, must be easy to extend, must be secure-by-default, must include tests.\nDifficulty: expert. Assume schema evolves frequently; design for migrations.\n\nOutput: design + implementation guidance suitable for shipping.\nDeliverable: CI/CD pipeline (GitHub Actions) with quality gates.\n\n```yaml\nname: ci\non:\n pull_request:\n push:\n branches: [main]\n\njobs:\n test:\n runs-on: ubuntu-latest\n steps:\n - uses: actions/checkout@v4\n - uses: actions/setup-python@v5\n with:\n python-version: \"3.11\"\n - run: python -m pip install -U pip\n - run: pip install -r requirements.txt\n - run: pip install -r requirements-dev.txt\n - run: ruff check .\n - run: mypy .\n - run: pytest -q --maxfail=1 --disable-warnings\n\n docker:\n needs: test\n runs-on: ubuntu-latest\n steps:\n - uses: actions/checkout@v4\n - uses: docker/setup-buildx-action@v3\n - run: docker build -t app:${{ github.sha }} .\n```\n\nDeployment strategy:\n- main → build → deploy to staging → smoke tests → canary to prod.\n- Rollback: redeploy previous image + DB migration rollback plan.\n\n\nHard-mode checks: concurrency safety, idempotency, and rollback validated; add chaos tests where feasible.", "source": "WithinUsAI/GOD_Coder_100k"} {"text": "Refactor to typed, mostly-immutable Python and add minimal tests.\n\n```python\nclass C77202:\n def __init__(self, values): self.values=list(values)\n def mean(self): return sum(self.values)/len(self.values)\n```\nReturn `m90554.py` and `test_m90554.py`.\n\n```python\n# m90554.py\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom typing import Iterable, Tuple\n\n@dataclass(frozen=True)\nclass C77202:\n values: Tuple[float, ...]\n\n @staticmethod\n def create(values: Iterable[float]) -> \"C77202\":\n vals = tuple(float(v) for v in values)\n if not vals: raise ValueError(\"empty\")\n return C77202(vals)\n\n def mean(self) -> float:\n return sum(self.values)/len(self.values)\n```\n\n```python\n# test_m90554.py\nimport pytest\nfrom m90554 import C77202\n\ndef test_mean():\n assert C77202.create([1,2,3]).mean() == 2.0\ndef test_empty():\n with pytest.raises(ValueError):\n C77202.create([])\n```", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Improve typing and robustness of a Python module used for configuration loading.\nRequirements: provide type-safe APIs (generics/protocols where appropriate) and include tests.\nConstraints: must be memory-efficient, must include docstrings, must provide clear error messages, must include tests.\nDifficulty: hard. Support both Windows and POSIX paths correctly.\n\nDeliverable: API + reference implementation + tests.\n```python\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom typing import Callable, Generic, Iterable, Protocol, TypeVar\n\nT = TypeVar(\"T\")\nR = TypeVar(\"R\")\n\nclass Mapper(Protocol[T, R]):\n def __call__(self, x: T) -> R: ...\n\n@dataclass(frozen=True, slots=True)\nclass Batch(Generic[T]):\n items: tuple[T, ...]\n\ndef map_batch(batch: Batch[T], fn: Mapper[T, R]) -> Batch[R]:\n return Batch(items=tuple(fn(x) for x in batch.items))\n\ndef chunked(xs: Iterable[T], size: int) -> Iterable[Batch[T]]:\n if size <= 0:\n raise ValueError(\"size must be > 0\")\n buf: list[T] = []\n for x in xs:\n buf.append(x)\n if len(buf) == size:\n yield Batch(items=tuple(buf))\n buf.clear()\n if buf:\n yield Batch(items=tuple(buf))\n```\n\n```python\nimport pytest\nfrom module_under_test import Batch, map_batch, chunked\n\ndef test_map_batch():\n b = Batch(items=(1,2,3))\n assert map_batch(b, lambda x: x*2).items == (2,4,6)\n\ndef test_chunked():\n out = list(chunked([1,2,3,4,5], 2))\n assert [b.items for b in out] == [(1,2),(3,4),(5,)]\n```", "source": "WithinUsAI/python_GOD_coder_100k"} {"text": "Implement webhooks for a customer support product.\nTarget platform: infra (Docker + Kubernetes).\nRequirements: provide production-ready code, configuration, and tests.\nConstraints: must avoid global state, must be performant under load, must be easy to extend, must include tests, must be secure-by-default.\nDifficulty: expert. Assume untrusted input; validate everything.\n\nOutput: actionable implementation and verification artifacts.\nDeliverable: production-grade reference implementation (FastAPI) + tests.\n\n```python\n# app.py\nfrom __future__ import annotations\n\nimport hashlib\nimport json\nfrom dataclasses import dataclass\nfrom datetime import datetime, timezone\nfrom typing import Any, Optional\n\nfrom fastapi import FastAPI, Header, HTTPException\nfrom pydantic import BaseModel, Field\n\napp = FastAPI(title=\"Idempotent API\")\n\nclass CreateReq(BaseModel):\n tenant_id: str = Field(min_length=1)\n amount_cents: int = Field(ge=0)\n currency: str = Field(min_length=3, max_length=3)\n\nclass CreateResp(BaseModel):\n id: str\n created_at: str\n echo: CreateReq\n\n@dataclass\nclass _IdempoEntry:\n request_hash: str\n response_json: str\n\n# In production: Postgres table with UNIQUE(tenant_id, key)\n_IDEMPO: dict[tuple[str, str], _IdempoEntry] = {}\n\ndef _hash_req(req: CreateReq) -> str:\n raw = req.model_dump_json()\n return hashlib.sha256(raw.encode(\"utf-8\")).hexdigest()\n\n@app.post(\"/v1/payments\", response_model=CreateResp)\ndef create_payment(\n req: CreateReq,\n idempotency_key: Optional[str] = Header(default=None, alias=\"Idempotency-Key\"),\n) -> Any:\n if not idempotency_key:\n raise HTTPException(status_code=400, detail=\"Missing Idempotency-Key\")\n if len(idempotency_key) > 128:\n raise HTTPException(status_code=400, detail=\"Idempotency-Key too long\")\n\n key = (req.tenant_id, idempotency_key)\n rh = _hash_req(req)\n\n existing = _IDEMPO.get(key)\n if existing:\n if existing.request_hash != rh:\n raise HTTPException(status_code=409, detail=\"Idempotency-Key reuse with different payload\")\n return json.loads(existing.response_json)\n\n # Create new payment (stubbed)\n pid = hashlib.md5(f\"{req.tenant_id}:{idempotency_key}\".encode()).hexdigest()\n resp = CreateResp(\n id=pid,\n created_at=datetime.now(timezone.utc).isoformat(),\n echo=req,\n )\n _IDEMPO[key] = _IdempoEntry(request_hash=rh, response_json=resp.model_dump_json())\n return resp\n```\n\n```python\n# test_app.py (pytest)\nfrom fastapi.testclient import TestClient\nfrom app import app\n\nclient = TestClient(app)\n\ndef test_idempotent_replay():\n headers = {\"Idempotency-Key\": \"abc\"}\n body = {\"tenant_id\":\"t1\",\"amount_cents\":100,\"currency\":\"USD\"}\n r1 = client.post(\"/v1/payments\", json=body, headers=headers)\n r2 = client.post(\"/v1/payments\", json=body, headers=headers)\n assert r1.status_code == 200 and r2.status_code == 200\n assert r1.json() == r2.json()\n\ndef test_payload_conflict():\n headers = {\"Idempotency-Key\": \"abc\"}\n b1 = {\"tenant_id\":\"t1\",\"amount_cents\":100,\"currency\":\"USD\"}\n b2 = {\"tenant_id\":\"t1\",\"amount_cents\":200,\"currency\":\"USD\"}\n assert client.post(\"/v1/payments\", json=b1, headers=headers).status_code == 200\n assert client.post(\"/v1/payments\", json=b2, headers=headers).status_code == 409\n```\n\nNotes:\n- Replace in-memory store with a DB table and transaction.\n- Store response + request hash to detect key reuse with different payload.\n\n\nHard-mode checks: concurrency safety, idempotency, and rollback validated; add chaos tests where feasible.", "source": "WithinUsAI/GOD_Coder_100k"} {"text": "Fix a subtle bug in a Python module used for ETL pipelines.\nRequirements: explain root cause briefly, provide corrected code, and add regression tests.\nConstraints: stdlib-only, must be memory-efficient, must include docstrings, must handle Windows paths safely.\nDifficulty: expert. Support both Windows and POSIX paths correctly.\n\nDeliverable: implementation + tests.\n```python\nfrom __future__ import annotations\n\nfrom dataclasses import dataclass\nfrom pathlib import Path\nfrom typing import Iterable\nimport json\n\n\nclass ValidationError(ValueError):\n \"\"\"Raised when input validation fails.\"\"\"\n\n\ndef safe_join(base: Path, *parts: str) -> Path:\n \"\"\"Join paths while preventing traversal outside base.\"\"\"\n b = base.resolve()\n p = (b / Path(*parts)).resolve()\n if p != b and b not in p.parents:\n raise ValidationError(f\"unsafe path: {p}\")\n return p\n\n\n@dataclass(frozen=True, slots=True)\nclass Record:\n key: str\n value: int\n\n\ndef parse_jsonl(lines: Iterable[str]) -> list[Record]:\n out: list[Record] = []\n for idx, line in enumerate(lines, 1):\n s = line.strip()\n if not s:\n continue\n try:\n obj = json.loads(s)\n except json.JSONDecodeError as e:\n raise ValidationError(f\"line {idx}: invalid json\") from e\n if not isinstance(obj, dict):\n raise ValidationError(f\"line {idx}: expected object\")\n key = obj.get(\"key\")\n val = obj.get(\"value\")\n if not isinstance(key, str) or not key:\n raise ValidationError(f\"line {idx}: key must be non-empty str\")\n if not isinstance(val, int):\n raise ValidationError(f\"line {idx}: value must be int\")\n out.append(Record(key, val))\n return out\n\n\ndef write_jsonl(base: Path, rel: str, records: Iterable[Record]) -> Path:\n base.mkdir(parents=True, exist_ok=True)\n dst = safe_join(base, rel)\n dst.parent.mkdir(parents=True, exist_ok=True)\n with dst.open(\"w\", encoding=\"utf-8\", newline=\"\\n\") as f:\n for r in records:\n f.write(json.dumps({\"key\": r.key, \"value\": r.value}, ensure_ascii=False) + \"\\n\")\n return dst\n```\n\n```python\n# tests (pytest-style)\nimport json\nfrom pathlib import Path\nimport pytest\nfrom module_under_test import ValidationError, Record, parse_jsonl, write_jsonl\n\ndef test_parse_ok():\n lines = [json.dumps({\"key\":\"a\",\"value\":1}), json.dumps({\"key\":\"b\",\"value\":2})]\n assert parse_jsonl(lines) == [Record(\"a\",1), Record(\"b\",2)]\n\ndef test_parse_rejects_bad_json():\n with pytest.raises(ValidationError):\n parse_jsonl([\"{not json}\"])\n\ndef test_safe_join_blocks_traversal(tmp_path: Path):\n with pytest.raises(ValidationError):\n write_jsonl(tmp_path, \"../x.jsonl\", [Record(\"a\",1)])\n```", "source": "WithinUsAI/python_GOD_coder_100k"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: Language: JavaScript\nFramework/tooling: React\nDomain: payments platform\nLogic challenge: broken pagination cursor\nTask type: cross_stack_outage_fix\nDifficulty: expert\n\nReturn a rigorous engineering answer:\n- identify the hidden root cause or logical failure\n- present the corrected implementation\n- add tests that prove the fix\n- list verification commands\n- explain why naive fixes are insufficient when relevant\n\nRepository sketch:\nrepo/\n src/\n api.js\n service.js\n utils.js\n tests/\n api.test.js\n package.json\n\nFocus: Focus on staff-level problem solving with multi-file patches, rollout implications, performance and security tradeoffs.\n\nassistant: Diagnosis:\n- Staff-level diagnosis: broken pagination cursor impacts correctness, operability, and future maintenance, so the fix must be minimal where possible but complete where necessary.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```javascript\ntype Payload = Record;\n\nexport function normalizePayload(payload: Payload): Payload {\n if (!payload || typeof payload !== \"object\" || Array.isArray(payload)) {\n throw new TypeError(\"payload must be a plain object\");\n }\n return Object.fromEntries(\n Object.entries(payload)\n .filter(([, value]) => value !== null && value !== undefined)\n .map(([key, value]) => [String(key).trim(), value])\n );\n}\n\nexport function handleBrokenPaginationCursor(payload: Payload) {\n const clean = normalizePayload(payload);\n if (!(\"id\" in clean)) {\n return { ok: false, data: {}, error: \"missing id\" };\n }\n return { ok: true, data: clean, error: null };\n}\n```\n\nTests:\n```javascript\nimport { describe, it, expect } from \"vitest\";\nimport { handleBrokenPaginationCursor } from \"../src/service\";\n\ndescribe(\"handler\", () => {\n it(\"accepts valid input\", () => {\n expect(handleBrokenPaginationCursor({ id: 7, name: \"ok\", unused: null })).toEqual({\n ok: true,\n data: { id: 7, name: \"ok\" },\n error: null\n });\n });\n\n it(\"rejects missing id\", () => {\n expect(handleBrokenPaginationCursor({ name: \"x\" }).error).toMatch(/missing id/);\n });\n});\n```\n\nVerification:\n- `npm test`\n- `npm run lint`\n\nEngineering notes:\n- Language: JavaScript\n- Framework/tooling: React\n- Stack context: Spring Boot, PostgreSQL, JUnit, Gradle, Docker, GitHub Actions\n- Domain: payments platform\n- Task type: cross_stack_outage_fix\n- Difficulty: expert\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Refactor to modern typed Python with immutability and tests.\n\nFile: enw1e2cpeddy.py\n```python\nclass Gr9Pzr72Bv:\n def __init__(self, name, values):\n self.name = name\n self.values = list(values)\n def add(self, v):\n self.values.append(v)\n def mean(self):\n s = 0\n for x in self.values:\n s += x\n return s / len(self.values)\n```\n\nReturn full new enw1e2cpeddy.py and test_enw1e2cpeddy.py.\n\n# enw1e2cpeddy.py\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom typing import Iterable, Tuple\n\n@dataclass(frozen=True)\nclass Gr9Pzr72Bv:\n name: str\n values: Tuple[float, ...]\n\n @staticmethod\n def create(name: str, values: Iterable[float]) -> \"Gr9Pzr72Bv\":\n vals = tuple(float(v) for v in values)\n if not vals:\n raise ValueError(\"values must be non-empty\")\n return Gr9Pzr72Bv(name=name, values=vals)\n\n def add(self, v: float) -> \"Gr9Pzr72Bv\":\n return Gr9Pzr72Bv(name=self.name, values=self.values + (float(v),))\n\n def mean(self) -> float:\n return sum(self.values) / len(self.values)\n\n# test_enw1e2cpeddy.py\nimport pytest\nfrom enw1e2cpeddy import Gr9Pzr72Bv\n\ndef test_mean_and_add():\n c = Gr9Pzr72Bv.create(\"a\", [1, 2, 3])\n assert c.mean() == 2.0\n assert c.add(5).mean() == (1 + 2 + 3 + 5) / 4\n\ndef test_empty_raises():\n with pytest.raises(ValueError):\n Gr9Pzr72Bv.create(\"x\", [])", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Build an elite-grade solution in the domain of operating systems for scenario: event ingestion.\nPrimary language: rust.\nDifficulty: expert.\nConstraints: design for backward compatibility and migrations, provide rollout and rollback guidance, avoid undefined behavior and data races, document performance characteristics.\nComponent: component_etfvhhy.\nAssume compliance requires data deletion with proofs.\nTask: Define a small DSL, implement tokenizer/parser, IR, and a codegen or interpreter. Include tests and complexity notes.\n\nOutput: rigorous solution with invariants, failure modes, and performance notes.\nOutput: DSL + parser + IR + interpreter/codegen + tests.\n\n**DSL**\n- Expressions: integers, identifiers, `+ - * /`, let-binding: `let x = expr in expr`\n- Example: `let x = 2+3 in x*10`\n\n**Pipeline**\n1. Tokenize\n2. Parse into AST\n3. Lower into IR (stack ops) or interpret AST directly\n\n**Reference (Rust-style outline)**\n- `enum Expr { Int(i64), Var(String), Bin(Op, Box, Box), Let(String, Box, Box) }`\n- Parser: Pratt or recursive descent.\n\n**Tests**\n- Golden tests for parse trees.\n- Property: pretty-print(parse(x)) round-trips for a corpus.\n- Eval tests for precedence and scoping.\n\n\nExpert checks: state-machine reasoning, concurrency stress, and upgrade/rollback validated.", "source": "WithinUsAI/Elite_GOD_Coder_100k"} {"text": "Build an elite-grade solution in the domain of networking for scenario: feature flagging.\nPrimary language: rust.\nDifficulty: hard.\nConstraints: document performance characteristics, include invariants and failure modes, avoid undefined behavior and data races, provide rollout and rollback guidance.\nComponent: component_hsjfboq.\nAssume schema changes every sprint; must be backward compatible.\nTask: Implement or outline a storage/indexing subsystem (LSM/B-Tree, WAL, snapshots). Include transaction/consistency considerations and benchmark plan.\n\nOutput: rigorous solution with invariants, failure modes, and performance notes.\nOutput: storage design + WAL + compaction + benchmarks.\n\n**Design**\n- WAL (append-only) for durability; fsync policy configurable.\n- Memtable (in-memory) → flush to immutable SSTables.\n- LSM compaction tiers; bloom filters per SSTable for point-lookups.\n- Manifest tracks SSTable set; atomic pointer swap on updates.\n\n**Correctness**\n- Crash recovery: replay WAL to rebuild memtable; manifest ensures last consistent set.\n- Reads: merge memtable + SSTables newest→oldest; tombstones override older values.\n\n**Bench plan**\n- Workloads: write-heavy, read-heavy, mixed; measure p50/p95 latency and write amplification.\n- Track compaction debt and space amplification.\n\n**Test plan**\n- Fuzz crash points: kill after WAL append / after manifest update; verify invariants on restart.\n\n\nHard checks: failure injection tests and performance regressions gated.", "source": "WithinUsAI/Elite_GOD_Coder_100k"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: Language: SQL\nFramework/tooling: PostgreSQL\nDomain: job scheduler\nLogic challenge: dead-letter queue replay\nTask type: cross_stack_outage_fix\nDifficulty: expert\n\nReturn a rigorous engineering answer:\n- identify the hidden root cause or logical failure\n- present the corrected implementation\n- add tests that prove the fix\n- list verification commands\n- explain why naive fixes are insufficient when relevant\n\nRepository sketch:\nrepo/\n migrations/\n 001_init.sql\n 002_add_index.sql\n queries/\n report.sql\n tests/\n report_cases.md\n\nFocus: Focus on staff-level problem solving with multi-file patches, rollout implications, performance and security tradeoffs.\n\nassistant: Diagnosis:\n- Staff-level diagnosis: dead-letter queue replay impacts correctness, operability, and future maintenance, so the fix must be minimal where possible but complete where necessary.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```sql\nWITH ranked AS (\n SELECT\n user_id,\n created_at,\n amount,\n ROW_NUMBER() OVER (PARTITION BY user_id ORDER BY created_at DESC, id DESC) AS rn\n FROM orders\n)\nSELECT user_id, created_at, amount\nFROM ranked\nWHERE rn = 1;\n```\n\nTests:\n```sql\n-- Correctness checks:\n-- 1) multiple rows per user\n-- 2) identical timestamps require deterministic tie-breaker\n-- 3) null values handled by business rules\n```\n\nVerification:\n- `run migration checks`\n- `run query correctness cases`\n\nEngineering notes:\n- Language: SQL\n- Framework/tooling: PostgreSQL\n- Stack context: Next.js, Node.js, Prisma, PostgreSQL, Playwright, Docker\n- Domain: job scheduler\n- Task type: cross_stack_outage_fix\n- Difficulty: expert\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "Build an elite-grade solution in the domain of high-performance services for scenario: feature flagging.\nPrimary language: go.\nDifficulty: medium.\nConstraints: design for backward compatibility and migrations, include invariants and failure modes, make the interface contract explicit, include tests or verification strategy, document performance characteristics.\nComponent: component_idifdnu.\nAssume strict auditability and replayable history.\nTask: Design an application-level protocol (framing, retries, timeouts, backpressure). Provide client/server skeleton and test vectors.\n\nOutput: elite-grade engineering answer with contracts, edge cases, and verification.\nOutput: protocol framing + retry policy + client/server skeleton.\n\n**Framing**\n- Length-prefixed: uint32_be length + payload\n- Payload: msgpack/json; include request_id, type, and optional checksum\n\n**Reliability**\n- Retries only for idempotent ops; exponential backoff + jitter.\n- Timeouts: connect, read, overall; enforce max in-flight to provide backpressure.\n\n**Test vectors**\n- Corrupted length / truncated frame rejected\n- Duplicate request_id returns cached response\n- Slowloris protection by read deadlines\n\n\nChecks: boundary validation and deterministic behavior verified.", "source": "WithinUsAI/Elite_GOD_Coder_100k"} {"text": "Fix the bug and add pytest tests.\n\n```python\ndef f36801(n: int) -> int:\n # sum 1..n inclusive\n if n < 0: raise ValueError\n total = 0\n for k in range(n): # BUG\n total += k\n return total\n```\nReturn unified diffs for `m19543.py` and `test_m19543.py`.\n\n*** Begin Patch\n*** Update File: m19543.py\n@@\n def f36801(n: int) -> int:\n@@\n- for k in range(n): # BUG\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_m19543.py\n+import pytest\n+from m19543 import f36801\n+\n+def test_small():\n+ assert f36801(7) == 28\n+\n+def test_zero():\n+ assert f36801(0) == 0\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ f36801(-1)\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Refactor to modern typed Python with immutability and tests.\n\nFile: mt4vynlmm2jj.py\n```python\nclass Xi5Tux42Xve:\n def __init__(self, name, values):\n self.name = name\n self.values = list(values)\n def add(self, v):\n self.values.append(v)\n def mean(self):\n s = 0\n for x in self.values:\n s += x\n return s / len(self.values)\n```\n\nReturn full new mt4vynlmm2jj.py and test_mt4vynlmm2jj.py.\n\n# mt4vynlmm2jj.py\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom typing import Iterable, Tuple\n\n@dataclass(frozen=True)\nclass Xi5Tux42Xve:\n name: str\n values: Tuple[float, ...]\n\n @staticmethod\n def create(name: str, values: Iterable[float]) -> \"Xi5Tux42Xve\":\n vals = tuple(float(v) for v in values)\n if not vals:\n raise ValueError(\"values must be non-empty\")\n return Xi5Tux42Xve(name=name, values=vals)\n\n def add(self, v: float) -> \"Xi5Tux42Xve\":\n return Xi5Tux42Xve(name=self.name, values=self.values + (float(v),))\n\n def mean(self) -> float:\n return sum(self.values) / len(self.values)\n\n# test_mt4vynlmm2jj.py\nimport pytest\nfrom mt4vynlmm2jj import Xi5Tux42Xve\n\ndef test_mean_and_add():\n c = Xi5Tux42Xve.create(\"a\", [1, 2, 3])\n assert c.mean() == 2.0\n assert c.add(5).mean() == (1 + 2 + 3 + 5) / 4\n\ndef test_empty_raises():\n with pytest.raises(ValueError):\n Xi5Tux42Xve.create(\"x\", [])", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Fix a bug and add tests.\n\nFile: kv0vh1ek2w3.py\n```python\ndef ce9c5u5_(n: int) -> int:\n \"\"\"Sum 1..n inclusive.\"\"\"\n if n < 0:\n raise ValueError(\"n must be non-negative\")\n total = 0\n for k in range(n): # BUG: should include n\n total += k\n return total\n```\n\nReturn unified diffs for kv0vh1ek2w3.py and test_kv0vh1ek2w3.py (pytest).\n\n*** Begin Patch\n*** Update File: kv0vh1ek2w3.py\n@@\n def ce9c5u5_(n: int) -> int:\n@@\n total = 0\n- for k in range(n): # BUG: should include n\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_kv0vh1ek2w3.py\n+import pytest\n+from kv0vh1ek2w3 import ce9c5u5_\n+\n+def test_zero():\n+ assert ce9c5u5_(0) == 0\n+\n+def test_one():\n+ assert ce9c5u5_(1) == 1\n+\n+def test_small():\n+ assert ce9c5u5_(7) == 28\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ ce9c5u5_(-1)\n+\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Fix a bug and add tests.\n\nFile: x6am4nsqx.py\n```python\ndef o_dsu3i_(n: int) -> int:\n \"\"\"Sum 1..n inclusive.\"\"\"\n if n < 0:\n raise ValueError(\"n must be non-negative\")\n total = 0\n for k in range(n): # BUG: should include n\n total += k\n return total\n```\n\nReturn unified diffs for x6am4nsqx.py and test_x6am4nsqx.py (pytest).\n\n*** Begin Patch\n*** Update File: x6am4nsqx.py\n@@\n def o_dsu3i_(n: int) -> int:\n@@\n total = 0\n- for k in range(n): # BUG: should include n\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_x6am4nsqx.py\n+import pytest\n+from x6am4nsqx import o_dsu3i_\n+\n+def test_zero():\n+ assert o_dsu3i_(0) == 0\n+\n+def test_one():\n+ assert o_dsu3i_(1) == 1\n+\n+def test_small():\n+ assert o_dsu3i_(7) == 28\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ o_dsu3i_(-1)\n+\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Design and implement an algorithm for report generation.\nRequirements: define inputs/outputs, implement solution with complexity analysis, and include tests.\nConstraints: must be streaming-friendly, must include tests, must be easy to extend.\nDifficulty: expert. Provide helpful exceptions with actionable messages.\n\nDeliverable: production-ready reference solution.\nProblem: compute rolling sums over events (ts:int,value:int) with window W seconds. Events may be out-of-order.\n\nComplexity: sorting O(n log n); window maintenance O(n); memory O(k).\n\n```python\nfrom __future__ import annotations\nfrom collections import deque\nfrom dataclasses import dataclass\nfrom typing import Iterable, List, Tuple\n\n@dataclass(frozen=True, slots=True)\nclass Event:\n ts: int\n value: int\n\ndef rolling_sum(events: Iterable[Event], window_s: int) -> List[Tuple[int,int]]:\n if window_s < 0:\n raise ValueError(\"window_s must be >= 0\")\n evs = sorted(events, key=lambda e: e.ts)\n q: deque[Event] = deque()\n s = 0\n out: List[Tuple[int,int]] = []\n for e in evs:\n q.append(e)\n s += e.value\n cutoff = e.ts - window_s\n while q and q[0].ts < cutoff:\n old = q.popleft()\n s -= old.value\n out.append((e.ts, s))\n return out\n```\n\n```python\nimport pytest\nfrom module_under_test import Event, rolling_sum\n\ndef test_rolling_sum():\n ev = [Event(10,1), Event(11,2), Event(20,5)]\n assert rolling_sum(ev, 5) == [(10,1),(11,3),(20,5)]\n```", "source": "WithinUsAI/python_GOD_coder_100k"} {"text": "Build an elite-grade solution in the domain of edge/IoT for scenario: edge sync.\nPrimary language: rust.\nDifficulty: hard.\nConstraints: make the interface contract explicit, include invariants and failure modes, assume untrusted inputs; validate and sanitize.\nComponent: component_pxddzmm.\nAssume compliance requires data deletion with proofs.\nTask: Design a replication/consistency approach (e.g., leader-based, quorum reads/writes). Provide message flows, failure handling, and a minimal reference implementation skeleton.\n\nOutput: elite-grade engineering answer with contracts, edge cases, and verification.\nOutput: replication design + failure handling + minimal skeleton.\n\n**Model**\n- Leader-based replication with term + log index.\n- Quorum acks for durability: write committed when majority acks.\n- Read options: leader-read (linearizable) or quorum-read (monotonic if using read-index).\n\n**Message flow (write)**\n1. Client → Leader: Put(request_id, payload)\n2. Leader appends to log, sends AppendEntries to followers\n3. Followers append + ack\n4. On majority ack: commit index advances; apply to state machine; respond to client\n\n**Failure modes**\n- Leader crash: new election; uncommitted entries may be rolled back.\n- Partition: minority side cannot commit.\n- Duplicate requests: deduplicate by request_id stored in state.\n\n**Skeleton (Go pseudo)**\n```go\ntype Entry struct { Term uint64; Index uint64; Cmd []byte }\ntype Node struct {\n id int\n term uint64\n log []Entry\n commit uint64\n seen map[string][]byte // request_id -> response\n}\n```\n\n**Verification**\n- Invariant: committed index never decreases.\n- Property: if a write is committed, all future leaders contain it.\n- Test with simulated partitions and crash/restart.\n\n\nHard checks: failure injection tests and performance regressions gated.", "source": "WithinUsAI/Elite_GOD_Coder_100k"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: Repository domain: model serving gateway\nPrimary language: C#\nFramework/tooling: xUnit\nReported problem: rate-limit bypass\nTask type: security_patch\nDifficulty: medium\n\nProduce a complete professional engineering response:\n1. Diagnose the root cause.\n2. Provide the corrected implementation or patch.\n3. Add tests.\n4. Add verification commands.\n5. Note edge cases and any migration or rollback risk.\n\nRepository sketch:\nrepo/\n src/App/Program.cs\n src/App/Service.cs\n tests/App.Tests/ServiceTests.cs\n App.sln\n\nQuality target:\n- Minimal diff unless redesign is clearly required\n- Production-ready code\n- No placeholders\n- Secure defaults\n- Clear acceptance of failure cases\n\nFocus: Focus on complete implementation quality, patch correctness, tests, and production readiness.\n\nassistant: Diagnosis:\n- Root cause: the failure around rate-limit bypass is caused by missing validation, weak edge-case handling, or unsafe lifecycle behavior in the current implementation.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```csharp\nusing System;\nusing System.Collections.Generic;\n\npublic static class RequestHandler\n{\n public static Dictionary HandleRequest(Dictionary payload)\n {\n var clean = new Dictionary();\n foreach (var entry in payload)\n {\n if (entry.Value != null)\n clean[entry.Key.Trim()] = entry.Value;\n }\n if (!clean.ContainsKey(\"id\"))\n throw new ArgumentException(\"missing id\");\n return new Dictionary\n {\n [\"ok\"] = true,\n [\"data\"] = clean\n };\n }\n}\n```\n\nTests:\n```csharp\nusing System;\nusing System.Collections.Generic;\nusing Xunit;\n\npublic class RequestHandlerTests\n{\n [Fact]\n public void RequiresId()\n {\n Assert.Throws(() => RequestHandler.HandleRequest(new Dictionary { [\"name\"] = \"x\" }));\n }\n}\n```\n\nVerification:\n- `dotnet test`\n- `dotnet build`\n\nEngineering notes:\n- Language: C#\n- Framework/tooling: xUnit\n- Stack context: Go, Gin, PostgreSQL, gRPC, Prometheus, Docker\n- Domain: model serving gateway\n- Task type: security_patch\n- Difficulty: medium\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "Optimize while preserving behavior and order.\n\n```python\ndef f32789(xs):\n out=[]\n for x in xs:\n if x not in out: out.append(x)\n return out\n```\nReturn `m61827.py` with types and O(n) average.\n\n```python\n# m61827.py\nfrom __future__ import annotations\nfrom typing import Iterable, List, Set, TypeVar\nT=TypeVar(\"T\")\n\ndef f32789(xs: Iterable[T]) -> List[T]:\n \"\"\"Unique items preserving first-seen order.\"\"\"\n seen: Set[T]=set()\n out: List[T]=[]\n for x in xs:\n if x in seen: continue\n seen.add(x); out.append(x)\n return out\n```", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Refactor a Python module used for parsing into a clean, extensible design.\nRequirements: outline the new architecture briefly, then provide the refactored code and tests.\nConstraints: must include docstrings, must include type hints.\nDifficulty: expert. Handle empty inputs and malformed records gracefully.\n\nDeliverable: API + reference implementation + tests.\nArchitecture:\n- Public facade class coordinating concerns (parsing, validation, persistence)\n- Small pure functions for testability\n- No global state; dependency injection for filesystem I/O\n\n```python\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom pathlib import Path\nfrom typing import Protocol, Iterable\nimport json\n\nclass Store(Protocol):\n def write_text(self, path: Path, data: str) -> None: ...\n\nclass FSStore:\n def write_text(self, path: Path, data: str) -> None:\n path.parent.mkdir(parents=True, exist_ok=True)\n path.write_text(data, encoding=\"utf-8\")\n\n@dataclass(frozen=True, slots=True)\nclass Item:\n name: str\n qty: int\n\ndef parse_items(lines: Iterable[str]) -> list[Item]:\n out: list[Item] = []\n for i, line in enumerate(lines, 1):\n s = line.strip()\n if not s:\n continue\n obj = json.loads(s)\n if not isinstance(obj, dict):\n raise ValueError(f\"line {i}: expected object\")\n name = obj.get(\"name\")\n qty = obj.get(\"qty\")\n if not isinstance(name, str) or not name:\n raise ValueError(f\"line {i}: name must be str\")\n if not isinstance(qty, int) or qty < 0:\n raise ValueError(f\"line {i}: qty must be non-negative int\")\n out.append(Item(name, qty))\n return out\n\nclass InventoryWriter:\n def __init__(self, base_dir: Path, store: Store | None = None) -> None:\n self._base = base_dir\n self._store: Store = store or FSStore()\n\n def write(self, rel_path: str, items: list[Item]) -> Path:\n dst = (self._base / rel_path).resolve()\n base = self._base.resolve()\n if dst != base and base not in dst.parents:\n raise ValueError(\"unsafe path traversal\")\n payload = json.dumps([item.__dict__ for item in items], ensure_ascii=False)\n self._store.write_text(dst, payload)\n return dst\n```\n\n```python\nimport json\nfrom pathlib import Path\nimport pytest\nfrom module_under_test import InventoryWriter, parse_items\n\ndef test_parse_items_valid():\n lines = [json.dumps({\"name\":\"x\",\"qty\":1})]\n assert parse_items(lines)[0].name == \"x\"\n\ndef test_writer_blocks_traversal(tmp_path: Path):\n w = InventoryWriter(tmp_path)\n with pytest.raises(ValueError):\n w.write(\"../evil.json\", [])\n```", "source": "WithinUsAI/python_GOD_coder_100k"} {"text": "Write pytest tests for `f70118`.\n\n```python\ndef f70118(a: int, b: int) -> int:\n return a*a + b*b\n```\nInclude edge cases and a property-style check.\n\n```python\nimport random\nfrom m52874 import f70118\n\ndef test_known():\n assert f70118(3,4) == 25\n\ndef test_zero():\n assert f70118(0,0) == 0\n\ndef test_property_nonnegative():\n for _ in range(200):\n a=random.randint(-50,50)\n b=random.randint(-50,50)\n assert f70118(a,b) >= 0\n```", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Optimize while preserving behavior.\n\nFile: u18kf36.py\n```python\ndef rvqdnn1(xs):\n out = []\n for x in xs:\n if x not in out:\n out.append(x)\n return out\n```\n\nRequirements: preserve first-seen order; O(n) average; add types + docstring.\n\n# u18kf36.py\nfrom __future__ import annotations\nfrom typing import Iterable, List, Set, TypeVar\n\nT = TypeVar(\"T\")\n\ndef rvqdnn1(xs: Iterable[T]) -> List[T]:\n \"\"\"Return unique items preserving first-seen order.\"\"\"\n seen: Set[T] = set()\n out: List[T] = []\n for x in xs:\n if x in seen:\n continue\n seen.add(x)\n out.append(x)\n return out", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Refactor to typed, mostly-immutable Python and add minimal tests.\n\n```python\nclass C34517:\n def __init__(self, values): self.values=list(values)\n def mean(self): return sum(self.values)/len(self.values)\n```\nReturn `m48809.py` and `test_m48809.py`.\n\n```python\n# m48809.py\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom typing import Iterable, Tuple\n\n@dataclass(frozen=True)\nclass C34517:\n values: Tuple[float, ...]\n\n @staticmethod\n def create(values: Iterable[float]) -> \"C34517\":\n vals = tuple(float(v) for v in values)\n if not vals: raise ValueError(\"empty\")\n return C34517(vals)\n\n def mean(self) -> float:\n return sum(self.values)/len(self.values)\n```\n\n```python\n# test_m48809.py\nimport pytest\nfrom m48809 import C34517\n\ndef test_mean():\n assert C34517.create([1,2,3]).mean() == 2.0\ndef test_empty():\n with pytest.raises(ValueError):\n C34517.create([])\n```", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Fix a subtle bug in a Python module used for caching layer.\nRequirements: explain root cause briefly, provide corrected code, and add regression tests.\nConstraints: must be easy to extend, must include type hints, must provide clear error messages.\nDifficulty: medium. Guarantee deterministic output ordering.\n\nDeliverable: corrected code and verification tests.\n```python\nfrom __future__ import annotations\n\nfrom dataclasses import dataclass\nfrom pathlib import Path\nfrom typing import Iterable\nimport json\n\n\nclass ValidationError(ValueError):\n \"\"\"Raised when input validation fails.\"\"\"\n\n\ndef safe_join(base: Path, *parts: str) -> Path:\n \"\"\"Join paths while preventing traversal outside base.\"\"\"\n b = base.resolve()\n p = (b / Path(*parts)).resolve()\n if p != b and b not in p.parents:\n raise ValidationError(f\"unsafe path: {p}\")\n return p\n\n\n@dataclass(frozen=True, slots=True)\nclass Record:\n key: str\n value: int\n\n\ndef parse_jsonl(lines: Iterable[str]) -> list[Record]:\n out: list[Record] = []\n for idx, line in enumerate(lines, 1):\n s = line.strip()\n if not s:\n continue\n try:\n obj = json.loads(s)\n except json.JSONDecodeError as e:\n raise ValidationError(f\"line {idx}: invalid json\") from e\n if not isinstance(obj, dict):\n raise ValidationError(f\"line {idx}: expected object\")\n key = obj.get(\"key\")\n val = obj.get(\"value\")\n if not isinstance(key, str) or not key:\n raise ValidationError(f\"line {idx}: key must be non-empty str\")\n if not isinstance(val, int):\n raise ValidationError(f\"line {idx}: value must be int\")\n out.append(Record(key, val))\n return out\n\n\ndef write_jsonl(base: Path, rel: str, records: Iterable[Record]) -> Path:\n base.mkdir(parents=True, exist_ok=True)\n dst = safe_join(base, rel)\n dst.parent.mkdir(parents=True, exist_ok=True)\n with dst.open(\"w\", encoding=\"utf-8\", newline=\"\\n\") as f:\n for r in records:\n f.write(json.dumps({\"key\": r.key, \"value\": r.value}, ensure_ascii=False) + \"\\n\")\n return dst\n```\n\n```python\n# tests (pytest-style)\nimport json\nfrom pathlib import Path\nimport pytest\nfrom module_under_test import ValidationError, Record, parse_jsonl, write_jsonl\n\ndef test_parse_ok():\n lines = [json.dumps({\"key\":\"a\",\"value\":1}), json.dumps({\"key\":\"b\",\"value\":2})]\n assert parse_jsonl(lines) == [Record(\"a\",1), Record(\"b\",2)]\n\ndef test_parse_rejects_bad_json():\n with pytest.raises(ValidationError):\n parse_jsonl([\"{not json}\"])\n\ndef test_safe_join_blocks_traversal(tmp_path: Path):\n with pytest.raises(ValidationError):\n write_jsonl(tmp_path, \"../x.jsonl\", [Record(\"a\",1)])\n```", "source": "WithinUsAI/python_GOD_coder_100k"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: System domain: data pipeline\nStack: Go, Gin, PostgreSQL, gRPC, Prometheus, Docker\nCross-layer incident: broken pagination cursor\nTask type: observability_debug_fix\nDifficulty: hard\n\nSolve this as a complete-project engineer.\nOutput must include:\n- root cause across layers\n- final implementation patch\n- tests touching at least two layers\n- deployment or observability note\n- verification commands\n\nRepository sketch:\nrepo/\n src/main.rs\n src/lib.rs\n src/service.rs\n src/store.rs\n tests/integration.rs\n Cargo.toml\n\nFocus: Focus on multi-layer debugging across frontend, backend, database, CI, caching, and deployment.\n\nassistant: Diagnosis:\n- Root cause: broken pagination cursor crosses service boundaries, so the fix must align code, contracts, tests, and deployment behavior.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```rust\nuse std::collections::HashMap;\n\npub fn normalize_payload(payload: HashMap) -> HashMap {\n payload\n .into_iter()\n .filter(|(_, v)| !v.trim().is_empty())\n .collect()\n}\n```\n\nTests:\n```rust\n#[test]\nfn normalize_payload_filters_empty_values() {\n use std::collections::HashMap;\n let mut payload = HashMap::new();\n payload.insert(\"id\".to_string(), \"7\".to_string());\n payload.insert(\"name\".to_string(), \"\".to_string());\n let out = normalize_payload(payload);\n assert!(out.contains_key(\"id\"));\n assert!(!out.contains_key(\"name\"));\n}\n```\n\nVerification:\n- `cargo test`\n- `cargo clippy -- -D warnings`\n\nEngineering notes:\n- Language: Rust\n- Framework/tooling: Axum\n- Stack context: Go, Gin, PostgreSQL, gRPC, Prometheus, Docker\n- Domain: data pipeline\n- Task type: observability_debug_fix\n- Difficulty: hard\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "Build an elite-grade solution in the domain of realtime systems for scenario: chat messaging.\nPrimary language: sql.\nDifficulty: medium.\nConstraints: include invariants and failure modes, include tests or verification strategy, assume untrusted inputs; validate and sanitize, make the interface contract explicit.\nComponent: component_mdjnqie.\nAssume strict auditability and replayable history.\nTask: Write a precise interface contract, list invariants, and provide a lightweight formal/spec-style description (pseudo-TLA+/state machine) plus reference implementation skeleton and tests.\n\nOutput: production blueprint plus correctness arguments and test strategy.\nOutput: contract + invariants + spec + reference skeleton.\n\n**Interface contract**\n- Commands: `Put(key, value, expected_version?)`, `Get(key)`, `Delete(key, expected_version?)`\n- Responses: `Ok(version, value?)`, `NotFound`, `Conflict(current_version)`, `InvalidInput`\n- Idempotency: client supplies `request_id`; server must de-duplicate per (tenant_id, request_id).\n\n**Invariants**\n1. Monotonic version per key (strictly increases on successful writes).\n2. Reads return latest committed value for a given consistency level.\n3. Exactly-once effect for a given `request_id` (at-most-once execution + replay response).\n4. Tenant isolation: keys are scoped by tenant_id.\n\n**State machine (pseudo)**\nState:\n- store: map[(tenant,key)] -> (version:int, value:bytes|tombstone)\n- seen: map[(tenant,request_id)] -> response\nTransition Put:\n- if request_id in seen: return seen[...]\n- validate input; if expected_version set and != current version -> Conflict\n- version' = version + 1; store[...] := (version', value); seen[...] := Ok(version', value)\n\n**Reference skeleton (Python)**\n```python\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom typing import Dict, Optional, Tuple\n\nclass Conflict(Exception): pass\nclass InvalidInput(ValueError): pass\n\n@dataclass(frozen=True, slots=True)\nclass Value:\n version: int\n data: Optional[bytes] # None == tombstone\n\n@dataclass(frozen=True, slots=True)\nclass Reply:\n kind: str\n version: Optional[int] = None\n data: Optional[bytes] = None\n\nclass KV:\n def __init__(self) -> None:\n self._store: Dict[Tuple[str,str], Value] = {}\n self._seen: Dict[Tuple[str,str], Reply] = {}\n\n def put(self, tenant: str, request_id: str, key: str, data: bytes, expected_version: Optional[int]=None) -> Reply:\n if not tenant or not request_id or not key:\n raise InvalidInput(\"tenant/request_id/key required\")\n de = self._seen.get((tenant, request_id))\n if de: \n return de\n cur = self._store.get((tenant, key), Value(0, None))\n if expected_version is not None and expected_version != cur.version:\n r = Reply(\"conflict\", version=cur.version)\n self._seen[(tenant, request_id)] = r\n return r\n nxt = Value(cur.version + 1, data)\n self._store[(tenant, key)] = nxt\n r = Reply(\"ok\", version=nxt.version)\n self._seen[(tenant, request_id)] = r\n return r\n```\n\n**Tests**\n- Determinism: same request_id → same reply.\n- Conflict detection and version monotonicity.\n\n\nChecks: boundary validation and deterministic behavior verified.", "source": "WithinUsAI/Elite_GOD_Coder_100k"} {"text": "Optimize while preserving behavior and order.\n\n```python\ndef f91580(xs):\n out=[]\n for x in xs:\n if x not in out: out.append(x)\n return out\n```\nReturn `m55940.py` with types and O(n) average.\n\n```python\n# m55940.py\nfrom __future__ import annotations\nfrom typing import Iterable, List, Set, TypeVar\nT=TypeVar(\"T\")\n\ndef f91580(xs: Iterable[T]) -> List[T]:\n \"\"\"Unique items preserving first-seen order.\"\"\"\n seen: Set[T]=set()\n out: List[T]=[]\n for x in xs:\n if x in seen: continue\n seen.add(x); out.append(x)\n return out\n```", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Fix the bug and add pytest tests.\n\n```python\ndef f13888(n: int) -> int:\n # sum 1..n inclusive\n if n < 0: raise ValueError\n total = 0\n for k in range(n): # BUG\n total += k\n return total\n```\nReturn unified diffs for `m01984.py` and `test_m01984.py`.\n\n*** Begin Patch\n*** Update File: m01984.py\n@@\n def f13888(n: int) -> int:\n@@\n- for k in range(n): # BUG\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_m01984.py\n+import pytest\n+from m01984 import f13888\n+\n+def test_small():\n+ assert f13888(7) == 28\n+\n+def test_zero():\n+ assert f13888(0) == 0\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ f13888(-1)\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Design and implement an algorithm for event dispatching.\nRequirements: define inputs/outputs, implement solution with complexity analysis, and include tests.\nConstraints: must provide clear error messages, must include tests, must include type hints, must be streaming-friendly.\nDifficulty: expert. Avoid quadratic behavior on large inputs.\n\nDeliverable: implementation + tests.\nProblem: compute rolling sums over events (ts:int,value:int) with window W seconds. Events may be out-of-order.\n\nComplexity: sorting O(n log n); window maintenance O(n); memory O(k).\n\n```python\nfrom __future__ import annotations\nfrom collections import deque\nfrom dataclasses import dataclass\nfrom typing import Iterable, List, Tuple\n\n@dataclass(frozen=True, slots=True)\nclass Event:\n ts: int\n value: int\n\ndef rolling_sum(events: Iterable[Event], window_s: int) -> List[Tuple[int,int]]:\n if window_s < 0:\n raise ValueError(\"window_s must be >= 0\")\n evs = sorted(events, key=lambda e: e.ts)\n q: deque[Event] = deque()\n s = 0\n out: List[Tuple[int,int]] = []\n for e in evs:\n q.append(e)\n s += e.value\n cutoff = e.ts - window_s\n while q and q[0].ts < cutoff:\n old = q.popleft()\n s -= old.value\n out.append((e.ts, s))\n return out\n```\n\n```python\nimport pytest\nfrom module_under_test import Event, rolling_sum\n\ndef test_rolling_sum():\n ev = [Event(10,1), Event(11,2), Event(20,5)]\n assert rolling_sum(ev, 5) == [(10,1),(11,3),(20,5)]\n```", "source": "WithinUsAI/python_GOD_coder_100k"} {"text": "Design a small, production-grade Python API for time series.\nRequirements: define data models and interfaces, implement reference version, include tests.\nConstraints: must handle Windows paths safely, must be easy to extend, must be streaming-friendly, must be memory-efficient.\nDifficulty: hard. Handle empty inputs and malformed records gracefully.\n\nDeliverable: production-ready reference solution.\nArchitecture:\n- Public facade class coordinating concerns (parsing, validation, persistence)\n- Small pure functions for testability\n- No global state; dependency injection for filesystem I/O\n\n```python\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom pathlib import Path\nfrom typing import Protocol, Iterable\nimport json\n\nclass Store(Protocol):\n def write_text(self, path: Path, data: str) -> None: ...\n\nclass FSStore:\n def write_text(self, path: Path, data: str) -> None:\n path.parent.mkdir(parents=True, exist_ok=True)\n path.write_text(data, encoding=\"utf-8\")\n\n@dataclass(frozen=True, slots=True)\nclass Item:\n name: str\n qty: int\n\ndef parse_items(lines: Iterable[str]) -> list[Item]:\n out: list[Item] = []\n for i, line in enumerate(lines, 1):\n s = line.strip()\n if not s:\n continue\n obj = json.loads(s)\n if not isinstance(obj, dict):\n raise ValueError(f\"line {i}: expected object\")\n name = obj.get(\"name\")\n qty = obj.get(\"qty\")\n if not isinstance(name, str) or not name:\n raise ValueError(f\"line {i}: name must be str\")\n if not isinstance(qty, int) or qty < 0:\n raise ValueError(f\"line {i}: qty must be non-negative int\")\n out.append(Item(name, qty))\n return out\n\nclass InventoryWriter:\n def __init__(self, base_dir: Path, store: Store | None = None) -> None:\n self._base = base_dir\n self._store: Store = store or FSStore()\n\n def write(self, rel_path: str, items: list[Item]) -> Path:\n dst = (self._base / rel_path).resolve()\n base = self._base.resolve()\n if dst != base and base not in dst.parents:\n raise ValueError(\"unsafe path traversal\")\n payload = json.dumps([item.__dict__ for item in items], ensure_ascii=False)\n self._store.write_text(dst, payload)\n return dst\n```\n\n```python\nimport json\nfrom pathlib import Path\nimport pytest\nfrom module_under_test import InventoryWriter, parse_items\n\ndef test_parse_items_valid():\n lines = [json.dumps({\"name\":\"x\",\"qty\":1})]\n assert parse_items(lines)[0].name == \"x\"\n\ndef test_writer_blocks_traversal(tmp_path: Path):\n w = InventoryWriter(tmp_path)\n with pytest.raises(ValueError):\n w.write(\"../evil.json\", [])\n```", "source": "WithinUsAI/python_GOD_coder_100k"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: Project domain: auth service\nImplementation stack: Next.js, Node.js, Prisma, PostgreSQL, Playwright, Docker\nSoftware delivery problem: streaming timeout handling\nTask type: incident_to_remediation\nDifficulty: hard\n\nReturn a complete delivery-grade response with:\n- diagnosis or design reasoning\n- implementation\n- test plan or tests\n- rollout plan\n- rollback or compatibility note\n- verification commands\n\nRepository sketch:\nrepo/\n src/\n api.ts\n service.ts\n schema.ts\n tests/\n api.test.ts\n package.json\n\nFocus: Focus on shipping production software with rollout safety, acceptance criteria, telemetry, and maintenance quality.\n\nassistant: Diagnosis:\n- Root cause or delivery blocker: streaming timeout handling needs both implementation work and a safe shipping plan.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```ts\ntype Payload = Record;\n\nexport function normalizePayload(payload: Payload): Payload {\n if (!payload || typeof payload !== \"object\" || Array.isArray(payload)) {\n throw new TypeError(\"payload must be a plain object\");\n }\n return Object.fromEntries(\n Object.entries(payload)\n .filter(([, value]) => value !== null && value !== undefined)\n .map(([key, value]) => [String(key).trim(), value])\n );\n}\n\nexport function handleStreamingTimeoutHandling(payload: Payload) {\n const clean = normalizePayload(payload);\n if (!(\"id\" in clean)) {\n return { ok: false, data: {}, error: \"missing id\" };\n }\n return { ok: true, data: clean, error: null };\n}\n```\n\nTests:\n```ts\nimport { describe, it, expect } from \"vitest\";\nimport { handleStreamingTimeoutHandling } from \"../src/service\";\n\ndescribe(\"handler\", () => {\n it(\"accepts valid input\", () => {\n expect(handleStreamingTimeoutHandling({ id: 7, name: \"ok\", unused: null })).toEqual({\n ok: true,\n data: { id: 7, name: \"ok\" },\n error: null\n });\n });\n\n it(\"rejects missing id\", () => {\n expect(handleStreamingTimeoutHandling({ name: \"x\" }).error).toMatch(/missing id/);\n });\n});\n```\n\nVerification:\n- `npm test`\n- `npm run typecheck`\n- `npm run lint`\n\nEngineering notes:\n- Language: TypeScript\n- Framework/tooling: Node.js\n- Stack context: Next.js, Node.js, Prisma, PostgreSQL, Playwright, Docker\n- Domain: auth service\n- Task type: incident_to_remediation\n- Difficulty: hard\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "Task type: formal_proof_sketch\nScenario: graph query service\nDomain focus: edge robotics (safe)\nPrimary language: rust\nDifficulty: hard\nScale/SLO: 10k RPS peak\nComponent: component_yjxdsnxh\nConstraints: explicit contracts and invariants, include test vectors and fuzz strategy, include performance model and limits, avoid data races and undefined behavior, include security threat model (defensive only), include verification strategy\nAssume crash-only processes; recovery must be deterministic.\nDeliverable: Provide a rigorous proof sketch for key invariants and show how to test/verify them in practice.\n\nOutput: contract-first solution with failure modes, security posture, and test/verification strategy.\n**Contract**\n- Inputs validated at the boundary; explicit error taxonomy.\n- Idempotency for side effects via request_id; deterministic replay.\n- Backward compatibility: additive changes by default; versioned breaking changes.\n**Invariants**\n- Determinism: replay of the same event log yields identical outputs.\n- Liveness: under bounded faults and stable network, progress occurs.\n- Isolation: tenant boundary enforced; no cross-tenant reads/writes.\n**Failure modes & recovery**\n- Duplicate requests: de-duplicate by (tenant, request_id) returning cached response.\n- Network partition: minority cannot commit; clients receive retriable errors.\n- Crash during commit: WAL replay completes or transaction aborts; no torn writes.\n**Security posture (defensive)**\n- Threat model: auth/authz, injection, replay/abuse, supply chain.\n- Least privilege; secrets in managed store; audit logs for sensitive ops.\n- Input normalization, parameterized queries, path traversal protections.\n**Verification strategy**\n- Canary + shadow traffic; invariants checked in production via assertions/metrics.\n- Property tests against a pure reference model (state machine).\n- Deterministic simulation with fault injection (crash/partition/latency).\n\n**Snippet**\n```text\nImplementation sketch: factor pure state-machine core; adapters for I/O; add deterministic replay log.\n```\nHard checks: fault injection tests gate merges; perf thresholds enforced in CI.", "source": "WithinUsAI/Omega_Genesis_Coder_100k"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: Language: Rust\nFramework/tooling: SQLx\nDomain: reporting engine\nLogic challenge: unsafe deserialization\nTask type: misleading_symptom_debug\nDifficulty: hard\n\nReturn a rigorous engineering answer:\n- identify the hidden root cause or logical failure\n- present the corrected implementation\n- add tests that prove the fix\n- list verification commands\n- explain why naive fixes are insufficient when relevant\n\nRepository sketch:\nrepo/\n src/main.rs\n src/lib.rs\n src/service.rs\n src/store.rs\n tests/integration.rs\n Cargo.toml\n\nFocus: Focus on ambiguity, misleading symptoms, hidden root causes, and high-stakes debugging.\n\nassistant: Diagnosis:\n- Hidden root cause: unsafe deserialization presents misleading symptoms, so the patch must target the actual logic boundary rather than the first visible failure.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```rust\nuse std::collections::HashMap;\n\npub fn normalize_payload(payload: HashMap) -> HashMap {\n payload\n .into_iter()\n .filter(|(_, v)| !v.trim().is_empty())\n .collect()\n}\n```\n\nTests:\n```rust\n#[test]\nfn normalize_payload_filters_empty_values() {\n use std::collections::HashMap;\n let mut payload = HashMap::new();\n payload.insert(\"id\".to_string(), \"7\".to_string());\n payload.insert(\"name\".to_string(), \"\".to_string());\n let out = normalize_payload(payload);\n assert!(out.contains_key(\"id\"));\n assert!(!out.contains_key(\"name\"));\n}\n```\n\nVerification:\n- `cargo test`\n- `cargo clippy -- -D warnings`\n\nEngineering notes:\n- Language: Rust\n- Framework/tooling: SQLx\n- Stack context: Next.js, Node.js, Prisma, PostgreSQL, Playwright, Docker\n- Domain: reporting engine\n- Task type: misleading_symptom_debug\n- Difficulty: hard\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "Task type: secure_architecture\nScenario: edge sync\nDomain focus: model checking\nPrimary language: bash\nDifficulty: hard\nScale/SLO: 10k RPS peak\nComponent: component_isuxpufk\nConstraints: include verification strategy, assume adversarial inputs; validate everything, explicit contracts and invariants, include backward compatibility and migration plan, include failure modes and recovery, include test vectors and fuzz strategy\nAssume weekly network partitions.\nDeliverable: Provide a defensive threat model and secure-by-default architecture; include monitoring/detection and tests (no offensive content).\n\nOutput: elite engineering answer optimized for correctness, performance, and operability.\n**Contract**\n- Inputs validated at the boundary; explicit error taxonomy.\n- Idempotency for side effects via request_id; deterministic replay.\n- Backward compatibility: additive changes by default; versioned breaking changes.\n**Invariants**\n- Determinism: replay of the same event log yields identical outputs.\n- Safety: state transitions preserve invariants; no partial commit leaks.\n- Liveness: under bounded faults and stable network, progress occurs.\n**Failure modes & recovery**\n- Duplicate requests: de-duplicate by (tenant, request_id) returning cached response.\n- Network partition: minority cannot commit; clients receive retriable errors.\n- Crash during commit: WAL replay completes or transaction aborts; no torn writes.\n**Security posture (defensive)**\n- Threat model: auth/authz, injection, replay/abuse, supply chain.\n- Least privilege; secrets in managed store; audit logs for sensitive ops.\n- Input normalization, parameterized queries, path traversal protections.\n**Verification strategy**\n- Fuzzing of parsers/framers/validators with corpus seeds.\n- Canary + shadow traffic; invariants checked in production via assertions/metrics.\n- Deterministic simulation with fault injection (crash/partition/latency).\n\n**Snippet**\n```text\nImplementation sketch: factor pure state-machine core; adapters for I/O; add deterministic replay log.\n```\nHard checks: fault injection tests gate merges; perf thresholds enforced in CI.", "source": "WithinUsAI/Omega_Genesis_Coder_100k"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: Language: Java\nFramework/tooling: Hibernate\nDomain: repo automation\nLogic challenge: rate-limit bypass\nTask type: algorithmic_correctness\nDifficulty: medium\n\nReturn a rigorous engineering answer:\n- identify the hidden root cause or logical failure\n- present the corrected implementation\n- add tests that prove the fix\n- list verification commands\n- explain why naive fixes are insufficient when relevant\n\nRepository sketch:\nrepo/\n src/main/java/com/acme/App.java\n src/main/java/com/acme/Service.java\n src/test/java/com/acme/AppTest.java\n pom.xml\n\nFocus: Focus on strong structured logic with edge cases, data validation, and concurrency safety.\n\nassistant: Diagnosis:\n- Root cause: the failure around rate-limit bypass is caused by missing validation, weak edge-case handling, or unsafe lifecycle behavior in the current implementation.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```java\nimport java.util.HashMap;\nimport java.util.Map;\n\npublic final class RequestHandler {\n public static Map handleRequest(Map payload) {\n Map clean = new HashMap<>();\n for (Map.Entry entry : payload.entrySet()) {\n if (entry.getValue() != null) clean.put(entry.getKey().trim(), entry.getValue());\n }\n if (!clean.containsKey(\"id\")) throw new IllegalArgumentException(\"missing id\");\n return Map.of(\"ok\", true, \"data\", clean);\n }\n}\n```\n\nTests:\n```java\nimport static org.junit.jupiter.api.Assertions.*;\nimport java.util.Map;\nimport org.junit.jupiter.api.Test;\n\nclass RequestHandlerTest {\n @Test\n void requiresId() {\n assertThrows(IllegalArgumentException.class, () -> RequestHandler.handleRequest(Map.of(\"name\", \"x\")));\n }\n}\n```\n\nVerification:\n- `./gradlew test`\n- `mvn test`\n\nEngineering notes:\n- Language: Java\n- Framework/tooling: Hibernate\n- Stack context: Go, Gin, PostgreSQL, gRPC, Prometheus, Docker\n- Domain: repo automation\n- Task type: algorithmic_correctness\n- Difficulty: medium\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: Language: Go\nFramework/tooling: sqlc\nDomain: repo automation\nLogic challenge: gRPC retry storm\nTask type: concurrency_fix\nDifficulty: hard\n\nReturn a rigorous engineering answer:\n- identify the hidden root cause or logical failure\n- present the corrected implementation\n- add tests that prove the fix\n- list verification commands\n- explain why naive fixes are insufficient when relevant\n\nRepository sketch:\nrepo/\n cmd/server/main.go\n internal/service/service.go\n internal/store/store.go\n internal/api/api.go\n service_test.go\n go.mod\n\nFocus: Focus on strong structured logic with edge cases, data validation, and concurrency safety.\n\nassistant: Diagnosis:\n- Root cause: the failure around gRPC retry storm is caused by missing validation, weak edge-case handling, or unsafe lifecycle behavior in the current implementation.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```go\npackage service\n\nimport \"fmt\"\n\nfunc NormalizePayload(payload map[string]any) map[string]any {\n\tout := make(map[string]any)\n\tfor k, v := range payload {\n\t\tif v == nil {\n\t\t\tcontinue\n\t\t}\n\t\tout[k] = v\n\t}\n\treturn out\n}\n\nfunc Handle(payload map[string]any) (map[string]any, error) {\n\tclean := NormalizePayload(payload)\n\tif _, ok := clean[\"id\"]; !ok {\n\t\treturn nil, fmt.Errorf(\"missing id\")\n\t}\n\treturn map[string]any{\"ok\": true, \"data\": clean}, nil\n}\n```\n\nTests:\n```go\npackage service\n\nimport \"testing\"\n\nfunc TestHandle(t *testing.T) {\n\tgot, err := Handle(map[string]any{\"id\": 7, \"name\": \"ok\", \"unused\": nil})\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tif got[\"ok\"] != true {\n\t\tt.Fatalf(\"expected ok=true\")\n\t}\n\tif _, err := Handle(map[string]any{\"name\": \"x\"}); err == nil {\n\t\tt.Fatalf(\"expected missing id error\")\n\t}\n}\n```\n\nVerification:\n- `go test ./...`\n- `go vet ./...`\n\nEngineering notes:\n- Language: Go\n- Framework/tooling: sqlc\n- Stack context: Go, Gin, PostgreSQL, gRPC, Prometheus, Docker\n- Domain: repo automation\n- Task type: concurrency_fix\n- Difficulty: hard\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "Fix the bug and add pytest tests.\n\n```python\ndef f25821(n: int) -> int:\n # sum 1..n inclusive\n if n < 0: raise ValueError\n total = 0\n for k in range(n): # BUG\n total += k\n return total\n```\nReturn unified diffs for `m89403.py` and `test_m89403.py`.\n\n*** Begin Patch\n*** Update File: m89403.py\n@@\n def f25821(n: int) -> int:\n@@\n- for k in range(n): # BUG\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_m89403.py\n+import pytest\n+from m89403 import f25821\n+\n+def test_small():\n+ assert f25821(7) == 28\n+\n+def test_zero():\n+ assert f25821(0) == 0\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ f25821(-1)\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Build an elite-grade solution in the domain of security engineering (defensive) for scenario: multi-tenant SaaS.\nPrimary language: rust.\nDifficulty: medium.\nConstraints: avoid undefined behavior and data races, include tests or verification strategy, include invariants and failure modes, provide rollout and rollback guidance.\nComponent: component_paxxqjl.\nAssume strict auditability and replayable history.\nTask: Define an API and evolving schema strategy (versioning, migrations, compatibility rules). Provide example schemas and validation tests.\n\nOutput: production blueprint plus correctness arguments and test strategy.\nOutput: GPU pipeline design for throughput and tail-latency.\n\n**Pipeline**\n- Request batching with max batch size + max wait (e.g., 5ms) to control p99.\n- Separate CPU pre/post-processing threads; pin memory for transfers if available.\n- Model warmup; cache weights in VRAM; use concurrency limits.\n\n**Monitoring**\n- GPU utilization, queue wait time, batch size distribution, OOM events.\n\n**Fallback**\n- Graceful degradation to smaller batch size; circuit breaker on repeated OOM.\n\n\nChecks: boundary validation and deterministic behavior verified.", "source": "WithinUsAI/Elite_GOD_Coder_100k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Fix a bug and add tests.\n\nFile: pc58xm02xe4w.py\n```python\ndef fr5k4highkd(n: int) -> int:\n \"\"\"Sum 1..n inclusive.\"\"\"\n if n < 0:\n raise ValueError(\"n must be non-negative\")\n total = 0\n for k in range(n): # BUG: should include n\n total += k\n return total\n```\n\nReturn unified diffs for pc58xm02xe4w.py and test_pc58xm02xe4w.py (pytest).\n\n*** Begin Patch\n*** Update File: pc58xm02xe4w.py\n@@\n def fr5k4highkd(n: int) -> int:\n@@\n total = 0\n- for k in range(n): # BUG: should include n\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_pc58xm02xe4w.py\n+import pytest\n+from pc58xm02xe4w import fr5k4highkd\n+\n+def test_zero():\n+ assert fr5k4highkd(0) == 0\n+\n+def test_one():\n+ assert fr5k4highkd(1) == 1\n+\n+def test_small():\n+ assert fr5k4highkd(7) == 28\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ fr5k4highkd(-1)\n+\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Design a production system for education supporting audit logs.\nTarget platform: web (React + TypeScript).\nRequirements: APIs, data model, scaling strategy, failure modes, and security.\nConstraints: must include documentation/comments, must include type hints where applicable, must include clear error handling.\nDifficulty: easy. Assume untrusted input; validate everything.\n\nOutput: actionable implementation and verification artifacts.\nDeliverable: system design with APIs, data model, and operational plan.\n\n**High-level architecture**\n- Edge: API Gateway + WAF\n- Core service: stateless app pods behind L7 LB\n- Data: Postgres (primary), Redis (cache + rate limit tokens), Object storage (uploads if needed)\n- Async: message queue (e.g., SQS/Rabbit) + worker pool for background jobs\n- Observability: structured logs + metrics + tracing\n\n**APIs (example)**\n- `POST /v1/{resource}` create (idempotent via `Idempotency-Key`)\n- `GET /v1/{resource}/{id}` read\n- `POST /v1/{resource}/{id}:action` command endpoint when side effects exist\n\n**Data model (Postgres)**\n- `resources(id UUID PK, tenant_id UUID, status TEXT, payload JSONB, created_at, updated_at)`\n- Unique constraint for idempotency: `(tenant_id, idempotency_key)` in a separate table:\n - `idempotency(tenant_id, key TEXT, request_hash TEXT, response JSONB, created_at, PRIMARY KEY(tenant_id,key))`\n\n**Scaling**\n- App layer scales horizontally; keep sessions out of process.\n- Cache reads in Redis; write-through invalidation on mutations.\n- Use connection pooling; consider read replicas for heavy reads.\n\n**Failure modes**\n- Retries: only for safe/ idempotent operations; exponential backoff + jitter.\n- Partial failures: background jobs must be idempotent; use a de-dup key.\n\n**Security**\n- AuthN: JWT/OIDC; AuthZ: RBAC/ABAC with tenant isolation\n- Validate all inputs; enforce per-tenant quotas/rate limits.\n\n**Rollout**\n- Dark launch + feature flags; canary; rapid rollback by toggling flags.\n\n\nChecks: input validation, tests, and safe defaults included.", "source": "WithinUsAI/GOD_Coder_100k"} {"text": "Fix the bug and add pytest tests.\n\n```python\ndef f93395(n: int) -> int:\n # sum 1..n inclusive\n if n < 0: raise ValueError\n total = 0\n for k in range(n): # BUG\n total += k\n return total\n```\nReturn unified diffs for `m70485.py` and `test_m70485.py`.\n\n*** Begin Patch\n*** Update File: m70485.py\n@@\n def f93395(n: int) -> int:\n@@\n- for k in range(n): # BUG\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_m70485.py\n+import pytest\n+from m70485 import f93395\n+\n+def test_small():\n+ assert f93395(7) == 28\n+\n+def test_zero():\n+ assert f93395(0) == 0\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ f93395(-1)\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Design a production system for enterprise SaaS supporting background jobs.\nTarget platform: infra (Terraform).\nRequirements: APIs, data model, scaling strategy, failure modes, and security.\nConstraints: must include documentation/comments, must be easy to extend, must be secure-by-default, must be performant under load.\nDifficulty: expert. Assume schema evolves frequently; design for migrations.\n\nOutput: engineering-grade answer with edge cases covered.\nDeliverable: system design with APIs, data model, and operational plan.\n\n**High-level architecture**\n- Edge: API Gateway + WAF\n- Core service: stateless app pods behind L7 LB\n- Data: Postgres (primary), Redis (cache + rate limit tokens), Object storage (uploads if needed)\n- Async: message queue (e.g., SQS/Rabbit) + worker pool for background jobs\n- Observability: structured logs + metrics + tracing\n\n**APIs (example)**\n- `POST /v1/{resource}` create (idempotent via `Idempotency-Key`)\n- `GET /v1/{resource}/{id}` read\n- `POST /v1/{resource}/{id}:action` command endpoint when side effects exist\n\n**Data model (Postgres)**\n- `resources(id UUID PK, tenant_id UUID, status TEXT, payload JSONB, created_at, updated_at)`\n- Unique constraint for idempotency: `(tenant_id, idempotency_key)` in a separate table:\n - `idempotency(tenant_id, key TEXT, request_hash TEXT, response JSONB, created_at, PRIMARY KEY(tenant_id,key))`\n\n**Scaling**\n- App layer scales horizontally; keep sessions out of process.\n- Cache reads in Redis; write-through invalidation on mutations.\n- Use connection pooling; consider read replicas for heavy reads.\n\n**Failure modes**\n- Retries: only for safe/ idempotent operations; exponential backoff + jitter.\n- Partial failures: background jobs must be idempotent; use a de-dup key.\n\n**Security**\n- AuthN: JWT/OIDC; AuthZ: RBAC/ABAC with tenant isolation\n- Validate all inputs; enforce per-tenant quotas/rate limits.\n\n**Rollout**\n- Dark launch + feature flags; canary; rapid rollback by toggling flags.\n\n\nHard-mode checks: concurrency safety, idempotency, and rollback validated; add chaos tests where feasible.", "source": "WithinUsAI/GOD_Coder_100k"} {"text": "Debug and fix a subtle production bug related to webhooks in a healthtech service.\nTarget platform: web (React + TypeScript).\nRequirements: identify root cause, provide patch, and add regression tests.\nConstraints: must be secure-by-default, must be easy to extend, must be observable (logs/metrics/traces).\nDifficulty: expert. Include rollback strategy.\n\nOutput: design + implementation guidance suitable for shipping.\nDeliverable: production-grade reference implementation (FastAPI) + tests.\n\n```python\n# app.py\nfrom __future__ import annotations\n\nimport hashlib\nimport json\nfrom dataclasses import dataclass\nfrom datetime import datetime, timezone\nfrom typing import Any, Optional\n\nfrom fastapi import FastAPI, Header, HTTPException\nfrom pydantic import BaseModel, Field\n\napp = FastAPI(title=\"Idempotent API\")\n\nclass CreateReq(BaseModel):\n tenant_id: str = Field(min_length=1)\n amount_cents: int = Field(ge=0)\n currency: str = Field(min_length=3, max_length=3)\n\nclass CreateResp(BaseModel):\n id: str\n created_at: str\n echo: CreateReq\n\n@dataclass\nclass _IdempoEntry:\n request_hash: str\n response_json: str\n\n# In production: Postgres table with UNIQUE(tenant_id, key)\n_IDEMPO: dict[tuple[str, str], _IdempoEntry] = {}\n\ndef _hash_req(req: CreateReq) -> str:\n raw = req.model_dump_json()\n return hashlib.sha256(raw.encode(\"utf-8\")).hexdigest()\n\n@app.post(\"/v1/payments\", response_model=CreateResp)\ndef create_payment(\n req: CreateReq,\n idempotency_key: Optional[str] = Header(default=None, alias=\"Idempotency-Key\"),\n) -> Any:\n if not idempotency_key:\n raise HTTPException(status_code=400, detail=\"Missing Idempotency-Key\")\n if len(idempotency_key) > 128:\n raise HTTPException(status_code=400, detail=\"Idempotency-Key too long\")\n\n key = (req.tenant_id, idempotency_key)\n rh = _hash_req(req)\n\n existing = _IDEMPO.get(key)\n if existing:\n if existing.request_hash != rh:\n raise HTTPException(status_code=409, detail=\"Idempotency-Key reuse with different payload\")\n return json.loads(existing.response_json)\n\n # Create new payment (stubbed)\n pid = hashlib.md5(f\"{req.tenant_id}:{idempotency_key}\".encode()).hexdigest()\n resp = CreateResp(\n id=pid,\n created_at=datetime.now(timezone.utc).isoformat(),\n echo=req,\n )\n _IDEMPO[key] = _IdempoEntry(request_hash=rh, response_json=resp.model_dump_json())\n return resp\n```\n\n```python\n# test_app.py (pytest)\nfrom fastapi.testclient import TestClient\nfrom app import app\n\nclient = TestClient(app)\n\ndef test_idempotent_replay():\n headers = {\"Idempotency-Key\": \"abc\"}\n body = {\"tenant_id\":\"t1\",\"amount_cents\":100,\"currency\":\"USD\"}\n r1 = client.post(\"/v1/payments\", json=body, headers=headers)\n r2 = client.post(\"/v1/payments\", json=body, headers=headers)\n assert r1.status_code == 200 and r2.status_code == 200\n assert r1.json() == r2.json()\n\ndef test_payload_conflict():\n headers = {\"Idempotency-Key\": \"abc\"}\n b1 = {\"tenant_id\":\"t1\",\"amount_cents\":100,\"currency\":\"USD\"}\n b2 = {\"tenant_id\":\"t1\",\"amount_cents\":200,\"currency\":\"USD\"}\n assert client.post(\"/v1/payments\", json=b1, headers=headers).status_code == 200\n assert client.post(\"/v1/payments\", json=b2, headers=headers).status_code == 409\n```\n\nNotes:\n- Replace in-memory store with a DB table and transaction.\n- Store response + request hash to detect key reuse with different payload.\n\n\nHard-mode checks: concurrency safety, idempotency, and rollback validated; add chaos tests where feasible.", "source": "WithinUsAI/GOD_Coder_100k"} {"text": "Perform a code review for a fintech PR implementing file uploads.\nTarget platform: ML (scikit + batch).\nRequirements: list critical issues, improvements, and provide an improved patch excerpt.\nConstraints: must be production-ready, must be easy to extend, must include type hints where applicable.\nDifficulty: easy. Include rollback strategy.\n\nOutput: design + implementation guidance suitable for shipping.\nDeliverable: code review findings + improved patch excerpt.\n\n**Critical issues**\n1. Missing input validation at boundary; potential unexpected exceptions.\n2. No idempotency / retry safety for side-effecting endpoint.\n3. No tests for edge cases (empty input, duplicates, timeouts).\n4. Observability gaps: no request_id correlation, no metrics.\n\n**Improvements**\n- Add strict validation and explicit error responses.\n- Add idempotency key support for create endpoints.\n- Add unit + integration tests with CI gating.\n- Add structured logs and basic metrics.\n\nPatch excerpt (illustrative):\n```python\nif not idem_key:\n raise HTTPException(400, \"Missing Idempotency-Key\")\n```\n\n\nChecks: input validation, tests, and safe defaults included.", "source": "WithinUsAI/GOD_Coder_100k"} {"text": "Design and implement an algorithm for data modeling.\nRequirements: define inputs/outputs, implement solution with complexity analysis, and include tests.\nConstraints: must be memory-efficient, must be streaming-friendly, must include docstrings.\nDifficulty: medium. Avoid quadratic behavior on large inputs.\n\nDeliverable: corrected code and verification tests.\nProblem: compute rolling sums over events (ts:int,value:int) with window W seconds. Events may be out-of-order.\n\nComplexity: sorting O(n log n); window maintenance O(n); memory O(k).\n\n```python\nfrom __future__ import annotations\nfrom collections import deque\nfrom dataclasses import dataclass\nfrom typing import Iterable, List, Tuple\n\n@dataclass(frozen=True, slots=True)\nclass Event:\n ts: int\n value: int\n\ndef rolling_sum(events: Iterable[Event], window_s: int) -> List[Tuple[int,int]]:\n if window_s < 0:\n raise ValueError(\"window_s must be >= 0\")\n evs = sorted(events, key=lambda e: e.ts)\n q: deque[Event] = deque()\n s = 0\n out: List[Tuple[int,int]] = []\n for e in evs:\n q.append(e)\n s += e.value\n cutoff = e.ts - window_s\n while q and q[0].ts < cutoff:\n old = q.popleft()\n s -= old.value\n out.append((e.ts, s))\n return out\n```\n\n```python\nimport pytest\nfrom module_under_test import Event, rolling_sum\n\ndef test_rolling_sum():\n ev = [Event(10,1), Event(11,2), Event(20,5)]\n assert rolling_sum(ev, 5) == [(10,1),(11,3),(20,5)]\n```", "source": "WithinUsAI/python_GOD_coder_100k"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: Language: Bash\nFramework/tooling: sed\nDomain: feature flag service\nLogic challenge: race condition on worker shutdown\nTask type: monorepo_toolchain_recovery\nDifficulty: hard\n\nReturn a rigorous engineering answer:\n- identify the hidden root cause or logical failure\n- present the corrected implementation\n- add tests that prove the fix\n- list verification commands\n- explain why naive fixes are insufficient when relevant\n\nRepository sketch:\nrepo/\n scripts/\n run.sh\n deploy.sh\n tests/\n smoke.sh\n\nFocus: Focus on staff-level problem solving with multi-file patches, rollout implications, performance and security tradeoffs.\n\nassistant: Diagnosis:\n- Staff-level diagnosis: race condition on worker shutdown impacts correctness, operability, and future maintenance, so the fix must be minimal where possible but complete where necessary.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```bash\n#!/usr/bin/env bash\nset -euo pipefail\n\ninput=\"${1:-}\"\nif [[ -z \"$input\" ]]; then\n echo \"missing input\" >&2\n exit 1\nfi\n\nprintf '%s\n' \"$input\" | tr -d '\r'\n```\n\nTests:\n```bash\noutput=\"$(bash scripts/run.sh \"abc\")\"\ntest \"$output\" = \"abc\"\n```\n\nVerification:\n- `bash tests/smoke.sh`\n- `shellcheck scripts/*.sh`\n\nEngineering notes:\n- Language: Bash\n- Framework/tooling: sed\n- Stack context: GitHub Actions, Docker Compose, Kubernetes, Terraform\n- Domain: feature flag service\n- Task type: monorepo_toolchain_recovery\n- Difficulty: hard\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Fix a bug and add tests.\n\nFile: s1i54ytb22.py\n```python\ndef t41na1a(n: int) -> int:\n \"\"\"Sum 1..n inclusive.\"\"\"\n if n < 0:\n raise ValueError(\"n must be non-negative\")\n total = 0\n for k in range(n): # BUG: should include n\n total += k\n return total\n```\n\nReturn unified diffs for s1i54ytb22.py and test_s1i54ytb22.py (pytest).\n\n*** Begin Patch\n*** Update File: s1i54ytb22.py\n@@\n def t41na1a(n: int) -> int:\n@@\n total = 0\n- for k in range(n): # BUG: should include n\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_s1i54ytb22.py\n+import pytest\n+from s1i54ytb22 import t41na1a\n+\n+def test_zero():\n+ assert t41na1a(0) == 0\n+\n+def test_one():\n+ assert t41na1a(1) == 1\n+\n+def test_small():\n+ assert t41na1a(7) == 28\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ t41na1a(-1)\n+\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Implement an ML engineering workflow for social media focusing on rate limiting.\nTarget platform: ML (training + serving).\nRequirements: data contract, training loop, evaluation, model registry, serving API, monitoring.\nConstraints: must include clear error handling, must be easy to extend, must include documentation/comments, must be production-ready, must include type hints where applicable.\nDifficulty: medium. Assume GDPR-style deletion requests must be supported.\n\nOutput: engineering-grade answer with edge cases covered.\nDeliverable: ML engineering blueprint (training + serving + monitoring), safe and production-oriented.\n\n**Data contract**\n- Define feature schema + ranges; validate at training and serving.\n\n**Training**\n- Deterministic split; baseline model; track metrics (AUC/F1/latency).\n- Store artifacts: model, config, feature stats.\n\n**Registry**\n- Promote models via approval gates; record lineage.\n\n**Serving**\n- Separate inference service with `/predict`.\n- Input validation + default handling; timeouts.\n\n**Monitoring**\n- Data drift: feature distribution checks.\n- Performance: online metrics + periodic labels; alert on regression.\n\nMinimal serving skeleton (FastAPI-ish):\n```python\n# validate input -> vectorize -> model.predict_proba -> return\n```\n\n\nChecks: input validation, tests, and safe defaults included.", "source": "WithinUsAI/GOD_Coder_100k"} {"text": "Fix the bug and add pytest tests.\n\n```python\ndef f57267(n: int) -> int:\n # sum 1..n inclusive\n if n < 0: raise ValueError\n total = 0\n for k in range(n): # BUG\n total += k\n return total\n```\nReturn unified diffs for `m08181.py` and `test_m08181.py`.\n\n*** Begin Patch\n*** Update File: m08181.py\n@@\n def f57267(n: int) -> int:\n@@\n- for k in range(n): # BUG\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_m08181.py\n+import pytest\n+from m08181 import f57267\n+\n+def test_small():\n+ assert f57267(7) == 28\n+\n+def test_zero():\n+ assert f57267(0) == 0\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ f57267(-1)\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Write pytest tests for `f56967`.\n\n```python\ndef f56967(a: int, b: int) -> int:\n return a*a + b*b\n```\nInclude edge cases and a property-style check.\n\n```python\nimport random\nfrom m65281 import f56967\n\ndef test_known():\n assert f56967(3,4) == 25\n\ndef test_zero():\n assert f56967(0,0) == 0\n\ndef test_property_nonnegative():\n for _ in range(200):\n a=random.randint(-50,50)\n b=random.randint(-50,50)\n assert f56967(a,b) >= 0\n```", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Fix a bug and add tests.\n\nFile: fmt7o60wn.py\n```python\ndef zfvwok(n: int) -> int:\n \"\"\"Sum 1..n inclusive.\"\"\"\n if n < 0:\n raise ValueError(\"n must be non-negative\")\n total = 0\n for k in range(n): # BUG: should include n\n total += k\n return total\n```\n\nReturn unified diffs for fmt7o60wn.py and test_fmt7o60wn.py (pytest).\n\n*** Begin Patch\n*** Update File: fmt7o60wn.py\n@@\n def zfvwok(n: int) -> int:\n@@\n total = 0\n- for k in range(n): # BUG: should include n\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_fmt7o60wn.py\n+import pytest\n+from fmt7o60wn import zfvwok\n+\n+def test_zero():\n+ assert zfvwok(0) == 0\n+\n+def test_one():\n+ assert zfvwok(1) == 1\n+\n+def test_small():\n+ assert zfvwok(7) == 28\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ zfvwok(-1)\n+\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Fix a subtle bug in a Python module used for log processing.\nRequirements: explain root cause briefly, provide corrected code, and add regression tests.\nConstraints: must include docstrings, must provide clear error messages.\nDifficulty: expert. Include a small CLI example if relevant.\n\nDeliverable: production-ready reference solution.\n```python\nfrom __future__ import annotations\n\nfrom dataclasses import dataclass\nfrom pathlib import Path\nfrom typing import Iterable\nimport json\n\n\nclass ValidationError(ValueError):\n \"\"\"Raised when input validation fails.\"\"\"\n\n\ndef safe_join(base: Path, *parts: str) -> Path:\n \"\"\"Join paths while preventing traversal outside base.\"\"\"\n b = base.resolve()\n p = (b / Path(*parts)).resolve()\n if p != b and b not in p.parents:\n raise ValidationError(f\"unsafe path: {p}\")\n return p\n\n\n@dataclass(frozen=True, slots=True)\nclass Record:\n key: str\n value: int\n\n\ndef parse_jsonl(lines: Iterable[str]) -> list[Record]:\n out: list[Record] = []\n for idx, line in enumerate(lines, 1):\n s = line.strip()\n if not s:\n continue\n try:\n obj = json.loads(s)\n except json.JSONDecodeError as e:\n raise ValidationError(f\"line {idx}: invalid json\") from e\n if not isinstance(obj, dict):\n raise ValidationError(f\"line {idx}: expected object\")\n key = obj.get(\"key\")\n val = obj.get(\"value\")\n if not isinstance(key, str) or not key:\n raise ValidationError(f\"line {idx}: key must be non-empty str\")\n if not isinstance(val, int):\n raise ValidationError(f\"line {idx}: value must be int\")\n out.append(Record(key, val))\n return out\n\n\ndef write_jsonl(base: Path, rel: str, records: Iterable[Record]) -> Path:\n base.mkdir(parents=True, exist_ok=True)\n dst = safe_join(base, rel)\n dst.parent.mkdir(parents=True, exist_ok=True)\n with dst.open(\"w\", encoding=\"utf-8\", newline=\"\\n\") as f:\n for r in records:\n f.write(json.dumps({\"key\": r.key, \"value\": r.value}, ensure_ascii=False) + \"\\n\")\n return dst\n```\n\n```python\n# tests (pytest-style)\nimport json\nfrom pathlib import Path\nimport pytest\nfrom module_under_test import ValidationError, Record, parse_jsonl, write_jsonl\n\ndef test_parse_ok():\n lines = [json.dumps({\"key\":\"a\",\"value\":1}), json.dumps({\"key\":\"b\",\"value\":2})]\n assert parse_jsonl(lines) == [Record(\"a\",1), Record(\"b\",2)]\n\ndef test_parse_rejects_bad_json():\n with pytest.raises(ValidationError):\n parse_jsonl([\"{not json}\"])\n\ndef test_safe_join_blocks_traversal(tmp_path: Path):\n with pytest.raises(ValidationError):\n write_jsonl(tmp_path, \"../x.jsonl\", [Record(\"a\",1)])\n```", "source": "WithinUsAI/python_GOD_coder_100k"} {"text": "Write a thorough test suite for a Python component used for validation.\nRequirements: cover edge cases, invalid inputs, and behavior invariants.\nConstraints: must handle Windows paths safely, stdlib-only, must include type hints.\nDifficulty: easy. Include a small CLI example if relevant.\n\nDeliverable: production-ready reference solution.\n```python\n# tests (pytest-style) for a module providing: normalize(), parse_lines(), compute_stats()\nimport math\nimport pytest\n\ndef test_normalize_idempotent(module_under_test):\n x = \" A\\tB \"\n assert module_under_test.normalize(module_under_test.normalize(x)) == module_under_test.normalize(x)\n\ndef test_parse_lines_rejects_invalid(module_under_test):\n with pytest.raises(ValueError):\n module_under_test.parse_lines([\"\", \"???\", None]) # type: ignore[arg-type]\n\ndef test_compute_stats_basic(module_under_test):\n data = [1, 2, 3, 4]\n s = module_under_test.compute_stats(data)\n assert s.count == 4\n assert s.total == 10\n assert math.isclose(s.mean, 2.5)\n```", "source": "WithinUsAI/python_GOD_coder_100k"} {"text": "Build an elite-grade solution in the domain of security engineering (defensive) for scenario: event ingestion.\nPrimary language: typescript.\nDifficulty: hard.\nConstraints: document performance characteristics, include invariants and failure modes, assume untrusted inputs; validate and sanitize.\nComponent: component_rbfvjhk.\nAssume partial network partitions occur weekly.\nTask: Provide SLOs, alerting, dashboards, runbooks, and incident playbook. Include chaos testing and safe rollout strategy.\n\nOutput: elite-grade engineering answer with contracts, edge cases, and verification.\nOutput: SLOs + alerts + runbooks + chaos strategy.\n\n**SLOs**\n- Availability: 99.9% monthly\n- Latency: p95 < 200ms, p99 < 400ms\n- Error rate: < 0.1%\n\n**Alerts**\n- Burn-rate alerts for SLOs (fast/slow windows)\n- Saturation: CPU, memory, queue depth, DB connections\n- Dependency health: cache hit rate drop, downstream timeouts\n\n**Runbooks**\n- Triage: identify blast radius, feature-flag rollback, capacity mitigation\n- Post-incident: timeline, contributing factors, action items\n\n**Chaos**\n- Inject latency, partial outages, and restarts in staging; verify steady-state SLOs.\n\n\nHard checks: failure injection tests and performance regressions gated.", "source": "WithinUsAI/Elite_GOD_Coder_100k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Refactor to modern typed Python with immutability and tests.\n\nFile: brrv_76r5vu.py\n```python\nclass P9Nvtb042:\n def __init__(self, name, values):\n self.name = name\n self.values = list(values)\n def add(self, v):\n self.values.append(v)\n def mean(self):\n s = 0\n for x in self.values:\n s += x\n return s / len(self.values)\n```\n\nReturn full new brrv_76r5vu.py and test_brrv_76r5vu.py.\n\n# brrv_76r5vu.py\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom typing import Iterable, Tuple\n\n@dataclass(frozen=True)\nclass P9Nvtb042:\n name: str\n values: Tuple[float, ...]\n\n @staticmethod\n def create(name: str, values: Iterable[float]) -> \"P9Nvtb042\":\n vals = tuple(float(v) for v in values)\n if not vals:\n raise ValueError(\"values must be non-empty\")\n return P9Nvtb042(name=name, values=vals)\n\n def add(self, v: float) -> \"P9Nvtb042\":\n return P9Nvtb042(name=self.name, values=self.values + (float(v),))\n\n def mean(self) -> float:\n return sum(self.values) / len(self.values)\n\n# test_brrv_76r5vu.py\nimport pytest\nfrom brrv_76r5vu import P9Nvtb042\n\ndef test_mean_and_add():\n c = P9Nvtb042.create(\"a\", [1, 2, 3])\n assert c.mean() == 2.0\n assert c.add(5).mean() == (1 + 2 + 3 + 5) / 4\n\ndef test_empty_raises():\n with pytest.raises(ValueError):\n P9Nvtb042.create(\"x\", [])", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: Project stack: Next.js, Node.js, Prisma, PostgreSQL, Playwright, Docker\nLanguage: Rust\nDependency challenge: migration ordering failure\nTask type: cve_dependency_remediation\nDifficulty: medium\n\nFix this as a senior engineer.\nRequired:\n- identify the version or compatibility failure mode\n- produce the corrected config/code/build patch\n- explain rollback-safe migration notes\n- add regression tests or reproducibility checks\n- include concrete verification commands\n\nRepository sketch:\nrepo/\n src/main.rs\n src/lib.rs\n src/service.rs\n src/store.rs\n tests/integration.rs\n Cargo.toml\n\nFocus: Focus on versioning, migrations, lockfiles, runtime compatibility, and secure dependency handling.\n\nassistant: Diagnosis:\n- Root cause: the issue around migration ordering failure is a dependency, migration, or runtime-compatibility mismatch that needs a rollback-safe patch.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```rust\nuse std::collections::HashMap;\n\npub fn normalize_payload(payload: HashMap) -> HashMap {\n payload\n .into_iter()\n .filter(|(_, v)| !v.trim().is_empty())\n .collect()\n}\n```\n\nTests:\n```rust\n#[test]\nfn normalize_payload_filters_empty_values() {\n use std::collections::HashMap;\n let mut payload = HashMap::new();\n payload.insert(\"id\".to_string(), \"7\".to_string());\n payload.insert(\"name\".to_string(), \"\".to_string());\n let out = normalize_payload(payload);\n assert!(out.contains_key(\"id\"));\n assert!(!out.contains_key(\"name\"));\n}\n```\n\nVerification:\n- `cargo test`\n- `cargo clippy -- -D warnings`\n\nEngineering notes:\n- Language: Rust\n- Framework/tooling: cargo test\n- Stack context: Next.js, Node.js, Prisma, PostgreSQL, Playwright, Docker\n- Domain: developer platform\n- Task type: cve_dependency_remediation\n- Difficulty: medium\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "Optimize while preserving behavior and order.\n\n```python\ndef f70944(xs):\n out=[]\n for x in xs:\n if x not in out: out.append(x)\n return out\n```\nReturn `m52992.py` with types and O(n) average.\n\n```python\n# m52992.py\nfrom __future__ import annotations\nfrom typing import Iterable, List, Set, TypeVar\nT=TypeVar(\"T\")\n\ndef f70944(xs: Iterable[T]) -> List[T]:\n \"\"\"Unique items preserving first-seen order.\"\"\"\n seen: Set[T]=set()\n out: List[T]=[]\n for x in xs:\n if x in seen: continue\n seen.add(x); out.append(x)\n return out\n```", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Refactor to modern typed Python with immutability and tests.\n\nFile: x20hdqu1f.py\n```python\nclass L7Sl6N5Yocc6:\n def __init__(self, name, values):\n self.name = name\n self.values = list(values)\n def add(self, v):\n self.values.append(v)\n def mean(self):\n s = 0\n for x in self.values:\n s += x\n return s / len(self.values)\n```\n\nReturn full new x20hdqu1f.py and test_x20hdqu1f.py.\n\n# x20hdqu1f.py\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom typing import Iterable, Tuple\n\n@dataclass(frozen=True)\nclass L7Sl6N5Yocc6:\n name: str\n values: Tuple[float, ...]\n\n @staticmethod\n def create(name: str, values: Iterable[float]) -> \"L7Sl6N5Yocc6\":\n vals = tuple(float(v) for v in values)\n if not vals:\n raise ValueError(\"values must be non-empty\")\n return L7Sl6N5Yocc6(name=name, values=vals)\n\n def add(self, v: float) -> \"L7Sl6N5Yocc6\":\n return L7Sl6N5Yocc6(name=self.name, values=self.values + (float(v),))\n\n def mean(self) -> float:\n return sum(self.values) / len(self.values)\n\n# test_x20hdqu1f.py\nimport pytest\nfrom x20hdqu1f import L7Sl6N5Yocc6\n\ndef test_mean_and_add():\n c = L7Sl6N5Yocc6.create(\"a\", [1, 2, 3])\n assert c.mean() == 2.0\n assert c.add(5).mean() == (1 + 2 + 3 + 5) / 4\n\ndef test_empty_raises():\n with pytest.raises(ValueError):\n L7Sl6N5Yocc6.create(\"x\", [])", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: Repository domain: auth service\nPrimary language: C++\nFramework/tooling: Catch2\nReported problem: slow cold start\nTask type: feature_delivery\nDifficulty: medium\n\nProduce a complete professional engineering response:\n1. Diagnose the root cause.\n2. Provide the corrected implementation or patch.\n3. Add tests.\n4. Add verification commands.\n5. Note edge cases and any migration or rollback risk.\n\nRepository sketch:\nrepo/\n src/main.cpp\n src/service.cpp\n include/service.h\n tests/test_service.cpp\n CMakeLists.txt\n\nQuality target:\n- Minimal diff unless redesign is clearly required\n- Production-ready code\n- No placeholders\n- Secure defaults\n- Clear acceptance of failure cases\n\nFocus: Focus on complete implementation quality, patch correctness, tests, and production readiness.\n\nassistant: Diagnosis:\n- Root cause: the failure around slow cold start is caused by missing validation, weak edge-case handling, or unsafe lifecycle behavior in the current implementation.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```cpp\n#include \n#include \n\nusing Payload = std::unordered_map;\n\nPayload normalize_payload(const Payload& in) {\n Payload out;\n for (const auto& [k, v] : in) {\n if (!v.empty()) out[k] = v;\n }\n return out;\n}\n```\n\nTests:\n```cpp\nTEST_CASE(\"normalize_payload filters empty values\") {\n Payload in{{\"id\",\"7\"},{\"name\",\"\"}};\n auto out = normalize_payload(in);\n REQUIRE(out.count(\"id\") == 1);\n REQUIRE(out.count(\"name\") == 0);\n}\n```\n\nVerification:\n- `cmake --build build`\n- `ctest --test-dir build`\n\nEngineering notes:\n- Language: C++\n- Framework/tooling: Catch2\n- Stack context: GitHub Actions, Docker Compose, Kubernetes, Terraform\n- Domain: auth service\n- Task type: feature_delivery\n- Difficulty: medium\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Fix a bug and add tests.\n\nFile: ctaz10bl7.py\n```python\ndef xsksp2c_hb(n: int) -> int:\n \"\"\"Sum 1..n inclusive.\"\"\"\n if n < 0:\n raise ValueError(\"n must be non-negative\")\n total = 0\n for k in range(n): # BUG: should include n\n total += k\n return total\n```\n\nReturn unified diffs for ctaz10bl7.py and test_ctaz10bl7.py (pytest).\n\n*** Begin Patch\n*** Update File: ctaz10bl7.py\n@@\n def xsksp2c_hb(n: int) -> int:\n@@\n total = 0\n- for k in range(n): # BUG: should include n\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_ctaz10bl7.py\n+import pytest\n+from ctaz10bl7 import xsksp2c_hb\n+\n+def test_zero():\n+ assert xsksp2c_hb(0) == 0\n+\n+def test_one():\n+ assert xsksp2c_hb(1) == 1\n+\n+def test_small():\n+ assert xsksp2c_hb(7) == 28\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ xsksp2c_hb(-1)\n+\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Build an elite-grade solution in the domain of distributed systems for scenario: rate limiting gateway.\nPrimary language: bash.\nDifficulty: medium.\nConstraints: provide rollout and rollback guidance, avoid undefined behavior and data races, make the interface contract explicit.\nComponent: component_akssrbq.\nAssume schema changes every sprint; must be backward compatible.\nTask: Define properties/invariants and implement property-based tests (or generative tests) with a reference model and edge-case generators.\n\nOutput: production blueprint plus correctness arguments and test strategy.\nOutput: properties + reference model + generative tests.\n\n**Properties**\n- Idempotency: replayed command yields same result.\n- Monotonicity: versions only increase.\n- Conservation: for queues, produced items == consumed items (multiset) under no-loss assumption.\n\n**Approach**\n- Write a small reference model (pure function).\n- Generate random sequences of operations; compare implementation outputs to model.\n\n\nChecks: boundary validation and deterministic behavior verified.", "source": "WithinUsAI/Elite_GOD_Coder_100k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Refactor to modern typed Python with immutability and tests.\n\nFile: e7ahci1ss.py\n```python\nclass Q2Nu84Dc:\n def __init__(self, name, values):\n self.name = name\n self.values = list(values)\n def add(self, v):\n self.values.append(v)\n def mean(self):\n s = 0\n for x in self.values:\n s += x\n return s / len(self.values)\n```\n\nReturn full new e7ahci1ss.py and test_e7ahci1ss.py.\n\n# e7ahci1ss.py\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom typing import Iterable, Tuple\n\n@dataclass(frozen=True)\nclass Q2Nu84Dc:\n name: str\n values: Tuple[float, ...]\n\n @staticmethod\n def create(name: str, values: Iterable[float]) -> \"Q2Nu84Dc\":\n vals = tuple(float(v) for v in values)\n if not vals:\n raise ValueError(\"values must be non-empty\")\n return Q2Nu84Dc(name=name, values=vals)\n\n def add(self, v: float) -> \"Q2Nu84Dc\":\n return Q2Nu84Dc(name=self.name, values=self.values + (float(v),))\n\n def mean(self) -> float:\n return sum(self.values) / len(self.values)\n\n# test_e7ahci1ss.py\nimport pytest\nfrom e7ahci1ss import Q2Nu84Dc\n\ndef test_mean_and_add():\n c = Q2Nu84Dc.create(\"a\", [1, 2, 3])\n assert c.mean() == 2.0\n assert c.add(5).mean() == (1 + 2 + 3 + 5) / 4\n\ndef test_empty_raises():\n with pytest.raises(ValueError):\n Q2Nu84Dc.create(\"x\", [])", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Fix a bug and add tests.\n\nFile: vvth2_t2.py\n```python\ndef if_gs8ky34o(n: int) -> int:\n \"\"\"Sum 1..n inclusive.\"\"\"\n if n < 0:\n raise ValueError(\"n must be non-negative\")\n total = 0\n for k in range(n): # BUG: should include n\n total += k\n return total\n```\n\nReturn unified diffs for vvth2_t2.py and test_vvth2_t2.py (pytest).\n\n*** Begin Patch\n*** Update File: vvth2_t2.py\n@@\n def if_gs8ky34o(n: int) -> int:\n@@\n total = 0\n- for k in range(n): # BUG: should include n\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_vvth2_t2.py\n+import pytest\n+from vvth2_t2 import if_gs8ky34o\n+\n+def test_zero():\n+ assert if_gs8ky34o(0) == 0\n+\n+def test_one():\n+ assert if_gs8ky34o(1) == 1\n+\n+def test_small():\n+ assert if_gs8ky34o(7) == 28\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ if_gs8ky34o(-1)\n+\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Build an elite-grade solution in the domain of stream processing for scenario: chat messaging.\nPrimary language: typescript.\nDifficulty: medium.\nConstraints: document performance characteristics, avoid undefined behavior and data races, include tests or verification strategy.\nComponent: component_kbidyhp.\nAssume compliance requires data deletion with proofs.\nTask: Provide SLOs, alerting, dashboards, runbooks, and incident playbook. Include chaos testing and safe rollout strategy.\n\nOutput: elite-grade engineering answer with contracts, edge cases, and verification.\nOutput: SLOs + alerts + runbooks + chaos strategy.\n\n**SLOs**\n- Availability: 99.9% monthly\n- Latency: p95 < 200ms, p99 < 400ms\n- Error rate: < 0.1%\n\n**Alerts**\n- Burn-rate alerts for SLOs (fast/slow windows)\n- Saturation: CPU, memory, queue depth, DB connections\n- Dependency health: cache hit rate drop, downstream timeouts\n\n**Runbooks**\n- Triage: identify blast radius, feature-flag rollback, capacity mitigation\n- Post-incident: timeline, contributing factors, action items\n\n**Chaos**\n- Inject latency, partial outages, and restarts in staging; verify steady-state SLOs.\n\n\nChecks: boundary validation and deterministic behavior verified.", "source": "WithinUsAI/Elite_GOD_Coder_100k"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: Project domain: developer platform\nImplementation stack: Spring Boot, PostgreSQL, JUnit, Gradle, Docker, GitHub Actions\nSoftware delivery problem: idempotent retry design\nTask type: release_engineering_fix\nDifficulty: medium\n\nReturn a complete delivery-grade response with:\n- diagnosis or design reasoning\n- implementation\n- test plan or tests\n- rollout plan\n- rollback or compatibility note\n- verification commands\n\nRepository sketch:\nrepo/\n migrations/\n 001_init.sql\n 002_add_index.sql\n queries/\n report.sql\n tests/\n report_cases.md\n\nFocus: Focus on shipping production software with rollout safety, acceptance criteria, telemetry, and maintenance quality.\n\nassistant: Diagnosis:\n- Root cause or delivery blocker: idempotent retry design needs both implementation work and a safe shipping plan.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```sql\nWITH ranked AS (\n SELECT\n user_id,\n created_at,\n amount,\n ROW_NUMBER() OVER (PARTITION BY user_id ORDER BY created_at DESC, id DESC) AS rn\n FROM orders\n)\nSELECT user_id, created_at, amount\nFROM ranked\nWHERE rn = 1;\n```\n\nTests:\n```sql\n-- Correctness checks:\n-- 1) multiple rows per user\n-- 2) identical timestamps require deterministic tie-breaker\n-- 3) null values handled by business rules\n```\n\nVerification:\n- `run migration checks`\n- `run query correctness cases`\n\nEngineering notes:\n- Language: SQL\n- Framework/tooling: SQLite\n- Stack context: Spring Boot, PostgreSQL, JUnit, Gradle, Docker, GitHub Actions\n- Domain: developer platform\n- Task type: release_engineering_fix\n- Difficulty: medium\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Refactor to modern typed Python with immutability and tests.\n\nFile: ket7k28x02pk.py\n```python\nclass Lff2Vi62:\n def __init__(self, name, values):\n self.name = name\n self.values = list(values)\n def add(self, v):\n self.values.append(v)\n def mean(self):\n s = 0\n for x in self.values:\n s += x\n return s / len(self.values)\n```\n\nReturn full new ket7k28x02pk.py and test_ket7k28x02pk.py.\n\n# ket7k28x02pk.py\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom typing import Iterable, Tuple\n\n@dataclass(frozen=True)\nclass Lff2Vi62:\n name: str\n values: Tuple[float, ...]\n\n @staticmethod\n def create(name: str, values: Iterable[float]) -> \"Lff2Vi62\":\n vals = tuple(float(v) for v in values)\n if not vals:\n raise ValueError(\"values must be non-empty\")\n return Lff2Vi62(name=name, values=vals)\n\n def add(self, v: float) -> \"Lff2Vi62\":\n return Lff2Vi62(name=self.name, values=self.values + (float(v),))\n\n def mean(self) -> float:\n return sum(self.values) / len(self.values)\n\n# test_ket7k28x02pk.py\nimport pytest\nfrom ket7k28x02pk import Lff2Vi62\n\ndef test_mean_and_add():\n c = Lff2Vi62.create(\"a\", [1, 2, 3])\n assert c.mean() == 2.0\n assert c.add(5).mean() == (1 + 2 + 3 + 5) / 4\n\ndef test_empty_raises():\n with pytest.raises(ValueError):\n Lff2Vi62.create(\"x\", [])", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Fix a bug and add tests.\n\nFile: fisxn_e8.py\n```python\ndef m4a3xdujltea(n: int) -> int:\n \"\"\"Sum 1..n inclusive.\"\"\"\n if n < 0:\n raise ValueError(\"n must be non-negative\")\n total = 0\n for k in range(n): # BUG: should include n\n total += k\n return total\n```\n\nReturn unified diffs for fisxn_e8.py and test_fisxn_e8.py (pytest).\n\n*** Begin Patch\n*** Update File: fisxn_e8.py\n@@\n def m4a3xdujltea(n: int) -> int:\n@@\n total = 0\n- for k in range(n): # BUG: should include n\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_fisxn_e8.py\n+import pytest\n+from fisxn_e8 import m4a3xdujltea\n+\n+def test_zero():\n+ assert m4a3xdujltea(0) == 0\n+\n+def test_one():\n+ assert m4a3xdujltea(1) == 1\n+\n+def test_small():\n+ assert m4a3xdujltea(7) == 28\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ m4a3xdujltea(-1)\n+\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Fix a bug and add tests.\n\nFile: thni69t6t82p.py\n```python\ndef z7ofv292k(n: int) -> int:\n \"\"\"Sum 1..n inclusive.\"\"\"\n if n < 0:\n raise ValueError(\"n must be non-negative\")\n total = 0\n for k in range(n): # BUG: should include n\n total += k\n return total\n```\n\nReturn unified diffs for thni69t6t82p.py and test_thni69t6t82p.py (pytest).\n\n*** Begin Patch\n*** Update File: thni69t6t82p.py\n@@\n def z7ofv292k(n: int) -> int:\n@@\n total = 0\n- for k in range(n): # BUG: should include n\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_thni69t6t82p.py\n+import pytest\n+from thni69t6t82p import z7ofv292k\n+\n+def test_zero():\n+ assert z7ofv292k(0) == 0\n+\n+def test_one():\n+ assert z7ofv292k(1) == 1\n+\n+def test_small():\n+ assert z7ofv292k(7) == 28\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ z7ofv292k(-1)\n+\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Optimize while preserving behavior and order.\n\n```python\ndef f57613(xs):\n out=[]\n for x in xs:\n if x not in out: out.append(x)\n return out\n```\nReturn `m79659.py` with types and O(n) average.\n\n```python\n# m79659.py\nfrom __future__ import annotations\nfrom typing import Iterable, List, Set, TypeVar\nT=TypeVar(\"T\")\n\ndef f57613(xs: Iterable[T]) -> List[T]:\n \"\"\"Unique items preserving first-seen order.\"\"\"\n seen: Set[T]=set()\n out: List[T]=[]\n for x in xs:\n if x in seen: continue\n seen.add(x); out.append(x)\n return out\n```", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: Repository domain: artifact registry\nPrimary language: Java\nFramework/tooling: Hibernate\nReported problem: gRPC retry storm\nTask type: performance_patch\nDifficulty: medium\n\nProduce a complete professional engineering response:\n1. Diagnose the root cause.\n2. Provide the corrected implementation or patch.\n3. Add tests.\n4. Add verification commands.\n5. Note edge cases and any migration or rollback risk.\n\nRepository sketch:\nrepo/\n src/main/java/com/acme/App.java\n src/main/java/com/acme/Service.java\n src/test/java/com/acme/AppTest.java\n pom.xml\n\nQuality target:\n- Minimal diff unless redesign is clearly required\n- Production-ready code\n- No placeholders\n- Secure defaults\n- Clear acceptance of failure cases\n\nFocus: Focus on complete implementation quality, patch correctness, tests, and production readiness.\n\nassistant: Diagnosis:\n- Root cause: the failure around gRPC retry storm is caused by missing validation, weak edge-case handling, or unsafe lifecycle behavior in the current implementation.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```java\nimport java.util.HashMap;\nimport java.util.Map;\n\npublic final class RequestHandler {\n public static Map handleRequest(Map payload) {\n Map clean = new HashMap<>();\n for (Map.Entry entry : payload.entrySet()) {\n if (entry.getValue() != null) clean.put(entry.getKey().trim(), entry.getValue());\n }\n if (!clean.containsKey(\"id\")) throw new IllegalArgumentException(\"missing id\");\n return Map.of(\"ok\", true, \"data\", clean);\n }\n}\n```\n\nTests:\n```java\nimport static org.junit.jupiter.api.Assertions.*;\nimport java.util.Map;\nimport org.junit.jupiter.api.Test;\n\nclass RequestHandlerTest {\n @Test\n void requiresId() {\n assertThrows(IllegalArgumentException.class, () -> RequestHandler.handleRequest(Map.of(\"name\", \"x\")));\n }\n}\n```\n\nVerification:\n- `./gradlew test`\n- `mvn test`\n\nEngineering notes:\n- Language: Java\n- Framework/tooling: Hibernate\n- Stack context: ASP.NET Core, SQL Server, EF Core, xUnit, Docker\n- Domain: artifact registry\n- Task type: performance_patch\n- Difficulty: medium\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "Fix the bug and add pytest tests.\n\n```python\ndef f57753(n: int) -> int:\n # sum 1..n inclusive\n if n < 0: raise ValueError\n total = 0\n for k in range(n): # BUG\n total += k\n return total\n```\nReturn unified diffs for `m79679.py` and `test_m79679.py`.\n\n*** Begin Patch\n*** Update File: m79679.py\n@@\n def f57753(n: int) -> int:\n@@\n- for k in range(n): # BUG\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_m79679.py\n+import pytest\n+from m79679 import f57753\n+\n+def test_small():\n+ assert f57753(7) == 28\n+\n+def test_zero():\n+ assert f57753(0) == 0\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ f57753(-1)\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Produce an offline-first self-evolving code assistant architecture named `r38iu95`.\nMust include: module layout, patch-safety policy, evaluation gates (tests/lint/types), versioned memory index.\n\nArchitecture: `r38iu95` (offline-first, self-evolving)\n\nModules\n- core/loop.py: evolve → validate → accept/reject (bounded iterations)\n- patching/: diff builder, safe apply, atomic writes, rollback points\n- policy/: allowlist paths, deny globs (.git/, __pycache__/, binaries), patch size caps\n- signals/: parse pytest/ruff/mypy into normalized findings\n- memory/index.jsonl: append-only snapshots (hashes, metrics, rationale)\n\nSafety gates\n- refuse path traversal/symlink escapes; never edit binaries\n- accept only if tests/lint/types stay green or improve", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Build an elite-grade solution in the domain of stream processing for scenario: analytics pipeline.\nPrimary language: rust.\nDifficulty: expert.\nConstraints: provide rollout and rollback guidance, make the interface contract explicit, include invariants and failure modes.\nComponent: component_qjcryab.\nAssume partial network partitions occur weekly.\nTask: Design an application-level protocol (framing, retries, timeouts, backpressure). Provide client/server skeleton and test vectors.\n\nOutput: production blueprint plus correctness arguments and test strategy.\nOutput: protocol framing + retry policy + client/server skeleton.\n\n**Framing**\n- Length-prefixed: uint32_be length + payload\n- Payload: msgpack/json; include request_id, type, and optional checksum\n\n**Reliability**\n- Retries only for idempotent ops; exponential backoff + jitter.\n- Timeouts: connect, read, overall; enforce max in-flight to provide backpressure.\n\n**Test vectors**\n- Corrupted length / truncated frame rejected\n- Duplicate request_id returns cached response\n- Slowloris protection by read deadlines\n\n\nExpert checks: state-machine reasoning, concurrency stress, and upgrade/rollback validated.", "source": "WithinUsAI/Elite_GOD_Coder_100k"} {"text": "Create a comprehensive test plan and automated tests for A/B experimentation in a content moderation product.\nTarget platform: ML (scikit + batch).\nRequirements: unit/integration tests, edge cases, load tests strategy, and CI gates.\nConstraints: must be performant under load, must be easy to extend, must be observable (logs/metrics/traces).\nDifficulty: hard. Assume untrusted input; validate everything.\n\nOutput: actionable implementation and verification artifacts.\nDeliverable: test plan + automation guidance.\n\n**Unit tests**\n- Validation: malformed payloads rejected with correct codes.\n- AuthZ: tenant boundary enforced.\n- Idempotency: replay returns same response; conflicting reuse yields 409.\n\n**Integration tests**\n- DB transaction behavior; unique constraints.\n- Cache behavior: correctness under concurrent requests.\n\n**Load tests**\n- 10k RPS target: measure p95 latency, error rate, saturation.\n\n**CI gates**\n- Lint + typecheck + unit tests required.\n- Coverage threshold for critical modules.\n- Block merge on flaky test detection.\n\n\nHard-mode checks: concurrency safety, idempotency, and rollback validated; add chaos tests where feasible.", "source": "WithinUsAI/GOD_Coder_100k"} {"text": "Build an elite-grade solution in the domain of ml systems for scenario: event ingestion.\nPrimary language: rust.\nDifficulty: medium.\nConstraints: assume untrusted inputs; validate and sanitize, include tests or verification strategy, make the interface contract explicit, avoid undefined behavior and data races, document performance characteristics.\nComponent: component_ewulojm.\nAssume 50k RPS and p99 < 250ms.\nTask: Optimize a hot path with profiling-driven approach; propose micro/meso optimizations, and supply a benchmark harness with acceptance thresholds.\n\nOutput: production blueprint plus correctness arguments and test strategy.\nOutput: profiling-first optimization + benchmark harness.\n\n**Plan**\n1. Establish baseline with microbench + representative dataset.\n2. Profile (CPU, allocations, syscalls).\n3. Apply optimizations: reduce allocations, reuse buffers, batch I/O, vectorize parsing where safe.\n4. Validate with regression suite and perf thresholds.\n\n**Benchmark guidance**\n- Use p50/p95 and throughput; pin CPU frequency if possible.\n- Acceptance: p95 improves ≥ X% with no correctness regressions.\n\n\nChecks: boundary validation and deterministic behavior verified.", "source": "WithinUsAI/Elite_GOD_Coder_100k"} {"text": "Fix the bug and add pytest tests.\n\n```python\ndef f18133(n: int) -> int:\n # sum 1..n inclusive\n if n < 0: raise ValueError\n total = 0\n for k in range(n): # BUG\n total += k\n return total\n```\nReturn unified diffs for `m74019.py` and `test_m74019.py`.\n\n*** Begin Patch\n*** Update File: m74019.py\n@@\n def f18133(n: int) -> int:\n@@\n- for k in range(n): # BUG\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_m74019.py\n+import pytest\n+from m74019 import f18133\n+\n+def test_small():\n+ assert f18133(7) == 28\n+\n+def test_zero():\n+ assert f18133(0) == 0\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ f18133(-1)\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Task type: compiler_backend_ir\nScenario: document indexing pipeline\nDomain focus: large-scale ML systems\nPrimary language: cpp\nDifficulty: hard\nScale/SLO: 50 TB/day ingestion\nComponent: component_ffhvcmju\nConstraints: include failure modes and recovery, include backward compatibility and migration plan, explicit contracts and invariants, include deterministic replay plan, avoid data races and undefined behavior, include security threat model (defensive only), include performance model and limits\nAssume weekly network partitions.\nDeliverable: Design an IR and lowering pipeline; include an optimization pass and correctness checks. Provide minimal code skeleton and tests.\n\nOutput: contract-first solution with failure modes, security posture, and test/verification strategy.\n**Contract**\n- Inputs validated at the boundary; explicit error taxonomy.\n- Idempotency for side effects via request_id; deterministic replay.\n- Backward compatibility: additive changes by default; versioned breaking changes.\n**Invariants**\n- Liveness: under bounded faults and stable network, progress occurs.\n- Isolation: tenant boundary enforced; no cross-tenant reads/writes.\n- Determinism: replay of the same event log yields identical outputs.\n**Failure modes & recovery**\n- Duplicate requests: de-duplicate by (tenant, request_id) returning cached response.\n- Data corruption: checksums + scrubber; quarantine and rebuild from replicas/snapshots.\n- Crash during commit: WAL replay completes or transaction aborts; no torn writes.\n**Security posture (defensive)**\n- Threat model: auth/authz, injection, replay/abuse, supply chain.\n- Least privilege; secrets in managed store; audit logs for sensitive ops.\n- Input normalization, parameterized queries, path traversal protections.\n**Verification strategy**\n- Fuzzing of parsers/framers/validators with corpus seeds.\n- Canary + shadow traffic; invariants checked in production via assertions/metrics.\n- Deterministic simulation with fault injection (crash/partition/latency).\n\n**Snippet**\n```text\nImplementation sketch: factor pure state-machine core; adapters for I/O; add deterministic replay log.\n```\nHard checks: fault injection tests gate merges; perf thresholds enforced in CI.", "source": "WithinUsAI/Omega_Genesis_Coder_100k"} {"text": "Build an elite-grade solution in the domain of stream processing for scenario: time-series metrics.\nPrimary language: bash.\nDifficulty: expert.\nConstraints: document performance characteristics, include tests or verification strategy, avoid undefined behavior and data races.\nComponent: component_fzxtqrz.\nAssume compliance requires data deletion with proofs.\nTask: Write a precise interface contract, list invariants, and provide a lightweight formal/spec-style description (pseudo-TLA+/state machine) plus reference implementation skeleton and tests.\n\nOutput: elite-grade engineering answer with contracts, edge cases, and verification.\nOutput: contract + invariants + spec + reference skeleton.\n\n**Interface contract**\n- Commands: `Put(key, value, expected_version?)`, `Get(key)`, `Delete(key, expected_version?)`\n- Responses: `Ok(version, value?)`, `NotFound`, `Conflict(current_version)`, `InvalidInput`\n- Idempotency: client supplies `request_id`; server must de-duplicate per (tenant_id, request_id).\n\n**Invariants**\n1. Monotonic version per key (strictly increases on successful writes).\n2. Reads return latest committed value for a given consistency level.\n3. Exactly-once effect for a given `request_id` (at-most-once execution + replay response).\n4. Tenant isolation: keys are scoped by tenant_id.\n\n**State machine (pseudo)**\nState:\n- store: map[(tenant,key)] -> (version:int, value:bytes|tombstone)\n- seen: map[(tenant,request_id)] -> response\nTransition Put:\n- if request_id in seen: return seen[...]\n- validate input; if expected_version set and != current version -> Conflict\n- version' = version + 1; store[...] := (version', value); seen[...] := Ok(version', value)\n\n**Reference skeleton (Python)**\n```python\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom typing import Dict, Optional, Tuple\n\nclass Conflict(Exception): pass\nclass InvalidInput(ValueError): pass\n\n@dataclass(frozen=True, slots=True)\nclass Value:\n version: int\n data: Optional[bytes] # None == tombstone\n\n@dataclass(frozen=True, slots=True)\nclass Reply:\n kind: str\n version: Optional[int] = None\n data: Optional[bytes] = None\n\nclass KV:\n def __init__(self) -> None:\n self._store: Dict[Tuple[str,str], Value] = {}\n self._seen: Dict[Tuple[str,str], Reply] = {}\n\n def put(self, tenant: str, request_id: str, key: str, data: bytes, expected_version: Optional[int]=None) -> Reply:\n if not tenant or not request_id or not key:\n raise InvalidInput(\"tenant/request_id/key required\")\n de = self._seen.get((tenant, request_id))\n if de: \n return de\n cur = self._store.get((tenant, key), Value(0, None))\n if expected_version is not None and expected_version != cur.version:\n r = Reply(\"conflict\", version=cur.version)\n self._seen[(tenant, request_id)] = r\n return r\n nxt = Value(cur.version + 1, data)\n self._store[(tenant, key)] = nxt\n r = Reply(\"ok\", version=nxt.version)\n self._seen[(tenant, request_id)] = r\n return r\n```\n\n**Tests**\n- Determinism: same request_id → same reply.\n- Conflict detection and version monotonicity.\n\n\nExpert checks: state-machine reasoning, concurrency stress, and upgrade/rollback validated.", "source": "WithinUsAI/Elite_GOD_Coder_100k"} {"text": "Implement a concurrent Python solution for CLI tooling.\nRequirements: choose appropriate concurrency model, handle cancellation/timeouts, include tests.\nConstraints: stdlib-only, must be easy to extend, must provide clear error messages, must be streaming-friendly.\nDifficulty: hard. Guarantee deterministic output ordering.\n\nDeliverable: API + reference implementation + tests.\n```python\nfrom __future__ import annotations\nimport asyncio\nfrom dataclasses import dataclass\nfrom typing import Awaitable, Callable, Iterable, Optional\n\n@dataclass(frozen=True, slots=True)\nclass JobResult:\n ok: bool\n value: Optional[int]\n error: Optional[str]\n\nasync def run_bounded(\n factories: Iterable[Callable[[], Awaitable[int]]],\n *,\n limit: int = 10,\n timeout_s: float = 5.0,\n) -> list[JobResult]:\n if limit <= 0:\n raise ValueError(\"limit must be > 0\")\n sem = asyncio.Semaphore(limit)\n results: list[JobResult] = []\n\n async def one(factory: Callable[[], Awaitable[int]]) -> None:\n async with sem:\n try:\n v = await asyncio.wait_for(factory(), timeout=timeout_s)\n results.append(JobResult(True, v, None))\n except Exception as e:\n results.append(JobResult(False, None, str(e)))\n\n tasks = [asyncio.create_task(one(f)) for f in factories]\n try:\n await asyncio.gather(*tasks)\n finally:\n for t in tasks:\n if not t.done():\n t.cancel()\n return results\n```\n\n```python\nimport asyncio\nimport pytest\nfrom module_under_test import run_bounded\n\n@pytest.mark.asyncio\nasync def test_run_bounded_collects():\n async def work(x: int) -> int:\n await asyncio.sleep(0.01)\n return x\n fs = [(lambda i=i: work(i)) for i in range(30)]\n out = await run_bounded(fs, limit=5, timeout_s=1.0)\n assert len(out) == 30\n assert all(r.ok for r in out)\n```", "source": "WithinUsAI/python_GOD_coder_100k"} {"text": "Improve typing and robustness of a Python module used for caching layer.\nRequirements: provide type-safe APIs (generics/protocols where appropriate) and include tests.\nConstraints: must provide clear error messages, must handle Windows paths safely, must be easy to extend, must include docstrings.\nDifficulty: hard. Avoid quadratic behavior on large inputs.\n\nDeliverable: API + reference implementation + tests.\n```python\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom typing import Callable, Generic, Iterable, Protocol, TypeVar\n\nT = TypeVar(\"T\")\nR = TypeVar(\"R\")\n\nclass Mapper(Protocol[T, R]):\n def __call__(self, x: T) -> R: ...\n\n@dataclass(frozen=True, slots=True)\nclass Batch(Generic[T]):\n items: tuple[T, ...]\n\ndef map_batch(batch: Batch[T], fn: Mapper[T, R]) -> Batch[R]:\n return Batch(items=tuple(fn(x) for x in batch.items))\n\ndef chunked(xs: Iterable[T], size: int) -> Iterable[Batch[T]]:\n if size <= 0:\n raise ValueError(\"size must be > 0\")\n buf: list[T] = []\n for x in xs:\n buf.append(x)\n if len(buf) == size:\n yield Batch(items=tuple(buf))\n buf.clear()\n if buf:\n yield Batch(items=tuple(buf))\n```\n\n```python\nimport pytest\nfrom module_under_test import Batch, map_batch, chunked\n\ndef test_map_batch():\n b = Batch(items=(1,2,3))\n assert map_batch(b, lambda x: x*2).items == (2,4,6)\n\ndef test_chunked():\n out = list(chunked([1,2,3,4,5], 2))\n assert [b.items for b in out] == [(1,2),(3,4),(5,)]\n```", "source": "WithinUsAI/python_GOD_coder_100k"} {"text": "Optimize while preserving behavior and order.\n\n```python\ndef f32687(xs):\n out=[]\n for x in xs:\n if x not in out: out.append(x)\n return out\n```\nReturn `m33241.py` with types and O(n) average.\n\n```python\n# m33241.py\nfrom __future__ import annotations\nfrom typing import Iterable, List, Set, TypeVar\nT=TypeVar(\"T\")\n\ndef f32687(xs: Iterable[T]) -> List[T]:\n \"\"\"Unique items preserving first-seen order.\"\"\"\n seen: Set[T]=set()\n out: List[T]=[]\n for x in xs:\n if x in seen: continue\n seen.add(x); out.append(x)\n return out\n```", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: Language: Python\nFramework/tooling: Celery\nDomain: model serving gateway\nLogic challenge: partial checkpoint corruption\nTask type: backwards_compatible_redesign\nDifficulty: hard\n\nReturn a rigorous engineering answer:\n- identify the hidden root cause or logical failure\n- present the corrected implementation\n- add tests that prove the fix\n- list verification commands\n- explain why naive fixes are insufficient when relevant\n\nRepository sketch:\nrepo/\n app/\n api.py\n service.py\n models.py\n tests/\n test_api.py\n pyproject.toml\n\nFocus: Focus on staff-level problem solving with multi-file patches, rollout implications, performance and security tradeoffs.\n\nassistant: Diagnosis:\n- Staff-level diagnosis: partial checkpoint corruption impacts correctness, operability, and future maintenance, so the fix must be minimal where possible but complete where necessary.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```python\nfrom __future__ import annotations\n\nfrom dataclasses import dataclass\nfrom typing import Any\n\n@dataclass\nclass ServiceResult:\n ok: bool\n data: dict[str, Any]\n error: str | None = None\n\ndef normalize_payload(payload: dict[str, Any]) -> dict[str, Any]:\n if not isinstance(payload, dict):\n raise TypeError(\"payload must be a dict\")\n clean: dict[str, Any] = {}\n for key, value in payload.items():\n if value is None:\n continue\n clean[str(key).strip()] = value\n return clean\n\ndef handle_partial_checkpoint_corruption(payload: dict[str, Any]) -> ServiceResult:\n clean = normalize_payload(payload)\n if \"id\" not in clean:\n return ServiceResult(ok=False, data={}, error=\"missing id\")\n return ServiceResult(ok=True, data=clean)\n```\n\nTests:\n```python\nimport pytest\nfrom app.service import handle_jwt_refresh_token_rotation as handler\n\ndef test_handler_accepts_valid_payload():\n result = handler({\"id\": 7, \"name\": \"ok\", \"unused\": None})\n assert result.ok is True\n assert result.data == {\"id\": 7, \"name\": \"ok\"}\n\ndef test_handler_rejects_missing_id():\n result = handler({\"name\": \"x\"})\n assert result.ok is False\n assert result.error == \"missing id\"\n```\n\nVerification:\n- `pytest -q`\n- `ruff check .`\n- `python -m compileall .`\n\nEngineering notes:\n- Language: Python\n- Framework/tooling: Celery\n- Stack context: Airflow, dbt, DuckDB, MinIO, pytest\n- Domain: model serving gateway\n- Task type: backwards_compatible_redesign\n- Difficulty: hard\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Produce an offline-first self-evolving code assistant architecture named `y7zzs47a`.\nMust include: module layout, patch-safety policy, evaluation gates (tests/lint/types), versioned memory index.\n\nArchitecture: `y7zzs47a` (offline-first, self-evolving)\n\nModules\n- core/loop.py: evolve → validate → accept/reject (bounded iterations)\n- patching/: diff builder, safe apply, atomic writes, rollback points\n- policy/: allowlist paths, deny globs (.git/, __pycache__/, binaries), patch size caps\n- signals/: parse pytest/ruff/mypy into normalized findings\n- memory/index.jsonl: append-only snapshots (hashes, metrics, rationale)\n\nSafety gates\n- refuse path traversal/symlink escapes; never edit binaries\n- accept only if tests/lint/types stay green or improve", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Refactor a Python module used for data modeling into a clean, extensible design.\nRequirements: outline the new architecture briefly, then provide the refactored code and tests.\nConstraints: must be memory-efficient, stdlib-only, must include docstrings.\nDifficulty: easy. Avoid quadratic behavior on large inputs.\n\nDeliverable: API + reference implementation + tests.\nArchitecture:\n- Public facade class coordinating concerns (parsing, validation, persistence)\n- Small pure functions for testability\n- No global state; dependency injection for filesystem I/O\n\n```python\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom pathlib import Path\nfrom typing import Protocol, Iterable\nimport json\n\nclass Store(Protocol):\n def write_text(self, path: Path, data: str) -> None: ...\n\nclass FSStore:\n def write_text(self, path: Path, data: str) -> None:\n path.parent.mkdir(parents=True, exist_ok=True)\n path.write_text(data, encoding=\"utf-8\")\n\n@dataclass(frozen=True, slots=True)\nclass Item:\n name: str\n qty: int\n\ndef parse_items(lines: Iterable[str]) -> list[Item]:\n out: list[Item] = []\n for i, line in enumerate(lines, 1):\n s = line.strip()\n if not s:\n continue\n obj = json.loads(s)\n if not isinstance(obj, dict):\n raise ValueError(f\"line {i}: expected object\")\n name = obj.get(\"name\")\n qty = obj.get(\"qty\")\n if not isinstance(name, str) or not name:\n raise ValueError(f\"line {i}: name must be str\")\n if not isinstance(qty, int) or qty < 0:\n raise ValueError(f\"line {i}: qty must be non-negative int\")\n out.append(Item(name, qty))\n return out\n\nclass InventoryWriter:\n def __init__(self, base_dir: Path, store: Store | None = None) -> None:\n self._base = base_dir\n self._store: Store = store or FSStore()\n\n def write(self, rel_path: str, items: list[Item]) -> Path:\n dst = (self._base / rel_path).resolve()\n base = self._base.resolve()\n if dst != base and base not in dst.parents:\n raise ValueError(\"unsafe path traversal\")\n payload = json.dumps([item.__dict__ for item in items], ensure_ascii=False)\n self._store.write_text(dst, payload)\n return dst\n```\n\n```python\nimport json\nfrom pathlib import Path\nimport pytest\nfrom module_under_test import InventoryWriter, parse_items\n\ndef test_parse_items_valid():\n lines = [json.dumps({\"name\":\"x\",\"qty\":1})]\n assert parse_items(lines)[0].name == \"x\"\n\ndef test_writer_blocks_traversal(tmp_path: Path):\n w = InventoryWriter(tmp_path)\n with pytest.raises(ValueError):\n w.write(\"../evil.json\", [])\n```", "source": "WithinUsAI/python_GOD_coder_100k"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: Project stack: FastAPI, PostgreSQL, Redis, Celery, pytest, Docker\nLanguage: Bash\nDependency challenge: rate-limit bypass\nTask type: cve_dependency_remediation\nDifficulty: medium\n\nFix this as a senior engineer.\nRequired:\n- identify the version or compatibility failure mode\n- produce the corrected config/code/build patch\n- explain rollback-safe migration notes\n- add regression tests or reproducibility checks\n- include concrete verification commands\n\nRepository sketch:\nrepo/\n scripts/\n run.sh\n deploy.sh\n tests/\n smoke.sh\n\nFocus: Focus on versioning, migrations, lockfiles, runtime compatibility, and secure dependency handling.\n\nassistant: Diagnosis:\n- Root cause: the issue around rate-limit bypass is a dependency, migration, or runtime-compatibility mismatch that needs a rollback-safe patch.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```bash\n#!/usr/bin/env bash\nset -euo pipefail\n\ninput=\"${1:-}\"\nif [[ -z \"$input\" ]]; then\n echo \"missing input\" >&2\n exit 1\nfi\n\nprintf '%s\n' \"$input\" | tr -d '\r'\n```\n\nTests:\n```bash\noutput=\"$(bash scripts/run.sh \"abc\")\"\ntest \"$output\" = \"abc\"\n```\n\nVerification:\n- `bash tests/smoke.sh`\n- `shellcheck scripts/*.sh`\n\nEngineering notes:\n- Language: Bash\n- Framework/tooling: curl\n- Stack context: FastAPI, PostgreSQL, Redis, Celery, pytest, Docker\n- Domain: artifact registry\n- Task type: cve_dependency_remediation\n- Difficulty: medium\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Refactor to modern typed Python with immutability and tests.\n\nFile: o2kfmhpkb.py\n```python\nclass Mwp016:\n def __init__(self, name, values):\n self.name = name\n self.values = list(values)\n def add(self, v):\n self.values.append(v)\n def mean(self):\n s = 0\n for x in self.values:\n s += x\n return s / len(self.values)\n```\n\nReturn full new o2kfmhpkb.py and test_o2kfmhpkb.py.\n\n# o2kfmhpkb.py\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom typing import Iterable, Tuple\n\n@dataclass(frozen=True)\nclass Mwp016:\n name: str\n values: Tuple[float, ...]\n\n @staticmethod\n def create(name: str, values: Iterable[float]) -> \"Mwp016\":\n vals = tuple(float(v) for v in values)\n if not vals:\n raise ValueError(\"values must be non-empty\")\n return Mwp016(name=name, values=vals)\n\n def add(self, v: float) -> \"Mwp016\":\n return Mwp016(name=self.name, values=self.values + (float(v),))\n\n def mean(self) -> float:\n return sum(self.values) / len(self.values)\n\n# test_o2kfmhpkb.py\nimport pytest\nfrom o2kfmhpkb import Mwp016\n\ndef test_mean_and_add():\n c = Mwp016.create(\"a\", [1, 2, 3])\n assert c.mean() == 2.0\n assert c.add(5).mean() == (1 + 2 + 3 + 5) / 4\n\ndef test_empty_raises():\n with pytest.raises(ValueError):\n Mwp016.create(\"x\", [])", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Design and implement an algorithm for CLI tooling.\nRequirements: define inputs/outputs, implement solution with complexity analysis, and include tests.\nConstraints: must include tests, must be memory-efficient, stdlib-only, must include type hints.\nDifficulty: easy. Handle empty inputs and malformed records gracefully.\n\nDeliverable: production-ready reference solution.\nProblem: compute rolling sums over events (ts:int,value:int) with window W seconds. Events may be out-of-order.\n\nComplexity: sorting O(n log n); window maintenance O(n); memory O(k).\n\n```python\nfrom __future__ import annotations\nfrom collections import deque\nfrom dataclasses import dataclass\nfrom typing import Iterable, List, Tuple\n\n@dataclass(frozen=True, slots=True)\nclass Event:\n ts: int\n value: int\n\ndef rolling_sum(events: Iterable[Event], window_s: int) -> List[Tuple[int,int]]:\n if window_s < 0:\n raise ValueError(\"window_s must be >= 0\")\n evs = sorted(events, key=lambda e: e.ts)\n q: deque[Event] = deque()\n s = 0\n out: List[Tuple[int,int]] = []\n for e in evs:\n q.append(e)\n s += e.value\n cutoff = e.ts - window_s\n while q and q[0].ts < cutoff:\n old = q.popleft()\n s -= old.value\n out.append((e.ts, s))\n return out\n```\n\n```python\nimport pytest\nfrom module_under_test import Event, rolling_sum\n\ndef test_rolling_sum():\n ev = [Event(10,1), Event(11,2), Event(20,5)]\n assert rolling_sum(ev, 5) == [(10,1),(11,3),(20,5)]\n```", "source": "WithinUsAI/python_GOD_coder_100k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Optimize while preserving behavior.\n\nFile: lgnc65.py\n```python\ndef rgejw3(xs):\n out = []\n for x in xs:\n if x not in out:\n out.append(x)\n return out\n```\n\nRequirements: preserve first-seen order; O(n) average; add types + docstring.\n\n# lgnc65.py\nfrom __future__ import annotations\nfrom typing import Iterable, List, Set, TypeVar\n\nT = TypeVar(\"T\")\n\ndef rgejw3(xs: Iterable[T]) -> List[T]:\n \"\"\"Return unique items preserving first-seen order.\"\"\"\n seen: Set[T] = set()\n out: List[T] = []\n for x in xs:\n if x in seen:\n continue\n seen.add(x)\n out.append(x)\n return out", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Build an elite-grade solution in the domain of compilers for scenario: analytics pipeline.\nPrimary language: python.\nDifficulty: medium.\nConstraints: include invariants and failure modes, include tests or verification strategy, avoid undefined behavior and data races, provide rollout and rollback guidance, document performance characteristics.\nComponent: component_gfnsxak.\nAssume cold-start and memory limits are tight.\nTask: Design an application-level protocol (framing, retries, timeouts, backpressure). Provide client/server skeleton and test vectors.\n\nOutput: rigorous solution with invariants, failure modes, and performance notes.\nOutput: protocol framing + retry policy + client/server skeleton.\n\n**Framing**\n- Length-prefixed: uint32_be length + payload\n- Payload: msgpack/json; include request_id, type, and optional checksum\n\n**Reliability**\n- Retries only for idempotent ops; exponential backoff + jitter.\n- Timeouts: connect, read, overall; enforce max in-flight to provide backpressure.\n\n**Test vectors**\n- Corrupted length / truncated frame rejected\n- Duplicate request_id returns cached response\n- Slowloris protection by read deadlines\n\n\nChecks: boundary validation and deterministic behavior verified.", "source": "WithinUsAI/Elite_GOD_Coder_100k"} {"text": "Build a data pipeline for a content moderation product around analytics pipeline.\nTarget platform: data (SQL + Python).\nRequirements: schema, ingestion, validation, backfills, and tests.\nConstraints: must be secure-by-default, must be easy to extend, must include tests, must include clear error handling.\nDifficulty: medium. Assume PII must be protected.\n\nOutput: engineering-grade answer with edge cases covered.\nDeliverable: schema + ingestion + validation + backfill strategy.\n\n**Schema (example)**\n- events(event_id TEXT PK, tenant_id TEXT, ts TIMESTAMP, type TEXT, payload JSONB)\n\n**Ingestion**\n- Write to raw table first; validate; then materialize to curated tables.\n- Idempotency by event_id; enforce uniqueness.\n\n**Validation**\n- Reject missing tenant_id/type/ts.\n- Quarantine bad records with reason.\n\n**Backfills**\n- Re-run deterministic transforms from raw → curated.\n- Version transformations; store transform_version with outputs.\n\n**Tests**\n- Unit tests for validators and transforms.\n- Integration test: sample raw batch produces expected curated rows.\n\n\nChecks: input validation, tests, and safe defaults included.", "source": "WithinUsAI/GOD_Coder_100k"} {"text": "Refactor to typed, mostly-immutable Python and add minimal tests.\n\n```python\nclass C09942:\n def __init__(self, values): self.values=list(values)\n def mean(self): return sum(self.values)/len(self.values)\n```\nReturn `m31534.py` and `test_m31534.py`.\n\n```python\n# m31534.py\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom typing import Iterable, Tuple\n\n@dataclass(frozen=True)\nclass C09942:\n values: Tuple[float, ...]\n\n @staticmethod\n def create(values: Iterable[float]) -> \"C09942\":\n vals = tuple(float(v) for v in values)\n if not vals: raise ValueError(\"empty\")\n return C09942(vals)\n\n def mean(self) -> float:\n return sum(self.values)/len(self.values)\n```\n\n```python\n# test_m31534.py\nimport pytest\nfrom m31534 import C09942\n\ndef test_mean():\n assert C09942.create([1,2,3]).mean() == 2.0\ndef test_empty():\n with pytest.raises(ValueError):\n C09942.create([])\n```", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Fix a bug and add tests.\n\nFile: z5lynm_03.py\n```python\ndef igsoqg9idl(n: int) -> int:\n \"\"\"Sum 1..n inclusive.\"\"\"\n if n < 0:\n raise ValueError(\"n must be non-negative\")\n total = 0\n for k in range(n): # BUG: should include n\n total += k\n return total\n```\n\nReturn unified diffs for z5lynm_03.py and test_z5lynm_03.py (pytest).\n\n*** Begin Patch\n*** Update File: z5lynm_03.py\n@@\n def igsoqg9idl(n: int) -> int:\n@@\n total = 0\n- for k in range(n): # BUG: should include n\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_z5lynm_03.py\n+import pytest\n+from z5lynm_03 import igsoqg9idl\n+\n+def test_zero():\n+ assert igsoqg9idl(0) == 0\n+\n+def test_one():\n+ assert igsoqg9idl(1) == 1\n+\n+def test_small():\n+ assert igsoqg9idl(7) == 28\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ igsoqg9idl(-1)\n+\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Refactor to modern typed Python with immutability and tests.\n\nFile: kzovchkftp8t.py\n```python\nclass Rfc683R4Oetc:\n def __init__(self, name, values):\n self.name = name\n self.values = list(values)\n def add(self, v):\n self.values.append(v)\n def mean(self):\n s = 0\n for x in self.values:\n s += x\n return s / len(self.values)\n```\n\nReturn full new kzovchkftp8t.py and test_kzovchkftp8t.py.\n\n# kzovchkftp8t.py\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom typing import Iterable, Tuple\n\n@dataclass(frozen=True)\nclass Rfc683R4Oetc:\n name: str\n values: Tuple[float, ...]\n\n @staticmethod\n def create(name: str, values: Iterable[float]) -> \"Rfc683R4Oetc\":\n vals = tuple(float(v) for v in values)\n if not vals:\n raise ValueError(\"values must be non-empty\")\n return Rfc683R4Oetc(name=name, values=vals)\n\n def add(self, v: float) -> \"Rfc683R4Oetc\":\n return Rfc683R4Oetc(name=self.name, values=self.values + (float(v),))\n\n def mean(self) -> float:\n return sum(self.values) / len(self.values)\n\n# test_kzovchkftp8t.py\nimport pytest\nfrom kzovchkftp8t import Rfc683R4Oetc\n\ndef test_mean_and_add():\n c = Rfc683R4Oetc.create(\"a\", [1, 2, 3])\n assert c.mean() == 2.0\n assert c.add(5).mean() == (1 + 2 + 3 + 5) / 4\n\ndef test_empty_raises():\n with pytest.raises(ValueError):\n Rfc683R4Oetc.create(\"x\", [])", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Implement an ML engineering workflow for enterprise SaaS focusing on webhooks.\nTarget platform: ML (training + serving).\nRequirements: data contract, training loop, evaluation, model registry, serving API, monitoring.\nConstraints: must include clear error handling, must be easy to extend, must include tests, must include documentation/comments.\nDifficulty: easy. Assume strict latency budget (p95 < 200ms).\n\nOutput: production-oriented blueprint with code where appropriate.\nDeliverable: ML engineering blueprint (training + serving + monitoring), safe and production-oriented.\n\n**Data contract**\n- Define feature schema + ranges; validate at training and serving.\n\n**Training**\n- Deterministic split; baseline model; track metrics (AUC/F1/latency).\n- Store artifacts: model, config, feature stats.\n\n**Registry**\n- Promote models via approval gates; record lineage.\n\n**Serving**\n- Separate inference service with `/predict`.\n- Input validation + default handling; timeouts.\n\n**Monitoring**\n- Data drift: feature distribution checks.\n- Performance: online metrics + periodic labels; alert on regression.\n\nMinimal serving skeleton (FastAPI-ish):\n```python\n# validate input -> vectorize -> model.predict_proba -> return\n```\n\n\nChecks: input validation, tests, and safe defaults included.", "source": "WithinUsAI/GOD_Coder_100k"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: Language: Go\nFramework/tooling: testify\nDomain: auth service\nLogic challenge: multi-tenant access leak\nTask type: misleading_symptom_debug\nDifficulty: hard\n\nReturn a rigorous engineering answer:\n- identify the hidden root cause or logical failure\n- present the corrected implementation\n- add tests that prove the fix\n- list verification commands\n- explain why naive fixes are insufficient when relevant\n\nRepository sketch:\nrepo/\n cmd/server/main.go\n internal/service/service.go\n internal/store/store.go\n internal/api/api.go\n service_test.go\n go.mod\n\nFocus: Focus on ambiguity, misleading symptoms, hidden root causes, and high-stakes debugging.\n\nassistant: Diagnosis:\n- Hidden root cause: multi-tenant access leak presents misleading symptoms, so the patch must target the actual logic boundary rather than the first visible failure.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```go\npackage service\n\nimport \"fmt\"\n\nfunc NormalizePayload(payload map[string]any) map[string]any {\n\tout := make(map[string]any)\n\tfor k, v := range payload {\n\t\tif v == nil {\n\t\t\tcontinue\n\t\t}\n\t\tout[k] = v\n\t}\n\treturn out\n}\n\nfunc Handle(payload map[string]any) (map[string]any, error) {\n\tclean := NormalizePayload(payload)\n\tif _, ok := clean[\"id\"]; !ok {\n\t\treturn nil, fmt.Errorf(\"missing id\")\n\t}\n\treturn map[string]any{\"ok\": true, \"data\": clean}, nil\n}\n```\n\nTests:\n```go\npackage service\n\nimport \"testing\"\n\nfunc TestHandle(t *testing.T) {\n\tgot, err := Handle(map[string]any{\"id\": 7, \"name\": \"ok\", \"unused\": nil})\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tif got[\"ok\"] != true {\n\t\tt.Fatalf(\"expected ok=true\")\n\t}\n\tif _, err := Handle(map[string]any{\"name\": \"x\"}); err == nil {\n\t\tt.Fatalf(\"expected missing id error\")\n\t}\n}\n```\n\nVerification:\n- `go test ./...`\n- `go vet ./...`\n\nEngineering notes:\n- Language: Go\n- Framework/tooling: testify\n- Stack context: FastAPI, PostgreSQL, Redis, Celery, pytest, Docker\n- Domain: auth service\n- Task type: misleading_symptom_debug\n- Difficulty: hard\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Produce an offline-first self-evolving code assistant architecture named `eappy9cx`.\nMust include: module layout, patch-safety policy, evaluation gates (tests/lint/types), versioned memory index.\n\nArchitecture: `eappy9cx` (offline-first, self-evolving)\n\nModules\n- core/loop.py: evolve → validate → accept/reject (bounded iterations)\n- patching/: diff builder, safe apply, atomic writes, rollback points\n- policy/: allowlist paths, deny globs (.git/, __pycache__/, binaries), patch size caps\n- signals/: parse pytest/ruff/mypy into normalized findings\n- memory/index.jsonl: append-only snapshots (hashes, metrics, rationale)\n\nSafety gates\n- refuse path traversal/symlink escapes; never edit binaries\n- accept only if tests/lint/types stay green or improve", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Debug and fix a subtle production bug related to caching in a education service.\nTarget platform: ML (PyTorch + serving).\nRequirements: identify root cause, provide patch, and add regression tests.\nConstraints: must include tests, must be production-ready, must avoid global state, must include clear error handling.\nDifficulty: easy. Include rollback strategy.\n\nOutput: production-oriented blueprint with code where appropriate.\nDeliverable: production-grade reference implementation (FastAPI) + tests.\n\n```python\n# app.py\nfrom __future__ import annotations\n\nimport hashlib\nimport json\nfrom dataclasses import dataclass\nfrom datetime import datetime, timezone\nfrom typing import Any, Optional\n\nfrom fastapi import FastAPI, Header, HTTPException\nfrom pydantic import BaseModel, Field\n\napp = FastAPI(title=\"Idempotent API\")\n\nclass CreateReq(BaseModel):\n tenant_id: str = Field(min_length=1)\n amount_cents: int = Field(ge=0)\n currency: str = Field(min_length=3, max_length=3)\n\nclass CreateResp(BaseModel):\n id: str\n created_at: str\n echo: CreateReq\n\n@dataclass\nclass _IdempoEntry:\n request_hash: str\n response_json: str\n\n# In production: Postgres table with UNIQUE(tenant_id, key)\n_IDEMPO: dict[tuple[str, str], _IdempoEntry] = {}\n\ndef _hash_req(req: CreateReq) -> str:\n raw = req.model_dump_json()\n return hashlib.sha256(raw.encode(\"utf-8\")).hexdigest()\n\n@app.post(\"/v1/payments\", response_model=CreateResp)\ndef create_payment(\n req: CreateReq,\n idempotency_key: Optional[str] = Header(default=None, alias=\"Idempotency-Key\"),\n) -> Any:\n if not idempotency_key:\n raise HTTPException(status_code=400, detail=\"Missing Idempotency-Key\")\n if len(idempotency_key) > 128:\n raise HTTPException(status_code=400, detail=\"Idempotency-Key too long\")\n\n key = (req.tenant_id, idempotency_key)\n rh = _hash_req(req)\n\n existing = _IDEMPO.get(key)\n if existing:\n if existing.request_hash != rh:\n raise HTTPException(status_code=409, detail=\"Idempotency-Key reuse with different payload\")\n return json.loads(existing.response_json)\n\n # Create new payment (stubbed)\n pid = hashlib.md5(f\"{req.tenant_id}:{idempotency_key}\".encode()).hexdigest()\n resp = CreateResp(\n id=pid,\n created_at=datetime.now(timezone.utc).isoformat(),\n echo=req,\n )\n _IDEMPO[key] = _IdempoEntry(request_hash=rh, response_json=resp.model_dump_json())\n return resp\n```\n\n```python\n# test_app.py (pytest)\nfrom fastapi.testclient import TestClient\nfrom app import app\n\nclient = TestClient(app)\n\ndef test_idempotent_replay():\n headers = {\"Idempotency-Key\": \"abc\"}\n body = {\"tenant_id\":\"t1\",\"amount_cents\":100,\"currency\":\"USD\"}\n r1 = client.post(\"/v1/payments\", json=body, headers=headers)\n r2 = client.post(\"/v1/payments\", json=body, headers=headers)\n assert r1.status_code == 200 and r2.status_code == 200\n assert r1.json() == r2.json()\n\ndef test_payload_conflict():\n headers = {\"Idempotency-Key\": \"abc\"}\n b1 = {\"tenant_id\":\"t1\",\"amount_cents\":100,\"currency\":\"USD\"}\n b2 = {\"tenant_id\":\"t1\",\"amount_cents\":200,\"currency\":\"USD\"}\n assert client.post(\"/v1/payments\", json=b1, headers=headers).status_code == 200\n assert client.post(\"/v1/payments\", json=b2, headers=headers).status_code == 409\n```\n\nNotes:\n- Replace in-memory store with a DB table and transaction.\n- Store response + request hash to detect key reuse with different payload.\n\n\nChecks: input validation, tests, and safe defaults included.", "source": "WithinUsAI/GOD_Coder_100k"} {"text": "Refactor an existing codebase in customer support to support caching cleanly.\nTarget platform: mobile (Android Kotlin).\nRequirements: propose new modules/layers, dependency boundaries, and migration plan.\nConstraints: must include documentation/comments, must be observable (logs/metrics/traces), must be production-ready, must include type hints where applicable, must include clear error handling.\nDifficulty: easy. Assume GDPR-style deletion requests must be supported.\n\nOutput: design + implementation guidance suitable for shipping.\nDeliverable: refactor plan + module boundaries.\n\n**Proposed modules**\n- `domain/` pure business logic (no I/O)\n- `adapters/` DB, cache, external APIs\n- `api/` request/response validation and routing\n- `observability/` logging/metrics/tracing\n- `tests/` unit + integration suites\n\n**Migration plan**\n1. Introduce new interfaces + adapters behind feature flags.\n2. Dual-write or read-compat layer if schema changes.\n3. Incremental cutover; deprecate legacy module.\n\nKey rule: dependencies flow inward; domain has no framework imports.\n\n\nChecks: input validation, tests, and safe defaults included.", "source": "WithinUsAI/GOD_Coder_100k"} {"text": "Create a comprehensive test plan and automated tests for webhooks in a fraud detection product.\nTarget platform: mobile (iOS Swift).\nRequirements: unit/integration tests, edge cases, load tests strategy, and CI gates.\nConstraints: must include tests, must include clear error handling, must be observable (logs/metrics/traces), must be secure-by-default, must include documentation/comments.\nDifficulty: easy. Assume schema evolves frequently; design for migrations.\n\nOutput: production-oriented blueprint with code where appropriate.\nDeliverable: test plan + automation guidance.\n\n**Unit tests**\n- Validation: malformed payloads rejected with correct codes.\n- AuthZ: tenant boundary enforced.\n- Idempotency: replay returns same response; conflicting reuse yields 409.\n\n**Integration tests**\n- DB transaction behavior; unique constraints.\n- Cache behavior: correctness under concurrent requests.\n\n**Load tests**\n- 10k RPS target: measure p95 latency, error rate, saturation.\n\n**CI gates**\n- Lint + typecheck + unit tests required.\n- Coverage threshold for critical modules.\n- Block merge on flaky test detection.\n\n\nChecks: input validation, tests, and safe defaults included.", "source": "WithinUsAI/GOD_Coder_100k"} {"text": "Fix the bug and add pytest tests.\n\n```python\ndef f38226(n: int) -> int:\n # sum 1..n inclusive\n if n < 0: raise ValueError\n total = 0\n for k in range(n): # BUG\n total += k\n return total\n```\nReturn unified diffs for `m48318.py` and `test_m48318.py`.\n\n*** Begin Patch\n*** Update File: m48318.py\n@@\n def f38226(n: int) -> int:\n@@\n- for k in range(n): # BUG\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_m48318.py\n+import pytest\n+from m48318 import f38226\n+\n+def test_small():\n+ assert f38226(7) == 28\n+\n+def test_zero():\n+ assert f38226(0) == 0\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ f38226(-1)\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Refactor to typed, mostly-immutable Python and add minimal tests.\n\n```python\nclass C86972:\n def __init__(self, values): self.values=list(values)\n def mean(self): return sum(self.values)/len(self.values)\n```\nReturn `m52844.py` and `test_m52844.py`.\n\n```python\n# m52844.py\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom typing import Iterable, Tuple\n\n@dataclass(frozen=True)\nclass C86972:\n values: Tuple[float, ...]\n\n @staticmethod\n def create(values: Iterable[float]) -> \"C86972\":\n vals = tuple(float(v) for v in values)\n if not vals: raise ValueError(\"empty\")\n return C86972(vals)\n\n def mean(self) -> float:\n return sum(self.values)/len(self.values)\n```\n\n```python\n# test_m52844.py\nimport pytest\nfrom m52844 import C86972\n\ndef test_mean():\n assert C86972.create([1,2,3]).mean() == 2.0\ndef test_empty():\n with pytest.raises(ValueError):\n C86972.create([])\n```", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Refactor to modern typed Python with immutability and tests.\n\nFile: lt8rhsa4jbaz.py\n```python\nclass UC6Dcp5:\n def __init__(self, name, values):\n self.name = name\n self.values = list(values)\n def add(self, v):\n self.values.append(v)\n def mean(self):\n s = 0\n for x in self.values:\n s += x\n return s / len(self.values)\n```\n\nReturn full new lt8rhsa4jbaz.py and test_lt8rhsa4jbaz.py.\n\n# lt8rhsa4jbaz.py\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom typing import Iterable, Tuple\n\n@dataclass(frozen=True)\nclass UC6Dcp5:\n name: str\n values: Tuple[float, ...]\n\n @staticmethod\n def create(name: str, values: Iterable[float]) -> \"UC6Dcp5\":\n vals = tuple(float(v) for v in values)\n if not vals:\n raise ValueError(\"values must be non-empty\")\n return UC6Dcp5(name=name, values=vals)\n\n def add(self, v: float) -> \"UC6Dcp5\":\n return UC6Dcp5(name=self.name, values=self.values + (float(v),))\n\n def mean(self) -> float:\n return sum(self.values) / len(self.values)\n\n# test_lt8rhsa4jbaz.py\nimport pytest\nfrom lt8rhsa4jbaz import UC6Dcp5\n\ndef test_mean_and_add():\n c = UC6Dcp5.create(\"a\", [1, 2, 3])\n assert c.mean() == 2.0\n assert c.add(5).mean() == (1 + 2 + 3 + 5) / 4\n\ndef test_empty_raises():\n with pytest.raises(ValueError):\n UC6Dcp5.create(\"x\", [])", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: Project domain: team dashboard\nImplementation stack: Spring Boot, PostgreSQL, JUnit, Gradle, Docker, GitHub Actions\nSoftware delivery problem: build reproducibility failure\nTask type: prd_to_patch\nDifficulty: medium\n\nReturn a complete delivery-grade response with:\n- diagnosis or design reasoning\n- implementation\n- test plan or tests\n- rollout plan\n- rollback or compatibility note\n- verification commands\n\nRepository sketch:\nrepo/\n migrations/\n 001_init.sql\n 002_add_index.sql\n queries/\n report.sql\n tests/\n report_cases.md\n\nFocus: Focus on shipping production software with rollout safety, acceptance criteria, telemetry, and maintenance quality.\n\nassistant: Diagnosis:\n- Root cause or delivery blocker: build reproducibility failure needs both implementation work and a safe shipping plan.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```sql\nWITH ranked AS (\n SELECT\n user_id,\n created_at,\n amount,\n ROW_NUMBER() OVER (PARTITION BY user_id ORDER BY created_at DESC, id DESC) AS rn\n FROM orders\n)\nSELECT user_id, created_at, amount\nFROM ranked\nWHERE rn = 1;\n```\n\nTests:\n```sql\n-- Correctness checks:\n-- 1) multiple rows per user\n-- 2) identical timestamps require deterministic tie-breaker\n-- 3) null values handled by business rules\n```\n\nVerification:\n- `run migration checks`\n- `run query correctness cases`\n\nEngineering notes:\n- Language: SQL\n- Framework/tooling: PostgreSQL\n- Stack context: Spring Boot, PostgreSQL, JUnit, Gradle, Docker, GitHub Actions\n- Domain: team dashboard\n- Task type: prd_to_patch\n- Difficulty: medium\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: Language: YAML\nFramework/tooling: Kubernetes\nDomain: model serving gateway\nLogic challenge: invalid rollback sequence\nTask type: multi_file_migration_repair\nDifficulty: expert\n\nReturn a rigorous engineering answer:\n- identify the hidden root cause or logical failure\n- present the corrected implementation\n- add tests that prove the fix\n- list verification commands\n- explain why naive fixes are insufficient when relevant\n\nRepository sketch:\nrepo/\n .github/workflows/ci.yml\n docker-compose.yml\n deploy/\n app.yaml\n\nFocus: Focus on staff-level problem solving with multi-file patches, rollout implications, performance and security tradeoffs.\n\nassistant: Diagnosis:\n- Staff-level diagnosis: invalid rollback sequence impacts correctness, operability, and future maintenance, so the fix must be minimal where possible but complete where necessary.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```yaml\nname: ci\non: [push, pull_request]\njobs:\n test:\n runs-on: ubuntu-latest\n steps:\n - uses: actions/checkout@v4\n - name: Validate\n run: echo \"validated\"\n```\n\nTests:\n```yaml\n# Verification:\n# - validate syntax\n# - run smoke workflow\n# - fail fast on broken config\n```\n\nVerification:\n- `validate workflow syntax`\n- `run CI smoke job`\n\nEngineering notes:\n- Language: YAML\n- Framework/tooling: Kubernetes\n- Stack context: ASP.NET Core, SQL Server, EF Core, xUnit, Docker\n- Domain: model serving gateway\n- Task type: multi_file_migration_repair\n- Difficulty: expert\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: Language: TypeScript\nFramework/tooling: Express\nDomain: reporting engine\nLogic challenge: broken pagination cursor\nTask type: cross_stack_outage_fix\nDifficulty: hard\n\nReturn a rigorous engineering answer:\n- identify the hidden root cause or logical failure\n- present the corrected implementation\n- add tests that prove the fix\n- list verification commands\n- explain why naive fixes are insufficient when relevant\n\nRepository sketch:\nrepo/\n src/\n api.ts\n service.ts\n schema.ts\n tests/\n api.test.ts\n package.json\n\nFocus: Focus on staff-level problem solving with multi-file patches, rollout implications, performance and security tradeoffs.\n\nassistant: Diagnosis:\n- Staff-level diagnosis: broken pagination cursor impacts correctness, operability, and future maintenance, so the fix must be minimal where possible but complete where necessary.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```ts\ntype Payload = Record;\n\nexport function normalizePayload(payload: Payload): Payload {\n if (!payload || typeof payload !== \"object\" || Array.isArray(payload)) {\n throw new TypeError(\"payload must be a plain object\");\n }\n return Object.fromEntries(\n Object.entries(payload)\n .filter(([, value]) => value !== null && value !== undefined)\n .map(([key, value]) => [String(key).trim(), value])\n );\n}\n\nexport function handleBrokenPaginationCursor(payload: Payload) {\n const clean = normalizePayload(payload);\n if (!(\"id\" in clean)) {\n return { ok: false, data: {}, error: \"missing id\" };\n }\n return { ok: true, data: clean, error: null };\n}\n```\n\nTests:\n```ts\nimport { describe, it, expect } from \"vitest\";\nimport { handleBrokenPaginationCursor } from \"../src/service\";\n\ndescribe(\"handler\", () => {\n it(\"accepts valid input\", () => {\n expect(handleBrokenPaginationCursor({ id: 7, name: \"ok\", unused: null })).toEqual({\n ok: true,\n data: { id: 7, name: \"ok\" },\n error: null\n });\n });\n\n it(\"rejects missing id\", () => {\n expect(handleBrokenPaginationCursor({ name: \"x\" }).error).toMatch(/missing id/);\n });\n});\n```\n\nVerification:\n- `npm test`\n- `npm run typecheck`\n- `npm run lint`\n\nEngineering notes:\n- Language: TypeScript\n- Framework/tooling: Express\n- Stack context: Rust, Axum, SQLx, Redis, Tokio, Docker\n- Domain: reporting engine\n- Task type: cross_stack_outage_fix\n- Difficulty: hard\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Fix a bug and add tests.\n\nFile: f9wg3337n22u.py\n```python\ndef upzin_6x(n: int) -> int:\n \"\"\"Sum 1..n inclusive.\"\"\"\n if n < 0:\n raise ValueError(\"n must be non-negative\")\n total = 0\n for k in range(n): # BUG: should include n\n total += k\n return total\n```\n\nReturn unified diffs for f9wg3337n22u.py and test_f9wg3337n22u.py (pytest).\n\n*** Begin Patch\n*** Update File: f9wg3337n22u.py\n@@\n def upzin_6x(n: int) -> int:\n@@\n total = 0\n- for k in range(n): # BUG: should include n\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_f9wg3337n22u.py\n+import pytest\n+from f9wg3337n22u import upzin_6x\n+\n+def test_zero():\n+ assert upzin_6x(0) == 0\n+\n+def test_one():\n+ assert upzin_6x(1) == 1\n+\n+def test_small():\n+ assert upzin_6x(7) == 28\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ upzin_6x(-1)\n+\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Implement webhooks for a customer support product.\nTarget platform: ML (PyTorch + serving).\nRequirements: provide production-ready code, configuration, and tests.\nConstraints: must include type hints where applicable, must be easy to extend, must be production-ready, must include tests, must avoid global state.\nDifficulty: easy. Assume schema evolves frequently; design for migrations.\n\nOutput: actionable implementation and verification artifacts.\nDeliverable: production-grade reference implementation (FastAPI) + tests.\n\n```python\n# app.py\nfrom __future__ import annotations\n\nimport hashlib\nimport json\nfrom dataclasses import dataclass\nfrom datetime import datetime, timezone\nfrom typing import Any, Optional\n\nfrom fastapi import FastAPI, Header, HTTPException\nfrom pydantic import BaseModel, Field\n\napp = FastAPI(title=\"Idempotent API\")\n\nclass CreateReq(BaseModel):\n tenant_id: str = Field(min_length=1)\n amount_cents: int = Field(ge=0)\n currency: str = Field(min_length=3, max_length=3)\n\nclass CreateResp(BaseModel):\n id: str\n created_at: str\n echo: CreateReq\n\n@dataclass\nclass _IdempoEntry:\n request_hash: str\n response_json: str\n\n# In production: Postgres table with UNIQUE(tenant_id, key)\n_IDEMPO: dict[tuple[str, str], _IdempoEntry] = {}\n\ndef _hash_req(req: CreateReq) -> str:\n raw = req.model_dump_json()\n return hashlib.sha256(raw.encode(\"utf-8\")).hexdigest()\n\n@app.post(\"/v1/payments\", response_model=CreateResp)\ndef create_payment(\n req: CreateReq,\n idempotency_key: Optional[str] = Header(default=None, alias=\"Idempotency-Key\"),\n) -> Any:\n if not idempotency_key:\n raise HTTPException(status_code=400, detail=\"Missing Idempotency-Key\")\n if len(idempotency_key) > 128:\n raise HTTPException(status_code=400, detail=\"Idempotency-Key too long\")\n\n key = (req.tenant_id, idempotency_key)\n rh = _hash_req(req)\n\n existing = _IDEMPO.get(key)\n if existing:\n if existing.request_hash != rh:\n raise HTTPException(status_code=409, detail=\"Idempotency-Key reuse with different payload\")\n return json.loads(existing.response_json)\n\n # Create new payment (stubbed)\n pid = hashlib.md5(f\"{req.tenant_id}:{idempotency_key}\".encode()).hexdigest()\n resp = CreateResp(\n id=pid,\n created_at=datetime.now(timezone.utc).isoformat(),\n echo=req,\n )\n _IDEMPO[key] = _IdempoEntry(request_hash=rh, response_json=resp.model_dump_json())\n return resp\n```\n\n```python\n# test_app.py (pytest)\nfrom fastapi.testclient import TestClient\nfrom app import app\n\nclient = TestClient(app)\n\ndef test_idempotent_replay():\n headers = {\"Idempotency-Key\": \"abc\"}\n body = {\"tenant_id\":\"t1\",\"amount_cents\":100,\"currency\":\"USD\"}\n r1 = client.post(\"/v1/payments\", json=body, headers=headers)\n r2 = client.post(\"/v1/payments\", json=body, headers=headers)\n assert r1.status_code == 200 and r2.status_code == 200\n assert r1.json() == r2.json()\n\ndef test_payload_conflict():\n headers = {\"Idempotency-Key\": \"abc\"}\n b1 = {\"tenant_id\":\"t1\",\"amount_cents\":100,\"currency\":\"USD\"}\n b2 = {\"tenant_id\":\"t1\",\"amount_cents\":200,\"currency\":\"USD\"}\n assert client.post(\"/v1/payments\", json=b1, headers=headers).status_code == 200\n assert client.post(\"/v1/payments\", json=b2, headers=headers).status_code == 409\n```\n\nNotes:\n- Replace in-memory store with a DB table and transaction.\n- Store response + request hash to detect key reuse with different payload.\n\n\nChecks: input validation, tests, and safe defaults included.", "source": "WithinUsAI/GOD_Coder_100k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Refactor to modern typed Python with immutability and tests.\n\nFile: uifcnp.py\n```python\nclass H4Nl8Ng4Z0Y:\n def __init__(self, name, values):\n self.name = name\n self.values = list(values)\n def add(self, v):\n self.values.append(v)\n def mean(self):\n s = 0\n for x in self.values:\n s += x\n return s / len(self.values)\n```\n\nReturn full new uifcnp.py and test_uifcnp.py.\n\n# uifcnp.py\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom typing import Iterable, Tuple\n\n@dataclass(frozen=True)\nclass H4Nl8Ng4Z0Y:\n name: str\n values: Tuple[float, ...]\n\n @staticmethod\n def create(name: str, values: Iterable[float]) -> \"H4Nl8Ng4Z0Y\":\n vals = tuple(float(v) for v in values)\n if not vals:\n raise ValueError(\"values must be non-empty\")\n return H4Nl8Ng4Z0Y(name=name, values=vals)\n\n def add(self, v: float) -> \"H4Nl8Ng4Z0Y\":\n return H4Nl8Ng4Z0Y(name=self.name, values=self.values + (float(v),))\n\n def mean(self) -> float:\n return sum(self.values) / len(self.values)\n\n# test_uifcnp.py\nimport pytest\nfrom uifcnp import H4Nl8Ng4Z0Y\n\ndef test_mean_and_add():\n c = H4Nl8Ng4Z0Y.create(\"a\", [1, 2, 3])\n assert c.mean() == 2.0\n assert c.add(5).mean() == (1 + 2 + 3 + 5) / 4\n\ndef test_empty_raises():\n with pytest.raises(ValueError):\n H4Nl8Ng4Z0Y.create(\"x\", [])", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Fix a bug and add tests.\n\nFile: wh3t5s5a.py\n```python\ndef ac31r342b8(n: int) -> int:\n \"\"\"Sum 1..n inclusive.\"\"\"\n if n < 0:\n raise ValueError(\"n must be non-negative\")\n total = 0\n for k in range(n): # BUG: should include n\n total += k\n return total\n```\n\nReturn unified diffs for wh3t5s5a.py and test_wh3t5s5a.py (pytest).\n\n*** Begin Patch\n*** Update File: wh3t5s5a.py\n@@\n def ac31r342b8(n: int) -> int:\n@@\n total = 0\n- for k in range(n): # BUG: should include n\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_wh3t5s5a.py\n+import pytest\n+from wh3t5s5a import ac31r342b8\n+\n+def test_zero():\n+ assert ac31r342b8(0) == 0\n+\n+def test_one():\n+ assert ac31r342b8(1) == 1\n+\n+def test_small():\n+ assert ac31r342b8(7) == 28\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ ac31r342b8(-1)\n+\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Refactor to typed, mostly-immutable Python and add minimal tests.\n\n```python\nclass C81307:\n def __init__(self, values): self.values=list(values)\n def mean(self): return sum(self.values)/len(self.values)\n```\nReturn `m21639.py` and `test_m21639.py`.\n\n```python\n# m21639.py\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom typing import Iterable, Tuple\n\n@dataclass(frozen=True)\nclass C81307:\n values: Tuple[float, ...]\n\n @staticmethod\n def create(values: Iterable[float]) -> \"C81307\":\n vals = tuple(float(v) for v in values)\n if not vals: raise ValueError(\"empty\")\n return C81307(vals)\n\n def mean(self) -> float:\n return sum(self.values)/len(self.values)\n```\n\n```python\n# test_m21639.py\nimport pytest\nfrom m21639 import C81307\n\ndef test_mean():\n assert C81307.create([1,2,3]).mean() == 2.0\ndef test_empty():\n with pytest.raises(ValueError):\n C81307.create([])\n```", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Secure-by-default implementation for background jobs in a calendar/scheduling product.\nTarget platform: web (React + TypeScript).\nRequirements: threat model, input validation, authz/authn guidance, safe storage, tests.\nConstraints: must include type hints where applicable, must be secure-by-default, must be production-ready, must be easy to extend.\nDifficulty: expert. Assume 10k RPS peak traffic.\n\nOutput: engineering-grade answer with edge cases covered.\nDeliverable: threat model + secure patterns (no offensive content).\n\n**Threat model**\n- Input: untrusted clients → validation required\n- Auth: token theft / privilege escalation → short-lived tokens + RBAC checks\n- Data: PII exposure → encryption at rest + access logging + least privilege\n- Webhooks/callbacks: SSRF → allowlist destinations + timeouts + egress controls\n\n**Secure implementation patterns**\n- Validate and normalize inputs at boundaries (API/CLI/file).\n- Use parameterized SQL; never string interpolate.\n- Prevent path traversal when writing files (resolve + base containment).\n- Use idempotency keys for side-effecting endpoints; safe retries.\n- Centralize authorization checks in one layer; test them.\n\n**Test checklist**\n- Invalid inputs rejected with clear error messages.\n- AuthZ tests for tenant boundary violations.\n- Replay/idempotency conflict test.\n\n\nHard-mode checks: concurrency safety, idempotency, and rollback validated; add chaos tests where feasible.", "source": "WithinUsAI/GOD_Coder_100k"} {"text": "Perform a code review for a developer tooling PR implementing event-driven workflows.\nTarget platform: infra (Terraform).\nRequirements: list critical issues, improvements, and provide an improved patch excerpt.\nConstraints: must be easy to extend, must include clear error handling, must include tests, must be secure-by-default.\nDifficulty: expert. Include rollback strategy.\n\nOutput: production-oriented blueprint with code where appropriate.\nDeliverable: code review findings + improved patch excerpt.\n\n**Critical issues**\n1. Missing input validation at boundary; potential unexpected exceptions.\n2. No idempotency / retry safety for side-effecting endpoint.\n3. No tests for edge cases (empty input, duplicates, timeouts).\n4. Observability gaps: no request_id correlation, no metrics.\n\n**Improvements**\n- Add strict validation and explicit error responses.\n- Add idempotency key support for create endpoints.\n- Add unit + integration tests with CI gating.\n- Add structured logs and basic metrics.\n\nPatch excerpt (illustrative):\n```python\nif not idem_key:\n raise HTTPException(400, \"Missing Idempotency-Key\")\n```\n\n\nHard-mode checks: concurrency safety, idempotency, and rollback validated; add chaos tests where feasible.", "source": "WithinUsAI/GOD_Coder_100k"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: Language: Go\nFramework/tooling: sqlc\nDomain: repo automation\nLogic challenge: rate-limit bypass\nTask type: transaction_integrity_fix\nDifficulty: hard\n\nReturn a rigorous engineering answer:\n- identify the hidden root cause or logical failure\n- present the corrected implementation\n- add tests that prove the fix\n- list verification commands\n- explain why naive fixes are insufficient when relevant\n\nRepository sketch:\nrepo/\n cmd/server/main.go\n internal/service/service.go\n internal/store/store.go\n internal/api/api.go\n service_test.go\n go.mod\n\nFocus: Focus on ambiguity, misleading symptoms, hidden root causes, and high-stakes debugging.\n\nassistant: Diagnosis:\n- Hidden root cause: rate-limit bypass presents misleading symptoms, so the patch must target the actual logic boundary rather than the first visible failure.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```go\npackage service\n\nimport \"fmt\"\n\nfunc NormalizePayload(payload map[string]any) map[string]any {\n\tout := make(map[string]any)\n\tfor k, v := range payload {\n\t\tif v == nil {\n\t\t\tcontinue\n\t\t}\n\t\tout[k] = v\n\t}\n\treturn out\n}\n\nfunc Handle(payload map[string]any) (map[string]any, error) {\n\tclean := NormalizePayload(payload)\n\tif _, ok := clean[\"id\"]; !ok {\n\t\treturn nil, fmt.Errorf(\"missing id\")\n\t}\n\treturn map[string]any{\"ok\": true, \"data\": clean}, nil\n}\n```\n\nTests:\n```go\npackage service\n\nimport \"testing\"\n\nfunc TestHandle(t *testing.T) {\n\tgot, err := Handle(map[string]any{\"id\": 7, \"name\": \"ok\", \"unused\": nil})\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tif got[\"ok\"] != true {\n\t\tt.Fatalf(\"expected ok=true\")\n\t}\n\tif _, err := Handle(map[string]any{\"name\": \"x\"}); err == nil {\n\t\tt.Fatalf(\"expected missing id error\")\n\t}\n}\n```\n\nVerification:\n- `go test ./...`\n- `go vet ./...`\n\nEngineering notes:\n- Language: Go\n- Framework/tooling: sqlc\n- Stack context: Go, Gin, PostgreSQL, gRPC, Prometheus, Docker\n- Domain: repo automation\n- Task type: transaction_integrity_fix\n- Difficulty: hard\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "Fix a subtle bug in a Python module used for task scheduling.\nRequirements: explain root cause briefly, provide corrected code, and add regression tests.\nConstraints: must be streaming-friendly, must include type hints, must include tests.\nDifficulty: medium. Provide helpful exceptions with actionable messages.\n\nDeliverable: production-ready reference solution.\n```python\nfrom __future__ import annotations\n\nfrom dataclasses import dataclass\nfrom pathlib import Path\nfrom typing import Iterable\nimport json\n\n\nclass ValidationError(ValueError):\n \"\"\"Raised when input validation fails.\"\"\"\n\n\ndef safe_join(base: Path, *parts: str) -> Path:\n \"\"\"Join paths while preventing traversal outside base.\"\"\"\n b = base.resolve()\n p = (b / Path(*parts)).resolve()\n if p != b and b not in p.parents:\n raise ValidationError(f\"unsafe path: {p}\")\n return p\n\n\n@dataclass(frozen=True, slots=True)\nclass Record:\n key: str\n value: int\n\n\ndef parse_jsonl(lines: Iterable[str]) -> list[Record]:\n out: list[Record] = []\n for idx, line in enumerate(lines, 1):\n s = line.strip()\n if not s:\n continue\n try:\n obj = json.loads(s)\n except json.JSONDecodeError as e:\n raise ValidationError(f\"line {idx}: invalid json\") from e\n if not isinstance(obj, dict):\n raise ValidationError(f\"line {idx}: expected object\")\n key = obj.get(\"key\")\n val = obj.get(\"value\")\n if not isinstance(key, str) or not key:\n raise ValidationError(f\"line {idx}: key must be non-empty str\")\n if not isinstance(val, int):\n raise ValidationError(f\"line {idx}: value must be int\")\n out.append(Record(key, val))\n return out\n\n\ndef write_jsonl(base: Path, rel: str, records: Iterable[Record]) -> Path:\n base.mkdir(parents=True, exist_ok=True)\n dst = safe_join(base, rel)\n dst.parent.mkdir(parents=True, exist_ok=True)\n with dst.open(\"w\", encoding=\"utf-8\", newline=\"\\n\") as f:\n for r in records:\n f.write(json.dumps({\"key\": r.key, \"value\": r.value}, ensure_ascii=False) + \"\\n\")\n return dst\n```\n\n```python\n# tests (pytest-style)\nimport json\nfrom pathlib import Path\nimport pytest\nfrom module_under_test import ValidationError, Record, parse_jsonl, write_jsonl\n\ndef test_parse_ok():\n lines = [json.dumps({\"key\":\"a\",\"value\":1}), json.dumps({\"key\":\"b\",\"value\":2})]\n assert parse_jsonl(lines) == [Record(\"a\",1), Record(\"b\",2)]\n\ndef test_parse_rejects_bad_json():\n with pytest.raises(ValidationError):\n parse_jsonl([\"{not json}\"])\n\ndef test_safe_join_blocks_traversal(tmp_path: Path):\n with pytest.raises(ValidationError):\n write_jsonl(tmp_path, \"../x.jsonl\", [Record(\"a\",1)])\n```", "source": "WithinUsAI/python_GOD_coder_100k"} {"text": "Design CI/CD for a social media service delivering audit logs.\nTarget platform: infra (Docker + Kubernetes).\nRequirements: pipelines, checks, artifact strategy, deployments, and rollbacks.\nConstraints: must be performant under load, must be observable (logs/metrics/traces), must be easy to extend, must include tests.\nDifficulty: expert. Assume 10k RPS peak traffic.\n\nOutput: actionable implementation and verification artifacts.\nDeliverable: CI/CD pipeline (GitHub Actions) with quality gates.\n\n```yaml\nname: ci\non:\n pull_request:\n push:\n branches: [main]\n\njobs:\n test:\n runs-on: ubuntu-latest\n steps:\n - uses: actions/checkout@v4\n - uses: actions/setup-python@v5\n with:\n python-version: \"3.11\"\n - run: python -m pip install -U pip\n - run: pip install -r requirements.txt\n - run: pip install -r requirements-dev.txt\n - run: ruff check .\n - run: mypy .\n - run: pytest -q --maxfail=1 --disable-warnings\n\n docker:\n needs: test\n runs-on: ubuntu-latest\n steps:\n - uses: actions/checkout@v4\n - uses: docker/setup-buildx-action@v3\n - run: docker build -t app:${{ github.sha }} .\n```\n\nDeployment strategy:\n- main → build → deploy to staging → smoke tests → canary to prod.\n- Rollback: redeploy previous image + DB migration rollback plan.\n\n\nHard-mode checks: concurrency safety, idempotency, and rollback validated; add chaos tests where feasible.", "source": "WithinUsAI/GOD_Coder_100k"} {"text": "Write a thorough test suite for a Python component used for task scheduling.\nRequirements: cover edge cases, invalid inputs, and behavior invariants.\nConstraints: must avoid global state, must include type hints, must be easy to extend.\nDifficulty: easy. Include a small CLI example if relevant.\n\nDeliverable: implementation + tests.\n```python\n# tests (pytest-style) for a module providing: normalize(), parse_lines(), compute_stats()\nimport math\nimport pytest\n\ndef test_normalize_idempotent(module_under_test):\n x = \" A\\tB \"\n assert module_under_test.normalize(module_under_test.normalize(x)) == module_under_test.normalize(x)\n\ndef test_parse_lines_rejects_invalid(module_under_test):\n with pytest.raises(ValueError):\n module_under_test.parse_lines([\"\", \"???\", None]) # type: ignore[arg-type]\n\ndef test_compute_stats_basic(module_under_test):\n data = [1, 2, 3, 4]\n s = module_under_test.compute_stats(data)\n assert s.count == 4\n assert s.total == 10\n assert math.isclose(s.mean, 2.5)\n```", "source": "WithinUsAI/python_GOD_coder_100k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Fix a bug and add tests.\n\nFile: ls2js8037gy.py\n```python\ndef drc2lm4h(n: int) -> int:\n \"\"\"Sum 1..n inclusive.\"\"\"\n if n < 0:\n raise ValueError(\"n must be non-negative\")\n total = 0\n for k in range(n): # BUG: should include n\n total += k\n return total\n```\n\nReturn unified diffs for ls2js8037gy.py and test_ls2js8037gy.py (pytest).\n\n*** Begin Patch\n*** Update File: ls2js8037gy.py\n@@\n def drc2lm4h(n: int) -> int:\n@@\n total = 0\n- for k in range(n): # BUG: should include n\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_ls2js8037gy.py\n+import pytest\n+from ls2js8037gy import drc2lm4h\n+\n+def test_zero():\n+ assert drc2lm4h(0) == 0\n+\n+def test_one():\n+ assert drc2lm4h(1) == 1\n+\n+def test_small():\n+ assert drc2lm4h(7) == 28\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ drc2lm4h(-1)\n+\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Optimize a Python workflow for report generation.\nRequirements: provide an optimized implementation and a small benchmark harness.\nConstraints: must handle Windows paths safely, must provide clear error messages, must be memory-efficient.\nDifficulty: easy. Guarantee deterministic output ordering.\n\nDeliverable: implementation + tests.\nStrategy:\n- Avoid repeated parsing; precompile regex if needed; use local variables; stream processing.\n\n```python\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom typing import Iterable\nimport time\n\n@dataclass(frozen=True, slots=True)\nclass Stats:\n count: int\n total: int\n\ndef compute_stats_stream(values: Iterable[int]) -> Stats:\n c = 0\n t = 0\n for v in values:\n c += 1\n t += v\n return Stats(c, t)\n\ndef bench(n: int = 1_000_00) -> float:\n data = range(n)\n t0 = time.perf_counter()\n _ = compute_stats_stream(data)\n return time.perf_counter() - t0\n```\n\n```python\nfrom module_under_test import bench\ndef test_bench_runs_fast_enough():\n # Sanity: should run quickly on typical machines; adjust threshold for CI.\n assert bench(50_000) < 0.5\n```", "source": "WithinUsAI/python_GOD_coder_100k"} {"text": "Optimize while preserving behavior and order.\n\n```python\ndef f20264(xs):\n out=[]\n for x in xs:\n if x not in out: out.append(x)\n return out\n```\nReturn `m45752.py` with types and O(n) average.\n\n```python\n# m45752.py\nfrom __future__ import annotations\nfrom typing import Iterable, List, Set, TypeVar\nT=TypeVar(\"T\")\n\ndef f20264(xs: Iterable[T]) -> List[T]:\n \"\"\"Unique items preserving first-seen order.\"\"\"\n seen: Set[T]=set()\n out: List[T]=[]\n for x in xs:\n if x in seen: continue\n seen.add(x); out.append(x)\n return out\n```", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Design a production system for healthtech supporting analytics pipeline.\nTarget platform: backend (Go).\nRequirements: APIs, data model, scaling strategy, failure modes, and security.\nConstraints: must include tests, must be secure-by-default, must include type hints where applicable, must avoid global state.\nDifficulty: medium. Assume schema evolves frequently; design for migrations.\n\nOutput: production-oriented blueprint with code where appropriate.\nDeliverable: system design with APIs, data model, and operational plan.\n\n**High-level architecture**\n- Edge: API Gateway + WAF\n- Core service: stateless app pods behind L7 LB\n- Data: Postgres (primary), Redis (cache + rate limit tokens), Object storage (uploads if needed)\n- Async: message queue (e.g., SQS/Rabbit) + worker pool for background jobs\n- Observability: structured logs + metrics + tracing\n\n**APIs (example)**\n- `POST /v1/{resource}` create (idempotent via `Idempotency-Key`)\n- `GET /v1/{resource}/{id}` read\n- `POST /v1/{resource}/{id}:action` command endpoint when side effects exist\n\n**Data model (Postgres)**\n- `resources(id UUID PK, tenant_id UUID, status TEXT, payload JSONB, created_at, updated_at)`\n- Unique constraint for idempotency: `(tenant_id, idempotency_key)` in a separate table:\n - `idempotency(tenant_id, key TEXT, request_hash TEXT, response JSONB, created_at, PRIMARY KEY(tenant_id,key))`\n\n**Scaling**\n- App layer scales horizontally; keep sessions out of process.\n- Cache reads in Redis; write-through invalidation on mutations.\n- Use connection pooling; consider read replicas for heavy reads.\n\n**Failure modes**\n- Retries: only for safe/ idempotent operations; exponential backoff + jitter.\n- Partial failures: background jobs must be idempotent; use a de-dup key.\n\n**Security**\n- AuthN: JWT/OIDC; AuthZ: RBAC/ABAC with tenant isolation\n- Validate all inputs; enforce per-tenant quotas/rate limits.\n\n**Rollout**\n- Dark launch + feature flags; canary; rapid rollback by toggling flags.\n\n\nChecks: input validation, tests, and safe defaults included.", "source": "WithinUsAI/GOD_Coder_100k"} {"text": "Design and implement an algorithm for file synchronization.\nRequirements: define inputs/outputs, implement solution with complexity analysis, and include tests.\nConstraints: must include type hints, must be memory-efficient, must avoid global state, must include tests.\nDifficulty: expert. Provide helpful exceptions with actionable messages.\n\nDeliverable: corrected code and verification tests.\nProblem: compute rolling sums over events (ts:int,value:int) with window W seconds. Events may be out-of-order.\n\nComplexity: sorting O(n log n); window maintenance O(n); memory O(k).\n\n```python\nfrom __future__ import annotations\nfrom collections import deque\nfrom dataclasses import dataclass\nfrom typing import Iterable, List, Tuple\n\n@dataclass(frozen=True, slots=True)\nclass Event:\n ts: int\n value: int\n\ndef rolling_sum(events: Iterable[Event], window_s: int) -> List[Tuple[int,int]]:\n if window_s < 0:\n raise ValueError(\"window_s must be >= 0\")\n evs = sorted(events, key=lambda e: e.ts)\n q: deque[Event] = deque()\n s = 0\n out: List[Tuple[int,int]] = []\n for e in evs:\n q.append(e)\n s += e.value\n cutoff = e.ts - window_s\n while q and q[0].ts < cutoff:\n old = q.popleft()\n s -= old.value\n out.append((e.ts, s))\n return out\n```\n\n```python\nimport pytest\nfrom module_under_test import Event, rolling_sum\n\ndef test_rolling_sum():\n ev = [Event(10,1), Event(11,2), Event(20,5)]\n assert rolling_sum(ev, 5) == [(10,1),(11,3),(20,5)]\n```", "source": "WithinUsAI/python_GOD_coder_100k"} {"text": "Design a production system for social media supporting audit logs.\nTarget platform: ML (PyTorch + serving).\nRequirements: APIs, data model, scaling strategy, failure modes, and security.\nConstraints: must be observable (logs/metrics/traces), must avoid global state, must include tests.\nDifficulty: medium. Assume GDPR-style deletion requests must be supported.\n\nOutput: production-oriented blueprint with code where appropriate.\nDeliverable: system design with APIs, data model, and operational plan.\n\n**High-level architecture**\n- Edge: API Gateway + WAF\n- Core service: stateless app pods behind L7 LB\n- Data: Postgres (primary), Redis (cache + rate limit tokens), Object storage (uploads if needed)\n- Async: message queue (e.g., SQS/Rabbit) + worker pool for background jobs\n- Observability: structured logs + metrics + tracing\n\n**APIs (example)**\n- `POST /v1/{resource}` create (idempotent via `Idempotency-Key`)\n- `GET /v1/{resource}/{id}` read\n- `POST /v1/{resource}/{id}:action` command endpoint when side effects exist\n\n**Data model (Postgres)**\n- `resources(id UUID PK, tenant_id UUID, status TEXT, payload JSONB, created_at, updated_at)`\n- Unique constraint for idempotency: `(tenant_id, idempotency_key)` in a separate table:\n - `idempotency(tenant_id, key TEXT, request_hash TEXT, response JSONB, created_at, PRIMARY KEY(tenant_id,key))`\n\n**Scaling**\n- App layer scales horizontally; keep sessions out of process.\n- Cache reads in Redis; write-through invalidation on mutations.\n- Use connection pooling; consider read replicas for heavy reads.\n\n**Failure modes**\n- Retries: only for safe/ idempotent operations; exponential backoff + jitter.\n- Partial failures: background jobs must be idempotent; use a de-dup key.\n\n**Security**\n- AuthN: JWT/OIDC; AuthZ: RBAC/ABAC with tenant isolation\n- Validate all inputs; enforce per-tenant quotas/rate limits.\n\n**Rollout**\n- Dark launch + feature flags; canary; rapid rollback by toggling flags.\n\n\nChecks: input validation, tests, and safe defaults included.", "source": "WithinUsAI/GOD_Coder_100k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Fix a bug and add tests.\n\nFile: he6cyl.py\n```python\ndef s0b88c(n: int) -> int:\n \"\"\"Sum 1..n inclusive.\"\"\"\n if n < 0:\n raise ValueError(\"n must be non-negative\")\n total = 0\n for k in range(n): # BUG: should include n\n total += k\n return total\n```\n\nReturn unified diffs for he6cyl.py and test_he6cyl.py (pytest).\n\n*** Begin Patch\n*** Update File: he6cyl.py\n@@\n def s0b88c(n: int) -> int:\n@@\n total = 0\n- for k in range(n): # BUG: should include n\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_he6cyl.py\n+import pytest\n+from he6cyl import s0b88c\n+\n+def test_zero():\n+ assert s0b88c(0) == 0\n+\n+def test_one():\n+ assert s0b88c(1) == 1\n+\n+def test_small():\n+ assert s0b88c(7) == 28\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ s0b88c(-1)\n+\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Fix the bug and add pytest tests.\n\n```python\ndef f65620(n: int) -> int:\n # sum 1..n inclusive\n if n < 0: raise ValueError\n total = 0\n for k in range(n): # BUG\n total += k\n return total\n```\nReturn unified diffs for `m23660.py` and `test_m23660.py`.\n\n*** Begin Patch\n*** Update File: m23660.py\n@@\n def f65620(n: int) -> int:\n@@\n- for k in range(n): # BUG\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_m23660.py\n+import pytest\n+from m23660 import f65620\n+\n+def test_small():\n+ assert f65620(7) == 28\n+\n+def test_zero():\n+ assert f65620(0) == 0\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ f65620(-1)\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Fix the bug and add pytest tests.\n\n```python\ndef f52112(n: int) -> int:\n # sum 1..n inclusive\n if n < 0: raise ValueError\n total = 0\n for k in range(n): # BUG\n total += k\n return total\n```\nReturn unified diffs for `m36016.py` and `test_m36016.py`.\n\n*** Begin Patch\n*** Update File: m36016.py\n@@\n def f52112(n: int) -> int:\n@@\n- for k in range(n): # BUG\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_m36016.py\n+import pytest\n+from m36016 import f52112\n+\n+def test_small():\n+ assert f52112(7) == 28\n+\n+def test_zero():\n+ assert f52112(0) == 0\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ f52112(-1)\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Implement multi-tenant isolation for a fraud detection product.\nTarget platform: backend (Python FastAPI).\nRequirements: provide production-ready code, configuration, and tests.\nConstraints: must include tests, must include documentation/comments, must include clear error handling, must avoid global state, must be easy to extend.\nDifficulty: easy. Assume mobile clients are occasionally offline.\n\nOutput: engineering-grade answer with edge cases covered.\nDeliverable: production-grade reference implementation (FastAPI) + tests.\n\n```python\n# app.py\nfrom __future__ import annotations\n\nimport hashlib\nimport json\nfrom dataclasses import dataclass\nfrom datetime import datetime, timezone\nfrom typing import Any, Optional\n\nfrom fastapi import FastAPI, Header, HTTPException\nfrom pydantic import BaseModel, Field\n\napp = FastAPI(title=\"Idempotent API\")\n\nclass CreateReq(BaseModel):\n tenant_id: str = Field(min_length=1)\n amount_cents: int = Field(ge=0)\n currency: str = Field(min_length=3, max_length=3)\n\nclass CreateResp(BaseModel):\n id: str\n created_at: str\n echo: CreateReq\n\n@dataclass\nclass _IdempoEntry:\n request_hash: str\n response_json: str\n\n# In production: Postgres table with UNIQUE(tenant_id, key)\n_IDEMPO: dict[tuple[str, str], _IdempoEntry] = {}\n\ndef _hash_req(req: CreateReq) -> str:\n raw = req.model_dump_json()\n return hashlib.sha256(raw.encode(\"utf-8\")).hexdigest()\n\n@app.post(\"/v1/payments\", response_model=CreateResp)\ndef create_payment(\n req: CreateReq,\n idempotency_key: Optional[str] = Header(default=None, alias=\"Idempotency-Key\"),\n) -> Any:\n if not idempotency_key:\n raise HTTPException(status_code=400, detail=\"Missing Idempotency-Key\")\n if len(idempotency_key) > 128:\n raise HTTPException(status_code=400, detail=\"Idempotency-Key too long\")\n\n key = (req.tenant_id, idempotency_key)\n rh = _hash_req(req)\n\n existing = _IDEMPO.get(key)\n if existing:\n if existing.request_hash != rh:\n raise HTTPException(status_code=409, detail=\"Idempotency-Key reuse with different payload\")\n return json.loads(existing.response_json)\n\n # Create new payment (stubbed)\n pid = hashlib.md5(f\"{req.tenant_id}:{idempotency_key}\".encode()).hexdigest()\n resp = CreateResp(\n id=pid,\n created_at=datetime.now(timezone.utc).isoformat(),\n echo=req,\n )\n _IDEMPO[key] = _IdempoEntry(request_hash=rh, response_json=resp.model_dump_json())\n return resp\n```\n\n```python\n# test_app.py (pytest)\nfrom fastapi.testclient import TestClient\nfrom app import app\n\nclient = TestClient(app)\n\ndef test_idempotent_replay():\n headers = {\"Idempotency-Key\": \"abc\"}\n body = {\"tenant_id\":\"t1\",\"amount_cents\":100,\"currency\":\"USD\"}\n r1 = client.post(\"/v1/payments\", json=body, headers=headers)\n r2 = client.post(\"/v1/payments\", json=body, headers=headers)\n assert r1.status_code == 200 and r2.status_code == 200\n assert r1.json() == r2.json()\n\ndef test_payload_conflict():\n headers = {\"Idempotency-Key\": \"abc\"}\n b1 = {\"tenant_id\":\"t1\",\"amount_cents\":100,\"currency\":\"USD\"}\n b2 = {\"tenant_id\":\"t1\",\"amount_cents\":200,\"currency\":\"USD\"}\n assert client.post(\"/v1/payments\", json=b1, headers=headers).status_code == 200\n assert client.post(\"/v1/payments\", json=b2, headers=headers).status_code == 409\n```\n\nNotes:\n- Replace in-memory store with a DB table and transaction.\n- Store response + request hash to detect key reuse with different payload.\n\n\nChecks: input validation, tests, and safe defaults included.", "source": "WithinUsAI/GOD_Coder_100k"} {"text": "Fix the bug and add pytest tests.\n\n```python\ndef f55879(n: int) -> int:\n # sum 1..n inclusive\n if n < 0: raise ValueError\n total = 0\n for k in range(n): # BUG\n total += k\n return total\n```\nReturn unified diffs for `m93697.py` and `test_m93697.py`.\n\n*** Begin Patch\n*** Update File: m93697.py\n@@\n def f55879(n: int) -> int:\n@@\n- for k in range(n): # BUG\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_m93697.py\n+import pytest\n+from m93697 import f55879\n+\n+def test_small():\n+ assert f55879(7) == 28\n+\n+def test_zero():\n+ assert f55879(0) == 0\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ f55879(-1)\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Build an elite-grade solution in the domain of realtime systems for scenario: time-series metrics.\nPrimary language: go.\nDifficulty: medium.\nConstraints: assume untrusted inputs; validate and sanitize, include tests or verification strategy, avoid undefined behavior and data races.\nComponent: component_tncrxrx.\nAssume strict auditability and replayable history.\nTask: Implement a concurrency primitive or subsystem (lock-free queue, thread pool, async runtime component). Explain memory ordering and correctness arguments; include stress tests.\n\nOutput: rigorous solution with invariants, failure modes, and performance notes.\nOutput: correctness-focused concurrency primitive + stress tests.\n\n**Primitive**\n- Bounded MPMC queue with backpressure (blocking push/pop) OR lock-free SPSC ring buffer.\n\n**Correctness notes**\n- For lock-free: use acquire/release semantics on head/tail indices.\n- Avoid ABA by monotonic counters; ring index = counter % capacity.\n\n**Stress tests**\n- Multi-thread producers/consumers; assert item multiset preserved.\n- Use time-bounded randomized schedules; detect deadlocks.\n\n\nChecks: boundary validation and deterministic behavior verified.", "source": "WithinUsAI/Elite_GOD_Coder_100k"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: Project stack: Go, Gin, PostgreSQL, gRPC, Prometheus, Docker\nLanguage: Go\nDependency challenge: CI failures after dependency upgrade\nTask type: version_conflict_resolution\nDifficulty: hard\n\nFix this as a senior engineer.\nRequired:\n- identify the version or compatibility failure mode\n- produce the corrected config/code/build patch\n- explain rollback-safe migration notes\n- add regression tests or reproducibility checks\n- include concrete verification commands\n\nRepository sketch:\nrepo/\n cmd/server/main.go\n internal/service/service.go\n internal/store/store.go\n internal/api/api.go\n service_test.go\n go.mod\n\nFocus: Focus on versioning, migrations, lockfiles, runtime compatibility, and secure dependency handling.\n\nassistant: Diagnosis:\n- Root cause: the issue around CI failures after dependency upgrade is a dependency, migration, or runtime-compatibility mismatch that needs a rollback-safe patch.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```go\npackage service\n\nimport \"fmt\"\n\nfunc NormalizePayload(payload map[string]any) map[string]any {\n\tout := make(map[string]any)\n\tfor k, v := range payload {\n\t\tif v == nil {\n\t\t\tcontinue\n\t\t}\n\t\tout[k] = v\n\t}\n\treturn out\n}\n\nfunc Handle(payload map[string]any) (map[string]any, error) {\n\tclean := NormalizePayload(payload)\n\tif _, ok := clean[\"id\"]; !ok {\n\t\treturn nil, fmt.Errorf(\"missing id\")\n\t}\n\treturn map[string]any{\"ok\": true, \"data\": clean}, nil\n}\n```\n\nTests:\n```go\npackage service\n\nimport \"testing\"\n\nfunc TestHandle(t *testing.T) {\n\tgot, err := Handle(map[string]any{\"id\": 7, \"name\": \"ok\", \"unused\": nil})\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tif got[\"ok\"] != true {\n\t\tt.Fatalf(\"expected ok=true\")\n\t}\n\tif _, err := Handle(map[string]any{\"name\": \"x\"}); err == nil {\n\t\tt.Fatalf(\"expected missing id error\")\n\t}\n}\n```\n\nVerification:\n- `go test ./...`\n- `go vet ./...`\n\nEngineering notes:\n- Language: Go\n- Framework/tooling: Fiber\n- Stack context: Go, Gin, PostgreSQL, gRPC, Prometheus, Docker\n- Domain: reporting engine\n- Task type: version_conflict_resolution\n- Difficulty: hard\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "Write pytest tests for `f27186`.\n\n```python\ndef f27186(a: int, b: int) -> int:\n return a*a + b*b\n```\nInclude edge cases and a property-style check.\n\n```python\nimport random\nfrom m89598 import f27186\n\ndef test_known():\n assert f27186(3,4) == 25\n\ndef test_zero():\n assert f27186(0,0) == 0\n\ndef test_property_nonnegative():\n for _ in range(200):\n a=random.randint(-50,50)\n b=random.randint(-50,50)\n assert f27186(a,b) >= 0\n```", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: Project domain: search service\nImplementation stack: ASP.NET Core, SQL Server, EF Core, xUnit, Docker\nSoftware delivery problem: streaming timeout handling\nTask type: test_strategy_implementation\nDifficulty: medium\n\nReturn a complete delivery-grade response with:\n- diagnosis or design reasoning\n- implementation\n- test plan or tests\n- rollout plan\n- rollback or compatibility note\n- verification commands\n\nRepository sketch:\nrepo/\n src/\n api.js\n service.js\n utils.js\n tests/\n api.test.js\n package.json\n\nFocus: Focus on shipping production software with rollout safety, acceptance criteria, telemetry, and maintenance quality.\n\nassistant: Diagnosis:\n- Root cause or delivery blocker: streaming timeout handling needs both implementation work and a safe shipping plan.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```javascript\ntype Payload = Record;\n\nexport function normalizePayload(payload: Payload): Payload {\n if (!payload || typeof payload !== \"object\" || Array.isArray(payload)) {\n throw new TypeError(\"payload must be a plain object\");\n }\n return Object.fromEntries(\n Object.entries(payload)\n .filter(([, value]) => value !== null && value !== undefined)\n .map(([key, value]) => [String(key).trim(), value])\n );\n}\n\nexport function handleStreamingTimeoutHandling(payload: Payload) {\n const clean = normalizePayload(payload);\n if (!(\"id\" in clean)) {\n return { ok: false, data: {}, error: \"missing id\" };\n }\n return { ok: true, data: clean, error: null };\n}\n```\n\nTests:\n```javascript\nimport { describe, it, expect } from \"vitest\";\nimport { handleStreamingTimeoutHandling } from \"../src/service\";\n\ndescribe(\"handler\", () => {\n it(\"accepts valid input\", () => {\n expect(handleStreamingTimeoutHandling({ id: 7, name: \"ok\", unused: null })).toEqual({\n ok: true,\n data: { id: 7, name: \"ok\" },\n error: null\n });\n });\n\n it(\"rejects missing id\", () => {\n expect(handleStreamingTimeoutHandling({ name: \"x\" }).error).toMatch(/missing id/);\n });\n});\n```\n\nVerification:\n- `npm test`\n- `npm run lint`\n\nEngineering notes:\n- Language: JavaScript\n- Framework/tooling: Jest\n- Stack context: ASP.NET Core, SQL Server, EF Core, xUnit, Docker\n- Domain: search service\n- Task type: test_strategy_implementation\n- Difficulty: medium\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "Fix the bug and add pytest tests.\n\n```python\ndef f89925(n: int) -> int:\n # sum 1..n inclusive\n if n < 0: raise ValueError\n total = 0\n for k in range(n): # BUG\n total += k\n return total\n```\nReturn unified diffs for `m84275.py` and `test_m84275.py`.\n\n*** Begin Patch\n*** Update File: m84275.py\n@@\n def f89925(n: int) -> int:\n@@\n- for k in range(n): # BUG\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_m84275.py\n+import pytest\n+from m84275 import f89925\n+\n+def test_small():\n+ assert f89925(7) == 28\n+\n+def test_zero():\n+ assert f89925(0) == 0\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ f89925(-1)\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Task type: mechanized_spec\nScenario: graph query service\nDomain focus: stream processing\nPrimary language: lean\nDifficulty: hard\nScale/SLO: 100k RPS peak\nComponent: component_uksqnqkt\nConstraints: assume adversarial inputs; validate everything, include security threat model (defensive only), avoid data races and undefined behavior, include deterministic replay plan, include verification strategy, include test vectors and fuzz strategy, include performance model and limits\nAssume crash-only processes; recovery must be deterministic.\nDeliverable: Provide a mechanized-style spec outline (Lean-like), key definitions, and a proof plan. Include executable reference code skeleton and tests.\n\nOutput: elite engineering answer optimized for correctness, performance, and operability.\n**Contract**\n- Inputs validated at the boundary; explicit error taxonomy.\n- Idempotency for side effects via request_id; deterministic replay.\n- Backward compatibility: additive changes by default; versioned breaking changes.\n**Invariants**\n- Isolation: tenant boundary enforced; no cross-tenant reads/writes.\n- Determinism: replay of the same event log yields identical outputs.\n- Safety: state transitions preserve invariants; no partial commit leaks.\n**Failure modes & recovery**\n- Crash during commit: WAL replay completes or transaction aborts; no torn writes.\n- Network partition: minority cannot commit; clients receive retriable errors.\n- Data corruption: checksums + scrubber; quarantine and rebuild from replicas/snapshots.\n**Security posture (defensive)**\n- Threat model: auth/authz, injection, replay/abuse, supply chain.\n- Least privilege; secrets in managed store; audit logs for sensitive ops.\n- Input normalization, parameterized queries, path traversal protections.\n**Verification strategy**\n- Fuzzing of parsers/framers/validators with corpus seeds.\n- Deterministic simulation with fault injection (crash/partition/latency).\n- Canary + shadow traffic; invariants checked in production via assertions/metrics.\n\n**Snippet**\n```lean\n-- Pseudo-Lean outline\nstructure State where\n ver : Nat\n val : Option ByteArray\n\ndef invariant (s : State) : Prop := True\n\ntheorem step_preserves_invariant :\n ∀ s, invariant s → ∀ s', Step s s' → invariant s' := by\n intro s hs s' hstep\n -- proof plan: case analysis on transition; trivial here\n trivial\n```\n\nHard checks: fault injection tests gate merges; perf thresholds enforced in CI.", "source": "WithinUsAI/Omega_Genesis_Coder_100k"} {"text": "Optimize while preserving behavior and order.\n\n```python\ndef f42133(xs):\n out=[]\n for x in xs:\n if x not in out: out.append(x)\n return out\n```\nReturn `m06019.py` with types and O(n) average.\n\n```python\n# m06019.py\nfrom __future__ import annotations\nfrom typing import Iterable, List, Set, TypeVar\nT=TypeVar(\"T\")\n\ndef f42133(xs: Iterable[T]) -> List[T]:\n \"\"\"Unique items preserving first-seen order.\"\"\"\n seen: Set[T]=set()\n out: List[T]=[]\n for x in xs:\n if x in seen: continue\n seen.add(x); out.append(x)\n return out\n```", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Implement a web feature for IoT telemetry: idempotent payments.\nTarget platform: web (React + TypeScript).\nRequirements: accessible UI, API integration, and tests.\nConstraints: must avoid global state, must be secure-by-default, must be performant under load, must be easy to extend.\nDifficulty: hard. Assume 10k RPS peak traffic.\n\nOutput: design + implementation guidance suitable for shipping.\nDeliverable: accessible React + TypeScript feature skeleton with tests.\n\n```tsx\n// Feature.tsx\nimport React, { useEffect, useMemo, useState } from \"react\";\n\ntype Item = { id: string; label: string };\n\nexport function Feature({ fetchItems }: { fetchItems: () => Promise }) {\n const [items, setItems] = useState([]);\n const [q, setQ] = useState(\"\");\n const filtered = useMemo(\n () => items.filter(i => i.label.toLowerCase().includes(q.toLowerCase())),\n [items, q]\n );\n\n useEffect(() => {\n let cancelled = false;\n fetchItems().then(xs => { if (!cancelled) setItems(xs); });\n return () => { cancelled = true; };\n }, [fetchItems]);\n\n return (\n
\n \n
    \n {filtered.map(i =>
  • {i.label}
  • )}\n
\n
\n );\n}\n```\n\n```tsx\n// Feature.test.tsx (vitest + testing-library)\nimport { render, screen } from \"@testing-library/react\";\nimport userEvent from \"@testing-library/user-event\";\nimport { Feature } from \"./Feature\";\n\ntest(\"filters items\", async () => {\n const fetchItems = async () => [{ id:\"1\", label:\"Alpha\" }, { id:\"2\", label:\"Beta\" }];\n render();\n expect(await screen.findByText(\"Alpha\")).toBeInTheDocument();\n await userEvent.type(screen.getByLabelText(\"Search\"), \"be\");\n expect(screen.queryByText(\"Alpha\")).toBeNull();\n expect(screen.getByText(\"Beta\")).toBeInTheDocument();\n});\n```\n\n\nHard-mode checks: concurrency safety, idempotency, and rollback validated; add chaos tests where feasible.", "source": "WithinUsAI/GOD_Coder_100k"} {"text": "Optimize while preserving behavior and order.\n\n```python\ndef f93061(xs):\n out=[]\n for x in xs:\n if x not in out: out.append(x)\n return out\n```\nReturn `m84723.py` with types and O(n) average.\n\n```python\n# m84723.py\nfrom __future__ import annotations\nfrom typing import Iterable, List, Set, TypeVar\nT=TypeVar(\"T\")\n\ndef f93061(xs: Iterable[T]) -> List[T]:\n \"\"\"Unique items preserving first-seen order.\"\"\"\n seen: Set[T]=set()\n out: List[T]=[]\n for x in xs:\n if x in seen: continue\n seen.add(x); out.append(x)\n return out\n```", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Debug and fix a subtle production bug related to multi-tenant isolation in a customer support service.\nTarget platform: mobile (iOS Swift).\nRequirements: identify root cause, provide patch, and add regression tests.\nConstraints: must be observable (logs/metrics/traces), must include clear error handling, must be production-ready, must include tests.\nDifficulty: medium. Include rollback strategy.\n\nOutput: engineering-grade answer with edge cases covered.\nDeliverable: production-grade reference implementation (FastAPI) + tests.\n\n```python\n# app.py\nfrom __future__ import annotations\n\nimport hashlib\nimport json\nfrom dataclasses import dataclass\nfrom datetime import datetime, timezone\nfrom typing import Any, Optional\n\nfrom fastapi import FastAPI, Header, HTTPException\nfrom pydantic import BaseModel, Field\n\napp = FastAPI(title=\"Idempotent API\")\n\nclass CreateReq(BaseModel):\n tenant_id: str = Field(min_length=1)\n amount_cents: int = Field(ge=0)\n currency: str = Field(min_length=3, max_length=3)\n\nclass CreateResp(BaseModel):\n id: str\n created_at: str\n echo: CreateReq\n\n@dataclass\nclass _IdempoEntry:\n request_hash: str\n response_json: str\n\n# In production: Postgres table with UNIQUE(tenant_id, key)\n_IDEMPO: dict[tuple[str, str], _IdempoEntry] = {}\n\ndef _hash_req(req: CreateReq) -> str:\n raw = req.model_dump_json()\n return hashlib.sha256(raw.encode(\"utf-8\")).hexdigest()\n\n@app.post(\"/v1/payments\", response_model=CreateResp)\ndef create_payment(\n req: CreateReq,\n idempotency_key: Optional[str] = Header(default=None, alias=\"Idempotency-Key\"),\n) -> Any:\n if not idempotency_key:\n raise HTTPException(status_code=400, detail=\"Missing Idempotency-Key\")\n if len(idempotency_key) > 128:\n raise HTTPException(status_code=400, detail=\"Idempotency-Key too long\")\n\n key = (req.tenant_id, idempotency_key)\n rh = _hash_req(req)\n\n existing = _IDEMPO.get(key)\n if existing:\n if existing.request_hash != rh:\n raise HTTPException(status_code=409, detail=\"Idempotency-Key reuse with different payload\")\n return json.loads(existing.response_json)\n\n # Create new payment (stubbed)\n pid = hashlib.md5(f\"{req.tenant_id}:{idempotency_key}\".encode()).hexdigest()\n resp = CreateResp(\n id=pid,\n created_at=datetime.now(timezone.utc).isoformat(),\n echo=req,\n )\n _IDEMPO[key] = _IdempoEntry(request_hash=rh, response_json=resp.model_dump_json())\n return resp\n```\n\n```python\n# test_app.py (pytest)\nfrom fastapi.testclient import TestClient\nfrom app import app\n\nclient = TestClient(app)\n\ndef test_idempotent_replay():\n headers = {\"Idempotency-Key\": \"abc\"}\n body = {\"tenant_id\":\"t1\",\"amount_cents\":100,\"currency\":\"USD\"}\n r1 = client.post(\"/v1/payments\", json=body, headers=headers)\n r2 = client.post(\"/v1/payments\", json=body, headers=headers)\n assert r1.status_code == 200 and r2.status_code == 200\n assert r1.json() == r2.json()\n\ndef test_payload_conflict():\n headers = {\"Idempotency-Key\": \"abc\"}\n b1 = {\"tenant_id\":\"t1\",\"amount_cents\":100,\"currency\":\"USD\"}\n b2 = {\"tenant_id\":\"t1\",\"amount_cents\":200,\"currency\":\"USD\"}\n assert client.post(\"/v1/payments\", json=b1, headers=headers).status_code == 200\n assert client.post(\"/v1/payments\", json=b2, headers=headers).status_code == 409\n```\n\nNotes:\n- Replace in-memory store with a DB table and transaction.\n- Store response + request hash to detect key reuse with different payload.\n\n\nChecks: input validation, tests, and safe defaults included.", "source": "WithinUsAI/GOD_Coder_100k"} {"text": "Write a thorough test suite for a Python component used for telemetry ingestion.\nRequirements: cover edge cases, invalid inputs, and behavior invariants.\nConstraints: must avoid global state, must be streaming-friendly, must include tests, must handle Windows paths safely.\nDifficulty: medium. Avoid quadratic behavior on large inputs.\n\nDeliverable: implementation + tests.\n```python\n# tests (pytest-style) for a module providing: normalize(), parse_lines(), compute_stats()\nimport math\nimport pytest\n\ndef test_normalize_idempotent(module_under_test):\n x = \" A\\tB \"\n assert module_under_test.normalize(module_under_test.normalize(x)) == module_under_test.normalize(x)\n\ndef test_parse_lines_rejects_invalid(module_under_test):\n with pytest.raises(ValueError):\n module_under_test.parse_lines([\"\", \"???\", None]) # type: ignore[arg-type]\n\ndef test_compute_stats_basic(module_under_test):\n data = [1, 2, 3, 4]\n s = module_under_test.compute_stats(data)\n assert s.count == 4\n assert s.total == 10\n assert math.isclose(s.mean, 2.5)\n```", "source": "WithinUsAI/python_GOD_coder_100k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Refactor to modern typed Python with immutability and tests.\n\nFile: vffrrh55.py\n```python\nclass KipC80:\n def __init__(self, name, values):\n self.name = name\n self.values = list(values)\n def add(self, v):\n self.values.append(v)\n def mean(self):\n s = 0\n for x in self.values:\n s += x\n return s / len(self.values)\n```\n\nReturn full new vffrrh55.py and test_vffrrh55.py.\n\n# vffrrh55.py\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom typing import Iterable, Tuple\n\n@dataclass(frozen=True)\nclass KipC80:\n name: str\n values: Tuple[float, ...]\n\n @staticmethod\n def create(name: str, values: Iterable[float]) -> \"KipC80\":\n vals = tuple(float(v) for v in values)\n if not vals:\n raise ValueError(\"values must be non-empty\")\n return KipC80(name=name, values=vals)\n\n def add(self, v: float) -> \"KipC80\":\n return KipC80(name=self.name, values=self.values + (float(v),))\n\n def mean(self) -> float:\n return sum(self.values) / len(self.values)\n\n# test_vffrrh55.py\nimport pytest\nfrom vffrrh55 import KipC80\n\ndef test_mean_and_add():\n c = KipC80.create(\"a\", [1, 2, 3])\n assert c.mean() == 2.0\n assert c.add(5).mean() == (1 + 2 + 3 + 5) / 4\n\ndef test_empty_raises():\n with pytest.raises(ValueError):\n KipC80.create(\"x\", [])", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Build an elite-grade solution in the domain of realtime systems for scenario: document indexing.\nPrimary language: typescript.\nDifficulty: expert.\nConstraints: assume untrusted inputs; validate and sanitize, include invariants and failure modes, avoid undefined behavior and data races, make the interface contract explicit, design for backward compatibility and migrations.\nComponent: component_urhsqwz.\nAssume cold-start and memory limits are tight.\nTask: Provide SLOs, alerting, dashboards, runbooks, and incident playbook. Include chaos testing and safe rollout strategy.\n\nOutput: production blueprint plus correctness arguments and test strategy.\nOutput: SLOs + alerts + runbooks + chaos strategy.\n\n**SLOs**\n- Availability: 99.9% monthly\n- Latency: p95 < 200ms, p99 < 400ms\n- Error rate: < 0.1%\n\n**Alerts**\n- Burn-rate alerts for SLOs (fast/slow windows)\n- Saturation: CPU, memory, queue depth, DB connections\n- Dependency health: cache hit rate drop, downstream timeouts\n\n**Runbooks**\n- Triage: identify blast radius, feature-flag rollback, capacity mitigation\n- Post-incident: timeline, contributing factors, action items\n\n**Chaos**\n- Inject latency, partial outages, and restarts in staging; verify steady-state SLOs.\n\n\nExpert checks: state-machine reasoning, concurrency stress, and upgrade/rollback validated.", "source": "WithinUsAI/Elite_GOD_Coder_100k"} {"text": "Task type: supply_chain_security\nScenario: document indexing pipeline\nDomain focus: large-scale ML systems\nPrimary language: sql\nDifficulty: expert\nScale/SLO: 100k RPS peak\nComponent: component_flytlren\nConstraints: assume adversarial inputs; validate everything, include backward compatibility and migration plan, explicit contracts and invariants, include failure modes and recovery, include verification strategy, avoid data races and undefined behavior, include security threat model (defensive only)\nAssume strict auditability and replayable history.\nDeliverable: Design a supply-chain security plan: SBOM, signing, provenance, dependency policy, and CI gates.\n\nOutput: elite engineering answer optimized for correctness, performance, and operability.\n**Contract**\n- Inputs validated at the boundary; explicit error taxonomy.\n- Idempotency for side effects via request_id; deterministic replay.\n- Backward compatibility: additive changes by default; versioned breaking changes.\n**Invariants**\n- Liveness: under bounded faults and stable network, progress occurs.\n- Safety: state transitions preserve invariants; no partial commit leaks.\n- Determinism: replay of the same event log yields identical outputs.\n**Failure modes & recovery**\n- Crash during commit: WAL replay completes or transaction aborts; no torn writes.\n- Data corruption: checksums + scrubber; quarantine and rebuild from replicas/snapshots.\n- Duplicate requests: de-duplicate by (tenant, request_id) returning cached response.\n**Security posture (defensive)**\n- Threat model: auth/authz, injection, replay/abuse, supply chain.\n- Least privilege; secrets in managed store; audit logs for sensitive ops.\n- Input normalization, parameterized queries, path traversal protections.\n**Verification strategy**\n- Property tests against a pure reference model (state machine).\n- Canary + shadow traffic; invariants checked in production via assertions/metrics.\n- Deterministic simulation with fault injection (crash/partition/latency).\n\n**Snippet**\n```text\nImplementation sketch: factor pure state-machine core; adapters for I/O; add deterministic replay log.\n```\nExpert checks: state-machine proof sketch + model checking; upgrade/rollback rehearsed.", "source": "WithinUsAI/Omega_Genesis_Coder_100k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Refactor to modern typed Python with immutability and tests.\n\nFile: i8uxp4rfp.py\n```python\nclass Dugeowopcquz:\n def __init__(self, name, values):\n self.name = name\n self.values = list(values)\n def add(self, v):\n self.values.append(v)\n def mean(self):\n s = 0\n for x in self.values:\n s += x\n return s / len(self.values)\n```\n\nReturn full new i8uxp4rfp.py and test_i8uxp4rfp.py.\n\n# i8uxp4rfp.py\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom typing import Iterable, Tuple\n\n@dataclass(frozen=True)\nclass Dugeowopcquz:\n name: str\n values: Tuple[float, ...]\n\n @staticmethod\n def create(name: str, values: Iterable[float]) -> \"Dugeowopcquz\":\n vals = tuple(float(v) for v in values)\n if not vals:\n raise ValueError(\"values must be non-empty\")\n return Dugeowopcquz(name=name, values=vals)\n\n def add(self, v: float) -> \"Dugeowopcquz\":\n return Dugeowopcquz(name=self.name, values=self.values + (float(v),))\n\n def mean(self) -> float:\n return sum(self.values) / len(self.values)\n\n# test_i8uxp4rfp.py\nimport pytest\nfrom i8uxp4rfp import Dugeowopcquz\n\ndef test_mean_and_add():\n c = Dugeowopcquz.create(\"a\", [1, 2, 3])\n assert c.mean() == 2.0\n assert c.add(5).mean() == (1 + 2 + 3 + 5) / 4\n\ndef test_empty_raises():\n with pytest.raises(ValueError):\n Dugeowopcquz.create(\"x\", [])", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Design CI/CD for a document processing service delivering multi-tenant isolation.\nTarget platform: ML (scikit + batch).\nRequirements: pipelines, checks, artifact strategy, deployments, and rollbacks.\nConstraints: must be easy to extend, must include clear error handling, must be production-ready, must include tests.\nDifficulty: medium. Assume strict latency budget (p95 < 200ms).\n\nOutput: production-oriented blueprint with code where appropriate.\nDeliverable: CI/CD pipeline (GitHub Actions) with quality gates.\n\n```yaml\nname: ci\non:\n pull_request:\n push:\n branches: [main]\n\njobs:\n test:\n runs-on: ubuntu-latest\n steps:\n - uses: actions/checkout@v4\n - uses: actions/setup-python@v5\n with:\n python-version: \"3.11\"\n - run: python -m pip install -U pip\n - run: pip install -r requirements.txt\n - run: pip install -r requirements-dev.txt\n - run: ruff check .\n - run: mypy .\n - run: pytest -q --maxfail=1 --disable-warnings\n\n docker:\n needs: test\n runs-on: ubuntu-latest\n steps:\n - uses: actions/checkout@v4\n - uses: docker/setup-buildx-action@v3\n - run: docker build -t app:${{ github.sha }} .\n```\n\nDeployment strategy:\n- main → build → deploy to staging → smoke tests → canary to prod.\n- Rollback: redeploy previous image + DB migration rollback plan.\n\n\nChecks: input validation, tests, and safe defaults included.", "source": "WithinUsAI/GOD_Coder_100k"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: Language: SQL\nFramework/tooling: PostgreSQL\nDomain: artifact registry\nLogic challenge: websocket reconnect storm\nTask type: cross_stack_outage_fix\nDifficulty: expert\n\nReturn a rigorous engineering answer:\n- identify the hidden root cause or logical failure\n- present the corrected implementation\n- add tests that prove the fix\n- list verification commands\n- explain why naive fixes are insufficient when relevant\n\nRepository sketch:\nrepo/\n migrations/\n 001_init.sql\n 002_add_index.sql\n queries/\n report.sql\n tests/\n report_cases.md\n\nFocus: Focus on staff-level problem solving with multi-file patches, rollout implications, performance and security tradeoffs.\n\nassistant: Diagnosis:\n- Staff-level diagnosis: websocket reconnect storm impacts correctness, operability, and future maintenance, so the fix must be minimal where possible but complete where necessary.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```sql\nWITH ranked AS (\n SELECT\n user_id,\n created_at,\n amount,\n ROW_NUMBER() OVER (PARTITION BY user_id ORDER BY created_at DESC, id DESC) AS rn\n FROM orders\n)\nSELECT user_id, created_at, amount\nFROM ranked\nWHERE rn = 1;\n```\n\nTests:\n```sql\n-- Correctness checks:\n-- 1) multiple rows per user\n-- 2) identical timestamps require deterministic tie-breaker\n-- 3) null values handled by business rules\n```\n\nVerification:\n- `run migration checks`\n- `run query correctness cases`\n\nEngineering notes:\n- Language: SQL\n- Framework/tooling: PostgreSQL\n- Stack context: GitHub Actions, Docker Compose, Kubernetes, Terraform\n- Domain: artifact registry\n- Task type: cross_stack_outage_fix\n- Difficulty: expert\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: Language: Bash\nFramework/tooling: awk\nDomain: artifact registry\nLogic challenge: broken pagination cursor\nTask type: parser_validation_logic\nDifficulty: medium\n\nReturn a rigorous engineering answer:\n- identify the hidden root cause or logical failure\n- present the corrected implementation\n- add tests that prove the fix\n- list verification commands\n- explain why naive fixes are insufficient when relevant\n\nRepository sketch:\nrepo/\n scripts/\n run.sh\n deploy.sh\n tests/\n smoke.sh\n\nFocus: Focus on strong structured logic with edge cases, data validation, and concurrency safety.\n\nassistant: Diagnosis:\n- Root cause: the failure around broken pagination cursor is caused by missing validation, weak edge-case handling, or unsafe lifecycle behavior in the current implementation.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```bash\n#!/usr/bin/env bash\nset -euo pipefail\n\ninput=\"${1:-}\"\nif [[ -z \"$input\" ]]; then\n echo \"missing input\" >&2\n exit 1\nfi\n\nprintf '%s\n' \"$input\" | tr -d '\r'\n```\n\nTests:\n```bash\noutput=\"$(bash scripts/run.sh \"abc\")\"\ntest \"$output\" = \"abc\"\n```\n\nVerification:\n- `bash tests/smoke.sh`\n- `shellcheck scripts/*.sh`\n\nEngineering notes:\n- Language: Bash\n- Framework/tooling: awk\n- Stack context: ASP.NET Core, SQL Server, EF Core, xUnit, Docker\n- Domain: artifact registry\n- Task type: parser_validation_logic\n- Difficulty: medium\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: Language: JavaScript\nFramework/tooling: Jest\nDomain: team dashboard\nLogic challenge: dead-letter queue replay\nTask type: cross_stack_outage_fix\nDifficulty: hard\n\nReturn a rigorous engineering answer:\n- identify the hidden root cause or logical failure\n- present the corrected implementation\n- add tests that prove the fix\n- list verification commands\n- explain why naive fixes are insufficient when relevant\n\nRepository sketch:\nrepo/\n src/\n api.js\n service.js\n utils.js\n tests/\n api.test.js\n package.json\n\nFocus: Focus on staff-level problem solving with multi-file patches, rollout implications, performance and security tradeoffs.\n\nassistant: Diagnosis:\n- Staff-level diagnosis: dead-letter queue replay impacts correctness, operability, and future maintenance, so the fix must be minimal where possible but complete where necessary.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```javascript\ntype Payload = Record;\n\nexport function normalizePayload(payload: Payload): Payload {\n if (!payload || typeof payload !== \"object\" || Array.isArray(payload)) {\n throw new TypeError(\"payload must be a plain object\");\n }\n return Object.fromEntries(\n Object.entries(payload)\n .filter(([, value]) => value !== null && value !== undefined)\n .map(([key, value]) => [String(key).trim(), value])\n );\n}\n\nexport function handleDeadLetterQueueReplay(payload: Payload) {\n const clean = normalizePayload(payload);\n if (!(\"id\" in clean)) {\n return { ok: false, data: {}, error: \"missing id\" };\n }\n return { ok: true, data: clean, error: null };\n}\n```\n\nTests:\n```javascript\nimport { describe, it, expect } from \"vitest\";\nimport { handleDeadLetterQueueReplay } from \"../src/service\";\n\ndescribe(\"handler\", () => {\n it(\"accepts valid input\", () => {\n expect(handleDeadLetterQueueReplay({ id: 7, name: \"ok\", unused: null })).toEqual({\n ok: true,\n data: { id: 7, name: \"ok\" },\n error: null\n });\n });\n\n it(\"rejects missing id\", () => {\n expect(handleDeadLetterQueueReplay({ name: \"x\" }).error).toMatch(/missing id/);\n });\n});\n```\n\nVerification:\n- `npm test`\n- `npm run lint`\n\nEngineering notes:\n- Language: JavaScript\n- Framework/tooling: Jest\n- Stack context: Next.js, Node.js, Prisma, PostgreSQL, Playwright, Docker\n- Domain: team dashboard\n- Task type: cross_stack_outage_fix\n- Difficulty: hard\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "Refactor an existing codebase in gaming to support offline-first sync cleanly.\nTarget platform: infra (Docker + Kubernetes).\nRequirements: propose new modules/layers, dependency boundaries, and migration plan.\nConstraints: must avoid global state, must be observable (logs/metrics/traces), must include clear error handling, must be secure-by-default.\nDifficulty: medium. Include rollback strategy.\n\nOutput: production-oriented blueprint with code where appropriate.\nDeliverable: refactor plan + module boundaries.\n\n**Proposed modules**\n- `domain/` pure business logic (no I/O)\n- `adapters/` DB, cache, external APIs\n- `api/` request/response validation and routing\n- `observability/` logging/metrics/tracing\n- `tests/` unit + integration suites\n\n**Migration plan**\n1. Introduce new interfaces + adapters behind feature flags.\n2. Dual-write or read-compat layer if schema changes.\n3. Incremental cutover; deprecate legacy module.\n\nKey rule: dependencies flow inward; domain has no framework imports.\n\n\nChecks: input validation, tests, and safe defaults included.", "source": "WithinUsAI/GOD_Coder_100k"} {"text": "Build an elite-grade solution in the domain of sre/observability for scenario: inventory & ordering.\nPrimary language: go.\nDifficulty: hard.\nConstraints: include tests or verification strategy, design for backward compatibility and migrations, document performance characteristics.\nComponent: component_rguzlbe.\nAssume compliance requires data deletion with proofs.\nTask: Implement or outline a storage/indexing subsystem (LSM/B-Tree, WAL, snapshots). Include transaction/consistency considerations and benchmark plan.\n\nOutput: elite-grade engineering answer with contracts, edge cases, and verification.\nOutput: storage design + WAL + compaction + benchmarks.\n\n**Design**\n- WAL (append-only) for durability; fsync policy configurable.\n- Memtable (in-memory) → flush to immutable SSTables.\n- LSM compaction tiers; bloom filters per SSTable for point-lookups.\n- Manifest tracks SSTable set; atomic pointer swap on updates.\n\n**Correctness**\n- Crash recovery: replay WAL to rebuild memtable; manifest ensures last consistent set.\n- Reads: merge memtable + SSTables newest→oldest; tombstones override older values.\n\n**Bench plan**\n- Workloads: write-heavy, read-heavy, mixed; measure p50/p95 latency and write amplification.\n- Track compaction debt and space amplification.\n\n**Test plan**\n- Fuzz crash points: kill after WAL append / after manifest update; verify invariants on restart.\n\n\nHard checks: failure injection tests and performance regressions gated.", "source": "WithinUsAI/Elite_GOD_Coder_100k"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: Language: Go\nFramework/tooling: net/http\nDomain: team dashboard\nLogic challenge: partial checkpoint corruption\nTask type: security_logic_interaction\nDifficulty: hard\n\nReturn a rigorous engineering answer:\n- identify the hidden root cause or logical failure\n- present the corrected implementation\n- add tests that prove the fix\n- list verification commands\n- explain why naive fixes are insufficient when relevant\n\nRepository sketch:\nrepo/\n cmd/server/main.go\n internal/service/service.go\n internal/store/store.go\n internal/api/api.go\n service_test.go\n go.mod\n\nFocus: Focus on ambiguity, misleading symptoms, hidden root causes, and high-stakes debugging.\n\nassistant: Diagnosis:\n- Hidden root cause: partial checkpoint corruption presents misleading symptoms, so the patch must target the actual logic boundary rather than the first visible failure.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```go\npackage service\n\nimport \"fmt\"\n\nfunc NormalizePayload(payload map[string]any) map[string]any {\n\tout := make(map[string]any)\n\tfor k, v := range payload {\n\t\tif v == nil {\n\t\t\tcontinue\n\t\t}\n\t\tout[k] = v\n\t}\n\treturn out\n}\n\nfunc Handle(payload map[string]any) (map[string]any, error) {\n\tclean := NormalizePayload(payload)\n\tif _, ok := clean[\"id\"]; !ok {\n\t\treturn nil, fmt.Errorf(\"missing id\")\n\t}\n\treturn map[string]any{\"ok\": true, \"data\": clean}, nil\n}\n```\n\nTests:\n```go\npackage service\n\nimport \"testing\"\n\nfunc TestHandle(t *testing.T) {\n\tgot, err := Handle(map[string]any{\"id\": 7, \"name\": \"ok\", \"unused\": nil})\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tif got[\"ok\"] != true {\n\t\tt.Fatalf(\"expected ok=true\")\n\t}\n\tif _, err := Handle(map[string]any{\"name\": \"x\"}); err == nil {\n\t\tt.Fatalf(\"expected missing id error\")\n\t}\n}\n```\n\nVerification:\n- `go test ./...`\n- `go vet ./...`\n\nEngineering notes:\n- Language: Go\n- Framework/tooling: net/http\n- Stack context: Next.js, Node.js, Prisma, PostgreSQL, Playwright, Docker\n- Domain: team dashboard\n- Task type: security_logic_interaction\n- Difficulty: hard\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: Language: TypeScript\nFramework/tooling: React\nDomain: artifact registry\nLogic challenge: partial checkpoint corruption\nTask type: monorepo_toolchain_recovery\nDifficulty: expert\n\nReturn a rigorous engineering answer:\n- identify the hidden root cause or logical failure\n- present the corrected implementation\n- add tests that prove the fix\n- list verification commands\n- explain why naive fixes are insufficient when relevant\n\nRepository sketch:\nrepo/\n src/\n api.ts\n service.ts\n schema.ts\n tests/\n api.test.ts\n package.json\n\nFocus: Focus on staff-level problem solving with multi-file patches, rollout implications, performance and security tradeoffs.\n\nassistant: Diagnosis:\n- Staff-level diagnosis: partial checkpoint corruption impacts correctness, operability, and future maintenance, so the fix must be minimal where possible but complete where necessary.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```ts\ntype Payload = Record;\n\nexport function normalizePayload(payload: Payload): Payload {\n if (!payload || typeof payload !== \"object\" || Array.isArray(payload)) {\n throw new TypeError(\"payload must be a plain object\");\n }\n return Object.fromEntries(\n Object.entries(payload)\n .filter(([, value]) => value !== null && value !== undefined)\n .map(([key, value]) => [String(key).trim(), value])\n );\n}\n\nexport function handlePartialCheckpointCorruption(payload: Payload) {\n const clean = normalizePayload(payload);\n if (!(\"id\" in clean)) {\n return { ok: false, data: {}, error: \"missing id\" };\n }\n return { ok: true, data: clean, error: null };\n}\n```\n\nTests:\n```ts\nimport { describe, it, expect } from \"vitest\";\nimport { handlePartialCheckpointCorruption } from \"../src/service\";\n\ndescribe(\"handler\", () => {\n it(\"accepts valid input\", () => {\n expect(handlePartialCheckpointCorruption({ id: 7, name: \"ok\", unused: null })).toEqual({\n ok: true,\n data: { id: 7, name: \"ok\" },\n error: null\n });\n });\n\n it(\"rejects missing id\", () => {\n expect(handlePartialCheckpointCorruption({ name: \"x\" }).error).toMatch(/missing id/);\n });\n});\n```\n\nVerification:\n- `npm test`\n- `npm run typecheck`\n- `npm run lint`\n\nEngineering notes:\n- Language: TypeScript\n- Framework/tooling: React\n- Stack context: Spring Boot, PostgreSQL, JUnit, Gradle, Docker, GitHub Actions\n- Domain: artifact registry\n- Task type: monorepo_toolchain_recovery\n- Difficulty: expert\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "Build a data pipeline for a education product around role-based access control.\nTarget platform: data (SQL + Python).\nRequirements: schema, ingestion, validation, backfills, and tests.\nConstraints: must be easy to extend, must include tests, must be performant under load, must avoid global state, must be production-ready.\nDifficulty: hard. Assume mobile clients are occasionally offline.\n\nOutput: production-oriented blueprint with code where appropriate.\nDeliverable: schema + ingestion + validation + backfill strategy.\n\n**Schema (example)**\n- events(event_id TEXT PK, tenant_id TEXT, ts TIMESTAMP, type TEXT, payload JSONB)\n\n**Ingestion**\n- Write to raw table first; validate; then materialize to curated tables.\n- Idempotency by event_id; enforce uniqueness.\n\n**Validation**\n- Reject missing tenant_id/type/ts.\n- Quarantine bad records with reason.\n\n**Backfills**\n- Re-run deterministic transforms from raw → curated.\n- Version transformations; store transform_version with outputs.\n\n**Tests**\n- Unit tests for validators and transforms.\n- Integration test: sample raw batch produces expected curated rows.\n\n\nHard-mode checks: concurrency safety, idempotency, and rollback validated; add chaos tests where feasible.", "source": "WithinUsAI/GOD_Coder_100k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Fix a bug and add tests.\n\nFile: qpbisqjd.py\n```python\ndef g5b2v0gf(n: int) -> int:\n \"\"\"Sum 1..n inclusive.\"\"\"\n if n < 0:\n raise ValueError(\"n must be non-negative\")\n total = 0\n for k in range(n): # BUG: should include n\n total += k\n return total\n```\n\nReturn unified diffs for qpbisqjd.py and test_qpbisqjd.py (pytest).\n\n*** Begin Patch\n*** Update File: qpbisqjd.py\n@@\n def g5b2v0gf(n: int) -> int:\n@@\n total = 0\n- for k in range(n): # BUG: should include n\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_qpbisqjd.py\n+import pytest\n+from qpbisqjd import g5b2v0gf\n+\n+def test_zero():\n+ assert g5b2v0gf(0) == 0\n+\n+def test_one():\n+ assert g5b2v0gf(1) == 1\n+\n+def test_small():\n+ assert g5b2v0gf(7) == 28\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ g5b2v0gf(-1)\n+\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Fix a bug and add tests.\n\nFile: r30wk4.py\n```python\ndef br39ll8nknm(n: int) -> int:\n \"\"\"Sum 1..n inclusive.\"\"\"\n if n < 0:\n raise ValueError(\"n must be non-negative\")\n total = 0\n for k in range(n): # BUG: should include n\n total += k\n return total\n```\n\nReturn unified diffs for r30wk4.py and test_r30wk4.py (pytest).\n\n*** Begin Patch\n*** Update File: r30wk4.py\n@@\n def br39ll8nknm(n: int) -> int:\n@@\n total = 0\n- for k in range(n): # BUG: should include n\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_r30wk4.py\n+import pytest\n+from r30wk4 import br39ll8nknm\n+\n+def test_zero():\n+ assert br39ll8nknm(0) == 0\n+\n+def test_one():\n+ assert br39ll8nknm(1) == 1\n+\n+def test_small():\n+ assert br39ll8nknm(7) == 28\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ br39ll8nknm(-1)\n+\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Fix a bug and add tests.\n\nFile: eovmy1pf0.py\n```python\ndef tqdyfj6_g292(n: int) -> int:\n \"\"\"Sum 1..n inclusive.\"\"\"\n if n < 0:\n raise ValueError(\"n must be non-negative\")\n total = 0\n for k in range(n): # BUG: should include n\n total += k\n return total\n```\n\nReturn unified diffs for eovmy1pf0.py and test_eovmy1pf0.py (pytest).\n\n*** Begin Patch\n*** Update File: eovmy1pf0.py\n@@\n def tqdyfj6_g292(n: int) -> int:\n@@\n total = 0\n- for k in range(n): # BUG: should include n\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_eovmy1pf0.py\n+import pytest\n+from eovmy1pf0 import tqdyfj6_g292\n+\n+def test_zero():\n+ assert tqdyfj6_g292(0) == 0\n+\n+def test_one():\n+ assert tqdyfj6_g292(1) == 1\n+\n+def test_small():\n+ assert tqdyfj6_g292(7) == 28\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ tqdyfj6_g292(-1)\n+\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Task type: runtime_gc\nScenario: edge sync\nDomain focus: cryptography engineering (defensive)\nPrimary language: go\nDifficulty: hard\nScale/SLO: multi-region active-active\nComponent: component_grtjnrhs\nConstraints: include test vectors and fuzz strategy, include backward compatibility and migration plan, include failure modes and recovery, include verification strategy, assume adversarial inputs; validate everything, avoid data races and undefined behavior\nAssume weekly network partitions.\nDeliverable: Design a GC/runtime component (mark-sweep/arena/RC hybrid); include pause-time strategy and tests.\n\nOutput: rigorous design + invariants + verification plan + implementation sketch.\n**Contract**\n- Inputs validated at the boundary; explicit error taxonomy.\n- Idempotency for side effects via request_id; deterministic replay.\n- Backward compatibility: additive changes by default; versioned breaking changes.\n**Invariants**\n- Safety: state transitions preserve invariants; no partial commit leaks.\n- Determinism: replay of the same event log yields identical outputs.\n- Isolation: tenant boundary enforced; no cross-tenant reads/writes.\n**Failure modes & recovery**\n- Crash during commit: WAL replay completes or transaction aborts; no torn writes.\n- Duplicate requests: de-duplicate by (tenant, request_id) returning cached response.\n- Network partition: minority cannot commit; clients receive retriable errors.\n**Security posture (defensive)**\n- Threat model: auth/authz, injection, replay/abuse, supply chain.\n- Least privilege; secrets in managed store; audit logs for sensitive ops.\n- Input normalization, parameterized queries, path traversal protections.\n**Verification strategy**\n- Deterministic simulation with fault injection (crash/partition/latency).\n- Canary + shadow traffic; invariants checked in production via assertions/metrics.\n- Property tests against a pure reference model (state machine).\n\n**Snippet**\n```text\nImplementation sketch: factor pure state-machine core; adapters for I/O; add deterministic replay log.\n```\nHard checks: fault injection tests gate merges; perf thresholds enforced in CI.", "source": "WithinUsAI/Omega_Genesis_Coder_100k"} {"text": "Design CI/CD for a customer support service delivering offline-first sync.\nTarget platform: backend (Go).\nRequirements: pipelines, checks, artifact strategy, deployments, and rollbacks.\nConstraints: must avoid global state, must include type hints where applicable, must be observable (logs/metrics/traces), must be easy to extend.\nDifficulty: expert. Assume mobile clients are occasionally offline.\n\nOutput: actionable implementation and verification artifacts.\nDeliverable: CI/CD pipeline (GitHub Actions) with quality gates.\n\n```yaml\nname: ci\non:\n pull_request:\n push:\n branches: [main]\n\njobs:\n test:\n runs-on: ubuntu-latest\n steps:\n - uses: actions/checkout@v4\n - uses: actions/setup-python@v5\n with:\n python-version: \"3.11\"\n - run: python -m pip install -U pip\n - run: pip install -r requirements.txt\n - run: pip install -r requirements-dev.txt\n - run: ruff check .\n - run: mypy .\n - run: pytest -q --maxfail=1 --disable-warnings\n\n docker:\n needs: test\n runs-on: ubuntu-latest\n steps:\n - uses: actions/checkout@v4\n - uses: docker/setup-buildx-action@v3\n - run: docker build -t app:${{ github.sha }} .\n```\n\nDeployment strategy:\n- main → build → deploy to staging → smoke tests → canary to prod.\n- Rollback: redeploy previous image + DB migration rollback plan.\n\n\nHard-mode checks: concurrency safety, idempotency, and rollback validated; add chaos tests where feasible.", "source": "WithinUsAI/GOD_Coder_100k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Optimize while preserving behavior.\n\nFile: hw50w1x.py\n```python\ndef gn76h_c2o0fv(xs):\n out = []\n for x in xs:\n if x not in out:\n out.append(x)\n return out\n```\n\nRequirements: preserve first-seen order; O(n) average; add types + docstring.\n\n# hw50w1x.py\nfrom __future__ import annotations\nfrom typing import Iterable, List, Set, TypeVar\n\nT = TypeVar(\"T\")\n\ndef gn76h_c2o0fv(xs: Iterable[T]) -> List[T]:\n \"\"\"Return unique items preserving first-seen order.\"\"\"\n seen: Set[T] = set()\n out: List[T] = []\n for x in xs:\n if x in seen:\n continue\n seen.add(x)\n out.append(x)\n return out", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Build an elite-grade solution in the domain of databases for scenario: edge sync.\nPrimary language: rust.\nDifficulty: expert.\nConstraints: document performance characteristics, design for backward compatibility and migrations, provide rollout and rollback guidance.\nComponent: component_kbnrrbm.\nAssume 50k RPS and p99 < 250ms.\nTask: Implement a concurrency primitive or subsystem (lock-free queue, thread pool, async runtime component). Explain memory ordering and correctness arguments; include stress tests.\n\nOutput: rigorous solution with invariants, failure modes, and performance notes.\nOutput: correctness-focused concurrency primitive + stress tests.\n\n**Primitive**\n- Bounded MPMC queue with backpressure (blocking push/pop) OR lock-free SPSC ring buffer.\n\n**Correctness notes**\n- For lock-free: use acquire/release semantics on head/tail indices.\n- Avoid ABA by monotonic counters; ring index = counter % capacity.\n\n**Stress tests**\n- Multi-thread producers/consumers; assert item multiset preserved.\n- Use time-bounded randomized schedules; detect deadlocks.\n\n\nExpert checks: state-machine reasoning, concurrency stress, and upgrade/rollback validated.", "source": "WithinUsAI/Elite_GOD_Coder_100k"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: Language: YAML\nFramework/tooling: Helm\nDomain: document processing API\nLogic challenge: timezone bug in reporting\nTask type: misleading_symptom_debug\nDifficulty: hard\n\nReturn a rigorous engineering answer:\n- identify the hidden root cause or logical failure\n- present the corrected implementation\n- add tests that prove the fix\n- list verification commands\n- explain why naive fixes are insufficient when relevant\n\nRepository sketch:\nrepo/\n .github/workflows/ci.yml\n docker-compose.yml\n deploy/\n app.yaml\n\nFocus: Focus on ambiguity, misleading symptoms, hidden root causes, and high-stakes debugging.\n\nassistant: Diagnosis:\n- Hidden root cause: timezone bug in reporting presents misleading symptoms, so the patch must target the actual logic boundary rather than the first visible failure.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```yaml\nname: ci\non: [push, pull_request]\njobs:\n test:\n runs-on: ubuntu-latest\n steps:\n - uses: actions/checkout@v4\n - name: Validate\n run: echo \"validated\"\n```\n\nTests:\n```yaml\n# Verification:\n# - validate syntax\n# - run smoke workflow\n# - fail fast on broken config\n```\n\nVerification:\n- `validate workflow syntax`\n- `run CI smoke job`\n\nEngineering notes:\n- Language: YAML\n- Framework/tooling: Helm\n- Stack context: ASP.NET Core, SQL Server, EF Core, xUnit, Docker\n- Domain: document processing API\n- Task type: misleading_symptom_debug\n- Difficulty: hard\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "Add a clear docstring and type hints to this function:\n\n```python\ndef f10667(s):\n return ''.join(x for x in s if x.isalnum()).lower()\n```\n\n```python\nfrom __future__ import annotations\n\ndef f10667(s: str) -> str:\n \"\"\"Normalize a string: keep only alphanumerics and lowercase the result.\"\"\"\n return \"\".join(ch for ch in s if ch.isalnum()).lower()\n```", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Implement a mobile feature for gaming: file uploads.\nTarget platform: mobile.\nRequirements: offline-safe behavior, UI state handling, and tests.\nConstraints: must include documentation/comments, must be easy to extend, must avoid global state.\nDifficulty: expert. Include rollback strategy.\n\nOutput: design + implementation guidance suitable for shipping.\nDeliverable: offline-safe mobile approach (Kotlin) + key snippets.\n\n```kotlin\n// Repository.kt\ninterface Api {\n suspend fun fetch(): List\n suspend fun post(item: Item): Item\n}\n\ninterface LocalStore {\n suspend fun getAll(): List\n suspend fun upsert(items: List)\n suspend fun enqueuePending(item: Item)\n suspend fun pending(): List\n suspend fun markSent(id: String)\n}\n\nclass Repo(private val api: Api, private val db: LocalStore) {\n suspend fun sync(): List {\n val local = db.getAll()\n // optimistic: show local first, then refresh\n return try {\n val remote = api.fetch()\n db.upsert(remote)\n flushPending()\n remote\n } catch (e: Exception) {\n local\n }\n }\n\n suspend fun createOfflineFirst(item: Item): Item {\n db.enqueuePending(item)\n return item\n }\n\n private suspend fun flushPending() {\n for (p in db.pending()) {\n try {\n api.post(p)\n db.markSent(p.id)\n } catch (_: Exception) {\n // keep pending; retry later with backoff in a WorkManager job\n }\n }\n }\n}\n```\n\nTesting guidance:\n- Unit test Repo with fake Api/LocalStore.\n- Integration test offline queue + retry policy (WorkManager).\n\n\nHard-mode checks: concurrency safety, idempotency, and rollback validated; add chaos tests where feasible.", "source": "WithinUsAI/GOD_Coder_100k"} {"text": "Task type: distributed_algorithm\nScenario: feature-flag evaluation\nDomain focus: large-scale ML systems\nPrimary language: sql\nDifficulty: expert\nScale/SLO: 10k RPS peak\nComponent: component_ehgxbjlj\nConstraints: include verification strategy, include deterministic replay plan, include failure modes and recovery, avoid data races and undefined behavior, assume adversarial inputs; validate everything, explicit contracts and invariants, include performance model and limits\nAssume partial data corruption; include scrubbing strategy.\nDeliverable: Design an algorithm with message flows and correctness arguments (safety + liveness). Include failure handling and a minimal reference implementation skeleton.\n\nOutput: elite engineering answer optimized for correctness, performance, and operability.\n**Contract**\n- Inputs validated at the boundary; explicit error taxonomy.\n- Idempotency for side effects via request_id; deterministic replay.\n- Backward compatibility: additive changes by default; versioned breaking changes.\n**Invariants**\n- Isolation: tenant boundary enforced; no cross-tenant reads/writes.\n- Liveness: under bounded faults and stable network, progress occurs.\n- Safety: state transitions preserve invariants; no partial commit leaks.\n**Failure modes & recovery**\n- Duplicate requests: de-duplicate by (tenant, request_id) returning cached response.\n- Data corruption: checksums + scrubber; quarantine and rebuild from replicas/snapshots.\n- Network partition: minority cannot commit; clients receive retriable errors.\n**Security posture (defensive)**\n- Threat model: auth/authz, injection, replay/abuse, supply chain.\n- Least privilege; secrets in managed store; audit logs for sensitive ops.\n- Input normalization, parameterized queries, path traversal protections.\n**Verification strategy**\n- Fuzzing of parsers/framers/validators with corpus seeds.\n- Property tests against a pure reference model (state machine).\n- Deterministic simulation with fault injection (crash/partition/latency).\n\n**Snippet**\n```text\nImplementation sketch: factor pure state-machine core; adapters for I/O; add deterministic replay log.\n```\nExpert checks: state-machine proof sketch + model checking; upgrade/rollback rehearsed.", "source": "WithinUsAI/Omega_Genesis_Coder_100k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Fix a bug and add tests.\n\nFile: bdm45dg.py\n```python\ndef o0kp34uat(n: int) -> int:\n \"\"\"Sum 1..n inclusive.\"\"\"\n if n < 0:\n raise ValueError(\"n must be non-negative\")\n total = 0\n for k in range(n): # BUG: should include n\n total += k\n return total\n```\n\nReturn unified diffs for bdm45dg.py and test_bdm45dg.py (pytest).\n\n*** Begin Patch\n*** Update File: bdm45dg.py\n@@\n def o0kp34uat(n: int) -> int:\n@@\n total = 0\n- for k in range(n): # BUG: should include n\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_bdm45dg.py\n+import pytest\n+from bdm45dg import o0kp34uat\n+\n+def test_zero():\n+ assert o0kp34uat(0) == 0\n+\n+def test_one():\n+ assert o0kp34uat(1) == 1\n+\n+def test_small():\n+ assert o0kp34uat(7) == 28\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ o0kp34uat(-1)\n+\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Write pytest tests for `f03952`.\n\n```python\ndef f03952(a: int, b: int) -> int:\n return a*a + b*b\n```\nInclude edge cases and a property-style check.\n\n```python\nimport random\nfrom m29136 import f03952\n\ndef test_known():\n assert f03952(3,4) == 25\n\ndef test_zero():\n assert f03952(0,0) == 0\n\ndef test_property_nonnegative():\n for _ in range(200):\n a=random.randint(-50,50)\n b=random.randint(-50,50)\n assert f03952(a,b) >= 0\n```", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Produce an offline-first self-evolving code assistant architecture named `mfk4kpv6if`.\nMust include: module layout, patch-safety policy, evaluation gates (tests/lint/types), versioned memory index.\n\nArchitecture: `mfk4kpv6if` (offline-first, self-evolving)\n\nModules\n- core/loop.py: evolve → validate → accept/reject (bounded iterations)\n- patching/: diff builder, safe apply, atomic writes, rollback points\n- policy/: allowlist paths, deny globs (.git/, __pycache__/, binaries), patch size caps\n- signals/: parse pytest/ruff/mypy into normalized findings\n- memory/index.jsonl: append-only snapshots (hashes, metrics, rationale)\n\nSafety gates\n- refuse path traversal/symlink escapes; never edit binaries\n- accept only if tests/lint/types stay green or improve", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Implement an ML engineering workflow for content moderation focusing on analytics pipeline.\nTarget platform: ML (training + serving).\nRequirements: data contract, training loop, evaluation, model registry, serving API, monitoring.\nConstraints: must be production-ready, must include tests, must be performant under load.\nDifficulty: expert. Assume strict latency budget (p95 < 200ms).\n\nOutput: actionable implementation and verification artifacts.\nDeliverable: ML engineering blueprint (training + serving + monitoring), safe and production-oriented.\n\n**Data contract**\n- Define feature schema + ranges; validate at training and serving.\n\n**Training**\n- Deterministic split; baseline model; track metrics (AUC/F1/latency).\n- Store artifacts: model, config, feature stats.\n\n**Registry**\n- Promote models via approval gates; record lineage.\n\n**Serving**\n- Separate inference service with `/predict`.\n- Input validation + default handling; timeouts.\n\n**Monitoring**\n- Data drift: feature distribution checks.\n- Performance: online metrics + periodic labels; alert on regression.\n\nMinimal serving skeleton (FastAPI-ish):\n```python\n# validate input -> vectorize -> model.predict_proba -> return\n```\n\n\nHard-mode checks: concurrency safety, idempotency, and rollback validated; add chaos tests where feasible.", "source": "WithinUsAI/GOD_Coder_100k"} {"text": "Build an elite-grade solution in the domain of databases for scenario: multi-tenant SaaS.\nPrimary language: python.\nDifficulty: medium.\nConstraints: design for backward compatibility and migrations, avoid undefined behavior and data races, provide rollout and rollback guidance, include invariants and failure modes.\nComponent: component_fhmuldc.\nAssume cold-start and memory limits are tight.\nTask: Design a replication/consistency approach (e.g., leader-based, quorum reads/writes). Provide message flows, failure handling, and a minimal reference implementation skeleton.\n\nOutput: rigorous solution with invariants, failure modes, and performance notes.\nOutput: replication design + failure handling + minimal skeleton.\n\n**Model**\n- Leader-based replication with term + log index.\n- Quorum acks for durability: write committed when majority acks.\n- Read options: leader-read (linearizable) or quorum-read (monotonic if using read-index).\n\n**Message flow (write)**\n1. Client → Leader: Put(request_id, payload)\n2. Leader appends to log, sends AppendEntries to followers\n3. Followers append + ack\n4. On majority ack: commit index advances; apply to state machine; respond to client\n\n**Failure modes**\n- Leader crash: new election; uncommitted entries may be rolled back.\n- Partition: minority side cannot commit.\n- Duplicate requests: deduplicate by request_id stored in state.\n\n**Skeleton (Go pseudo)**\n```go\ntype Entry struct { Term uint64; Index uint64; Cmd []byte }\ntype Node struct {\n id int\n term uint64\n log []Entry\n commit uint64\n seen map[string][]byte // request_id -> response\n}\n```\n\n**Verification**\n- Invariant: committed index never decreases.\n- Property: if a write is committed, all future leaders contain it.\n- Test with simulated partitions and crash/restart.\n\n\nChecks: boundary validation and deterministic behavior verified.", "source": "WithinUsAI/Elite_GOD_Coder_100k"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: Project domain: document processing API\nImplementation stack: Spring Boot, PostgreSQL, JUnit, Gradle, Docker, GitHub Actions\nSoftware delivery problem: idempotent retry design\nTask type: prd_to_patch\nDifficulty: hard\n\nReturn a complete delivery-grade response with:\n- diagnosis or design reasoning\n- implementation\n- test plan or tests\n- rollout plan\n- rollback or compatibility note\n- verification commands\n\nRepository sketch:\nrepo/\n cmd/server/main.go\n internal/service/service.go\n internal/store/store.go\n internal/api/api.go\n service_test.go\n go.mod\n\nFocus: Focus on shipping production software with rollout safety, acceptance criteria, telemetry, and maintenance quality.\n\nassistant: Diagnosis:\n- Root cause or delivery blocker: idempotent retry design needs both implementation work and a safe shipping plan.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```go\npackage service\n\nimport \"fmt\"\n\nfunc NormalizePayload(payload map[string]any) map[string]any {\n\tout := make(map[string]any)\n\tfor k, v := range payload {\n\t\tif v == nil {\n\t\t\tcontinue\n\t\t}\n\t\tout[k] = v\n\t}\n\treturn out\n}\n\nfunc Handle(payload map[string]any) (map[string]any, error) {\n\tclean := NormalizePayload(payload)\n\tif _, ok := clean[\"id\"]; !ok {\n\t\treturn nil, fmt.Errorf(\"missing id\")\n\t}\n\treturn map[string]any{\"ok\": true, \"data\": clean}, nil\n}\n```\n\nTests:\n```go\npackage service\n\nimport \"testing\"\n\nfunc TestHandle(t *testing.T) {\n\tgot, err := Handle(map[string]any{\"id\": 7, \"name\": \"ok\", \"unused\": nil})\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tif got[\"ok\"] != true {\n\t\tt.Fatalf(\"expected ok=true\")\n\t}\n\tif _, err := Handle(map[string]any{\"name\": \"x\"}); err == nil {\n\t\tt.Fatalf(\"expected missing id error\")\n\t}\n}\n```\n\nVerification:\n- `go test ./...`\n- `go vet ./...`\n\nEngineering notes:\n- Language: Go\n- Framework/tooling: testify\n- Stack context: Spring Boot, PostgreSQL, JUnit, Gradle, Docker, GitHub Actions\n- Domain: document processing API\n- Task type: prd_to_patch\n- Difficulty: hard\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: Language: C++\nFramework/tooling: Catch2\nDomain: payments platform\nLogic challenge: invalid rollback sequence\nTask type: transaction_integrity_fix\nDifficulty: hard\n\nReturn a rigorous engineering answer:\n- identify the hidden root cause or logical failure\n- present the corrected implementation\n- add tests that prove the fix\n- list verification commands\n- explain why naive fixes are insufficient when relevant\n\nRepository sketch:\nrepo/\n src/main.cpp\n src/service.cpp\n include/service.h\n tests/test_service.cpp\n CMakeLists.txt\n\nFocus: Focus on ambiguity, misleading symptoms, hidden root causes, and high-stakes debugging.\n\nassistant: Diagnosis:\n- Hidden root cause: invalid rollback sequence presents misleading symptoms, so the patch must target the actual logic boundary rather than the first visible failure.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```cpp\n#include \n#include \n\nusing Payload = std::unordered_map;\n\nPayload normalize_payload(const Payload& in) {\n Payload out;\n for (const auto& [k, v] : in) {\n if (!v.empty()) out[k] = v;\n }\n return out;\n}\n```\n\nTests:\n```cpp\nTEST_CASE(\"normalize_payload filters empty values\") {\n Payload in{{\"id\",\"7\"},{\"name\",\"\"}};\n auto out = normalize_payload(in);\n REQUIRE(out.count(\"id\") == 1);\n REQUIRE(out.count(\"name\") == 0);\n}\n```\n\nVerification:\n- `cmake --build build`\n- `ctest --test-dir build`\n\nEngineering notes:\n- Language: C++\n- Framework/tooling: Catch2\n- Stack context: GitHub Actions, Docker Compose, Kubernetes, Terraform\n- Domain: payments platform\n- Task type: transaction_integrity_fix\n- Difficulty: hard\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: Language: JavaScript\nFramework/tooling: Playwright\nDomain: job scheduler\nLogic challenge: timezone bug in reporting\nTask type: performance_bottleneck_patch\nDifficulty: hard\n\nReturn a rigorous engineering answer:\n- identify the hidden root cause or logical failure\n- present the corrected implementation\n- add tests that prove the fix\n- list verification commands\n- explain why naive fixes are insufficient when relevant\n\nRepository sketch:\nrepo/\n src/\n api.js\n service.js\n utils.js\n tests/\n api.test.js\n package.json\n\nFocus: Focus on ambiguity, misleading symptoms, hidden root causes, and high-stakes debugging.\n\nassistant: Diagnosis:\n- Hidden root cause: timezone bug in reporting presents misleading symptoms, so the patch must target the actual logic boundary rather than the first visible failure.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```javascript\ntype Payload = Record;\n\nexport function normalizePayload(payload: Payload): Payload {\n if (!payload || typeof payload !== \"object\" || Array.isArray(payload)) {\n throw new TypeError(\"payload must be a plain object\");\n }\n return Object.fromEntries(\n Object.entries(payload)\n .filter(([, value]) => value !== null && value !== undefined)\n .map(([key, value]) => [String(key).trim(), value])\n );\n}\n\nexport function handleTimezoneBugInReporting(payload: Payload) {\n const clean = normalizePayload(payload);\n if (!(\"id\" in clean)) {\n return { ok: false, data: {}, error: \"missing id\" };\n }\n return { ok: true, data: clean, error: null };\n}\n```\n\nTests:\n```javascript\nimport { describe, it, expect } from \"vitest\";\nimport { handleTimezoneBugInReporting } from \"../src/service\";\n\ndescribe(\"handler\", () => {\n it(\"accepts valid input\", () => {\n expect(handleTimezoneBugInReporting({ id: 7, name: \"ok\", unused: null })).toEqual({\n ok: true,\n data: { id: 7, name: \"ok\" },\n error: null\n });\n });\n\n it(\"rejects missing id\", () => {\n expect(handleTimezoneBugInReporting({ name: \"x\" }).error).toMatch(/missing id/);\n });\n});\n```\n\nVerification:\n- `npm test`\n- `npm run lint`\n\nEngineering notes:\n- Language: JavaScript\n- Framework/tooling: Playwright\n- Stack context: FastAPI, PostgreSQL, Redis, Celery, pytest, Docker\n- Domain: job scheduler\n- Task type: performance_bottleneck_patch\n- Difficulty: hard\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Fix a bug and add tests.\n\nFile: jix61_8y7z.py\n```python\ndef y5jcoikt8l(n: int) -> int:\n \"\"\"Sum 1..n inclusive.\"\"\"\n if n < 0:\n raise ValueError(\"n must be non-negative\")\n total = 0\n for k in range(n): # BUG: should include n\n total += k\n return total\n```\n\nReturn unified diffs for jix61_8y7z.py and test_jix61_8y7z.py (pytest).\n\n*** Begin Patch\n*** Update File: jix61_8y7z.py\n@@\n def y5jcoikt8l(n: int) -> int:\n@@\n total = 0\n- for k in range(n): # BUG: should include n\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_jix61_8y7z.py\n+import pytest\n+from jix61_8y7z import y5jcoikt8l\n+\n+def test_zero():\n+ assert y5jcoikt8l(0) == 0\n+\n+def test_one():\n+ assert y5jcoikt8l(1) == 1\n+\n+def test_small():\n+ assert y5jcoikt8l(7) == 28\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ y5jcoikt8l(-1)\n+\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Implement a mobile feature for document processing: webhooks.\nTarget platform: mobile.\nRequirements: offline-safe behavior, UI state handling, and tests.\nConstraints: must include tests, must include clear error handling, must be performant under load, must be production-ready, must include type hints where applicable.\nDifficulty: easy. Include rollback strategy.\n\nOutput: engineering-grade answer with edge cases covered.\nDeliverable: offline-safe mobile approach (Kotlin) + key snippets.\n\n```kotlin\n// Repository.kt\ninterface Api {\n suspend fun fetch(): List\n suspend fun post(item: Item): Item\n}\n\ninterface LocalStore {\n suspend fun getAll(): List\n suspend fun upsert(items: List)\n suspend fun enqueuePending(item: Item)\n suspend fun pending(): List\n suspend fun markSent(id: String)\n}\n\nclass Repo(private val api: Api, private val db: LocalStore) {\n suspend fun sync(): List {\n val local = db.getAll()\n // optimistic: show local first, then refresh\n return try {\n val remote = api.fetch()\n db.upsert(remote)\n flushPending()\n remote\n } catch (e: Exception) {\n local\n }\n }\n\n suspend fun createOfflineFirst(item: Item): Item {\n db.enqueuePending(item)\n return item\n }\n\n private suspend fun flushPending() {\n for (p in db.pending()) {\n try {\n api.post(p)\n db.markSent(p.id)\n } catch (_: Exception) {\n // keep pending; retry later with backoff in a WorkManager job\n }\n }\n }\n}\n```\n\nTesting guidance:\n- Unit test Repo with fake Api/LocalStore.\n- Integration test offline queue + retry policy (WorkManager).\n\n\nChecks: input validation, tests, and safe defaults included.", "source": "WithinUsAI/GOD_Coder_100k"} {"text": "Debug and fix a subtle production bug related to A/B experimentation in a fintech service.\nTarget platform: infra (Docker + Kubernetes).\nRequirements: identify root cause, provide patch, and add regression tests.\nConstraints: must be easy to extend, must include tests, must be observable (logs/metrics/traces), must include clear error handling.\nDifficulty: medium. Assume untrusted input; validate everything.\n\nOutput: actionable implementation and verification artifacts.\nDeliverable: production-grade reference implementation (FastAPI) + tests.\n\n```python\n# app.py\nfrom __future__ import annotations\n\nimport hashlib\nimport json\nfrom dataclasses import dataclass\nfrom datetime import datetime, timezone\nfrom typing import Any, Optional\n\nfrom fastapi import FastAPI, Header, HTTPException\nfrom pydantic import BaseModel, Field\n\napp = FastAPI(title=\"Idempotent API\")\n\nclass CreateReq(BaseModel):\n tenant_id: str = Field(min_length=1)\n amount_cents: int = Field(ge=0)\n currency: str = Field(min_length=3, max_length=3)\n\nclass CreateResp(BaseModel):\n id: str\n created_at: str\n echo: CreateReq\n\n@dataclass\nclass _IdempoEntry:\n request_hash: str\n response_json: str\n\n# In production: Postgres table with UNIQUE(tenant_id, key)\n_IDEMPO: dict[tuple[str, str], _IdempoEntry] = {}\n\ndef _hash_req(req: CreateReq) -> str:\n raw = req.model_dump_json()\n return hashlib.sha256(raw.encode(\"utf-8\")).hexdigest()\n\n@app.post(\"/v1/payments\", response_model=CreateResp)\ndef create_payment(\n req: CreateReq,\n idempotency_key: Optional[str] = Header(default=None, alias=\"Idempotency-Key\"),\n) -> Any:\n if not idempotency_key:\n raise HTTPException(status_code=400, detail=\"Missing Idempotency-Key\")\n if len(idempotency_key) > 128:\n raise HTTPException(status_code=400, detail=\"Idempotency-Key too long\")\n\n key = (req.tenant_id, idempotency_key)\n rh = _hash_req(req)\n\n existing = _IDEMPO.get(key)\n if existing:\n if existing.request_hash != rh:\n raise HTTPException(status_code=409, detail=\"Idempotency-Key reuse with different payload\")\n return json.loads(existing.response_json)\n\n # Create new payment (stubbed)\n pid = hashlib.md5(f\"{req.tenant_id}:{idempotency_key}\".encode()).hexdigest()\n resp = CreateResp(\n id=pid,\n created_at=datetime.now(timezone.utc).isoformat(),\n echo=req,\n )\n _IDEMPO[key] = _IdempoEntry(request_hash=rh, response_json=resp.model_dump_json())\n return resp\n```\n\n```python\n# test_app.py (pytest)\nfrom fastapi.testclient import TestClient\nfrom app import app\n\nclient = TestClient(app)\n\ndef test_idempotent_replay():\n headers = {\"Idempotency-Key\": \"abc\"}\n body = {\"tenant_id\":\"t1\",\"amount_cents\":100,\"currency\":\"USD\"}\n r1 = client.post(\"/v1/payments\", json=body, headers=headers)\n r2 = client.post(\"/v1/payments\", json=body, headers=headers)\n assert r1.status_code == 200 and r2.status_code == 200\n assert r1.json() == r2.json()\n\ndef test_payload_conflict():\n headers = {\"Idempotency-Key\": \"abc\"}\n b1 = {\"tenant_id\":\"t1\",\"amount_cents\":100,\"currency\":\"USD\"}\n b2 = {\"tenant_id\":\"t1\",\"amount_cents\":200,\"currency\":\"USD\"}\n assert client.post(\"/v1/payments\", json=b1, headers=headers).status_code == 200\n assert client.post(\"/v1/payments\", json=b2, headers=headers).status_code == 409\n```\n\nNotes:\n- Replace in-memory store with a DB table and transaction.\n- Store response + request hash to detect key reuse with different payload.\n\n\nChecks: input validation, tests, and safe defaults included.", "source": "WithinUsAI/GOD_Coder_100k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Fix a bug and add tests.\n\nFile: syi2vb98j.py\n```python\ndef uh8hz7dkb(n: int) -> int:\n \"\"\"Sum 1..n inclusive.\"\"\"\n if n < 0:\n raise ValueError(\"n must be non-negative\")\n total = 0\n for k in range(n): # BUG: should include n\n total += k\n return total\n```\n\nReturn unified diffs for syi2vb98j.py and test_syi2vb98j.py (pytest).\n\n*** Begin Patch\n*** Update File: syi2vb98j.py\n@@\n def uh8hz7dkb(n: int) -> int:\n@@\n total = 0\n- for k in range(n): # BUG: should include n\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_syi2vb98j.py\n+import pytest\n+from syi2vb98j import uh8hz7dkb\n+\n+def test_zero():\n+ assert uh8hz7dkb(0) == 0\n+\n+def test_one():\n+ assert uh8hz7dkb(1) == 1\n+\n+def test_small():\n+ assert uh8hz7dkb(7) == 28\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ uh8hz7dkb(-1)\n+\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Write a thorough test suite for a Python component used for task scheduling.\nRequirements: cover edge cases, invalid inputs, and behavior invariants.\nConstraints: must provide clear error messages, must include tests.\nDifficulty: expert. Provide helpful exceptions with actionable messages.\n\nDeliverable: API + reference implementation + tests.\n```python\n# tests (pytest-style) for a module providing: normalize(), parse_lines(), compute_stats()\nimport math\nimport pytest\n\ndef test_normalize_idempotent(module_under_test):\n x = \" A\\tB \"\n assert module_under_test.normalize(module_under_test.normalize(x)) == module_under_test.normalize(x)\n\ndef test_parse_lines_rejects_invalid(module_under_test):\n with pytest.raises(ValueError):\n module_under_test.parse_lines([\"\", \"???\", None]) # type: ignore[arg-type]\n\ndef test_compute_stats_basic(module_under_test):\n data = [1, 2, 3, 4]\n s = module_under_test.compute_stats(data)\n assert s.count == 4\n assert s.total == 10\n assert math.isclose(s.mean, 2.5)\n```", "source": "WithinUsAI/python_GOD_coder_100k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Refactor to modern typed Python with immutability and tests.\n\nFile: hvrnkxk3nv5r.py\n```python\nclass Ewso4Gy:\n def __init__(self, name, values):\n self.name = name\n self.values = list(values)\n def add(self, v):\n self.values.append(v)\n def mean(self):\n s = 0\n for x in self.values:\n s += x\n return s / len(self.values)\n```\n\nReturn full new hvrnkxk3nv5r.py and test_hvrnkxk3nv5r.py.\n\n# hvrnkxk3nv5r.py\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom typing import Iterable, Tuple\n\n@dataclass(frozen=True)\nclass Ewso4Gy:\n name: str\n values: Tuple[float, ...]\n\n @staticmethod\n def create(name: str, values: Iterable[float]) -> \"Ewso4Gy\":\n vals = tuple(float(v) for v in values)\n if not vals:\n raise ValueError(\"values must be non-empty\")\n return Ewso4Gy(name=name, values=vals)\n\n def add(self, v: float) -> \"Ewso4Gy\":\n return Ewso4Gy(name=self.name, values=self.values + (float(v),))\n\n def mean(self) -> float:\n return sum(self.values) / len(self.values)\n\n# test_hvrnkxk3nv5r.py\nimport pytest\nfrom hvrnkxk3nv5r import Ewso4Gy\n\ndef test_mean_and_add():\n c = Ewso4Gy.create(\"a\", [1, 2, 3])\n assert c.mean() == 2.0\n assert c.add(5).mean() == (1 + 2 + 3 + 5) / 4\n\ndef test_empty_raises():\n with pytest.raises(ValueError):\n Ewso4Gy.create(\"x\", [])", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Optimize while preserving behavior and order.\n\n```python\ndef f69546(xs):\n out=[]\n for x in xs:\n if x not in out: out.append(x)\n return out\n```\nReturn `m67078.py` with types and O(n) average.\n\n```python\n# m67078.py\nfrom __future__ import annotations\nfrom typing import Iterable, List, Set, TypeVar\nT=TypeVar(\"T\")\n\ndef f69546(xs: Iterable[T]) -> List[T]:\n \"\"\"Unique items preserving first-seen order.\"\"\"\n seen: Set[T]=set()\n out: List[T]=[]\n for x in xs:\n if x in seen: continue\n seen.add(x); out.append(x)\n return out\n```", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Design a small, production-grade Python API for CLI tooling.\nRequirements: define data models and interfaces, implement reference version, include tests.\nConstraints: must avoid global state, must provide clear error messages.\nDifficulty: hard. Support both Windows and POSIX paths correctly.\n\nDeliverable: production-ready reference solution.\nArchitecture:\n- Public facade class coordinating concerns (parsing, validation, persistence)\n- Small pure functions for testability\n- No global state; dependency injection for filesystem I/O\n\n```python\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom pathlib import Path\nfrom typing import Protocol, Iterable\nimport json\n\nclass Store(Protocol):\n def write_text(self, path: Path, data: str) -> None: ...\n\nclass FSStore:\n def write_text(self, path: Path, data: str) -> None:\n path.parent.mkdir(parents=True, exist_ok=True)\n path.write_text(data, encoding=\"utf-8\")\n\n@dataclass(frozen=True, slots=True)\nclass Item:\n name: str\n qty: int\n\ndef parse_items(lines: Iterable[str]) -> list[Item]:\n out: list[Item] = []\n for i, line in enumerate(lines, 1):\n s = line.strip()\n if not s:\n continue\n obj = json.loads(s)\n if not isinstance(obj, dict):\n raise ValueError(f\"line {i}: expected object\")\n name = obj.get(\"name\")\n qty = obj.get(\"qty\")\n if not isinstance(name, str) or not name:\n raise ValueError(f\"line {i}: name must be str\")\n if not isinstance(qty, int) or qty < 0:\n raise ValueError(f\"line {i}: qty must be non-negative int\")\n out.append(Item(name, qty))\n return out\n\nclass InventoryWriter:\n def __init__(self, base_dir: Path, store: Store | None = None) -> None:\n self._base = base_dir\n self._store: Store = store or FSStore()\n\n def write(self, rel_path: str, items: list[Item]) -> Path:\n dst = (self._base / rel_path).resolve()\n base = self._base.resolve()\n if dst != base and base not in dst.parents:\n raise ValueError(\"unsafe path traversal\")\n payload = json.dumps([item.__dict__ for item in items], ensure_ascii=False)\n self._store.write_text(dst, payload)\n return dst\n```\n\n```python\nimport json\nfrom pathlib import Path\nimport pytest\nfrom module_under_test import InventoryWriter, parse_items\n\ndef test_parse_items_valid():\n lines = [json.dumps({\"name\":\"x\",\"qty\":1})]\n assert parse_items(lines)[0].name == \"x\"\n\ndef test_writer_blocks_traversal(tmp_path: Path):\n w = InventoryWriter(tmp_path)\n with pytest.raises(ValueError):\n w.write(\"../evil.json\", [])\n```", "source": "WithinUsAI/python_GOD_coder_100k"} {"text": "Add observability for idempotent payments in a fintech system.\nTarget platform: ML (PyTorch + serving).\nRequirements: structured logs, metrics, tracing, dashboards, and alerting rules.\nConstraints: must include documentation/comments, must include type hints where applicable, must include tests.\nDifficulty: easy. Assume 10k RPS peak traffic.\n\nOutput: actionable implementation and verification artifacts.\nDeliverable: observability plan + example instrumentation.\n\n**Logs**\n- JSON logs with: request_id, tenant_id, route, status, latency_ms, error_code.\n\n**Metrics**\n- Counters: requests_total{route,status}, errors_total{code}\n- Histograms: request_latency_ms{route}\n- Gauges: queue_depth, db_pool_in_use\n\n**Tracing**\n- Trace ID propagated via headers; spans around DB, cache, external calls.\n\n**Alerts**\n- p95 latency breach, error rate spike, saturation (CPU/mem), queue backlog.\n\nExample (Python structured logging pseudo):\n```python\nlog.info(\"request_done\", extra={\"route\": route, \"status\": status, \"latency_ms\": ms, \"request_id\": rid})\n```\n\n\nChecks: input validation, tests, and safe defaults included.", "source": "WithinUsAI/GOD_Coder_100k"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: System domain: payments platform\nStack: Next.js, Node.js, Prisma, PostgreSQL, Playwright, Docker\nCross-layer incident: path traversal on downloads\nTask type: deploy_runtime_patch\nDifficulty: hard\n\nSolve this as a complete-project engineer.\nOutput must include:\n- root cause across layers\n- final implementation patch\n- tests touching at least two layers\n- deployment or observability note\n- verification commands\n\nRepository sketch:\nrepo/\n src/main.rs\n src/lib.rs\n src/service.rs\n src/store.rs\n tests/integration.rs\n Cargo.toml\n\nFocus: Focus on multi-layer debugging across frontend, backend, database, CI, caching, and deployment.\n\nassistant: Diagnosis:\n- Root cause: path traversal on downloads crosses service boundaries, so the fix must align code, contracts, tests, and deployment behavior.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```rust\nuse std::collections::HashMap;\n\npub fn normalize_payload(payload: HashMap) -> HashMap {\n payload\n .into_iter()\n .filter(|(_, v)| !v.trim().is_empty())\n .collect()\n}\n```\n\nTests:\n```rust\n#[test]\nfn normalize_payload_filters_empty_values() {\n use std::collections::HashMap;\n let mut payload = HashMap::new();\n payload.insert(\"id\".to_string(), \"7\".to_string());\n payload.insert(\"name\".to_string(), \"\".to_string());\n let out = normalize_payload(payload);\n assert!(out.contains_key(\"id\"));\n assert!(!out.contains_key(\"name\"));\n}\n```\n\nVerification:\n- `cargo test`\n- `cargo clippy -- -D warnings`\n\nEngineering notes:\n- Language: Rust\n- Framework/tooling: Axum\n- Stack context: Next.js, Node.js, Prisma, PostgreSQL, Playwright, Docker\n- Domain: payments platform\n- Task type: deploy_runtime_patch\n- Difficulty: hard\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "Optimize while preserving behavior and order.\n\n```python\ndef f45494(xs):\n out=[]\n for x in xs:\n if x not in out: out.append(x)\n return out\n```\nReturn `m63642.py` with types and O(n) average.\n\n```python\n# m63642.py\nfrom __future__ import annotations\nfrom typing import Iterable, List, Set, TypeVar\nT=TypeVar(\"T\")\n\ndef f45494(xs: Iterable[T]) -> List[T]:\n \"\"\"Unique items preserving first-seen order.\"\"\"\n seen: Set[T]=set()\n out: List[T]=[]\n for x in xs:\n if x in seen: continue\n seen.add(x); out.append(x)\n return out\n```", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Task type: runtime_gc\nScenario: payment ledger\nDomain focus: GPU serving\nPrimary language: bash\nDifficulty: expert+\nScale/SLO: 100k RPS peak\nComponent: component_aokrqxcl\nConstraints: avoid data races and undefined behavior, include backward compatibility and migration plan, explicit contracts and invariants, include deterministic replay plan, include performance model and limits\nAssume tight memory budget and cold-start constraints.\nDeliverable: Design a GC/runtime component (mark-sweep/arena/RC hybrid); include pause-time strategy and tests.\n\nOutput: rigorous design + invariants + verification plan + implementation sketch.\n**Contract**\n- Inputs validated at the boundary; explicit error taxonomy.\n- Idempotency for side effects via request_id; deterministic replay.\n- Backward compatibility: additive changes by default; versioned breaking changes.\n**Invariants**\n- Safety: state transitions preserve invariants; no partial commit leaks.\n- Isolation: tenant boundary enforced; no cross-tenant reads/writes.\n- Liveness: under bounded faults and stable network, progress occurs.\n**Failure modes & recovery**\n- Network partition: minority cannot commit; clients receive retriable errors.\n- Data corruption: checksums + scrubber; quarantine and rebuild from replicas/snapshots.\n- Duplicate requests: de-duplicate by (tenant, request_id) returning cached response.\n**Security posture (defensive)**\n- Threat model: auth/authz, injection, replay/abuse, supply chain.\n- Least privilege; secrets in managed store; audit logs for sensitive ops.\n- Input normalization, parameterized queries, path traversal protections.\n**Verification strategy**\n- Deterministic simulation with fault injection (crash/partition/latency).\n- Canary + shadow traffic; invariants checked in production via assertions/metrics.\n- Fuzzing of parsers/framers/validators with corpus seeds.\n\n**Snippet**\n```text\nImplementation sketch: factor pure state-machine core; adapters for I/O; add deterministic replay log.\n```\nExpert+ checks: mechanized invariants (or exhaustive model checking), adversarial fuzzing, and multi-region failure drills.", "source": "WithinUsAI/Omega_Genesis_Coder_100k"} {"text": "Task type: mechanized_spec\nScenario: rate limit gateway\nDomain focus: zero-downtime migrations\nPrimary language: lean\nDifficulty: expert+\nScale/SLO: p99 < 150ms\nComponent: component_llhjktln\nConstraints: include test vectors and fuzz strategy, include security threat model (defensive only), include performance model and limits, include backward compatibility and migration plan, avoid data races and undefined behavior, include deterministic replay plan, explicit contracts and invariants\nAssume partial data corruption; include scrubbing strategy.\nDeliverable: Provide a mechanized-style spec outline (Lean-like), key definitions, and a proof plan. Include executable reference code skeleton and tests.\n\nOutput: rigorous design + invariants + verification plan + implementation sketch.\n**Contract**\n- Inputs validated at the boundary; explicit error taxonomy.\n- Idempotency for side effects via request_id; deterministic replay.\n- Backward compatibility: additive changes by default; versioned breaking changes.\n**Invariants**\n- Safety: state transitions preserve invariants; no partial commit leaks.\n- Isolation: tenant boundary enforced; no cross-tenant reads/writes.\n- Determinism: replay of the same event log yields identical outputs.\n**Failure modes & recovery**\n- Crash during commit: WAL replay completes or transaction aborts; no torn writes.\n- Data corruption: checksums + scrubber; quarantine and rebuild from replicas/snapshots.\n- Duplicate requests: de-duplicate by (tenant, request_id) returning cached response.\n**Security posture (defensive)**\n- Threat model: auth/authz, injection, replay/abuse, supply chain.\n- Least privilege; secrets in managed store; audit logs for sensitive ops.\n- Input normalization, parameterized queries, path traversal protections.\n**Verification strategy**\n- Deterministic simulation with fault injection (crash/partition/latency).\n- Property tests against a pure reference model (state machine).\n- Fuzzing of parsers/framers/validators with corpus seeds.\n\n**Snippet**\n```lean\n-- Pseudo-Lean outline\nstructure State where\n ver : Nat\n val : Option ByteArray\n\ndef invariant (s : State) : Prop := True\n\ntheorem step_preserves_invariant :\n ∀ s, invariant s → ∀ s', Step s s' → invariant s' := by\n intro s hs s' hstep\n -- proof plan: case analysis on transition; trivial here\n trivial\n```\n\nExpert+ checks: mechanized invariants (or exhaustive model checking), adversarial fuzzing, and multi-region failure drills.", "source": "WithinUsAI/Omega_Genesis_Coder_100k"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: Language: TypeScript\nFramework/tooling: Next.js\nDomain: developer platform\nLogic challenge: schema drift during deployment\nTask type: parser_validation_logic\nDifficulty: medium\n\nReturn a rigorous engineering answer:\n- identify the hidden root cause or logical failure\n- present the corrected implementation\n- add tests that prove the fix\n- list verification commands\n- explain why naive fixes are insufficient when relevant\n\nRepository sketch:\nrepo/\n src/\n api.ts\n service.ts\n schema.ts\n tests/\n api.test.ts\n package.json\n\nFocus: Focus on strong structured logic with edge cases, data validation, and concurrency safety.\n\nassistant: Diagnosis:\n- Root cause: the failure around schema drift during deployment is caused by missing validation, weak edge-case handling, or unsafe lifecycle behavior in the current implementation.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```ts\ntype Payload = Record;\n\nexport function normalizePayload(payload: Payload): Payload {\n if (!payload || typeof payload !== \"object\" || Array.isArray(payload)) {\n throw new TypeError(\"payload must be a plain object\");\n }\n return Object.fromEntries(\n Object.entries(payload)\n .filter(([, value]) => value !== null && value !== undefined)\n .map(([key, value]) => [String(key).trim(), value])\n );\n}\n\nexport function handleSchemaDriftDuringDeployment(payload: Payload) {\n const clean = normalizePayload(payload);\n if (!(\"id\" in clean)) {\n return { ok: false, data: {}, error: \"missing id\" };\n }\n return { ok: true, data: clean, error: null };\n}\n```\n\nTests:\n```ts\nimport { describe, it, expect } from \"vitest\";\nimport { handleSchemaDriftDuringDeployment } from \"../src/service\";\n\ndescribe(\"handler\", () => {\n it(\"accepts valid input\", () => {\n expect(handleSchemaDriftDuringDeployment({ id: 7, name: \"ok\", unused: null })).toEqual({\n ok: true,\n data: { id: 7, name: \"ok\" },\n error: null\n });\n });\n\n it(\"rejects missing id\", () => {\n expect(handleSchemaDriftDuringDeployment({ name: \"x\" }).error).toMatch(/missing id/);\n });\n});\n```\n\nVerification:\n- `npm test`\n- `npm run typecheck`\n- `npm run lint`\n\nEngineering notes:\n- Language: TypeScript\n- Framework/tooling: Next.js\n- Stack context: Go, Gin, PostgreSQL, gRPC, Prometheus, Docker\n- Domain: developer platform\n- Task type: parser_validation_logic\n- Difficulty: medium\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "Task type: distributed_algorithm\nScenario: job scheduler\nDomain focus: kernel primitives\nPrimary language: typescript\nDifficulty: hard\nScale/SLO: 100k RPS peak\nComponent: component_sihuppii\nConstraints: include performance model and limits, include backward compatibility and migration plan, avoid data races and undefined behavior, include deterministic replay plan, include verification strategy, include failure modes and recovery, include test vectors and fuzz strategy\nAssume crash-only processes; recovery must be deterministic.\nDeliverable: Design an algorithm with message flows and correctness arguments (safety + liveness). Include failure handling and a minimal reference implementation skeleton.\n\nOutput: elite engineering answer optimized for correctness, performance, and operability.\n**Contract**\n- Inputs validated at the boundary; explicit error taxonomy.\n- Idempotency for side effects via request_id; deterministic replay.\n- Backward compatibility: additive changes by default; versioned breaking changes.\n**Invariants**\n- Liveness: under bounded faults and stable network, progress occurs.\n- Determinism: replay of the same event log yields identical outputs.\n- Safety: state transitions preserve invariants; no partial commit leaks.\n**Failure modes & recovery**\n- Network partition: minority cannot commit; clients receive retriable errors.\n- Crash during commit: WAL replay completes or transaction aborts; no torn writes.\n- Data corruption: checksums + scrubber; quarantine and rebuild from replicas/snapshots.\n**Security posture (defensive)**\n- Threat model: auth/authz, injection, replay/abuse, supply chain.\n- Least privilege; secrets in managed store; audit logs for sensitive ops.\n- Input normalization, parameterized queries, path traversal protections.\n**Verification strategy**\n- Fuzzing of parsers/framers/validators with corpus seeds.\n- Property tests against a pure reference model (state machine).\n- Deterministic simulation with fault injection (crash/partition/latency).\n\n**Snippet**\n```text\nImplementation sketch: factor pure state-machine core; adapters for I/O; add deterministic replay log.\n```\nHard checks: fault injection tests gate merges; perf thresholds enforced in CI.", "source": "WithinUsAI/Omega_Genesis_Coder_100k"} {"text": "Optimize while preserving behavior and order.\n\n```python\ndef f52303(xs):\n out=[]\n for x in xs:\n if x not in out: out.append(x)\n return out\n```\nReturn `m50329.py` with types and O(n) average.\n\n```python\n# m50329.py\nfrom __future__ import annotations\nfrom typing import Iterable, List, Set, TypeVar\nT=TypeVar(\"T\")\n\ndef f52303(xs: Iterable[T]) -> List[T]:\n \"\"\"Unique items preserving first-seen order.\"\"\"\n seen: Set[T]=set()\n out: List[T]=[]\n for x in xs:\n if x in seen: continue\n seen.add(x); out.append(x)\n return out\n```", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Build an elite-grade solution in the domain of sre/observability for scenario: payment processing.\nPrimary language: go.\nDifficulty: expert.\nConstraints: make the interface contract explicit, include tests or verification strategy, include invariants and failure modes, provide rollout and rollback guidance, avoid undefined behavior and data races.\nComponent: component_gzbiqmh.\nAssume strict auditability and replayable history.\nTask: Implement a concurrency primitive or subsystem (lock-free queue, thread pool, async runtime component). Explain memory ordering and correctness arguments; include stress tests.\n\nOutput: rigorous solution with invariants, failure modes, and performance notes.\nOutput: correctness-focused concurrency primitive + stress tests.\n\n**Primitive**\n- Bounded MPMC queue with backpressure (blocking push/pop) OR lock-free SPSC ring buffer.\n\n**Correctness notes**\n- For lock-free: use acquire/release semantics on head/tail indices.\n- Avoid ABA by monotonic counters; ring index = counter % capacity.\n\n**Stress tests**\n- Multi-thread producers/consumers; assert item multiset preserved.\n- Use time-bounded randomized schedules; detect deadlocks.\n\n\nExpert checks: state-machine reasoning, concurrency stress, and upgrade/rollback validated.", "source": "WithinUsAI/Elite_GOD_Coder_100k"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: Project stack: GitHub Actions, Docker Compose, Kubernetes, Terraform\nLanguage: Python\nDependency challenge: idempotent retry design\nTask type: migration_patch\nDifficulty: medium\n\nFix this as a senior engineer.\nRequired:\n- identify the version or compatibility failure mode\n- produce the corrected config/code/build patch\n- explain rollback-safe migration notes\n- add regression tests or reproducibility checks\n- include concrete verification commands\n\nRepository sketch:\nrepo/\n app/\n api.py\n service.py\n models.py\n tests/\n test_api.py\n pyproject.toml\n\nFocus: Focus on versioning, migrations, lockfiles, runtime compatibility, and secure dependency handling.\n\nassistant: Diagnosis:\n- Root cause: the issue around idempotent retry design is a dependency, migration, or runtime-compatibility mismatch that needs a rollback-safe patch.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```python\nfrom __future__ import annotations\n\nfrom dataclasses import dataclass\nfrom typing import Any\n\n@dataclass\nclass ServiceResult:\n ok: bool\n data: dict[str, Any]\n error: str | None = None\n\ndef normalize_payload(payload: dict[str, Any]) -> dict[str, Any]:\n if not isinstance(payload, dict):\n raise TypeError(\"payload must be a dict\")\n clean: dict[str, Any] = {}\n for key, value in payload.items():\n if value is None:\n continue\n clean[str(key).strip()] = value\n return clean\n\ndef handle_idempotent_retry_design(payload: dict[str, Any]) -> ServiceResult:\n clean = normalize_payload(payload)\n if \"id\" not in clean:\n return ServiceResult(ok=False, data={}, error=\"missing id\")\n return ServiceResult(ok=True, data=clean)\n```\n\nTests:\n```python\nimport pytest\nfrom app.service import handle_jwt_refresh_token_rotation as handler\n\ndef test_handler_accepts_valid_payload():\n result = handler({\"id\": 7, \"name\": \"ok\", \"unused\": None})\n assert result.ok is True\n assert result.data == {\"id\": 7, \"name\": \"ok\"}\n\ndef test_handler_rejects_missing_id():\n result = handler({\"name\": \"x\"})\n assert result.ok is False\n assert result.error == \"missing id\"\n```\n\nVerification:\n- `pytest -q`\n- `ruff check .`\n- `python -m compileall .`\n\nEngineering notes:\n- Language: Python\n- Framework/tooling: SQLAlchemy\n- Stack context: GitHub Actions, Docker Compose, Kubernetes, Terraform\n- Domain: auth service\n- Task type: migration_patch\n- Difficulty: medium\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: Project stack: Airflow, dbt, DuckDB, MinIO, pytest\nLanguage: C++\nDependency challenge: invalid rollback sequence\nTask type: container_runtime_fix\nDifficulty: hard\n\nFix this as a senior engineer.\nRequired:\n- identify the version or compatibility failure mode\n- produce the corrected config/code/build patch\n- explain rollback-safe migration notes\n- add regression tests or reproducibility checks\n- include concrete verification commands\n\nRepository sketch:\nrepo/\n src/main.cpp\n src/service.cpp\n include/service.h\n tests/test_service.cpp\n CMakeLists.txt\n\nFocus: Focus on versioning, migrations, lockfiles, runtime compatibility, and secure dependency handling.\n\nassistant: Diagnosis:\n- Root cause: the issue around invalid rollback sequence is a dependency, migration, or runtime-compatibility mismatch that needs a rollback-safe patch.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```cpp\n#include \n#include \n\nusing Payload = std::unordered_map;\n\nPayload normalize_payload(const Payload& in) {\n Payload out;\n for (const auto& [k, v] : in) {\n if (!v.empty()) out[k] = v;\n }\n return out;\n}\n```\n\nTests:\n```cpp\nTEST_CASE(\"normalize_payload filters empty values\") {\n Payload in{{\"id\",\"7\"},{\"name\",\"\"}};\n auto out = normalize_payload(in);\n REQUIRE(out.count(\"id\") == 1);\n REQUIRE(out.count(\"name\") == 0);\n}\n```\n\nVerification:\n- `cmake --build build`\n- `ctest --test-dir build`\n\nEngineering notes:\n- Language: C++\n- Framework/tooling: Boost\n- Stack context: Airflow, dbt, DuckDB, MinIO, pytest\n- Domain: artifact registry\n- Task type: container_runtime_fix\n- Difficulty: hard\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: Language: TypeScript\nFramework/tooling: Express\nDomain: repo automation\nLogic challenge: optimistic locking conflict\nTask type: multi_service_security_patch\nDifficulty: hard\n\nReturn a rigorous engineering answer:\n- identify the hidden root cause or logical failure\n- present the corrected implementation\n- add tests that prove the fix\n- list verification commands\n- explain why naive fixes are insufficient when relevant\n\nRepository sketch:\nrepo/\n src/\n api.ts\n service.ts\n schema.ts\n tests/\n api.test.ts\n package.json\n\nFocus: Focus on staff-level problem solving with multi-file patches, rollout implications, performance and security tradeoffs.\n\nassistant: Diagnosis:\n- Staff-level diagnosis: optimistic locking conflict impacts correctness, operability, and future maintenance, so the fix must be minimal where possible but complete where necessary.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```ts\ntype Payload = Record;\n\nexport function normalizePayload(payload: Payload): Payload {\n if (!payload || typeof payload !== \"object\" || Array.isArray(payload)) {\n throw new TypeError(\"payload must be a plain object\");\n }\n return Object.fromEntries(\n Object.entries(payload)\n .filter(([, value]) => value !== null && value !== undefined)\n .map(([key, value]) => [String(key).trim(), value])\n );\n}\n\nexport function handleOptimisticLockingConflict(payload: Payload) {\n const clean = normalizePayload(payload);\n if (!(\"id\" in clean)) {\n return { ok: false, data: {}, error: \"missing id\" };\n }\n return { ok: true, data: clean, error: null };\n}\n```\n\nTests:\n```ts\nimport { describe, it, expect } from \"vitest\";\nimport { handleOptimisticLockingConflict } from \"../src/service\";\n\ndescribe(\"handler\", () => {\n it(\"accepts valid input\", () => {\n expect(handleOptimisticLockingConflict({ id: 7, name: \"ok\", unused: null })).toEqual({\n ok: true,\n data: { id: 7, name: \"ok\" },\n error: null\n });\n });\n\n it(\"rejects missing id\", () => {\n expect(handleOptimisticLockingConflict({ name: \"x\" }).error).toMatch(/missing id/);\n });\n});\n```\n\nVerification:\n- `npm test`\n- `npm run typecheck`\n- `npm run lint`\n\nEngineering notes:\n- Language: TypeScript\n- Framework/tooling: Express\n- Stack context: GitHub Actions, Docker Compose, Kubernetes, Terraform\n- Domain: repo automation\n- Task type: multi_service_security_patch\n- Difficulty: hard\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "Fix the bug and add pytest tests.\n\n```python\ndef f43977(n: int) -> int:\n # sum 1..n inclusive\n if n < 0: raise ValueError\n total = 0\n for k in range(n): # BUG\n total += k\n return total\n```\nReturn unified diffs for `m77711.py` and `test_m77711.py`.\n\n*** Begin Patch\n*** Update File: m77711.py\n@@\n def f43977(n: int) -> int:\n@@\n- for k in range(n): # BUG\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_m77711.py\n+import pytest\n+from m77711 import f43977\n+\n+def test_small():\n+ assert f43977(7) == 28\n+\n+def test_zero():\n+ assert f43977(0) == 0\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ f43977(-1)\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Refactor to typed, mostly-immutable Python and add minimal tests.\n\n```python\nclass C13896:\n def __init__(self, values): self.values=list(values)\n def mean(self): return sum(self.values)/len(self.values)\n```\nReturn `m77992.py` and `test_m77992.py`.\n\n```python\n# m77992.py\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom typing import Iterable, Tuple\n\n@dataclass(frozen=True)\nclass C13896:\n values: Tuple[float, ...]\n\n @staticmethod\n def create(values: Iterable[float]) -> \"C13896\":\n vals = tuple(float(v) for v in values)\n if not vals: raise ValueError(\"empty\")\n return C13896(vals)\n\n def mean(self) -> float:\n return sum(self.values)/len(self.values)\n```\n\n```python\n# test_m77992.py\nimport pytest\nfrom m77992 import C13896\n\ndef test_mean():\n assert C13896.create([1,2,3]).mean() == 2.0\ndef test_empty():\n with pytest.raises(ValueError):\n C13896.create([])\n```", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Produce an offline-first self-evolving code assistant architecture named `gyhn85`.\nMust include: module layout, patch-safety policy, evaluation gates (tests/lint/types), versioned memory index.\n\nArchitecture: `gyhn85` (offline-first, self-evolving)\n\nModules\n- core/loop.py: evolve → validate → accept/reject (bounded iterations)\n- patching/: diff builder, safe apply, atomic writes, rollback points\n- policy/: allowlist paths, deny globs (.git/, __pycache__/, binaries), patch size caps\n- signals/: parse pytest/ruff/mypy into normalized findings\n- memory/index.jsonl: append-only snapshots (hashes, metrics, rationale)\n\nSafety gates\n- refuse path traversal/symlink escapes; never edit binaries\n- accept only if tests/lint/types stay green or improve", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Refactor to typed, mostly-immutable Python and add minimal tests.\n\n```python\nclass C24864:\n def __init__(self, values): self.values=list(values)\n def mean(self): return sum(self.values)/len(self.values)\n```\nReturn `m86528.py` and `test_m86528.py`.\n\n```python\n# m86528.py\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom typing import Iterable, Tuple\n\n@dataclass(frozen=True)\nclass C24864:\n values: Tuple[float, ...]\n\n @staticmethod\n def create(values: Iterable[float]) -> \"C24864\":\n vals = tuple(float(v) for v in values)\n if not vals: raise ValueError(\"empty\")\n return C24864(vals)\n\n def mean(self) -> float:\n return sum(self.values)/len(self.values)\n```\n\n```python\n# test_m86528.py\nimport pytest\nfrom m86528 import C24864\n\ndef test_mean():\n assert C24864.create([1,2,3]).mean() == 2.0\ndef test_empty():\n with pytest.raises(ValueError):\n C24864.create([])\n```", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Optimize while preserving behavior and order.\n\n```python\ndef f18414(xs):\n out=[]\n for x in xs:\n if x not in out: out.append(x)\n return out\n```\nReturn `m31202.py` with types and O(n) average.\n\n```python\n# m31202.py\nfrom __future__ import annotations\nfrom typing import Iterable, List, Set, TypeVar\nT=TypeVar(\"T\")\n\ndef f18414(xs: Iterable[T]) -> List[T]:\n \"\"\"Unique items preserving first-seen order.\"\"\"\n seen: Set[T]=set()\n out: List[T]=[]\n for x in xs:\n if x in seen: continue\n seen.add(x); out.append(x)\n return out\n```", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Task type: lockfree_primitive\nScenario: document indexing pipeline\nDomain focus: zero-downtime migrations\nPrimary language: cpp\nDifficulty: hard\nScale/SLO: 50 TB/day ingestion\nComponent: component_oljhvmzq\nConstraints: include security threat model (defensive only), explicit contracts and invariants, include backward compatibility and migration plan, assume adversarial inputs; validate everything, include verification strategy, include deterministic replay plan\nAssume strict auditability and replayable history.\nDeliverable: Design a lock-free primitive with memory ordering reasoning and stress tests (no UB).\n\nOutput: elite engineering answer optimized for correctness, performance, and operability.\n**Contract**\n- Inputs validated at the boundary; explicit error taxonomy.\n- Idempotency for side effects via request_id; deterministic replay.\n- Backward compatibility: additive changes by default; versioned breaking changes.\n**Invariants**\n- Isolation: tenant boundary enforced; no cross-tenant reads/writes.\n- Liveness: under bounded faults and stable network, progress occurs.\n- Determinism: replay of the same event log yields identical outputs.\n**Failure modes & recovery**\n- Duplicate requests: de-duplicate by (tenant, request_id) returning cached response.\n- Network partition: minority cannot commit; clients receive retriable errors.\n- Crash during commit: WAL replay completes or transaction aborts; no torn writes.\n**Security posture (defensive)**\n- Threat model: auth/authz, injection, replay/abuse, supply chain.\n- Least privilege; secrets in managed store; audit logs for sensitive ops.\n- Input normalization, parameterized queries, path traversal protections.\n**Verification strategy**\n- Canary + shadow traffic; invariants checked in production via assertions/metrics.\n- Property tests against a pure reference model (state machine).\n- Fuzzing of parsers/framers/validators with corpus seeds.\n\n**Snippet**\n```rust\n// Skeleton: SPSC ring buffer with acquire/release (outline)\nuse std::sync::atomic::{AtomicUsize, Ordering};\n\npub struct Ring {\n buf: Vec>,\n head: AtomicUsize,\n tail: AtomicUsize,\n cap: usize,\n}\n\n// Correctness sketch: producer uses Release on tail store, consumer uses Acquire on tail load.\n```\n\nHard checks: fault injection tests gate merges; perf thresholds enforced in CI.", "source": "WithinUsAI/Omega_Genesis_Coder_100k"} {"text": "Refactor to typed, mostly-immutable Python and add minimal tests.\n\n```python\nclass C56180:\n def __init__(self, values): self.values=list(values)\n def mean(self): return sum(self.values)/len(self.values)\n```\nReturn `m65860.py` and `test_m65860.py`.\n\n```python\n# m65860.py\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom typing import Iterable, Tuple\n\n@dataclass(frozen=True)\nclass C56180:\n values: Tuple[float, ...]\n\n @staticmethod\n def create(values: Iterable[float]) -> \"C56180\":\n vals = tuple(float(v) for v in values)\n if not vals: raise ValueError(\"empty\")\n return C56180(vals)\n\n def mean(self) -> float:\n return sum(self.values)/len(self.values)\n```\n\n```python\n# test_m65860.py\nimport pytest\nfrom m65860 import C56180\n\ndef test_mean():\n assert C56180.create([1,2,3]).mean() == 2.0\ndef test_empty():\n with pytest.raises(ValueError):\n C56180.create([])\n```", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Task type: network_protocol\nScenario: identity and access\nDomain focus: model checking\nPrimary language: sql\nDifficulty: expert+\nScale/SLO: 50 TB/day ingestion\nComponent: component_kmddkrqp\nConstraints: include verification strategy, include security threat model (defensive only), include performance model and limits, assume adversarial inputs; validate everything, include test vectors and fuzz strategy, include failure modes and recovery, explicit contracts and invariants\nAssume hostile inputs and targeted abuse patterns.\nDeliverable: Design an application protocol: framing, retries, backpressure, timeouts; include client/server skeleton and test vectors.\n\nOutput: contract-first solution with failure modes, security posture, and test/verification strategy.\n**Contract**\n- Inputs validated at the boundary; explicit error taxonomy.\n- Idempotency for side effects via request_id; deterministic replay.\n- Backward compatibility: additive changes by default; versioned breaking changes.\n**Invariants**\n- Determinism: replay of the same event log yields identical outputs.\n- Liveness: under bounded faults and stable network, progress occurs.\n- Isolation: tenant boundary enforced; no cross-tenant reads/writes.\n**Failure modes & recovery**\n- Duplicate requests: de-duplicate by (tenant, request_id) returning cached response.\n- Crash during commit: WAL replay completes or transaction aborts; no torn writes.\n- Data corruption: checksums + scrubber; quarantine and rebuild from replicas/snapshots.\n**Security posture (defensive)**\n- Threat model: auth/authz, injection, replay/abuse, supply chain.\n- Least privilege; secrets in managed store; audit logs for sensitive ops.\n- Input normalization, parameterized queries, path traversal protections.\n**Verification strategy**\n- Canary + shadow traffic; invariants checked in production via assertions/metrics.\n- Deterministic simulation with fault injection (crash/partition/latency).\n- Property tests against a pure reference model (state machine).\n\n**Snippet**\n```text\nImplementation sketch: factor pure state-machine core; adapters for I/O; add deterministic replay log.\n```\nExpert+ checks: mechanized invariants (or exhaustive model checking), adversarial fuzzing, and multi-region failure drills.", "source": "WithinUsAI/Omega_Genesis_Coder_100k"} {"text": "Improve typing and robustness of a Python module used for configuration loading.\nRequirements: provide type-safe APIs (generics/protocols where appropriate) and include tests.\nConstraints: must provide clear error messages, must handle Windows paths safely, must include tests.\nDifficulty: easy. Include a small CLI example if relevant.\n\nDeliverable: implementation + tests.\n```python\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom typing import Callable, Generic, Iterable, Protocol, TypeVar\n\nT = TypeVar(\"T\")\nR = TypeVar(\"R\")\n\nclass Mapper(Protocol[T, R]):\n def __call__(self, x: T) -> R: ...\n\n@dataclass(frozen=True, slots=True)\nclass Batch(Generic[T]):\n items: tuple[T, ...]\n\ndef map_batch(batch: Batch[T], fn: Mapper[T, R]) -> Batch[R]:\n return Batch(items=tuple(fn(x) for x in batch.items))\n\ndef chunked(xs: Iterable[T], size: int) -> Iterable[Batch[T]]:\n if size <= 0:\n raise ValueError(\"size must be > 0\")\n buf: list[T] = []\n for x in xs:\n buf.append(x)\n if len(buf) == size:\n yield Batch(items=tuple(buf))\n buf.clear()\n if buf:\n yield Batch(items=tuple(buf))\n```\n\n```python\nimport pytest\nfrom module_under_test import Batch, map_batch, chunked\n\ndef test_map_batch():\n b = Batch(items=(1,2,3))\n assert map_batch(b, lambda x: x*2).items == (2,4,6)\n\ndef test_chunked():\n out = list(chunked([1,2,3,4,5], 2))\n assert [b.items for b in out] == [(1,2),(3,4),(5,)]\n```", "source": "WithinUsAI/python_GOD_coder_100k"} {"text": "Secure-by-default implementation for analytics pipeline in a IoT telemetry product.\nTarget platform: infra (Docker + Kubernetes).\nRequirements: threat model, input validation, authz/authn guidance, safe storage, tests.\nConstraints: must include clear error handling, must be secure-by-default, must be easy to extend, must include tests, must be observable (logs/metrics/traces).\nDifficulty: hard. Include rollback strategy.\n\nOutput: engineering-grade answer with edge cases covered.\nDeliverable: threat model + secure patterns (no offensive content).\n\n**Threat model**\n- Input: untrusted clients → validation required\n- Auth: token theft / privilege escalation → short-lived tokens + RBAC checks\n- Data: PII exposure → encryption at rest + access logging + least privilege\n- Webhooks/callbacks: SSRF → allowlist destinations + timeouts + egress controls\n\n**Secure implementation patterns**\n- Validate and normalize inputs at boundaries (API/CLI/file).\n- Use parameterized SQL; never string interpolate.\n- Prevent path traversal when writing files (resolve + base containment).\n- Use idempotency keys for side-effecting endpoints; safe retries.\n- Centralize authorization checks in one layer; test them.\n\n**Test checklist**\n- Invalid inputs rejected with clear error messages.\n- AuthZ tests for tenant boundary violations.\n- Replay/idempotency conflict test.\n\n\nHard-mode checks: concurrency safety, idempotency, and rollback validated; add chaos tests where feasible.", "source": "WithinUsAI/GOD_Coder_100k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Refactor to modern typed Python with immutability and tests.\n\nFile: yanngz3hl2t.py\n```python\nclass Sc6Q4Uwn:\n def __init__(self, name, values):\n self.name = name\n self.values = list(values)\n def add(self, v):\n self.values.append(v)\n def mean(self):\n s = 0\n for x in self.values:\n s += x\n return s / len(self.values)\n```\n\nReturn full new yanngz3hl2t.py and test_yanngz3hl2t.py.\n\n# yanngz3hl2t.py\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom typing import Iterable, Tuple\n\n@dataclass(frozen=True)\nclass Sc6Q4Uwn:\n name: str\n values: Tuple[float, ...]\n\n @staticmethod\n def create(name: str, values: Iterable[float]) -> \"Sc6Q4Uwn\":\n vals = tuple(float(v) for v in values)\n if not vals:\n raise ValueError(\"values must be non-empty\")\n return Sc6Q4Uwn(name=name, values=vals)\n\n def add(self, v: float) -> \"Sc6Q4Uwn\":\n return Sc6Q4Uwn(name=self.name, values=self.values + (float(v),))\n\n def mean(self) -> float:\n return sum(self.values) / len(self.values)\n\n# test_yanngz3hl2t.py\nimport pytest\nfrom yanngz3hl2t import Sc6Q4Uwn\n\ndef test_mean_and_add():\n c = Sc6Q4Uwn.create(\"a\", [1, 2, 3])\n assert c.mean() == 2.0\n assert c.add(5).mean() == (1 + 2 + 3 + 5) / 4\n\ndef test_empty_raises():\n with pytest.raises(ValueError):\n Sc6Q4Uwn.create(\"x\", [])", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Build a data pipeline for a calendar/scheduling product around search + pagination.\nTarget platform: data (SQL + Python).\nRequirements: schema, ingestion, validation, backfills, and tests.\nConstraints: must be easy to extend, must be production-ready, must avoid global state.\nDifficulty: medium. Include rollback strategy.\n\nOutput: design + implementation guidance suitable for shipping.\nDeliverable: schema + ingestion + validation + backfill strategy.\n\n**Schema (example)**\n- events(event_id TEXT PK, tenant_id TEXT, ts TIMESTAMP, type TEXT, payload JSONB)\n\n**Ingestion**\n- Write to raw table first; validate; then materialize to curated tables.\n- Idempotency by event_id; enforce uniqueness.\n\n**Validation**\n- Reject missing tenant_id/type/ts.\n- Quarantine bad records with reason.\n\n**Backfills**\n- Re-run deterministic transforms from raw → curated.\n- Version transformations; store transform_version with outputs.\n\n**Tests**\n- Unit tests for validators and transforms.\n- Integration test: sample raw batch produces expected curated rows.\n\n\nChecks: input validation, tests, and safe defaults included.", "source": "WithinUsAI/GOD_Coder_100k"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: Language: TypeScript\nFramework/tooling: Vitest\nDomain: auth service\nLogic challenge: race condition on worker shutdown\nTask type: distributed_debug\nDifficulty: hard\n\nReturn a rigorous engineering answer:\n- identify the hidden root cause or logical failure\n- present the corrected implementation\n- add tests that prove the fix\n- list verification commands\n- explain why naive fixes are insufficient when relevant\n\nRepository sketch:\nrepo/\n src/\n api.ts\n service.ts\n schema.ts\n tests/\n api.test.ts\n package.json\n\nFocus: Focus on ambiguity, misleading symptoms, hidden root causes, and high-stakes debugging.\n\nassistant: Diagnosis:\n- Hidden root cause: race condition on worker shutdown presents misleading symptoms, so the patch must target the actual logic boundary rather than the first visible failure.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```ts\ntype Payload = Record;\n\nexport function normalizePayload(payload: Payload): Payload {\n if (!payload || typeof payload !== \"object\" || Array.isArray(payload)) {\n throw new TypeError(\"payload must be a plain object\");\n }\n return Object.fromEntries(\n Object.entries(payload)\n .filter(([, value]) => value !== null && value !== undefined)\n .map(([key, value]) => [String(key).trim(), value])\n );\n}\n\nexport function handleRaceConditionOnWorkerShutdown(payload: Payload) {\n const clean = normalizePayload(payload);\n if (!(\"id\" in clean)) {\n return { ok: false, data: {}, error: \"missing id\" };\n }\n return { ok: true, data: clean, error: null };\n}\n```\n\nTests:\n```ts\nimport { describe, it, expect } from \"vitest\";\nimport { handleRaceConditionOnWorkerShutdown } from \"../src/service\";\n\ndescribe(\"handler\", () => {\n it(\"accepts valid input\", () => {\n expect(handleRaceConditionOnWorkerShutdown({ id: 7, name: \"ok\", unused: null })).toEqual({\n ok: true,\n data: { id: 7, name: \"ok\" },\n error: null\n });\n });\n\n it(\"rejects missing id\", () => {\n expect(handleRaceConditionOnWorkerShutdown({ name: \"x\" }).error).toMatch(/missing id/);\n });\n});\n```\n\nVerification:\n- `npm test`\n- `npm run typecheck`\n- `npm run lint`\n\nEngineering notes:\n- Language: TypeScript\n- Framework/tooling: Vitest\n- Stack context: Spring Boot, PostgreSQL, JUnit, Gradle, Docker, GitHub Actions\n- Domain: auth service\n- Task type: distributed_debug\n- Difficulty: hard\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "Provision infrastructure for a social media workload providing search + pagination.\nTarget platform: ML (scikit + batch).\nRequirements: IaC (Terraform or Kubernetes YAML), networking, secrets, autoscaling.\nConstraints: must avoid global state, must include documentation/comments, must include type hints where applicable.\nDifficulty: expert. Assume PII must be protected.\n\nOutput: actionable implementation and verification artifacts.\nDeliverable: Kubernetes deployment + basic security posture.\n\n```yaml\napiVersion: apps/v1\nkind: Deployment\nmetadata:\n name: app\nspec:\n replicas: 3\n selector:\n matchLabels: { app: app }\n template:\n metadata:\n labels: { app: app }\n spec:\n containers:\n - name: app\n image: app:latest\n ports: [{ containerPort: 8080 }]\n readinessProbe:\n httpGet: { path: /healthz, port: 8080 }\n resources:\n requests: { cpu: \"200m\", memory: \"256Mi\" }\n limits: { cpu: \"1\", memory: \"1Gi\" }\n```\n\nAdditions:\n- NetworkPolicy to restrict egress/ingress.\n- Secrets via external secret store; rotate regularly.\n- HPA for autoscaling; PodDisruptionBudget for availability.\n\n\nHard-mode checks: concurrency safety, idempotency, and rollback validated; add chaos tests where feasible.", "source": "WithinUsAI/GOD_Coder_100k"} {"text": "Build an elite-grade solution in the domain of ml systems for scenario: chat messaging.\nPrimary language: bash.\nDifficulty: expert.\nConstraints: make the interface contract explicit, include invariants and failure modes, assume untrusted inputs; validate and sanitize.\nComponent: component_euhwvqp.\nAssume schema changes every sprint; must be backward compatible.\nTask: Provide SLOs, alerting, dashboards, runbooks, and incident playbook. Include chaos testing and safe rollout strategy.\n\nOutput: rigorous solution with invariants, failure modes, and performance notes.\nOutput: SLOs + alerts + runbooks + chaos strategy.\n\n**SLOs**\n- Availability: 99.9% monthly\n- Latency: p95 < 200ms, p99 < 400ms\n- Error rate: < 0.1%\n\n**Alerts**\n- Burn-rate alerts for SLOs (fast/slow windows)\n- Saturation: CPU, memory, queue depth, DB connections\n- Dependency health: cache hit rate drop, downstream timeouts\n\n**Runbooks**\n- Triage: identify blast radius, feature-flag rollback, capacity mitigation\n- Post-incident: timeline, contributing factors, action items\n\n**Chaos**\n- Inject latency, partial outages, and restarts in staging; verify steady-state SLOs.\n\n\nExpert checks: state-machine reasoning, concurrency stress, and upgrade/rollback validated.", "source": "WithinUsAI/Elite_GOD_Coder_100k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Fix a bug and add tests.\n\nFile: alepe0vzm.py\n```python\ndef ju510z1g(n: int) -> int:\n \"\"\"Sum 1..n inclusive.\"\"\"\n if n < 0:\n raise ValueError(\"n must be non-negative\")\n total = 0\n for k in range(n): # BUG: should include n\n total += k\n return total\n```\n\nReturn unified diffs for alepe0vzm.py and test_alepe0vzm.py (pytest).\n\n*** Begin Patch\n*** Update File: alepe0vzm.py\n@@\n def ju510z1g(n: int) -> int:\n@@\n total = 0\n- for k in range(n): # BUG: should include n\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_alepe0vzm.py\n+import pytest\n+from alepe0vzm import ju510z1g\n+\n+def test_zero():\n+ assert ju510z1g(0) == 0\n+\n+def test_one():\n+ assert ju510z1g(1) == 1\n+\n+def test_small():\n+ assert ju510z1g(7) == 28\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ ju510z1g(-1)\n+\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Design CI/CD for a IoT telemetry service delivering offline-first sync.\nTarget platform: infra (Terraform).\nRequirements: pipelines, checks, artifact strategy, deployments, and rollbacks.\nConstraints: must be observable (logs/metrics/traces), must be performant under load, must include type hints where applicable.\nDifficulty: easy. Assume GDPR-style deletion requests must be supported.\n\nOutput: design + implementation guidance suitable for shipping.\nDeliverable: CI/CD pipeline (GitHub Actions) with quality gates.\n\n```yaml\nname: ci\non:\n pull_request:\n push:\n branches: [main]\n\njobs:\n test:\n runs-on: ubuntu-latest\n steps:\n - uses: actions/checkout@v4\n - uses: actions/setup-python@v5\n with:\n python-version: \"3.11\"\n - run: python -m pip install -U pip\n - run: pip install -r requirements.txt\n - run: pip install -r requirements-dev.txt\n - run: ruff check .\n - run: mypy .\n - run: pytest -q --maxfail=1 --disable-warnings\n\n docker:\n needs: test\n runs-on: ubuntu-latest\n steps:\n - uses: actions/checkout@v4\n - uses: docker/setup-buildx-action@v3\n - run: docker build -t app:${{ github.sha }} .\n```\n\nDeployment strategy:\n- main → build → deploy to staging → smoke tests → canary to prod.\n- Rollback: redeploy previous image + DB migration rollback plan.\n\n\nChecks: input validation, tests, and safe defaults included.", "source": "WithinUsAI/GOD_Coder_100k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Refactor to modern typed Python with immutability and tests.\n\nFile: wxt1d8xs_m.py\n```python\nclass S309Rx6Rx2A:\n def __init__(self, name, values):\n self.name = name\n self.values = list(values)\n def add(self, v):\n self.values.append(v)\n def mean(self):\n s = 0\n for x in self.values:\n s += x\n return s / len(self.values)\n```\n\nReturn full new wxt1d8xs_m.py and test_wxt1d8xs_m.py.\n\n# wxt1d8xs_m.py\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom typing import Iterable, Tuple\n\n@dataclass(frozen=True)\nclass S309Rx6Rx2A:\n name: str\n values: Tuple[float, ...]\n\n @staticmethod\n def create(name: str, values: Iterable[float]) -> \"S309Rx6Rx2A\":\n vals = tuple(float(v) for v in values)\n if not vals:\n raise ValueError(\"values must be non-empty\")\n return S309Rx6Rx2A(name=name, values=vals)\n\n def add(self, v: float) -> \"S309Rx6Rx2A\":\n return S309Rx6Rx2A(name=self.name, values=self.values + (float(v),))\n\n def mean(self) -> float:\n return sum(self.values) / len(self.values)\n\n# test_wxt1d8xs_m.py\nimport pytest\nfrom wxt1d8xs_m import S309Rx6Rx2A\n\ndef test_mean_and_add():\n c = S309Rx6Rx2A.create(\"a\", [1, 2, 3])\n assert c.mean() == 2.0\n assert c.add(5).mean() == (1 + 2 + 3 + 5) / 4\n\ndef test_empty_raises():\n with pytest.raises(ValueError):\n S309Rx6Rx2A.create(\"x\", [])", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: Language: Go\nFramework/tooling: net/http\nDomain: artifact registry\nLogic challenge: slow cold start\nTask type: multi_file_migration_repair\nDifficulty: hard\n\nReturn a rigorous engineering answer:\n- identify the hidden root cause or logical failure\n- present the corrected implementation\n- add tests that prove the fix\n- list verification commands\n- explain why naive fixes are insufficient when relevant\n\nRepository sketch:\nrepo/\n cmd/server/main.go\n internal/service/service.go\n internal/store/store.go\n internal/api/api.go\n service_test.go\n go.mod\n\nFocus: Focus on staff-level problem solving with multi-file patches, rollout implications, performance and security tradeoffs.\n\nassistant: Diagnosis:\n- Staff-level diagnosis: slow cold start impacts correctness, operability, and future maintenance, so the fix must be minimal where possible but complete where necessary.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```go\npackage service\n\nimport \"fmt\"\n\nfunc NormalizePayload(payload map[string]any) map[string]any {\n\tout := make(map[string]any)\n\tfor k, v := range payload {\n\t\tif v == nil {\n\t\t\tcontinue\n\t\t}\n\t\tout[k] = v\n\t}\n\treturn out\n}\n\nfunc Handle(payload map[string]any) (map[string]any, error) {\n\tclean := NormalizePayload(payload)\n\tif _, ok := clean[\"id\"]; !ok {\n\t\treturn nil, fmt.Errorf(\"missing id\")\n\t}\n\treturn map[string]any{\"ok\": true, \"data\": clean}, nil\n}\n```\n\nTests:\n```go\npackage service\n\nimport \"testing\"\n\nfunc TestHandle(t *testing.T) {\n\tgot, err := Handle(map[string]any{\"id\": 7, \"name\": \"ok\", \"unused\": nil})\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tif got[\"ok\"] != true {\n\t\tt.Fatalf(\"expected ok=true\")\n\t}\n\tif _, err := Handle(map[string]any{\"name\": \"x\"}); err == nil {\n\t\tt.Fatalf(\"expected missing id error\")\n\t}\n}\n```\n\nVerification:\n- `go test ./...`\n- `go vet ./...`\n\nEngineering notes:\n- Language: Go\n- Framework/tooling: net/http\n- Stack context: FastAPI, PostgreSQL, Redis, Celery, pytest, Docker\n- Domain: artifact registry\n- Task type: multi_file_migration_repair\n- Difficulty: hard\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Refactor to modern typed Python with immutability and tests.\n\nFile: elclkv4vh.py\n```python\nclass Ybi4N8:\n def __init__(self, name, values):\n self.name = name\n self.values = list(values)\n def add(self, v):\n self.values.append(v)\n def mean(self):\n s = 0\n for x in self.values:\n s += x\n return s / len(self.values)\n```\n\nReturn full new elclkv4vh.py and test_elclkv4vh.py.\n\n# elclkv4vh.py\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom typing import Iterable, Tuple\n\n@dataclass(frozen=True)\nclass Ybi4N8:\n name: str\n values: Tuple[float, ...]\n\n @staticmethod\n def create(name: str, values: Iterable[float]) -> \"Ybi4N8\":\n vals = tuple(float(v) for v in values)\n if not vals:\n raise ValueError(\"values must be non-empty\")\n return Ybi4N8(name=name, values=vals)\n\n def add(self, v: float) -> \"Ybi4N8\":\n return Ybi4N8(name=self.name, values=self.values + (float(v),))\n\n def mean(self) -> float:\n return sum(self.values) / len(self.values)\n\n# test_elclkv4vh.py\nimport pytest\nfrom elclkv4vh import Ybi4N8\n\ndef test_mean_and_add():\n c = Ybi4N8.create(\"a\", [1, 2, 3])\n assert c.mean() == 2.0\n assert c.add(5).mean() == (1 + 2 + 3 + 5) / 4\n\ndef test_empty_raises():\n with pytest.raises(ValueError):\n Ybi4N8.create(\"x\", [])", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Task type: lockfree_primitive\nScenario: rate limit gateway\nDomain focus: kernel primitives\nPrimary language: cpp\nDifficulty: hard\nScale/SLO: 50 TB/day ingestion\nComponent: component_gzhxdaiy\nConstraints: explicit contracts and invariants, include failure modes and recovery, avoid data races and undefined behavior, include security threat model (defensive only), include deterministic replay plan, assume adversarial inputs; validate everything\nAssume schema changes every sprint; must be backward compatible.\nDeliverable: Design a lock-free primitive with memory ordering reasoning and stress tests (no UB).\n\nOutput: elite engineering answer optimized for correctness, performance, and operability.\n**Contract**\n- Inputs validated at the boundary; explicit error taxonomy.\n- Idempotency for side effects via request_id; deterministic replay.\n- Backward compatibility: additive changes by default; versioned breaking changes.\n**Invariants**\n- Liveness: under bounded faults and stable network, progress occurs.\n- Isolation: tenant boundary enforced; no cross-tenant reads/writes.\n- Safety: state transitions preserve invariants; no partial commit leaks.\n**Failure modes & recovery**\n- Data corruption: checksums + scrubber; quarantine and rebuild from replicas/snapshots.\n- Crash during commit: WAL replay completes or transaction aborts; no torn writes.\n- Duplicate requests: de-duplicate by (tenant, request_id) returning cached response.\n**Security posture (defensive)**\n- Threat model: auth/authz, injection, replay/abuse, supply chain.\n- Least privilege; secrets in managed store; audit logs for sensitive ops.\n- Input normalization, parameterized queries, path traversal protections.\n**Verification strategy**\n- Canary + shadow traffic; invariants checked in production via assertions/metrics.\n- Fuzzing of parsers/framers/validators with corpus seeds.\n- Property tests against a pure reference model (state machine).\n\n**Snippet**\n```rust\n// Skeleton: SPSC ring buffer with acquire/release (outline)\nuse std::sync::atomic::{AtomicUsize, Ordering};\n\npub struct Ring {\n buf: Vec>,\n head: AtomicUsize,\n tail: AtomicUsize,\n cap: usize,\n}\n\n// Correctness sketch: producer uses Release on tail store, consumer uses Acquire on tail load.\n```\n\nHard checks: fault injection tests gate merges; perf thresholds enforced in CI.", "source": "WithinUsAI/Omega_Genesis_Coder_100k"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: Language: JavaScript\nFramework/tooling: Playwright\nDomain: notification service\nLogic challenge: mismatched API contract\nTask type: multi_service_security_patch\nDifficulty: expert\n\nReturn a rigorous engineering answer:\n- identify the hidden root cause or logical failure\n- present the corrected implementation\n- add tests that prove the fix\n- list verification commands\n- explain why naive fixes are insufficient when relevant\n\nRepository sketch:\nrepo/\n src/\n api.js\n service.js\n utils.js\n tests/\n api.test.js\n package.json\n\nFocus: Focus on staff-level problem solving with multi-file patches, rollout implications, performance and security tradeoffs.\n\nassistant: Diagnosis:\n- Staff-level diagnosis: mismatched API contract impacts correctness, operability, and future maintenance, so the fix must be minimal where possible but complete where necessary.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```javascript\ntype Payload = Record;\n\nexport function normalizePayload(payload: Payload): Payload {\n if (!payload || typeof payload !== \"object\" || Array.isArray(payload)) {\n throw new TypeError(\"payload must be a plain object\");\n }\n return Object.fromEntries(\n Object.entries(payload)\n .filter(([, value]) => value !== null && value !== undefined)\n .map(([key, value]) => [String(key).trim(), value])\n );\n}\n\nexport function handleMismatchedApiContract(payload: Payload) {\n const clean = normalizePayload(payload);\n if (!(\"id\" in clean)) {\n return { ok: false, data: {}, error: \"missing id\" };\n }\n return { ok: true, data: clean, error: null };\n}\n```\n\nTests:\n```javascript\nimport { describe, it, expect } from \"vitest\";\nimport { handleMismatchedApiContract } from \"../src/service\";\n\ndescribe(\"handler\", () => {\n it(\"accepts valid input\", () => {\n expect(handleMismatchedApiContract({ id: 7, name: \"ok\", unused: null })).toEqual({\n ok: true,\n data: { id: 7, name: \"ok\" },\n error: null\n });\n });\n\n it(\"rejects missing id\", () => {\n expect(handleMismatchedApiContract({ name: \"x\" }).error).toMatch(/missing id/);\n });\n});\n```\n\nVerification:\n- `npm test`\n- `npm run lint`\n\nEngineering notes:\n- Language: JavaScript\n- Framework/tooling: Playwright\n- Stack context: GitHub Actions, Docker Compose, Kubernetes, Terraform\n- Domain: notification service\n- Task type: multi_service_security_patch\n- Difficulty: expert\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "Add a clear docstring and type hints to this function:\n\n```python\ndef f14090(s):\n return ''.join(x for x in s if x.isalnum()).lower()\n```\n\n```python\nfrom __future__ import annotations\n\ndef f14090(s: str) -> str:\n \"\"\"Normalize a string: keep only alphanumerics and lowercase the result.\"\"\"\n return \"\".join(ch for ch in s if ch.isalnum()).lower()\n```", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: Project domain: reporting engine\nImplementation stack: Airflow, dbt, DuckDB, MinIO, pytest\nSoftware delivery problem: websocket reconnect storm\nTask type: rollback_safe_migration\nDifficulty: hard\n\nReturn a complete delivery-grade response with:\n- diagnosis or design reasoning\n- implementation\n- test plan or tests\n- rollout plan\n- rollback or compatibility note\n- verification commands\n\nRepository sketch:\nrepo/\n scripts/\n run.sh\n deploy.sh\n tests/\n smoke.sh\n\nFocus: Focus on shipping production software with rollout safety, acceptance criteria, telemetry, and maintenance quality.\n\nassistant: Diagnosis:\n- Root cause or delivery blocker: websocket reconnect storm needs both implementation work and a safe shipping plan.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```bash\n#!/usr/bin/env bash\nset -euo pipefail\n\ninput=\"${1:-}\"\nif [[ -z \"$input\" ]]; then\n echo \"missing input\" >&2\n exit 1\nfi\n\nprintf '%s\n' \"$input\" | tr -d '\r'\n```\n\nTests:\n```bash\noutput=\"$(bash scripts/run.sh \"abc\")\"\ntest \"$output\" = \"abc\"\n```\n\nVerification:\n- `bash tests/smoke.sh`\n- `shellcheck scripts/*.sh`\n\nEngineering notes:\n- Language: Bash\n- Framework/tooling: awk\n- Stack context: Airflow, dbt, DuckDB, MinIO, pytest\n- Domain: reporting engine\n- Task type: rollback_safe_migration\n- Difficulty: hard\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Refactor to modern typed Python with immutability and tests.\n\nFile: tdb_ve.py\n```python\nclass G9Uqwsvn:\n def __init__(self, name, values):\n self.name = name\n self.values = list(values)\n def add(self, v):\n self.values.append(v)\n def mean(self):\n s = 0\n for x in self.values:\n s += x\n return s / len(self.values)\n```\n\nReturn full new tdb_ve.py and test_tdb_ve.py.\n\n# tdb_ve.py\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom typing import Iterable, Tuple\n\n@dataclass(frozen=True)\nclass G9Uqwsvn:\n name: str\n values: Tuple[float, ...]\n\n @staticmethod\n def create(name: str, values: Iterable[float]) -> \"G9Uqwsvn\":\n vals = tuple(float(v) for v in values)\n if not vals:\n raise ValueError(\"values must be non-empty\")\n return G9Uqwsvn(name=name, values=vals)\n\n def add(self, v: float) -> \"G9Uqwsvn\":\n return G9Uqwsvn(name=self.name, values=self.values + (float(v),))\n\n def mean(self) -> float:\n return sum(self.values) / len(self.values)\n\n# test_tdb_ve.py\nimport pytest\nfrom tdb_ve import G9Uqwsvn\n\ndef test_mean_and_add():\n c = G9Uqwsvn.create(\"a\", [1, 2, 3])\n assert c.mean() == 2.0\n assert c.add(5).mean() == (1 + 2 + 3 + 5) / 4\n\ndef test_empty_raises():\n with pytest.raises(ValueError):\n G9Uqwsvn.create(\"x\", [])", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Refactor to modern typed Python with immutability and tests.\n\nFile: b8486vby8fa.py\n```python\nclass Ej38Pu910Xd:\n def __init__(self, name, values):\n self.name = name\n self.values = list(values)\n def add(self, v):\n self.values.append(v)\n def mean(self):\n s = 0\n for x in self.values:\n s += x\n return s / len(self.values)\n```\n\nReturn full new b8486vby8fa.py and test_b8486vby8fa.py.\n\n# b8486vby8fa.py\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom typing import Iterable, Tuple\n\n@dataclass(frozen=True)\nclass Ej38Pu910Xd:\n name: str\n values: Tuple[float, ...]\n\n @staticmethod\n def create(name: str, values: Iterable[float]) -> \"Ej38Pu910Xd\":\n vals = tuple(float(v) for v in values)\n if not vals:\n raise ValueError(\"values must be non-empty\")\n return Ej38Pu910Xd(name=name, values=vals)\n\n def add(self, v: float) -> \"Ej38Pu910Xd\":\n return Ej38Pu910Xd(name=self.name, values=self.values + (float(v),))\n\n def mean(self) -> float:\n return sum(self.values) / len(self.values)\n\n# test_b8486vby8fa.py\nimport pytest\nfrom b8486vby8fa import Ej38Pu910Xd\n\ndef test_mean_and_add():\n c = Ej38Pu910Xd.create(\"a\", [1, 2, 3])\n assert c.mean() == 2.0\n assert c.add(5).mean() == (1 + 2 + 3 + 5) / 4\n\ndef test_empty_raises():\n with pytest.raises(ValueError):\n Ej38Pu910Xd.create(\"x\", [])", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Fix a bug and add tests.\n\nFile: q0td7po_0.py\n```python\ndef saxuxe(n: int) -> int:\n \"\"\"Sum 1..n inclusive.\"\"\"\n if n < 0:\n raise ValueError(\"n must be non-negative\")\n total = 0\n for k in range(n): # BUG: should include n\n total += k\n return total\n```\n\nReturn unified diffs for q0td7po_0.py and test_q0td7po_0.py (pytest).\n\n*** Begin Patch\n*** Update File: q0td7po_0.py\n@@\n def saxuxe(n: int) -> int:\n@@\n total = 0\n- for k in range(n): # BUG: should include n\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_q0td7po_0.py\n+import pytest\n+from q0td7po_0 import saxuxe\n+\n+def test_zero():\n+ assert saxuxe(0) == 0\n+\n+def test_one():\n+ assert saxuxe(1) == 1\n+\n+def test_small():\n+ assert saxuxe(7) == 28\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ saxuxe(-1)\n+\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Produce an offline-first self-evolving code assistant architecture named `mdr2e38z`.\nMust include: module layout, patch-safety policy, evaluation gates (tests/lint/types), versioned memory index.\n\nArchitecture: `mdr2e38z` (offline-first, self-evolving)\n\nModules\n- core/loop.py: evolve → validate → accept/reject (bounded iterations)\n- patching/: diff builder, safe apply, atomic writes, rollback points\n- policy/: allowlist paths, deny globs (.git/, __pycache__/, binaries), patch size caps\n- signals/: parse pytest/ruff/mypy into normalized findings\n- memory/index.jsonl: append-only snapshots (hashes, metrics, rationale)\n\nSafety gates\n- refuse path traversal/symlink escapes; never edit binaries\n- accept only if tests/lint/types stay green or improve", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Produce an offline-first self-evolving code assistant architecture named `nkt52r`.\nMust include: module layout, patch-safety policy, evaluation gates (tests/lint/types), versioned memory index.\n\nArchitecture: `nkt52r` (offline-first, self-evolving)\n\nModules\n- core/loop.py: evolve → validate → accept/reject (bounded iterations)\n- patching/: diff builder, safe apply, atomic writes, rollback points\n- policy/: allowlist paths, deny globs (.git/, __pycache__/, binaries), patch size caps\n- signals/: parse pytest/ruff/mypy into normalized findings\n- memory/index.jsonl: append-only snapshots (hashes, metrics, rationale)\n\nSafety gates\n- refuse path traversal/symlink escapes; never edit binaries\n- accept only if tests/lint/types stay green or improve", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Design a production system for education supporting background jobs.\nTarget platform: mobile (Android Kotlin).\nRequirements: APIs, data model, scaling strategy, failure modes, and security.\nConstraints: must be easy to extend, must be performant under load, must avoid global state, must include tests, must be secure-by-default.\nDifficulty: expert. Assume PII must be protected.\n\nOutput: actionable implementation and verification artifacts.\nDeliverable: system design with APIs, data model, and operational plan.\n\n**High-level architecture**\n- Edge: API Gateway + WAF\n- Core service: stateless app pods behind L7 LB\n- Data: Postgres (primary), Redis (cache + rate limit tokens), Object storage (uploads if needed)\n- Async: message queue (e.g., SQS/Rabbit) + worker pool for background jobs\n- Observability: structured logs + metrics + tracing\n\n**APIs (example)**\n- `POST /v1/{resource}` create (idempotent via `Idempotency-Key`)\n- `GET /v1/{resource}/{id}` read\n- `POST /v1/{resource}/{id}:action` command endpoint when side effects exist\n\n**Data model (Postgres)**\n- `resources(id UUID PK, tenant_id UUID, status TEXT, payload JSONB, created_at, updated_at)`\n- Unique constraint for idempotency: `(tenant_id, idempotency_key)` in a separate table:\n - `idempotency(tenant_id, key TEXT, request_hash TEXT, response JSONB, created_at, PRIMARY KEY(tenant_id,key))`\n\n**Scaling**\n- App layer scales horizontally; keep sessions out of process.\n- Cache reads in Redis; write-through invalidation on mutations.\n- Use connection pooling; consider read replicas for heavy reads.\n\n**Failure modes**\n- Retries: only for safe/ idempotent operations; exponential backoff + jitter.\n- Partial failures: background jobs must be idempotent; use a de-dup key.\n\n**Security**\n- AuthN: JWT/OIDC; AuthZ: RBAC/ABAC with tenant isolation\n- Validate all inputs; enforce per-tenant quotas/rate limits.\n\n**Rollout**\n- Dark launch + feature flags; canary; rapid rollback by toggling flags.\n\n\nHard-mode checks: concurrency safety, idempotency, and rollback validated; add chaos tests where feasible.", "source": "WithinUsAI/GOD_Coder_100k"} {"text": "Write pytest tests for `f17745`.\n\n```python\ndef f17745(a: int, b: int) -> int:\n return a*a + b*b\n```\nInclude edge cases and a property-style check.\n\n```python\nimport random\nfrom m02535 import f17745\n\ndef test_known():\n assert f17745(3,4) == 25\n\ndef test_zero():\n assert f17745(0,0) == 0\n\ndef test_property_nonnegative():\n for _ in range(200):\n a=random.randint(-50,50)\n b=random.randint(-50,50)\n assert f17745(a,b) >= 0\n```", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: Language: YAML\nFramework/tooling: Kubernetes\nDomain: job scheduler\nLogic challenge: unsafe deserialization\nTask type: concurrency_fix\nDifficulty: medium\n\nReturn a rigorous engineering answer:\n- identify the hidden root cause or logical failure\n- present the corrected implementation\n- add tests that prove the fix\n- list verification commands\n- explain why naive fixes are insufficient when relevant\n\nRepository sketch:\nrepo/\n .github/workflows/ci.yml\n docker-compose.yml\n deploy/\n app.yaml\n\nFocus: Focus on strong structured logic with edge cases, data validation, and concurrency safety.\n\nassistant: Diagnosis:\n- Root cause: the failure around unsafe deserialization is caused by missing validation, weak edge-case handling, or unsafe lifecycle behavior in the current implementation.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```yaml\nname: ci\non: [push, pull_request]\njobs:\n test:\n runs-on: ubuntu-latest\n steps:\n - uses: actions/checkout@v4\n - name: Validate\n run: echo \"validated\"\n```\n\nTests:\n```yaml\n# Verification:\n# - validate syntax\n# - run smoke workflow\n# - fail fast on broken config\n```\n\nVerification:\n- `validate workflow syntax`\n- `run CI smoke job`\n\nEngineering notes:\n- Language: YAML\n- Framework/tooling: Kubernetes\n- Stack context: FastAPI, PostgreSQL, Redis, Celery, pytest, Docker\n- Domain: job scheduler\n- Task type: concurrency_fix\n- Difficulty: medium\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Fix a bug and add tests.\n\nFile: ob3ab92.py\n```python\ndef ui_78zb(n: int) -> int:\n \"\"\"Sum 1..n inclusive.\"\"\"\n if n < 0:\n raise ValueError(\"n must be non-negative\")\n total = 0\n for k in range(n): # BUG: should include n\n total += k\n return total\n```\n\nReturn unified diffs for ob3ab92.py and test_ob3ab92.py (pytest).\n\n*** Begin Patch\n*** Update File: ob3ab92.py\n@@\n def ui_78zb(n: int) -> int:\n@@\n total = 0\n- for k in range(n): # BUG: should include n\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_ob3ab92.py\n+import pytest\n+from ob3ab92 import ui_78zb\n+\n+def test_zero():\n+ assert ui_78zb(0) == 0\n+\n+def test_one():\n+ assert ui_78zb(1) == 1\n+\n+def test_small():\n+ assert ui_78zb(7) == 28\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ ui_78zb(-1)\n+\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Improve typing and robustness of a Python module used for data modeling.\nRequirements: provide type-safe APIs (generics/protocols where appropriate) and include tests.\nConstraints: must include tests, must include type hints, must be streaming-friendly.\nDifficulty: easy. Provide helpful exceptions with actionable messages.\n\nDeliverable: production-ready reference solution.\n```python\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom typing import Callable, Generic, Iterable, Protocol, TypeVar\n\nT = TypeVar(\"T\")\nR = TypeVar(\"R\")\n\nclass Mapper(Protocol[T, R]):\n def __call__(self, x: T) -> R: ...\n\n@dataclass(frozen=True, slots=True)\nclass Batch(Generic[T]):\n items: tuple[T, ...]\n\ndef map_batch(batch: Batch[T], fn: Mapper[T, R]) -> Batch[R]:\n return Batch(items=tuple(fn(x) for x in batch.items))\n\ndef chunked(xs: Iterable[T], size: int) -> Iterable[Batch[T]]:\n if size <= 0:\n raise ValueError(\"size must be > 0\")\n buf: list[T] = []\n for x in xs:\n buf.append(x)\n if len(buf) == size:\n yield Batch(items=tuple(buf))\n buf.clear()\n if buf:\n yield Batch(items=tuple(buf))\n```\n\n```python\nimport pytest\nfrom module_under_test import Batch, map_batch, chunked\n\ndef test_map_batch():\n b = Batch(items=(1,2,3))\n assert map_batch(b, lambda x: x*2).items == (2,4,6)\n\ndef test_chunked():\n out = list(chunked([1,2,3,4,5], 2))\n assert [b.items for b in out] == [(1,2),(3,4),(5,)]\n```", "source": "WithinUsAI/python_GOD_coder_100k"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: Language: Go\nFramework/tooling: sqlc\nDomain: repo automation\nLogic challenge: memory leak in AST cache\nTask type: backwards_compatible_redesign\nDifficulty: hard\n\nReturn a rigorous engineering answer:\n- identify the hidden root cause or logical failure\n- present the corrected implementation\n- add tests that prove the fix\n- list verification commands\n- explain why naive fixes are insufficient when relevant\n\nRepository sketch:\nrepo/\n cmd/server/main.go\n internal/service/service.go\n internal/store/store.go\n internal/api/api.go\n service_test.go\n go.mod\n\nFocus: Focus on staff-level problem solving with multi-file patches, rollout implications, performance and security tradeoffs.\n\nassistant: Diagnosis:\n- Staff-level diagnosis: memory leak in AST cache impacts correctness, operability, and future maintenance, so the fix must be minimal where possible but complete where necessary.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```go\npackage service\n\nimport \"fmt\"\n\nfunc NormalizePayload(payload map[string]any) map[string]any {\n\tout := make(map[string]any)\n\tfor k, v := range payload {\n\t\tif v == nil {\n\t\t\tcontinue\n\t\t}\n\t\tout[k] = v\n\t}\n\treturn out\n}\n\nfunc Handle(payload map[string]any) (map[string]any, error) {\n\tclean := NormalizePayload(payload)\n\tif _, ok := clean[\"id\"]; !ok {\n\t\treturn nil, fmt.Errorf(\"missing id\")\n\t}\n\treturn map[string]any{\"ok\": true, \"data\": clean}, nil\n}\n```\n\nTests:\n```go\npackage service\n\nimport \"testing\"\n\nfunc TestHandle(t *testing.T) {\n\tgot, err := Handle(map[string]any{\"id\": 7, \"name\": \"ok\", \"unused\": nil})\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tif got[\"ok\"] != true {\n\t\tt.Fatalf(\"expected ok=true\")\n\t}\n\tif _, err := Handle(map[string]any{\"name\": \"x\"}); err == nil {\n\t\tt.Fatalf(\"expected missing id error\")\n\t}\n}\n```\n\nVerification:\n- `go test ./...`\n- `go vet ./...`\n\nEngineering notes:\n- Language: Go\n- Framework/tooling: sqlc\n- Stack context: Spring Boot, PostgreSQL, JUnit, Gradle, Docker, GitHub Actions\n- Domain: repo automation\n- Task type: backwards_compatible_redesign\n- Difficulty: hard\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "Fix the bug and add pytest tests.\n\n```python\ndef f86082(n: int) -> int:\n # sum 1..n inclusive\n if n < 0: raise ValueError\n total = 0\n for k in range(n): # BUG\n total += k\n return total\n```\nReturn unified diffs for `m83726.py` and `test_m83726.py`.\n\n*** Begin Patch\n*** Update File: m83726.py\n@@\n def f86082(n: int) -> int:\n@@\n- for k in range(n): # BUG\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_m83726.py\n+import pytest\n+from m83726 import f86082\n+\n+def test_small():\n+ assert f86082(7) == 28\n+\n+def test_zero():\n+ assert f86082(0) == 0\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ f86082(-1)\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: Language: C++\nFramework/tooling: Catch2\nDomain: model serving gateway\nLogic challenge: streaming timeout handling\nTask type: cross_stack_outage_fix\nDifficulty: hard\n\nReturn a rigorous engineering answer:\n- identify the hidden root cause or logical failure\n- present the corrected implementation\n- add tests that prove the fix\n- list verification commands\n- explain why naive fixes are insufficient when relevant\n\nRepository sketch:\nrepo/\n src/main.cpp\n src/service.cpp\n include/service.h\n tests/test_service.cpp\n CMakeLists.txt\n\nFocus: Focus on staff-level problem solving with multi-file patches, rollout implications, performance and security tradeoffs.\n\nassistant: Diagnosis:\n- Staff-level diagnosis: streaming timeout handling impacts correctness, operability, and future maintenance, so the fix must be minimal where possible but complete where necessary.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```cpp\n#include \n#include \n\nusing Payload = std::unordered_map;\n\nPayload normalize_payload(const Payload& in) {\n Payload out;\n for (const auto& [k, v] : in) {\n if (!v.empty()) out[k] = v;\n }\n return out;\n}\n```\n\nTests:\n```cpp\nTEST_CASE(\"normalize_payload filters empty values\") {\n Payload in{{\"id\",\"7\"},{\"name\",\"\"}};\n auto out = normalize_payload(in);\n REQUIRE(out.count(\"id\") == 1);\n REQUIRE(out.count(\"name\") == 0);\n}\n```\n\nVerification:\n- `cmake --build build`\n- `ctest --test-dir build`\n\nEngineering notes:\n- Language: C++\n- Framework/tooling: Catch2\n- Stack context: GitHub Actions, Docker Compose, Kubernetes, Terraform\n- Domain: model serving gateway\n- Task type: cross_stack_outage_fix\n- Difficulty: hard\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "Implement a mobile feature for education: rate limiting.\nTarget platform: mobile.\nRequirements: offline-safe behavior, UI state handling, and tests.\nConstraints: must be performant under load, must include type hints where applicable, must be easy to extend, must include clear error handling, must include documentation/comments.\nDifficulty: expert. Assume untrusted input; validate everything.\n\nOutput: actionable implementation and verification artifacts.\nDeliverable: offline-safe mobile approach (Kotlin) + key snippets.\n\n```kotlin\n// Repository.kt\ninterface Api {\n suspend fun fetch(): List\n suspend fun post(item: Item): Item\n}\n\ninterface LocalStore {\n suspend fun getAll(): List\n suspend fun upsert(items: List)\n suspend fun enqueuePending(item: Item)\n suspend fun pending(): List\n suspend fun markSent(id: String)\n}\n\nclass Repo(private val api: Api, private val db: LocalStore) {\n suspend fun sync(): List {\n val local = db.getAll()\n // optimistic: show local first, then refresh\n return try {\n val remote = api.fetch()\n db.upsert(remote)\n flushPending()\n remote\n } catch (e: Exception) {\n local\n }\n }\n\n suspend fun createOfflineFirst(item: Item): Item {\n db.enqueuePending(item)\n return item\n }\n\n private suspend fun flushPending() {\n for (p in db.pending()) {\n try {\n api.post(p)\n db.markSent(p.id)\n } catch (_: Exception) {\n // keep pending; retry later with backoff in a WorkManager job\n }\n }\n }\n}\n```\n\nTesting guidance:\n- Unit test Repo with fake Api/LocalStore.\n- Integration test offline queue + retry policy (WorkManager).\n\n\nHard-mode checks: concurrency safety, idempotency, and rollback validated; add chaos tests where feasible.", "source": "WithinUsAI/GOD_Coder_100k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Fix a bug and add tests.\n\nFile: lc9ui23hp_.py\n```python\ndef k1lh2w(n: int) -> int:\n \"\"\"Sum 1..n inclusive.\"\"\"\n if n < 0:\n raise ValueError(\"n must be non-negative\")\n total = 0\n for k in range(n): # BUG: should include n\n total += k\n return total\n```\n\nReturn unified diffs for lc9ui23hp_.py and test_lc9ui23hp_.py (pytest).\n\n*** Begin Patch\n*** Update File: lc9ui23hp_.py\n@@\n def k1lh2w(n: int) -> int:\n@@\n total = 0\n- for k in range(n): # BUG: should include n\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_lc9ui23hp_.py\n+import pytest\n+from lc9ui23hp_ import k1lh2w\n+\n+def test_zero():\n+ assert k1lh2w(0) == 0\n+\n+def test_one():\n+ assert k1lh2w(1) == 1\n+\n+def test_small():\n+ assert k1lh2w(7) == 28\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ k1lh2w(-1)\n+\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Create a comprehensive test plan and automated tests for webhooks in a content moderation product.\nTarget platform: ML (PyTorch + serving).\nRequirements: unit/integration tests, edge cases, load tests strategy, and CI gates.\nConstraints: must be observable (logs/metrics/traces), must be easy to extend, must be performant under load, must include clear error handling.\nDifficulty: expert. Assume strict latency budget (p95 < 200ms).\n\nOutput: design + implementation guidance suitable for shipping.\nDeliverable: test plan + automation guidance.\n\n**Unit tests**\n- Validation: malformed payloads rejected with correct codes.\n- AuthZ: tenant boundary enforced.\n- Idempotency: replay returns same response; conflicting reuse yields 409.\n\n**Integration tests**\n- DB transaction behavior; unique constraints.\n- Cache behavior: correctness under concurrent requests.\n\n**Load tests**\n- 10k RPS target: measure p95 latency, error rate, saturation.\n\n**CI gates**\n- Lint + typecheck + unit tests required.\n- Coverage threshold for critical modules.\n- Block merge on flaky test detection.\n\n\nHard-mode checks: concurrency safety, idempotency, and rollback validated; add chaos tests where feasible.", "source": "WithinUsAI/GOD_Coder_100k"} {"text": "Build an elite-grade solution in the domain of sre/observability for scenario: document indexing.\nPrimary language: go.\nDifficulty: hard.\nConstraints: include tests or verification strategy, make the interface contract explicit, document performance characteristics, assume untrusted inputs; validate and sanitize, include invariants and failure modes.\nComponent: component_hhkvqlr.\nAssume cold-start and memory limits are tight.\nTask: Implement or outline a storage/indexing subsystem (LSM/B-Tree, WAL, snapshots). Include transaction/consistency considerations and benchmark plan.\n\nOutput: elite-grade engineering answer with contracts, edge cases, and verification.\nOutput: storage design + WAL + compaction + benchmarks.\n\n**Design**\n- WAL (append-only) for durability; fsync policy configurable.\n- Memtable (in-memory) → flush to immutable SSTables.\n- LSM compaction tiers; bloom filters per SSTable for point-lookups.\n- Manifest tracks SSTable set; atomic pointer swap on updates.\n\n**Correctness**\n- Crash recovery: replay WAL to rebuild memtable; manifest ensures last consistent set.\n- Reads: merge memtable + SSTables newest→oldest; tombstones override older values.\n\n**Bench plan**\n- Workloads: write-heavy, read-heavy, mixed; measure p50/p95 latency and write amplification.\n- Track compaction debt and space amplification.\n\n**Test plan**\n- Fuzz crash points: kill after WAL append / after manifest update; verify invariants on restart.\n\n\nHard checks: failure injection tests and performance regressions gated.", "source": "WithinUsAI/Elite_GOD_Coder_100k"} {"text": "Optimize while preserving behavior and order.\n\n```python\ndef f62299(xs):\n out=[]\n for x in xs:\n if x not in out: out.append(x)\n return out\n```\nReturn `m51757.py` with types and O(n) average.\n\n```python\n# m51757.py\nfrom __future__ import annotations\nfrom typing import Iterable, List, Set, TypeVar\nT=TypeVar(\"T\")\n\ndef f62299(xs: Iterable[T]) -> List[T]:\n \"\"\"Unique items preserving first-seen order.\"\"\"\n seen: Set[T]=set()\n out: List[T]=[]\n for x in xs:\n if x in seen: continue\n seen.add(x); out.append(x)\n return out\n```", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Provision infrastructure for a education workload providing real-time notifications.\nTarget platform: ML (scikit + batch).\nRequirements: IaC (Terraform or Kubernetes YAML), networking, secrets, autoscaling.\nConstraints: must include clear error handling, must be performant under load, must be observable (logs/metrics/traces), must be secure-by-default.\nDifficulty: easy. Assume mobile clients are occasionally offline.\n\nOutput: engineering-grade answer with edge cases covered.\nDeliverable: Kubernetes deployment + basic security posture.\n\n```yaml\napiVersion: apps/v1\nkind: Deployment\nmetadata:\n name: app\nspec:\n replicas: 3\n selector:\n matchLabels: { app: app }\n template:\n metadata:\n labels: { app: app }\n spec:\n containers:\n - name: app\n image: app:latest\n ports: [{ containerPort: 8080 }]\n readinessProbe:\n httpGet: { path: /healthz, port: 8080 }\n resources:\n requests: { cpu: \"200m\", memory: \"256Mi\" }\n limits: { cpu: \"1\", memory: \"1Gi\" }\n```\n\nAdditions:\n- NetworkPolicy to restrict egress/ingress.\n- Secrets via external secret store; rotate regularly.\n- HPA for autoscaling; PodDisruptionBudget for availability.\n\n\nChecks: input validation, tests, and safe defaults included.", "source": "WithinUsAI/GOD_Coder_100k"} {"text": "Design and implement an algorithm for validation.\nRequirements: define inputs/outputs, implement solution with complexity analysis, and include tests.\nConstraints: must include tests, stdlib-only, must provide clear error messages.\nDifficulty: hard. Avoid quadratic behavior on large inputs.\n\nDeliverable: corrected code and verification tests.\nProblem: compute rolling sums over events (ts:int,value:int) with window W seconds. Events may be out-of-order.\n\nComplexity: sorting O(n log n); window maintenance O(n); memory O(k).\n\n```python\nfrom __future__ import annotations\nfrom collections import deque\nfrom dataclasses import dataclass\nfrom typing import Iterable, List, Tuple\n\n@dataclass(frozen=True, slots=True)\nclass Event:\n ts: int\n value: int\n\ndef rolling_sum(events: Iterable[Event], window_s: int) -> List[Tuple[int,int]]:\n if window_s < 0:\n raise ValueError(\"window_s must be >= 0\")\n evs = sorted(events, key=lambda e: e.ts)\n q: deque[Event] = deque()\n s = 0\n out: List[Tuple[int,int]] = []\n for e in evs:\n q.append(e)\n s += e.value\n cutoff = e.ts - window_s\n while q and q[0].ts < cutoff:\n old = q.popleft()\n s -= old.value\n out.append((e.ts, s))\n return out\n```\n\n```python\nimport pytest\nfrom module_under_test import Event, rolling_sum\n\ndef test_rolling_sum():\n ev = [Event(10,1), Event(11,2), Event(20,5)]\n assert rolling_sum(ev, 5) == [(10,1),(11,3),(20,5)]\n```", "source": "WithinUsAI/python_GOD_coder_100k"} {"text": "Provision infrastructure for a customer support workload providing idempotent payments.\nTarget platform: backend (Node.js).\nRequirements: IaC (Terraform or Kubernetes YAML), networking, secrets, autoscaling.\nConstraints: must be production-ready, must include clear error handling, must include documentation/comments, must be observable (logs/metrics/traces), must be secure-by-default.\nDifficulty: easy. Assume strict latency budget (p95 < 200ms).\n\nOutput: production-oriented blueprint with code where appropriate.\nDeliverable: Kubernetes deployment + basic security posture.\n\n```yaml\napiVersion: apps/v1\nkind: Deployment\nmetadata:\n name: app\nspec:\n replicas: 3\n selector:\n matchLabels: { app: app }\n template:\n metadata:\n labels: { app: app }\n spec:\n containers:\n - name: app\n image: app:latest\n ports: [{ containerPort: 8080 }]\n readinessProbe:\n httpGet: { path: /healthz, port: 8080 }\n resources:\n requests: { cpu: \"200m\", memory: \"256Mi\" }\n limits: { cpu: \"1\", memory: \"1Gi\" }\n```\n\nAdditions:\n- NetworkPolicy to restrict egress/ingress.\n- Secrets via external secret store; rotate regularly.\n- HPA for autoscaling; PodDisruptionBudget for availability.\n\n\nChecks: input validation, tests, and safe defaults included.", "source": "WithinUsAI/GOD_Coder_100k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Optimize while preserving behavior.\n\nFile: i00gsb.py\n```python\ndef i5g4hrcrw(xs):\n out = []\n for x in xs:\n if x not in out:\n out.append(x)\n return out\n```\n\nRequirements: preserve first-seen order; O(n) average; add types + docstring.\n\n# i00gsb.py\nfrom __future__ import annotations\nfrom typing import Iterable, List, Set, TypeVar\n\nT = TypeVar(\"T\")\n\ndef i5g4hrcrw(xs: Iterable[T]) -> List[T]:\n \"\"\"Return unique items preserving first-seen order.\"\"\"\n seen: Set[T] = set()\n out: List[T] = []\n for x in xs:\n if x in seen:\n continue\n seen.add(x)\n out.append(x)\n return out", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Build an elite-grade solution in the domain of sre/observability for scenario: chat messaging.\nPrimary language: go.\nDifficulty: hard.\nConstraints: include tests or verification strategy, provide rollout and rollback guidance, document performance characteristics, design for backward compatibility and migrations, include invariants and failure modes.\nComponent: component_ycenrdv.\nAssume 50k RPS and p99 < 250ms.\nTask: Implement a concurrency primitive or subsystem (lock-free queue, thread pool, async runtime component). Explain memory ordering and correctness arguments; include stress tests.\n\nOutput: rigorous solution with invariants, failure modes, and performance notes.\nOutput: correctness-focused concurrency primitive + stress tests.\n\n**Primitive**\n- Bounded MPMC queue with backpressure (blocking push/pop) OR lock-free SPSC ring buffer.\n\n**Correctness notes**\n- For lock-free: use acquire/release semantics on head/tail indices.\n- Avoid ABA by monotonic counters; ring index = counter % capacity.\n\n**Stress tests**\n- Multi-thread producers/consumers; assert item multiset preserved.\n- Use time-bounded randomized schedules; detect deadlocks.\n\n\nHard checks: failure injection tests and performance regressions gated.", "source": "WithinUsAI/Elite_GOD_Coder_100k"} {"text": "Create a small, production-ready Python package for metrics aggregation.\nRequirements: include module code, CLI entrypoint, logging, and a minimal pyproject.toml.\nConstraints: must be easy to extend, must handle Windows paths safely.\nDifficulty: medium. Avoid quadratic behavior on large inputs.\n\nDeliverable: corrected code and verification tests.\nPackage layout:\n- mypkg/core.py\n- mypkg/cli.py\n- pyproject.toml\n\n```python\n# mypkg/core.py\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom typing import Iterable\nimport logging\n\nlog = logging.getLogger(__name__)\n\n@dataclass(frozen=True, slots=True)\nclass Result:\n total: int\n count: int\n\ndef aggregate(values: Iterable[int]) -> Result:\n total = 0\n count = 0\n for v in values:\n if not isinstance(v, int):\n raise TypeError(\"values must be ints\")\n total += v\n count += 1\n log.debug(\"aggregate count=%s total=%s\", count, total)\n return Result(total, count)\n```\n\n```python\n# mypkg/cli.py\nfrom __future__ import annotations\nimport argparse\nimport logging\nimport sys\nfrom .core import aggregate\n\ndef main(argv: list[str] | None = None) -> int:\n p = argparse.ArgumentParser(prog=\"mypkg\")\n p.add_argument(\"--log-level\", default=\"WARNING\")\n args = p.parse_args(argv)\n logging.basicConfig(level=getattr(logging, args.log_level.upper(), logging.WARNING))\n data: list[int] = []\n for line in sys.stdin:\n line = line.strip()\n if line:\n data.append(int(line))\n r = aggregate(data)\n print(f\"count={r.count} total={r.total}\")\n return 0\n```\n\n```toml\n# pyproject.toml\n[project]\nname = \"mypkg\"\nversion = \"0.1.0\"\nrequires-python = \">=3.10\"\n\n[project.scripts]\nmypkg = \"mypkg.cli:main\"\n```", "source": "WithinUsAI/python_GOD_coder_100k"} {"text": "Fix the bug and add pytest tests.\n\n```python\ndef f52695(n: int) -> int:\n # sum 1..n inclusive\n if n < 0: raise ValueError\n total = 0\n for k in range(n): # BUG\n total += k\n return total\n```\nReturn unified diffs for `m50385.py` and `test_m50385.py`.\n\n*** Begin Patch\n*** Update File: m50385.py\n@@\n def f52695(n: int) -> int:\n@@\n- for k in range(n): # BUG\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_m50385.py\n+import pytest\n+from m50385 import f52695\n+\n+def test_small():\n+ assert f52695(7) == 28\n+\n+def test_zero():\n+ assert f52695(0) == 0\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ f52695(-1)\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Fix a bug and add tests.\n\nFile: dpvhqoe1297b.py\n```python\ndef zy816w_q(n: int) -> int:\n \"\"\"Sum 1..n inclusive.\"\"\"\n if n < 0:\n raise ValueError(\"n must be non-negative\")\n total = 0\n for k in range(n): # BUG: should include n\n total += k\n return total\n```\n\nReturn unified diffs for dpvhqoe1297b.py and test_dpvhqoe1297b.py (pytest).\n\n*** Begin Patch\n*** Update File: dpvhqoe1297b.py\n@@\n def zy816w_q(n: int) -> int:\n@@\n total = 0\n- for k in range(n): # BUG: should include n\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_dpvhqoe1297b.py\n+import pytest\n+from dpvhqoe1297b import zy816w_q\n+\n+def test_zero():\n+ assert zy816w_q(0) == 0\n+\n+def test_one():\n+ assert zy816w_q(1) == 1\n+\n+def test_small():\n+ assert zy816w_q(7) == 28\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ zy816w_q(-1)\n+\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Optimize while preserving behavior.\n\nFile: tl48ns2uk.py\n```python\ndef w_tcqn36(xs):\n out = []\n for x in xs:\n if x not in out:\n out.append(x)\n return out\n```\n\nRequirements: preserve first-seen order; O(n) average; add types + docstring.\n\n# tl48ns2uk.py\nfrom __future__ import annotations\nfrom typing import Iterable, List, Set, TypeVar\n\nT = TypeVar(\"T\")\n\ndef w_tcqn36(xs: Iterable[T]) -> List[T]:\n \"\"\"Return unique items preserving first-seen order.\"\"\"\n seen: Set[T] = set()\n out: List[T] = []\n for x in xs:\n if x in seen:\n continue\n seen.add(x)\n out.append(x)\n return out", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Fix a bug and add tests.\n\nFile: khziv7j.py\n```python\ndef cbddsvb(n: int) -> int:\n \"\"\"Sum 1..n inclusive.\"\"\"\n if n < 0:\n raise ValueError(\"n must be non-negative\")\n total = 0\n for k in range(n): # BUG: should include n\n total += k\n return total\n```\n\nReturn unified diffs for khziv7j.py and test_khziv7j.py (pytest).\n\n*** Begin Patch\n*** Update File: khziv7j.py\n@@\n def cbddsvb(n: int) -> int:\n@@\n total = 0\n- for k in range(n): # BUG: should include n\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_khziv7j.py\n+import pytest\n+from khziv7j import cbddsvb\n+\n+def test_zero():\n+ assert cbddsvb(0) == 0\n+\n+def test_one():\n+ assert cbddsvb(1) == 1\n+\n+def test_small():\n+ assert cbddsvb(7) == 28\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ cbddsvb(-1)\n+\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Refactor to modern typed Python with immutability and tests.\n\nFile: nx6kmcb.py\n```python\nclass It56Lu1Vb:\n def __init__(self, name, values):\n self.name = name\n self.values = list(values)\n def add(self, v):\n self.values.append(v)\n def mean(self):\n s = 0\n for x in self.values:\n s += x\n return s / len(self.values)\n```\n\nReturn full new nx6kmcb.py and test_nx6kmcb.py.\n\n# nx6kmcb.py\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom typing import Iterable, Tuple\n\n@dataclass(frozen=True)\nclass It56Lu1Vb:\n name: str\n values: Tuple[float, ...]\n\n @staticmethod\n def create(name: str, values: Iterable[float]) -> \"It56Lu1Vb\":\n vals = tuple(float(v) for v in values)\n if not vals:\n raise ValueError(\"values must be non-empty\")\n return It56Lu1Vb(name=name, values=vals)\n\n def add(self, v: float) -> \"It56Lu1Vb\":\n return It56Lu1Vb(name=self.name, values=self.values + (float(v),))\n\n def mean(self) -> float:\n return sum(self.values) / len(self.values)\n\n# test_nx6kmcb.py\nimport pytest\nfrom nx6kmcb import It56Lu1Vb\n\ndef test_mean_and_add():\n c = It56Lu1Vb.create(\"a\", [1, 2, 3])\n assert c.mean() == 2.0\n assert c.add(5).mean() == (1 + 2 + 3 + 5) / 4\n\ndef test_empty_raises():\n with pytest.raises(ValueError):\n It56Lu1Vb.create(\"x\", [])", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Provision infrastructure for a document processing workload providing webhooks.\nTarget platform: infra (Terraform).\nRequirements: IaC (Terraform or Kubernetes YAML), networking, secrets, autoscaling.\nConstraints: must include type hints where applicable, must be easy to extend, must be production-ready.\nDifficulty: easy. Assume strict latency budget (p95 < 200ms).\n\nOutput: engineering-grade answer with edge cases covered.\nDeliverable: Kubernetes deployment + basic security posture.\n\n```yaml\napiVersion: apps/v1\nkind: Deployment\nmetadata:\n name: app\nspec:\n replicas: 3\n selector:\n matchLabels: { app: app }\n template:\n metadata:\n labels: { app: app }\n spec:\n containers:\n - name: app\n image: app:latest\n ports: [{ containerPort: 8080 }]\n readinessProbe:\n httpGet: { path: /healthz, port: 8080 }\n resources:\n requests: { cpu: \"200m\", memory: \"256Mi\" }\n limits: { cpu: \"1\", memory: \"1Gi\" }\n```\n\nAdditions:\n- NetworkPolicy to restrict egress/ingress.\n- Secrets via external secret store; rotate regularly.\n- HPA for autoscaling; PodDisruptionBudget for availability.\n\n\nChecks: input validation, tests, and safe defaults included.", "source": "WithinUsAI/GOD_Coder_100k"} {"text": "Task type: schema_evolution_contracts\nScenario: streaming ETL\nDomain focus: network protocols\nPrimary language: sql\nDifficulty: expert\nScale/SLO: 10k RPS peak\nComponent: component_dckkfpqb\nConstraints: include verification strategy, include failure modes and recovery, avoid data races and undefined behavior, include backward compatibility and migration plan, explicit contracts and invariants, include deterministic replay plan, assume adversarial inputs; validate everything\nAssume hostile inputs and targeted abuse patterns.\nDeliverable: Design schema evolution rules and compatibility tests; include migration plan and examples.\n\nOutput: contract-first solution with failure modes, security posture, and test/verification strategy.\n**Contract**\n- Inputs validated at the boundary; explicit error taxonomy.\n- Idempotency for side effects via request_id; deterministic replay.\n- Backward compatibility: additive changes by default; versioned breaking changes.\n**Invariants**\n- Liveness: under bounded faults and stable network, progress occurs.\n- Safety: state transitions preserve invariants; no partial commit leaks.\n- Isolation: tenant boundary enforced; no cross-tenant reads/writes.\n**Failure modes & recovery**\n- Network partition: minority cannot commit; clients receive retriable errors.\n- Duplicate requests: de-duplicate by (tenant, request_id) returning cached response.\n- Crash during commit: WAL replay completes or transaction aborts; no torn writes.\n**Security posture (defensive)**\n- Threat model: auth/authz, injection, replay/abuse, supply chain.\n- Least privilege; secrets in managed store; audit logs for sensitive ops.\n- Input normalization, parameterized queries, path traversal protections.\n**Verification strategy**\n- Canary + shadow traffic; invariants checked in production via assertions/metrics.\n- Fuzzing of parsers/framers/validators with corpus seeds.\n- Property tests against a pure reference model (state machine).\n\n**Snippet**\n```text\nImplementation sketch: factor pure state-machine core; adapters for I/O; add deterministic replay log.\n```\nExpert checks: state-machine proof sketch + model checking; upgrade/rollback rehearsed.", "source": "WithinUsAI/Omega_Genesis_Coder_100k"} {"text": "Task type: mechanized_spec\nScenario: multi-tenant event ingestion\nDomain focus: fault injection & chaos engineering\nPrimary language: lean\nDifficulty: expert\nScale/SLO: 50 TB/day ingestion\nComponent: component_isyolgat\nConstraints: include failure modes and recovery, include backward compatibility and migration plan, include security threat model (defensive only), include test vectors and fuzz strategy, include verification strategy, explicit contracts and invariants, avoid data races and undefined behavior\nAssume tight memory budget and cold-start constraints.\nDeliverable: Provide a mechanized-style spec outline (Lean-like), key definitions, and a proof plan. Include executable reference code skeleton and tests.\n\nOutput: rigorous design + invariants + verification plan + implementation sketch.\n**Contract**\n- Inputs validated at the boundary; explicit error taxonomy.\n- Idempotency for side effects via request_id; deterministic replay.\n- Backward compatibility: additive changes by default; versioned breaking changes.\n**Invariants**\n- Determinism: replay of the same event log yields identical outputs.\n- Safety: state transitions preserve invariants; no partial commit leaks.\n- Isolation: tenant boundary enforced; no cross-tenant reads/writes.\n**Failure modes & recovery**\n- Data corruption: checksums + scrubber; quarantine and rebuild from replicas/snapshots.\n- Crash during commit: WAL replay completes or transaction aborts; no torn writes.\n- Network partition: minority cannot commit; clients receive retriable errors.\n**Security posture (defensive)**\n- Threat model: auth/authz, injection, replay/abuse, supply chain.\n- Least privilege; secrets in managed store; audit logs for sensitive ops.\n- Input normalization, parameterized queries, path traversal protections.\n**Verification strategy**\n- Property tests against a pure reference model (state machine).\n- Fuzzing of parsers/framers/validators with corpus seeds.\n- Deterministic simulation with fault injection (crash/partition/latency).\n\n**Snippet**\n```lean\n-- Pseudo-Lean outline\nstructure State where\n ver : Nat\n val : Option ByteArray\n\ndef invariant (s : State) : Prop := True\n\ntheorem step_preserves_invariant :\n ∀ s, invariant s → ∀ s', Step s s' → invariant s' := by\n intro s hs s' hstep\n -- proof plan: case analysis on transition; trivial here\n trivial\n```\n\nExpert checks: state-machine proof sketch + model checking; upgrade/rollback rehearsed.", "source": "WithinUsAI/Omega_Genesis_Coder_100k"} {"text": "Build an elite-grade solution in the domain of stream processing for scenario: rate limiting gateway.\nPrimary language: sql.\nDifficulty: expert.\nConstraints: document performance characteristics, provide rollout and rollback guidance, make the interface contract explicit, avoid undefined behavior and data races.\nComponent: component_ugobpaw.\nAssume strict auditability and replayable history.\nTask: Write a precise interface contract, list invariants, and provide a lightweight formal/spec-style description (pseudo-TLA+/state machine) plus reference implementation skeleton and tests.\n\nOutput: elite-grade engineering answer with contracts, edge cases, and verification.\nOutput: contract + invariants + spec + reference skeleton.\n\n**Interface contract**\n- Commands: `Put(key, value, expected_version?)`, `Get(key)`, `Delete(key, expected_version?)`\n- Responses: `Ok(version, value?)`, `NotFound`, `Conflict(current_version)`, `InvalidInput`\n- Idempotency: client supplies `request_id`; server must de-duplicate per (tenant_id, request_id).\n\n**Invariants**\n1. Monotonic version per key (strictly increases on successful writes).\n2. Reads return latest committed value for a given consistency level.\n3. Exactly-once effect for a given `request_id` (at-most-once execution + replay response).\n4. Tenant isolation: keys are scoped by tenant_id.\n\n**State machine (pseudo)**\nState:\n- store: map[(tenant,key)] -> (version:int, value:bytes|tombstone)\n- seen: map[(tenant,request_id)] -> response\nTransition Put:\n- if request_id in seen: return seen[...]\n- validate input; if expected_version set and != current version -> Conflict\n- version' = version + 1; store[...] := (version', value); seen[...] := Ok(version', value)\n\n**Reference skeleton (Python)**\n```python\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom typing import Dict, Optional, Tuple\n\nclass Conflict(Exception): pass\nclass InvalidInput(ValueError): pass\n\n@dataclass(frozen=True, slots=True)\nclass Value:\n version: int\n data: Optional[bytes] # None == tombstone\n\n@dataclass(frozen=True, slots=True)\nclass Reply:\n kind: str\n version: Optional[int] = None\n data: Optional[bytes] = None\n\nclass KV:\n def __init__(self) -> None:\n self._store: Dict[Tuple[str,str], Value] = {}\n self._seen: Dict[Tuple[str,str], Reply] = {}\n\n def put(self, tenant: str, request_id: str, key: str, data: bytes, expected_version: Optional[int]=None) -> Reply:\n if not tenant or not request_id or not key:\n raise InvalidInput(\"tenant/request_id/key required\")\n de = self._seen.get((tenant, request_id))\n if de: \n return de\n cur = self._store.get((tenant, key), Value(0, None))\n if expected_version is not None and expected_version != cur.version:\n r = Reply(\"conflict\", version=cur.version)\n self._seen[(tenant, request_id)] = r\n return r\n nxt = Value(cur.version + 1, data)\n self._store[(tenant, key)] = nxt\n r = Reply(\"ok\", version=nxt.version)\n self._seen[(tenant, request_id)] = r\n return r\n```\n\n**Tests**\n- Determinism: same request_id → same reply.\n- Conflict detection and version monotonicity.\n\n\nExpert checks: state-machine reasoning, concurrency stress, and upgrade/rollback validated.", "source": "WithinUsAI/Elite_GOD_Coder_100k"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: System domain: data pipeline\nStack: Next.js, Node.js, Prisma, PostgreSQL, Playwright, Docker\nCross-layer incident: unsafe deserialization\nTask type: cache_consistency_patch\nDifficulty: hard\n\nSolve this as a complete-project engineer.\nOutput must include:\n- root cause across layers\n- final implementation patch\n- tests touching at least two layers\n- deployment or observability note\n- verification commands\n\nRepository sketch:\nrepo/\n migrations/\n 001_init.sql\n 002_add_index.sql\n queries/\n report.sql\n tests/\n report_cases.md\n\nFocus: Focus on multi-layer debugging across frontend, backend, database, CI, caching, and deployment.\n\nassistant: Diagnosis:\n- Root cause: unsafe deserialization crosses service boundaries, so the fix must align code, contracts, tests, and deployment behavior.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```sql\nWITH ranked AS (\n SELECT\n user_id,\n created_at,\n amount,\n ROW_NUMBER() OVER (PARTITION BY user_id ORDER BY created_at DESC, id DESC) AS rn\n FROM orders\n)\nSELECT user_id, created_at, amount\nFROM ranked\nWHERE rn = 1;\n```\n\nTests:\n```sql\n-- Correctness checks:\n-- 1) multiple rows per user\n-- 2) identical timestamps require deterministic tie-breaker\n-- 3) null values handled by business rules\n```\n\nVerification:\n- `run migration checks`\n- `run query correctness cases`\n\nEngineering notes:\n- Language: SQL\n- Framework/tooling: DuckDB\n- Stack context: Next.js, Node.js, Prisma, PostgreSQL, Playwright, Docker\n- Domain: data pipeline\n- Task type: cache_consistency_patch\n- Difficulty: hard\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "Build an elite-grade solution in the domain of ml systems for scenario: job scheduler.\nPrimary language: go.\nDifficulty: medium.\nConstraints: provide rollout and rollback guidance, include tests or verification strategy, assume untrusted inputs; validate and sanitize, design for backward compatibility and migrations.\nComponent: component_pbyrcgl.\nAssume compliance requires data deletion with proofs.\nTask: Implement a concurrency primitive or subsystem (lock-free queue, thread pool, async runtime component). Explain memory ordering and correctness arguments; include stress tests.\n\nOutput: production blueprint plus correctness arguments and test strategy.\nOutput: correctness-focused concurrency primitive + stress tests.\n\n**Primitive**\n- Bounded MPMC queue with backpressure (blocking push/pop) OR lock-free SPSC ring buffer.\n\n**Correctness notes**\n- For lock-free: use acquire/release semantics on head/tail indices.\n- Avoid ABA by monotonic counters; ring index = counter % capacity.\n\n**Stress tests**\n- Multi-thread producers/consumers; assert item multiset preserved.\n- Use time-bounded randomized schedules; detect deadlocks.\n\n\nChecks: boundary validation and deterministic behavior verified.", "source": "WithinUsAI/Elite_GOD_Coder_100k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Produce an offline-first self-evolving code assistant architecture named `tiono8`.\nMust include: module layout, patch-safety policy, evaluation gates (tests/lint/types), versioned memory index.\n\nArchitecture: `tiono8` (offline-first, self-evolving)\n\nModules\n- core/loop.py: evolve → validate → accept/reject (bounded iterations)\n- patching/: diff builder, safe apply, atomic writes, rollback points\n- policy/: allowlist paths, deny globs (.git/, __pycache__/, binaries), patch size caps\n- signals/: parse pytest/ruff/mypy into normalized findings\n- memory/index.jsonl: append-only snapshots (hashes, metrics, rationale)\n\nSafety gates\n- refuse path traversal/symlink escapes; never edit binaries\n- accept only if tests/lint/types stay green or improve", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Fix a bug and add tests.\n\nFile: cu39h6p_h3.py\n```python\ndef mjp90wp6(n: int) -> int:\n \"\"\"Sum 1..n inclusive.\"\"\"\n if n < 0:\n raise ValueError(\"n must be non-negative\")\n total = 0\n for k in range(n): # BUG: should include n\n total += k\n return total\n```\n\nReturn unified diffs for cu39h6p_h3.py and test_cu39h6p_h3.py (pytest).\n\n*** Begin Patch\n*** Update File: cu39h6p_h3.py\n@@\n def mjp90wp6(n: int) -> int:\n@@\n total = 0\n- for k in range(n): # BUG: should include n\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_cu39h6p_h3.py\n+import pytest\n+from cu39h6p_h3 import mjp90wp6\n+\n+def test_zero():\n+ assert mjp90wp6(0) == 0\n+\n+def test_one():\n+ assert mjp90wp6(1) == 1\n+\n+def test_small():\n+ assert mjp90wp6(7) == 28\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ mjp90wp6(-1)\n+\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Fix a bug and add tests.\n\nFile: qzv8uufdn33.py\n```python\ndef kvcda0y5v(n: int) -> int:\n \"\"\"Sum 1..n inclusive.\"\"\"\n if n < 0:\n raise ValueError(\"n must be non-negative\")\n total = 0\n for k in range(n): # BUG: should include n\n total += k\n return total\n```\n\nReturn unified diffs for qzv8uufdn33.py and test_qzv8uufdn33.py (pytest).\n\n*** Begin Patch\n*** Update File: qzv8uufdn33.py\n@@\n def kvcda0y5v(n: int) -> int:\n@@\n total = 0\n- for k in range(n): # BUG: should include n\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_qzv8uufdn33.py\n+import pytest\n+from qzv8uufdn33 import kvcda0y5v\n+\n+def test_zero():\n+ assert kvcda0y5v(0) == 0\n+\n+def test_one():\n+ assert kvcda0y5v(1) == 1\n+\n+def test_small():\n+ assert kvcda0y5v(7) == 28\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ kvcda0y5v(-1)\n+\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Add a clear docstring and type hints to this function:\n\n```python\ndef f81838(s):\n return ''.join(x for x in s if x.isalnum()).lower()\n```\n\n```python\nfrom __future__ import annotations\n\ndef f81838(s: str) -> str:\n \"\"\"Normalize a string: keep only alphanumerics and lowercase the result.\"\"\"\n return \"\".join(ch for ch in s if ch.isalnum()).lower()\n```", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Task type: network_protocol\nScenario: real-time notification hub\nDomain focus: constraint solving\nPrimary language: python\nDifficulty: expert\nScale/SLO: 10k RPS peak\nComponent: component_uqsmixsh\nConstraints: assume adversarial inputs; validate everything, avoid data races and undefined behavior, include backward compatibility and migration plan, include failure modes and recovery, include test vectors and fuzz strategy, include security threat model (defensive only), include verification strategy\nAssume weekly network partitions.\nDeliverable: Design an application protocol: framing, retries, backpressure, timeouts; include client/server skeleton and test vectors.\n\nOutput: rigorous design + invariants + verification plan + implementation sketch.\n**Contract**\n- Inputs validated at the boundary; explicit error taxonomy.\n- Idempotency for side effects via request_id; deterministic replay.\n- Backward compatibility: additive changes by default; versioned breaking changes.\n**Invariants**\n- Safety: state transitions preserve invariants; no partial commit leaks.\n- Liveness: under bounded faults and stable network, progress occurs.\n- Determinism: replay of the same event log yields identical outputs.\n**Failure modes & recovery**\n- Data corruption: checksums + scrubber; quarantine and rebuild from replicas/snapshots.\n- Duplicate requests: de-duplicate by (tenant, request_id) returning cached response.\n- Network partition: minority cannot commit; clients receive retriable errors.\n**Security posture (defensive)**\n- Threat model: auth/authz, injection, replay/abuse, supply chain.\n- Least privilege; secrets in managed store; audit logs for sensitive ops.\n- Input normalization, parameterized queries, path traversal protections.\n**Verification strategy**\n- Canary + shadow traffic; invariants checked in production via assertions/metrics.\n- Property tests against a pure reference model (state machine).\n- Fuzzing of parsers/framers/validators with corpus seeds.\n\n**Snippet**\n```text\nImplementation sketch: factor pure state-machine core; adapters for I/O; add deterministic replay log.\n```\nExpert checks: state-machine proof sketch + model checking; upgrade/rollback rehearsed.", "source": "WithinUsAI/Omega_Genesis_Coder_100k"} {"text": "Fix a subtle bug in a Python module used for CLI tooling.\nRequirements: explain root cause briefly, provide corrected code, and add regression tests.\nConstraints: must provide clear error messages, must be easy to extend, must include docstrings, must be streaming-friendly.\nDifficulty: expert. Avoid quadratic behavior on large inputs.\n\nDeliverable: implementation + tests.\n```python\nfrom __future__ import annotations\n\nfrom dataclasses import dataclass\nfrom pathlib import Path\nfrom typing import Iterable\nimport json\n\n\nclass ValidationError(ValueError):\n \"\"\"Raised when input validation fails.\"\"\"\n\n\ndef safe_join(base: Path, *parts: str) -> Path:\n \"\"\"Join paths while preventing traversal outside base.\"\"\"\n b = base.resolve()\n p = (b / Path(*parts)).resolve()\n if p != b and b not in p.parents:\n raise ValidationError(f\"unsafe path: {p}\")\n return p\n\n\n@dataclass(frozen=True, slots=True)\nclass Record:\n key: str\n value: int\n\n\ndef parse_jsonl(lines: Iterable[str]) -> list[Record]:\n out: list[Record] = []\n for idx, line in enumerate(lines, 1):\n s = line.strip()\n if not s:\n continue\n try:\n obj = json.loads(s)\n except json.JSONDecodeError as e:\n raise ValidationError(f\"line {idx}: invalid json\") from e\n if not isinstance(obj, dict):\n raise ValidationError(f\"line {idx}: expected object\")\n key = obj.get(\"key\")\n val = obj.get(\"value\")\n if not isinstance(key, str) or not key:\n raise ValidationError(f\"line {idx}: key must be non-empty str\")\n if not isinstance(val, int):\n raise ValidationError(f\"line {idx}: value must be int\")\n out.append(Record(key, val))\n return out\n\n\ndef write_jsonl(base: Path, rel: str, records: Iterable[Record]) -> Path:\n base.mkdir(parents=True, exist_ok=True)\n dst = safe_join(base, rel)\n dst.parent.mkdir(parents=True, exist_ok=True)\n with dst.open(\"w\", encoding=\"utf-8\", newline=\"\\n\") as f:\n for r in records:\n f.write(json.dumps({\"key\": r.key, \"value\": r.value}, ensure_ascii=False) + \"\\n\")\n return dst\n```\n\n```python\n# tests (pytest-style)\nimport json\nfrom pathlib import Path\nimport pytest\nfrom module_under_test import ValidationError, Record, parse_jsonl, write_jsonl\n\ndef test_parse_ok():\n lines = [json.dumps({\"key\":\"a\",\"value\":1}), json.dumps({\"key\":\"b\",\"value\":2})]\n assert parse_jsonl(lines) == [Record(\"a\",1), Record(\"b\",2)]\n\ndef test_parse_rejects_bad_json():\n with pytest.raises(ValidationError):\n parse_jsonl([\"{not json}\"])\n\ndef test_safe_join_blocks_traversal(tmp_path: Path):\n with pytest.raises(ValidationError):\n write_jsonl(tmp_path, \"../x.jsonl\", [Record(\"a\",1)])\n```", "source": "WithinUsAI/python_GOD_coder_100k"} {"text": "Create a comprehensive test plan and automated tests for multi-tenant isolation in a developer tooling product.\nTarget platform: mobile (iOS Swift).\nRequirements: unit/integration tests, edge cases, load tests strategy, and CI gates.\nConstraints: must avoid global state, must include type hints where applicable, must include tests.\nDifficulty: expert. Assume untrusted input; validate everything.\n\nOutput: design + implementation guidance suitable for shipping.\nDeliverable: test plan + automation guidance.\n\n**Unit tests**\n- Validation: malformed payloads rejected with correct codes.\n- AuthZ: tenant boundary enforced.\n- Idempotency: replay returns same response; conflicting reuse yields 409.\n\n**Integration tests**\n- DB transaction behavior; unique constraints.\n- Cache behavior: correctness under concurrent requests.\n\n**Load tests**\n- 10k RPS target: measure p95 latency, error rate, saturation.\n\n**CI gates**\n- Lint + typecheck + unit tests required.\n- Coverage threshold for critical modules.\n- Block merge on flaky test detection.\n\n\nHard-mode checks: concurrency safety, idempotency, and rollback validated; add chaos tests where feasible.", "source": "WithinUsAI/GOD_Coder_100k"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: Project domain: reporting engine\nImplementation stack: Rust, Axum, SQLx, Redis, Tokio, Docker\nSoftware delivery problem: build reproducibility failure\nTask type: prd_to_patch\nDifficulty: hard\n\nReturn a complete delivery-grade response with:\n- diagnosis or design reasoning\n- implementation\n- test plan or tests\n- rollout plan\n- rollback or compatibility note\n- verification commands\n\nRepository sketch:\nrepo/\n cmd/server/main.go\n internal/service/service.go\n internal/store/store.go\n internal/api/api.go\n service_test.go\n go.mod\n\nFocus: Focus on shipping production software with rollout safety, acceptance criteria, telemetry, and maintenance quality.\n\nassistant: Diagnosis:\n- Root cause or delivery blocker: build reproducibility failure needs both implementation work and a safe shipping plan.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```go\npackage service\n\nimport \"fmt\"\n\nfunc NormalizePayload(payload map[string]any) map[string]any {\n\tout := make(map[string]any)\n\tfor k, v := range payload {\n\t\tif v == nil {\n\t\t\tcontinue\n\t\t}\n\t\tout[k] = v\n\t}\n\treturn out\n}\n\nfunc Handle(payload map[string]any) (map[string]any, error) {\n\tclean := NormalizePayload(payload)\n\tif _, ok := clean[\"id\"]; !ok {\n\t\treturn nil, fmt.Errorf(\"missing id\")\n\t}\n\treturn map[string]any{\"ok\": true, \"data\": clean}, nil\n}\n```\n\nTests:\n```go\npackage service\n\nimport \"testing\"\n\nfunc TestHandle(t *testing.T) {\n\tgot, err := Handle(map[string]any{\"id\": 7, \"name\": \"ok\", \"unused\": nil})\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tif got[\"ok\"] != true {\n\t\tt.Fatalf(\"expected ok=true\")\n\t}\n\tif _, err := Handle(map[string]any{\"name\": \"x\"}); err == nil {\n\t\tt.Fatalf(\"expected missing id error\")\n\t}\n}\n```\n\nVerification:\n- `go test ./...`\n- `go vet ./...`\n\nEngineering notes:\n- Language: Go\n- Framework/tooling: testify\n- Stack context: Rust, Axum, SQLx, Redis, Tokio, Docker\n- Domain: reporting engine\n- Task type: prd_to_patch\n- Difficulty: hard\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "Task type: tla_state_machine\nScenario: real-time notification hub\nDomain focus: network protocols\nPrimary language: tla+\nDifficulty: expert+\nScale/SLO: 50 TB/day ingestion\nComponent: component_alougubs\nConstraints: include test vectors and fuzz strategy, include verification strategy, include backward compatibility and migration plan, include deterministic replay plan, avoid data races and undefined behavior\nAssume partial data corruption; include scrubbing strategy.\nDeliverable: Provide a TLA+-style state machine (pseudo), safety/liveness properties, and a model-checking strategy. Include an implementation sketch and test vectors.\n\nOutput: elite engineering answer optimized for correctness, performance, and operability.\n**Contract**\n- Inputs validated at the boundary; explicit error taxonomy.\n- Idempotency for side effects via request_id; deterministic replay.\n- Backward compatibility: additive changes by default; versioned breaking changes.\n**Invariants**\n- Liveness: under bounded faults and stable network, progress occurs.\n- Determinism: replay of the same event log yields identical outputs.\n- Safety: state transitions preserve invariants; no partial commit leaks.\n**Failure modes & recovery**\n- Network partition: minority cannot commit; clients receive retriable errors.\n- Data corruption: checksums + scrubber; quarantine and rebuild from replicas/snapshots.\n- Crash during commit: WAL replay completes or transaction aborts; no torn writes.\n**Security posture (defensive)**\n- Threat model: auth/authz, injection, replay/abuse, supply chain.\n- Least privilege; secrets in managed store; audit logs for sensitive ops.\n- Input normalization, parameterized queries, path traversal protections.\n**Verification strategy**\n- Fuzzing of parsers/framers/validators with corpus seeds.\n- Property tests against a pure reference model (state machine).\n- Canary + shadow traffic; invariants checked in production via assertions/metrics.\n\n**Snippet**\n```tla\nVARIABLES state, log, seen\n\nInit == state = [k \\in Keys |-> <<0, NULL>>] /\\ log = << >> /\\ seen = [r \\in ReqIds |-> NULL]\n\nPut(req, k, v) ==\n IF seen[req] # NULL THEN UNCHANGED <>\n ELSE\n LET ver == state[k][1] + 1 IN\n /\\ state' = [state EXCEPT ![k] = <>]\n /\\ log' = Append(log, <>)\n /\\ seen' = [seen EXCEPT ![req] = <<\"ok\", ver>>]\n\nSafety == \\A k \\in Keys: state[k][1] >= 0\n```\n\nExpert+ checks: mechanized invariants (or exhaustive model checking), adversarial fuzzing, and multi-region failure drills.", "source": "WithinUsAI/Omega_Genesis_Coder_100k"} {"text": "Refactor an existing codebase in IoT telemetry to support webhooks cleanly.\nTarget platform: web (React + TypeScript).\nRequirements: propose new modules/layers, dependency boundaries, and migration plan.\nConstraints: must include tests, must avoid global state, must be secure-by-default, must include type hints where applicable, must be production-ready.\nDifficulty: expert. Assume mobile clients are occasionally offline.\n\nOutput: engineering-grade answer with edge cases covered.\nDeliverable: refactor plan + module boundaries.\n\n**Proposed modules**\n- `domain/` pure business logic (no I/O)\n- `adapters/` DB, cache, external APIs\n- `api/` request/response validation and routing\n- `observability/` logging/metrics/tracing\n- `tests/` unit + integration suites\n\n**Migration plan**\n1. Introduce new interfaces + adapters behind feature flags.\n2. Dual-write or read-compat layer if schema changes.\n3. Incremental cutover; deprecate legacy module.\n\nKey rule: dependencies flow inward; domain has no framework imports.\n\n\nHard-mode checks: concurrency safety, idempotency, and rollback validated; add chaos tests where feasible.", "source": "WithinUsAI/GOD_Coder_100k"} {"text": "Perform a code review for a content moderation PR implementing background jobs.\nTarget platform: backend (Node.js).\nRequirements: list critical issues, improvements, and provide an improved patch excerpt.\nConstraints: must include tests, must be observable (logs/metrics/traces), must include clear error handling, must be easy to extend.\nDifficulty: hard. Assume PII must be protected.\n\nOutput: production-oriented blueprint with code where appropriate.\nDeliverable: code review findings + improved patch excerpt.\n\n**Critical issues**\n1. Missing input validation at boundary; potential unexpected exceptions.\n2. No idempotency / retry safety for side-effecting endpoint.\n3. No tests for edge cases (empty input, duplicates, timeouts).\n4. Observability gaps: no request_id correlation, no metrics.\n\n**Improvements**\n- Add strict validation and explicit error responses.\n- Add idempotency key support for create endpoints.\n- Add unit + integration tests with CI gating.\n- Add structured logs and basic metrics.\n\nPatch excerpt (illustrative):\n```python\nif not idem_key:\n raise HTTPException(400, \"Missing Idempotency-Key\")\n```\n\n\nHard-mode checks: concurrency safety, idempotency, and rollback validated; add chaos tests where feasible.", "source": "WithinUsAI/GOD_Coder_100k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Fix a bug and add tests.\n\nFile: mu2aod_r.py\n```python\ndef w67b13(n: int) -> int:\n \"\"\"Sum 1..n inclusive.\"\"\"\n if n < 0:\n raise ValueError(\"n must be non-negative\")\n total = 0\n for k in range(n): # BUG: should include n\n total += k\n return total\n```\n\nReturn unified diffs for mu2aod_r.py and test_mu2aod_r.py (pytest).\n\n*** Begin Patch\n*** Update File: mu2aod_r.py\n@@\n def w67b13(n: int) -> int:\n@@\n total = 0\n- for k in range(n): # BUG: should include n\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_mu2aod_r.py\n+import pytest\n+from mu2aod_r import w67b13\n+\n+def test_zero():\n+ assert w67b13(0) == 0\n+\n+def test_one():\n+ assert w67b13(1) == 1\n+\n+def test_small():\n+ assert w67b13(7) == 28\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ w67b13(-1)\n+\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Provision infrastructure for a social media workload providing caching.\nTarget platform: backend (Node.js).\nRequirements: IaC (Terraform or Kubernetes YAML), networking, secrets, autoscaling.\nConstraints: must be secure-by-default, must include type hints where applicable, must be production-ready.\nDifficulty: medium. Assume 10k RPS peak traffic.\n\nOutput: design + implementation guidance suitable for shipping.\nDeliverable: Kubernetes deployment + basic security posture.\n\n```yaml\napiVersion: apps/v1\nkind: Deployment\nmetadata:\n name: app\nspec:\n replicas: 3\n selector:\n matchLabels: { app: app }\n template:\n metadata:\n labels: { app: app }\n spec:\n containers:\n - name: app\n image: app:latest\n ports: [{ containerPort: 8080 }]\n readinessProbe:\n httpGet: { path: /healthz, port: 8080 }\n resources:\n requests: { cpu: \"200m\", memory: \"256Mi\" }\n limits: { cpu: \"1\", memory: \"1Gi\" }\n```\n\nAdditions:\n- NetworkPolicy to restrict egress/ingress.\n- Secrets via external secret store; rotate regularly.\n- HPA for autoscaling; PodDisruptionBudget for availability.\n\n\nChecks: input validation, tests, and safe defaults included.", "source": "WithinUsAI/GOD_Coder_100k"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: Language: Python\nFramework/tooling: Celery\nDomain: model serving gateway\nLogic challenge: N+1 query explosion\nTask type: transaction_integrity_fix\nDifficulty: hard\n\nReturn a rigorous engineering answer:\n- identify the hidden root cause or logical failure\n- present the corrected implementation\n- add tests that prove the fix\n- list verification commands\n- explain why naive fixes are insufficient when relevant\n\nRepository sketch:\nrepo/\n app/\n api.py\n service.py\n models.py\n tests/\n test_api.py\n pyproject.toml\n\nFocus: Focus on ambiguity, misleading symptoms, hidden root causes, and high-stakes debugging.\n\nassistant: Diagnosis:\n- Hidden root cause: N+1 query explosion presents misleading symptoms, so the patch must target the actual logic boundary rather than the first visible failure.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```python\nfrom __future__ import annotations\n\nfrom dataclasses import dataclass\nfrom typing import Any\n\n@dataclass\nclass ServiceResult:\n ok: bool\n data: dict[str, Any]\n error: str | None = None\n\ndef normalize_payload(payload: dict[str, Any]) -> dict[str, Any]:\n if not isinstance(payload, dict):\n raise TypeError(\"payload must be a dict\")\n clean: dict[str, Any] = {}\n for key, value in payload.items():\n if value is None:\n continue\n clean[str(key).strip()] = value\n return clean\n\ndef handle_n+1_query_explosion(payload: dict[str, Any]) -> ServiceResult:\n clean = normalize_payload(payload)\n if \"id\" not in clean:\n return ServiceResult(ok=False, data={}, error=\"missing id\")\n return ServiceResult(ok=True, data=clean)\n```\n\nTests:\n```python\nimport pytest\nfrom app.service import handle_jwt_refresh_token_rotation as handler\n\ndef test_handler_accepts_valid_payload():\n result = handler({\"id\": 7, \"name\": \"ok\", \"unused\": None})\n assert result.ok is True\n assert result.data == {\"id\": 7, \"name\": \"ok\"}\n\ndef test_handler_rejects_missing_id():\n result = handler({\"name\": \"x\"})\n assert result.ok is False\n assert result.error == \"missing id\"\n```\n\nVerification:\n- `pytest -q`\n- `ruff check .`\n- `python -m compileall .`\n\nEngineering notes:\n- Language: Python\n- Framework/tooling: Celery\n- Stack context: Go, Gin, PostgreSQL, gRPC, Prometheus, Docker\n- Domain: model serving gateway\n- Task type: transaction_integrity_fix\n- Difficulty: hard\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Optimize while preserving behavior.\n\nFile: v3id2w5j.py\n```python\ndef e48oycwqn(xs):\n out = []\n for x in xs:\n if x not in out:\n out.append(x)\n return out\n```\n\nRequirements: preserve first-seen order; O(n) average; add types + docstring.\n\n# v3id2w5j.py\nfrom __future__ import annotations\nfrom typing import Iterable, List, Set, TypeVar\n\nT = TypeVar(\"T\")\n\ndef e48oycwqn(xs: Iterable[T]) -> List[T]:\n \"\"\"Return unique items preserving first-seen order.\"\"\"\n seen: Set[T] = set()\n out: List[T] = []\n for x in xs:\n if x in seen:\n continue\n seen.add(x)\n out.append(x)\n return out", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Add a clear docstring and type hints to this function:\n\n```python\ndef f18010(s):\n return ''.join(x for x in s if x.isalnum()).lower()\n```\n\n```python\nfrom __future__ import annotations\n\ndef f18010(s: str) -> str:\n \"\"\"Normalize a string: keep only alphanumerics and lowercase the result.\"\"\"\n return \"\".join(ch for ch in s if ch.isalnum()).lower()\n```", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Fix a subtle bug in a Python module used for rate limiting.\nRequirements: explain root cause briefly, provide corrected code, and add regression tests.\nConstraints: must provide clear error messages, must be easy to extend.\nDifficulty: easy. Include a small CLI example if relevant.\n\nDeliverable: API + reference implementation + tests.\n```python\nfrom __future__ import annotations\n\nfrom dataclasses import dataclass\nfrom pathlib import Path\nfrom typing import Iterable\nimport json\n\n\nclass ValidationError(ValueError):\n \"\"\"Raised when input validation fails.\"\"\"\n\n\ndef safe_join(base: Path, *parts: str) -> Path:\n \"\"\"Join paths while preventing traversal outside base.\"\"\"\n b = base.resolve()\n p = (b / Path(*parts)).resolve()\n if p != b and b not in p.parents:\n raise ValidationError(f\"unsafe path: {p}\")\n return p\n\n\n@dataclass(frozen=True, slots=True)\nclass Record:\n key: str\n value: int\n\n\ndef parse_jsonl(lines: Iterable[str]) -> list[Record]:\n out: list[Record] = []\n for idx, line in enumerate(lines, 1):\n s = line.strip()\n if not s:\n continue\n try:\n obj = json.loads(s)\n except json.JSONDecodeError as e:\n raise ValidationError(f\"line {idx}: invalid json\") from e\n if not isinstance(obj, dict):\n raise ValidationError(f\"line {idx}: expected object\")\n key = obj.get(\"key\")\n val = obj.get(\"value\")\n if not isinstance(key, str) or not key:\n raise ValidationError(f\"line {idx}: key must be non-empty str\")\n if not isinstance(val, int):\n raise ValidationError(f\"line {idx}: value must be int\")\n out.append(Record(key, val))\n return out\n\n\ndef write_jsonl(base: Path, rel: str, records: Iterable[Record]) -> Path:\n base.mkdir(parents=True, exist_ok=True)\n dst = safe_join(base, rel)\n dst.parent.mkdir(parents=True, exist_ok=True)\n with dst.open(\"w\", encoding=\"utf-8\", newline=\"\\n\") as f:\n for r in records:\n f.write(json.dumps({\"key\": r.key, \"value\": r.value}, ensure_ascii=False) + \"\\n\")\n return dst\n```\n\n```python\n# tests (pytest-style)\nimport json\nfrom pathlib import Path\nimport pytest\nfrom module_under_test import ValidationError, Record, parse_jsonl, write_jsonl\n\ndef test_parse_ok():\n lines = [json.dumps({\"key\":\"a\",\"value\":1}), json.dumps({\"key\":\"b\",\"value\":2})]\n assert parse_jsonl(lines) == [Record(\"a\",1), Record(\"b\",2)]\n\ndef test_parse_rejects_bad_json():\n with pytest.raises(ValidationError):\n parse_jsonl([\"{not json}\"])\n\ndef test_safe_join_blocks_traversal(tmp_path: Path):\n with pytest.raises(ValidationError):\n write_jsonl(tmp_path, \"../x.jsonl\", [Record(\"a\",1)])\n```", "source": "WithinUsAI/python_GOD_coder_100k"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: Repository domain: observability collector\nPrimary language: SQL\nFramework/tooling: SQLite\nReported problem: migration ordering failure\nTask type: api_endpoint_work\nDifficulty: hard\n\nProduce a complete professional engineering response:\n1. Diagnose the root cause.\n2. Provide the corrected implementation or patch.\n3. Add tests.\n4. Add verification commands.\n5. Note edge cases and any migration or rollback risk.\n\nRepository sketch:\nrepo/\n migrations/\n 001_init.sql\n 002_add_index.sql\n queries/\n report.sql\n tests/\n report_cases.md\n\nQuality target:\n- Minimal diff unless redesign is clearly required\n- Production-ready code\n- No placeholders\n- Secure defaults\n- Clear acceptance of failure cases\n\nFocus: Focus on complete implementation quality, patch correctness, tests, and production readiness.\n\nassistant: Diagnosis:\n- Root cause: the failure around migration ordering failure is caused by missing validation, weak edge-case handling, or unsafe lifecycle behavior in the current implementation.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```sql\nWITH ranked AS (\n SELECT\n user_id,\n created_at,\n amount,\n ROW_NUMBER() OVER (PARTITION BY user_id ORDER BY created_at DESC, id DESC) AS rn\n FROM orders\n)\nSELECT user_id, created_at, amount\nFROM ranked\nWHERE rn = 1;\n```\n\nTests:\n```sql\n-- Correctness checks:\n-- 1) multiple rows per user\n-- 2) identical timestamps require deterministic tie-breaker\n-- 3) null values handled by business rules\n```\n\nVerification:\n- `run migration checks`\n- `run query correctness cases`\n\nEngineering notes:\n- Language: SQL\n- Framework/tooling: SQLite\n- Stack context: Go, Gin, PostgreSQL, gRPC, Prometheus, Docker\n- Domain: observability collector\n- Task type: api_endpoint_work\n- Difficulty: hard\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Fix a bug and add tests.\n\nFile: cefj883ad.py\n```python\ndef ss7s13fpkf60(n: int) -> int:\n \"\"\"Sum 1..n inclusive.\"\"\"\n if n < 0:\n raise ValueError(\"n must be non-negative\")\n total = 0\n for k in range(n): # BUG: should include n\n total += k\n return total\n```\n\nReturn unified diffs for cefj883ad.py and test_cefj883ad.py (pytest).\n\n*** Begin Patch\n*** Update File: cefj883ad.py\n@@\n def ss7s13fpkf60(n: int) -> int:\n@@\n total = 0\n- for k in range(n): # BUG: should include n\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_cefj883ad.py\n+import pytest\n+from cefj883ad import ss7s13fpkf60\n+\n+def test_zero():\n+ assert ss7s13fpkf60(0) == 0\n+\n+def test_one():\n+ assert ss7s13fpkf60(1) == 1\n+\n+def test_small():\n+ assert ss7s13fpkf60(7) == 28\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ ss7s13fpkf60(-1)\n+\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Refactor to typed, mostly-immutable Python and add minimal tests.\n\n```python\nclass C56145:\n def __init__(self, values): self.values=list(values)\n def mean(self): return sum(self.values)/len(self.values)\n```\nReturn `m58165.py` and `test_m58165.py`.\n\n```python\n# m58165.py\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom typing import Iterable, Tuple\n\n@dataclass(frozen=True)\nclass C56145:\n values: Tuple[float, ...]\n\n @staticmethod\n def create(values: Iterable[float]) -> \"C56145\":\n vals = tuple(float(v) for v in values)\n if not vals: raise ValueError(\"empty\")\n return C56145(vals)\n\n def mean(self) -> float:\n return sum(self.values)/len(self.values)\n```\n\n```python\n# test_m58165.py\nimport pytest\nfrom m58165 import C56145\n\ndef test_mean():\n assert C56145.create([1,2,3]).mean() == 2.0\ndef test_empty():\n with pytest.raises(ValueError):\n C56145.create([])\n```", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Refactor a Python module used for rate limiting into a clean, extensible design.\nRequirements: outline the new architecture briefly, then provide the refactored code and tests.\nConstraints: must be streaming-friendly, must be memory-efficient.\nDifficulty: expert. Provide helpful exceptions with actionable messages.\n\nDeliverable: API + reference implementation + tests.\nArchitecture:\n- Public facade class coordinating concerns (parsing, validation, persistence)\n- Small pure functions for testability\n- No global state; dependency injection for filesystem I/O\n\n```python\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom pathlib import Path\nfrom typing import Protocol, Iterable\nimport json\n\nclass Store(Protocol):\n def write_text(self, path: Path, data: str) -> None: ...\n\nclass FSStore:\n def write_text(self, path: Path, data: str) -> None:\n path.parent.mkdir(parents=True, exist_ok=True)\n path.write_text(data, encoding=\"utf-8\")\n\n@dataclass(frozen=True, slots=True)\nclass Item:\n name: str\n qty: int\n\ndef parse_items(lines: Iterable[str]) -> list[Item]:\n out: list[Item] = []\n for i, line in enumerate(lines, 1):\n s = line.strip()\n if not s:\n continue\n obj = json.loads(s)\n if not isinstance(obj, dict):\n raise ValueError(f\"line {i}: expected object\")\n name = obj.get(\"name\")\n qty = obj.get(\"qty\")\n if not isinstance(name, str) or not name:\n raise ValueError(f\"line {i}: name must be str\")\n if not isinstance(qty, int) or qty < 0:\n raise ValueError(f\"line {i}: qty must be non-negative int\")\n out.append(Item(name, qty))\n return out\n\nclass InventoryWriter:\n def __init__(self, base_dir: Path, store: Store | None = None) -> None:\n self._base = base_dir\n self._store: Store = store or FSStore()\n\n def write(self, rel_path: str, items: list[Item]) -> Path:\n dst = (self._base / rel_path).resolve()\n base = self._base.resolve()\n if dst != base and base not in dst.parents:\n raise ValueError(\"unsafe path traversal\")\n payload = json.dumps([item.__dict__ for item in items], ensure_ascii=False)\n self._store.write_text(dst, payload)\n return dst\n```\n\n```python\nimport json\nfrom pathlib import Path\nimport pytest\nfrom module_under_test import InventoryWriter, parse_items\n\ndef test_parse_items_valid():\n lines = [json.dumps({\"name\":\"x\",\"qty\":1})]\n assert parse_items(lines)[0].name == \"x\"\n\ndef test_writer_blocks_traversal(tmp_path: Path):\n w = InventoryWriter(tmp_path)\n with pytest.raises(ValueError):\n w.write(\"../evil.json\", [])\n```", "source": "WithinUsAI/python_GOD_coder_100k"} {"text": "Add a clear docstring and type hints to this function:\n\n```python\ndef f28719(s):\n return ''.join(x for x in s if x.isalnum()).lower()\n```\n\n```python\nfrom __future__ import annotations\n\ndef f28719(s: str) -> str:\n \"\"\"Normalize a string: keep only alphanumerics and lowercase the result.\"\"\"\n return \"\".join(ch for ch in s if ch.isalnum()).lower()\n```", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Implement offline-first sync for a fraud detection product.\nTarget platform: web (React + TypeScript).\nRequirements: provide production-ready code, configuration, and tests.\nConstraints: must avoid global state, must be production-ready, must include documentation/comments, must be performant under load, must include clear error handling.\nDifficulty: easy. Assume strict latency budget (p95 < 200ms).\n\nOutput: production-oriented blueprint with code where appropriate.\nDeliverable: production-grade reference implementation (FastAPI) + tests.\n\n```python\n# app.py\nfrom __future__ import annotations\n\nimport hashlib\nimport json\nfrom dataclasses import dataclass\nfrom datetime import datetime, timezone\nfrom typing import Any, Optional\n\nfrom fastapi import FastAPI, Header, HTTPException\nfrom pydantic import BaseModel, Field\n\napp = FastAPI(title=\"Idempotent API\")\n\nclass CreateReq(BaseModel):\n tenant_id: str = Field(min_length=1)\n amount_cents: int = Field(ge=0)\n currency: str = Field(min_length=3, max_length=3)\n\nclass CreateResp(BaseModel):\n id: str\n created_at: str\n echo: CreateReq\n\n@dataclass\nclass _IdempoEntry:\n request_hash: str\n response_json: str\n\n# In production: Postgres table with UNIQUE(tenant_id, key)\n_IDEMPO: dict[tuple[str, str], _IdempoEntry] = {}\n\ndef _hash_req(req: CreateReq) -> str:\n raw = req.model_dump_json()\n return hashlib.sha256(raw.encode(\"utf-8\")).hexdigest()\n\n@app.post(\"/v1/payments\", response_model=CreateResp)\ndef create_payment(\n req: CreateReq,\n idempotency_key: Optional[str] = Header(default=None, alias=\"Idempotency-Key\"),\n) -> Any:\n if not idempotency_key:\n raise HTTPException(status_code=400, detail=\"Missing Idempotency-Key\")\n if len(idempotency_key) > 128:\n raise HTTPException(status_code=400, detail=\"Idempotency-Key too long\")\n\n key = (req.tenant_id, idempotency_key)\n rh = _hash_req(req)\n\n existing = _IDEMPO.get(key)\n if existing:\n if existing.request_hash != rh:\n raise HTTPException(status_code=409, detail=\"Idempotency-Key reuse with different payload\")\n return json.loads(existing.response_json)\n\n # Create new payment (stubbed)\n pid = hashlib.md5(f\"{req.tenant_id}:{idempotency_key}\".encode()).hexdigest()\n resp = CreateResp(\n id=pid,\n created_at=datetime.now(timezone.utc).isoformat(),\n echo=req,\n )\n _IDEMPO[key] = _IdempoEntry(request_hash=rh, response_json=resp.model_dump_json())\n return resp\n```\n\n```python\n# test_app.py (pytest)\nfrom fastapi.testclient import TestClient\nfrom app import app\n\nclient = TestClient(app)\n\ndef test_idempotent_replay():\n headers = {\"Idempotency-Key\": \"abc\"}\n body = {\"tenant_id\":\"t1\",\"amount_cents\":100,\"currency\":\"USD\"}\n r1 = client.post(\"/v1/payments\", json=body, headers=headers)\n r2 = client.post(\"/v1/payments\", json=body, headers=headers)\n assert r1.status_code == 200 and r2.status_code == 200\n assert r1.json() == r2.json()\n\ndef test_payload_conflict():\n headers = {\"Idempotency-Key\": \"abc\"}\n b1 = {\"tenant_id\":\"t1\",\"amount_cents\":100,\"currency\":\"USD\"}\n b2 = {\"tenant_id\":\"t1\",\"amount_cents\":200,\"currency\":\"USD\"}\n assert client.post(\"/v1/payments\", json=b1, headers=headers).status_code == 200\n assert client.post(\"/v1/payments\", json=b2, headers=headers).status_code == 409\n```\n\nNotes:\n- Replace in-memory store with a DB table and transaction.\n- Store response + request hash to detect key reuse with different payload.\n\n\nChecks: input validation, tests, and safe defaults included.", "source": "WithinUsAI/GOD_Coder_100k"} {"text": "Implement multi-tenant isolation for a customer support product.\nTarget platform: web (React + TypeScript).\nRequirements: provide production-ready code, configuration, and tests.\nConstraints: must be secure-by-default, must include type hints where applicable, must be performant under load, must be easy to extend.\nDifficulty: expert. Assume GDPR-style deletion requests must be supported.\n\nOutput: actionable implementation and verification artifacts.\nDeliverable: production-grade reference implementation (FastAPI) + tests.\n\n```python\n# app.py\nfrom __future__ import annotations\n\nimport hashlib\nimport json\nfrom dataclasses import dataclass\nfrom datetime import datetime, timezone\nfrom typing import Any, Optional\n\nfrom fastapi import FastAPI, Header, HTTPException\nfrom pydantic import BaseModel, Field\n\napp = FastAPI(title=\"Idempotent API\")\n\nclass CreateReq(BaseModel):\n tenant_id: str = Field(min_length=1)\n amount_cents: int = Field(ge=0)\n currency: str = Field(min_length=3, max_length=3)\n\nclass CreateResp(BaseModel):\n id: str\n created_at: str\n echo: CreateReq\n\n@dataclass\nclass _IdempoEntry:\n request_hash: str\n response_json: str\n\n# In production: Postgres table with UNIQUE(tenant_id, key)\n_IDEMPO: dict[tuple[str, str], _IdempoEntry] = {}\n\ndef _hash_req(req: CreateReq) -> str:\n raw = req.model_dump_json()\n return hashlib.sha256(raw.encode(\"utf-8\")).hexdigest()\n\n@app.post(\"/v1/payments\", response_model=CreateResp)\ndef create_payment(\n req: CreateReq,\n idempotency_key: Optional[str] = Header(default=None, alias=\"Idempotency-Key\"),\n) -> Any:\n if not idempotency_key:\n raise HTTPException(status_code=400, detail=\"Missing Idempotency-Key\")\n if len(idempotency_key) > 128:\n raise HTTPException(status_code=400, detail=\"Idempotency-Key too long\")\n\n key = (req.tenant_id, idempotency_key)\n rh = _hash_req(req)\n\n existing = _IDEMPO.get(key)\n if existing:\n if existing.request_hash != rh:\n raise HTTPException(status_code=409, detail=\"Idempotency-Key reuse with different payload\")\n return json.loads(existing.response_json)\n\n # Create new payment (stubbed)\n pid = hashlib.md5(f\"{req.tenant_id}:{idempotency_key}\".encode()).hexdigest()\n resp = CreateResp(\n id=pid,\n created_at=datetime.now(timezone.utc).isoformat(),\n echo=req,\n )\n _IDEMPO[key] = _IdempoEntry(request_hash=rh, response_json=resp.model_dump_json())\n return resp\n```\n\n```python\n# test_app.py (pytest)\nfrom fastapi.testclient import TestClient\nfrom app import app\n\nclient = TestClient(app)\n\ndef test_idempotent_replay():\n headers = {\"Idempotency-Key\": \"abc\"}\n body = {\"tenant_id\":\"t1\",\"amount_cents\":100,\"currency\":\"USD\"}\n r1 = client.post(\"/v1/payments\", json=body, headers=headers)\n r2 = client.post(\"/v1/payments\", json=body, headers=headers)\n assert r1.status_code == 200 and r2.status_code == 200\n assert r1.json() == r2.json()\n\ndef test_payload_conflict():\n headers = {\"Idempotency-Key\": \"abc\"}\n b1 = {\"tenant_id\":\"t1\",\"amount_cents\":100,\"currency\":\"USD\"}\n b2 = {\"tenant_id\":\"t1\",\"amount_cents\":200,\"currency\":\"USD\"}\n assert client.post(\"/v1/payments\", json=b1, headers=headers).status_code == 200\n assert client.post(\"/v1/payments\", json=b2, headers=headers).status_code == 409\n```\n\nNotes:\n- Replace in-memory store with a DB table and transaction.\n- Store response + request hash to detect key reuse with different payload.\n\n\nHard-mode checks: concurrency safety, idempotency, and rollback validated; add chaos tests where feasible.", "source": "WithinUsAI/GOD_Coder_100k"} {"text": "Design a production system for document processing supporting rate limiting.\nTarget platform: data (SQL + Python).\nRequirements: APIs, data model, scaling strategy, failure modes, and security.\nConstraints: must be easy to extend, must be secure-by-default, must include tests, must be observable (logs/metrics/traces), must be production-ready.\nDifficulty: expert. Assume strict latency budget (p95 < 200ms).\n\nOutput: design + implementation guidance suitable for shipping.\nDeliverable: system design with APIs, data model, and operational plan.\n\n**High-level architecture**\n- Edge: API Gateway + WAF\n- Core service: stateless app pods behind L7 LB\n- Data: Postgres (primary), Redis (cache + rate limit tokens), Object storage (uploads if needed)\n- Async: message queue (e.g., SQS/Rabbit) + worker pool for background jobs\n- Observability: structured logs + metrics + tracing\n\n**APIs (example)**\n- `POST /v1/{resource}` create (idempotent via `Idempotency-Key`)\n- `GET /v1/{resource}/{id}` read\n- `POST /v1/{resource}/{id}:action` command endpoint when side effects exist\n\n**Data model (Postgres)**\n- `resources(id UUID PK, tenant_id UUID, status TEXT, payload JSONB, created_at, updated_at)`\n- Unique constraint for idempotency: `(tenant_id, idempotency_key)` in a separate table:\n - `idempotency(tenant_id, key TEXT, request_hash TEXT, response JSONB, created_at, PRIMARY KEY(tenant_id,key))`\n\n**Scaling**\n- App layer scales horizontally; keep sessions out of process.\n- Cache reads in Redis; write-through invalidation on mutations.\n- Use connection pooling; consider read replicas for heavy reads.\n\n**Failure modes**\n- Retries: only for safe/ idempotent operations; exponential backoff + jitter.\n- Partial failures: background jobs must be idempotent; use a de-dup key.\n\n**Security**\n- AuthN: JWT/OIDC; AuthZ: RBAC/ABAC with tenant isolation\n- Validate all inputs; enforce per-tenant quotas/rate limits.\n\n**Rollout**\n- Dark launch + feature flags; canary; rapid rollback by toggling flags.\n\n\nHard-mode checks: concurrency safety, idempotency, and rollback validated; add chaos tests where feasible.", "source": "WithinUsAI/GOD_Coder_100k"} {"text": "Design and implement an algorithm for CLI tooling.\nRequirements: define inputs/outputs, implement solution with complexity analysis, and include tests.\nConstraints: must be easy to extend, must include docstrings, must be memory-efficient, must avoid global state.\nDifficulty: hard. Ensure the API is testable via dependency injection.\n\nDeliverable: API + reference implementation + tests.\nProblem: compute rolling sums over events (ts:int,value:int) with window W seconds. Events may be out-of-order.\n\nComplexity: sorting O(n log n); window maintenance O(n); memory O(k).\n\n```python\nfrom __future__ import annotations\nfrom collections import deque\nfrom dataclasses import dataclass\nfrom typing import Iterable, List, Tuple\n\n@dataclass(frozen=True, slots=True)\nclass Event:\n ts: int\n value: int\n\ndef rolling_sum(events: Iterable[Event], window_s: int) -> List[Tuple[int,int]]:\n if window_s < 0:\n raise ValueError(\"window_s must be >= 0\")\n evs = sorted(events, key=lambda e: e.ts)\n q: deque[Event] = deque()\n s = 0\n out: List[Tuple[int,int]] = []\n for e in evs:\n q.append(e)\n s += e.value\n cutoff = e.ts - window_s\n while q and q[0].ts < cutoff:\n old = q.popleft()\n s -= old.value\n out.append((e.ts, s))\n return out\n```\n\n```python\nimport pytest\nfrom module_under_test import Event, rolling_sum\n\ndef test_rolling_sum():\n ev = [Event(10,1), Event(11,2), Event(20,5)]\n assert rolling_sum(ev, 5) == [(10,1),(11,3),(20,5)]\n```", "source": "WithinUsAI/python_GOD_coder_100k"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: Project domain: benchmark harness\nImplementation stack: Go, Gin, PostgreSQL, gRPC, Prometheus, Docker\nSoftware delivery problem: slow cold start\nTask type: rollback_safe_migration\nDifficulty: medium\n\nReturn a complete delivery-grade response with:\n- diagnosis or design reasoning\n- implementation\n- test plan or tests\n- rollout plan\n- rollback or compatibility note\n- verification commands\n\nRepository sketch:\nrepo/\n scripts/\n run.sh\n deploy.sh\n tests/\n smoke.sh\n\nFocus: Focus on shipping production software with rollout safety, acceptance criteria, telemetry, and maintenance quality.\n\nassistant: Diagnosis:\n- Root cause or delivery blocker: slow cold start needs both implementation work and a safe shipping plan.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```bash\n#!/usr/bin/env bash\nset -euo pipefail\n\ninput=\"${1:-}\"\nif [[ -z \"$input\" ]]; then\n echo \"missing input\" >&2\n exit 1\nfi\n\nprintf '%s\n' \"$input\" | tr -d '\r'\n```\n\nTests:\n```bash\noutput=\"$(bash scripts/run.sh \"abc\")\"\ntest \"$output\" = \"abc\"\n```\n\nVerification:\n- `bash tests/smoke.sh`\n- `shellcheck scripts/*.sh`\n\nEngineering notes:\n- Language: Bash\n- Framework/tooling: awk\n- Stack context: Go, Gin, PostgreSQL, gRPC, Prometheus, Docker\n- Domain: benchmark harness\n- Task type: rollback_safe_migration\n- Difficulty: medium\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "Write a thorough test suite for a Python component used for telemetry ingestion.\nRequirements: cover edge cases, invalid inputs, and behavior invariants.\nConstraints: must include type hints, must include docstrings, stdlib-only.\nDifficulty: hard. Provide helpful exceptions with actionable messages.\n\nDeliverable: production-ready reference solution.\n```python\n# tests (pytest-style) for a module providing: normalize(), parse_lines(), compute_stats()\nimport math\nimport pytest\n\ndef test_normalize_idempotent(module_under_test):\n x = \" A\\tB \"\n assert module_under_test.normalize(module_under_test.normalize(x)) == module_under_test.normalize(x)\n\ndef test_parse_lines_rejects_invalid(module_under_test):\n with pytest.raises(ValueError):\n module_under_test.parse_lines([\"\", \"???\", None]) # type: ignore[arg-type]\n\ndef test_compute_stats_basic(module_under_test):\n data = [1, 2, 3, 4]\n s = module_under_test.compute_stats(data)\n assert s.count == 4\n assert s.total == 10\n assert math.isclose(s.mean, 2.5)\n```", "source": "WithinUsAI/python_GOD_coder_100k"} {"text": "Refactor a Python module used for report generation into a clean, extensible design.\nRequirements: outline the new architecture briefly, then provide the refactored code and tests.\nConstraints: stdlib-only, must include type hints, must provide clear error messages, must avoid global state.\nDifficulty: hard. Avoid quadratic behavior on large inputs.\n\nDeliverable: production-ready reference solution.\nArchitecture:\n- Public facade class coordinating concerns (parsing, validation, persistence)\n- Small pure functions for testability\n- No global state; dependency injection for filesystem I/O\n\n```python\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom pathlib import Path\nfrom typing import Protocol, Iterable\nimport json\n\nclass Store(Protocol):\n def write_text(self, path: Path, data: str) -> None: ...\n\nclass FSStore:\n def write_text(self, path: Path, data: str) -> None:\n path.parent.mkdir(parents=True, exist_ok=True)\n path.write_text(data, encoding=\"utf-8\")\n\n@dataclass(frozen=True, slots=True)\nclass Item:\n name: str\n qty: int\n\ndef parse_items(lines: Iterable[str]) -> list[Item]:\n out: list[Item] = []\n for i, line in enumerate(lines, 1):\n s = line.strip()\n if not s:\n continue\n obj = json.loads(s)\n if not isinstance(obj, dict):\n raise ValueError(f\"line {i}: expected object\")\n name = obj.get(\"name\")\n qty = obj.get(\"qty\")\n if not isinstance(name, str) or not name:\n raise ValueError(f\"line {i}: name must be str\")\n if not isinstance(qty, int) or qty < 0:\n raise ValueError(f\"line {i}: qty must be non-negative int\")\n out.append(Item(name, qty))\n return out\n\nclass InventoryWriter:\n def __init__(self, base_dir: Path, store: Store | None = None) -> None:\n self._base = base_dir\n self._store: Store = store or FSStore()\n\n def write(self, rel_path: str, items: list[Item]) -> Path:\n dst = (self._base / rel_path).resolve()\n base = self._base.resolve()\n if dst != base and base not in dst.parents:\n raise ValueError(\"unsafe path traversal\")\n payload = json.dumps([item.__dict__ for item in items], ensure_ascii=False)\n self._store.write_text(dst, payload)\n return dst\n```\n\n```python\nimport json\nfrom pathlib import Path\nimport pytest\nfrom module_under_test import InventoryWriter, parse_items\n\ndef test_parse_items_valid():\n lines = [json.dumps({\"name\":\"x\",\"qty\":1})]\n assert parse_items(lines)[0].name == \"x\"\n\ndef test_writer_blocks_traversal(tmp_path: Path):\n w = InventoryWriter(tmp_path)\n with pytest.raises(ValueError):\n w.write(\"../evil.json\", [])\n```", "source": "WithinUsAI/python_GOD_coder_100k"} {"text": "Fix the bug and add pytest tests.\n\n```python\ndef f84899(n: int) -> int:\n # sum 1..n inclusive\n if n < 0: raise ValueError\n total = 0\n for k in range(n): # BUG\n total += k\n return total\n```\nReturn unified diffs for `m83557.py` and `test_m83557.py`.\n\n*** Begin Patch\n*** Update File: m83557.py\n@@\n def f84899(n: int) -> int:\n@@\n- for k in range(n): # BUG\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_m83557.py\n+import pytest\n+from m83557 import f84899\n+\n+def test_small():\n+ assert f84899(7) == 28\n+\n+def test_zero():\n+ assert f84899(0) == 0\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ f84899(-1)\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Fix a bug and add tests.\n\nFile: mc2j2rh40k.py\n```python\ndef d61by0x3qxdu(n: int) -> int:\n \"\"\"Sum 1..n inclusive.\"\"\"\n if n < 0:\n raise ValueError(\"n must be non-negative\")\n total = 0\n for k in range(n): # BUG: should include n\n total += k\n return total\n```\n\nReturn unified diffs for mc2j2rh40k.py and test_mc2j2rh40k.py (pytest).\n\n*** Begin Patch\n*** Update File: mc2j2rh40k.py\n@@\n def d61by0x3qxdu(n: int) -> int:\n@@\n total = 0\n- for k in range(n): # BUG: should include n\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_mc2j2rh40k.py\n+import pytest\n+from mc2j2rh40k import d61by0x3qxdu\n+\n+def test_zero():\n+ assert d61by0x3qxdu(0) == 0\n+\n+def test_one():\n+ assert d61by0x3qxdu(1) == 1\n+\n+def test_small():\n+ assert d61by0x3qxdu(7) == 28\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ d61by0x3qxdu(-1)\n+\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Write a thorough test suite for a Python component used for task scheduling.\nRequirements: cover edge cases, invalid inputs, and behavior invariants.\nConstraints: stdlib-only, must be memory-efficient, must include docstrings, must provide clear error messages.\nDifficulty: hard. Ensure the API is testable via dependency injection.\n\nDeliverable: production-ready reference solution.\n```python\n# tests (pytest-style) for a module providing: normalize(), parse_lines(), compute_stats()\nimport math\nimport pytest\n\ndef test_normalize_idempotent(module_under_test):\n x = \" A\\tB \"\n assert module_under_test.normalize(module_under_test.normalize(x)) == module_under_test.normalize(x)\n\ndef test_parse_lines_rejects_invalid(module_under_test):\n with pytest.raises(ValueError):\n module_under_test.parse_lines([\"\", \"???\", None]) # type: ignore[arg-type]\n\ndef test_compute_stats_basic(module_under_test):\n data = [1, 2, 3, 4]\n s = module_under_test.compute_stats(data)\n assert s.count == 4\n assert s.total == 10\n assert math.isclose(s.mean, 2.5)\n```", "source": "WithinUsAI/python_GOD_coder_100k"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: System domain: auth service\nStack: Rust, Axum, SQLx, Redis, Tokio, Docker\nCross-layer incident: invalid rollback sequence\nTask type: schema_contract_alignment\nDifficulty: hard\n\nSolve this as a complete-project engineer.\nOutput must include:\n- root cause across layers\n- final implementation patch\n- tests touching at least two layers\n- deployment or observability note\n- verification commands\n\nRepository sketch:\nrepo/\n src/main.cpp\n src/service.cpp\n include/service.h\n tests/test_service.cpp\n CMakeLists.txt\n\nFocus: Focus on multi-layer debugging across frontend, backend, database, CI, caching, and deployment.\n\nassistant: Diagnosis:\n- Root cause: invalid rollback sequence crosses service boundaries, so the fix must align code, contracts, tests, and deployment behavior.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```cpp\n#include \n#include \n\nusing Payload = std::unordered_map;\n\nPayload normalize_payload(const Payload& in) {\n Payload out;\n for (const auto& [k, v] : in) {\n if (!v.empty()) out[k] = v;\n }\n return out;\n}\n```\n\nTests:\n```cpp\nTEST_CASE(\"normalize_payload filters empty values\") {\n Payload in{{\"id\",\"7\"},{\"name\",\"\"}};\n auto out = normalize_payload(in);\n REQUIRE(out.count(\"id\") == 1);\n REQUIRE(out.count(\"name\") == 0);\n}\n```\n\nVerification:\n- `cmake --build build`\n- `ctest --test-dir build`\n\nEngineering notes:\n- Language: C++\n- Framework/tooling: STL\n- Stack context: Rust, Axum, SQLx, Redis, Tokio, Docker\n- Domain: auth service\n- Task type: schema_contract_alignment\n- Difficulty: hard\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Refactor to modern typed Python with immutability and tests.\n\nFile: jrwla1_ssy.py\n```python\nclass Fkozekmw:\n def __init__(self, name, values):\n self.name = name\n self.values = list(values)\n def add(self, v):\n self.values.append(v)\n def mean(self):\n s = 0\n for x in self.values:\n s += x\n return s / len(self.values)\n```\n\nReturn full new jrwla1_ssy.py and test_jrwla1_ssy.py.\n\n# jrwla1_ssy.py\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom typing import Iterable, Tuple\n\n@dataclass(frozen=True)\nclass Fkozekmw:\n name: str\n values: Tuple[float, ...]\n\n @staticmethod\n def create(name: str, values: Iterable[float]) -> \"Fkozekmw\":\n vals = tuple(float(v) for v in values)\n if not vals:\n raise ValueError(\"values must be non-empty\")\n return Fkozekmw(name=name, values=vals)\n\n def add(self, v: float) -> \"Fkozekmw\":\n return Fkozekmw(name=self.name, values=self.values + (float(v),))\n\n def mean(self) -> float:\n return sum(self.values) / len(self.values)\n\n# test_jrwla1_ssy.py\nimport pytest\nfrom jrwla1_ssy import Fkozekmw\n\ndef test_mean_and_add():\n c = Fkozekmw.create(\"a\", [1, 2, 3])\n assert c.mean() == 2.0\n assert c.add(5).mean() == (1 + 2 + 3 + 5) / 4\n\ndef test_empty_raises():\n with pytest.raises(ValueError):\n Fkozekmw.create(\"x\", [])", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Write a thorough test suite for a Python component used for time series.\nRequirements: cover edge cases, invalid inputs, and behavior invariants.\nConstraints: must be streaming-friendly, must be easy to extend, must include type hints, must be memory-efficient.\nDifficulty: medium. Provide helpful exceptions with actionable messages.\n\nDeliverable: production-ready reference solution.\n```python\n# tests (pytest-style) for a module providing: normalize(), parse_lines(), compute_stats()\nimport math\nimport pytest\n\ndef test_normalize_idempotent(module_under_test):\n x = \" A\\tB \"\n assert module_under_test.normalize(module_under_test.normalize(x)) == module_under_test.normalize(x)\n\ndef test_parse_lines_rejects_invalid(module_under_test):\n with pytest.raises(ValueError):\n module_under_test.parse_lines([\"\", \"???\", None]) # type: ignore[arg-type]\n\ndef test_compute_stats_basic(module_under_test):\n data = [1, 2, 3, 4]\n s = module_under_test.compute_stats(data)\n assert s.count == 4\n assert s.total == 10\n assert math.isclose(s.mean, 2.5)\n```", "source": "WithinUsAI/python_GOD_coder_100k"} {"text": "Refactor a Python module used for telemetry ingestion into a clean, extensible design.\nRequirements: outline the new architecture briefly, then provide the refactored code and tests.\nConstraints: must be memory-efficient, must provide clear error messages.\nDifficulty: expert. Handle empty inputs and malformed records gracefully.\n\nDeliverable: corrected code and verification tests.\nArchitecture:\n- Public facade class coordinating concerns (parsing, validation, persistence)\n- Small pure functions for testability\n- No global state; dependency injection for filesystem I/O\n\n```python\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom pathlib import Path\nfrom typing import Protocol, Iterable\nimport json\n\nclass Store(Protocol):\n def write_text(self, path: Path, data: str) -> None: ...\n\nclass FSStore:\n def write_text(self, path: Path, data: str) -> None:\n path.parent.mkdir(parents=True, exist_ok=True)\n path.write_text(data, encoding=\"utf-8\")\n\n@dataclass(frozen=True, slots=True)\nclass Item:\n name: str\n qty: int\n\ndef parse_items(lines: Iterable[str]) -> list[Item]:\n out: list[Item] = []\n for i, line in enumerate(lines, 1):\n s = line.strip()\n if not s:\n continue\n obj = json.loads(s)\n if not isinstance(obj, dict):\n raise ValueError(f\"line {i}: expected object\")\n name = obj.get(\"name\")\n qty = obj.get(\"qty\")\n if not isinstance(name, str) or not name:\n raise ValueError(f\"line {i}: name must be str\")\n if not isinstance(qty, int) or qty < 0:\n raise ValueError(f\"line {i}: qty must be non-negative int\")\n out.append(Item(name, qty))\n return out\n\nclass InventoryWriter:\n def __init__(self, base_dir: Path, store: Store | None = None) -> None:\n self._base = base_dir\n self._store: Store = store or FSStore()\n\n def write(self, rel_path: str, items: list[Item]) -> Path:\n dst = (self._base / rel_path).resolve()\n base = self._base.resolve()\n if dst != base and base not in dst.parents:\n raise ValueError(\"unsafe path traversal\")\n payload = json.dumps([item.__dict__ for item in items], ensure_ascii=False)\n self._store.write_text(dst, payload)\n return dst\n```\n\n```python\nimport json\nfrom pathlib import Path\nimport pytest\nfrom module_under_test import InventoryWriter, parse_items\n\ndef test_parse_items_valid():\n lines = [json.dumps({\"name\":\"x\",\"qty\":1})]\n assert parse_items(lines)[0].name == \"x\"\n\ndef test_writer_blocks_traversal(tmp_path: Path):\n w = InventoryWriter(tmp_path)\n with pytest.raises(ValueError):\n w.write(\"../evil.json\", [])\n```", "source": "WithinUsAI/python_GOD_coder_100k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Refactor to modern typed Python with immutability and tests.\n\nFile: zp4u4lofj5.py\n```python\nclass Nc6G37Bz90:\n def __init__(self, name, values):\n self.name = name\n self.values = list(values)\n def add(self, v):\n self.values.append(v)\n def mean(self):\n s = 0\n for x in self.values:\n s += x\n return s / len(self.values)\n```\n\nReturn full new zp4u4lofj5.py and test_zp4u4lofj5.py.\n\n# zp4u4lofj5.py\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom typing import Iterable, Tuple\n\n@dataclass(frozen=True)\nclass Nc6G37Bz90:\n name: str\n values: Tuple[float, ...]\n\n @staticmethod\n def create(name: str, values: Iterable[float]) -> \"Nc6G37Bz90\":\n vals = tuple(float(v) for v in values)\n if not vals:\n raise ValueError(\"values must be non-empty\")\n return Nc6G37Bz90(name=name, values=vals)\n\n def add(self, v: float) -> \"Nc6G37Bz90\":\n return Nc6G37Bz90(name=self.name, values=self.values + (float(v),))\n\n def mean(self) -> float:\n return sum(self.values) / len(self.values)\n\n# test_zp4u4lofj5.py\nimport pytest\nfrom zp4u4lofj5 import Nc6G37Bz90\n\ndef test_mean_and_add():\n c = Nc6G37Bz90.create(\"a\", [1, 2, 3])\n assert c.mean() == 2.0\n assert c.add(5).mean() == (1 + 2 + 3 + 5) / 4\n\ndef test_empty_raises():\n with pytest.raises(ValueError):\n Nc6G37Bz90.create(\"x\", [])", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Refactor a Python module used for validation into a clean, extensible design.\nRequirements: outline the new architecture briefly, then provide the refactored code and tests.\nConstraints: must handle Windows paths safely, must include docstrings.\nDifficulty: hard. Ensure the API is testable via dependency injection.\n\nDeliverable: API + reference implementation + tests.\nArchitecture:\n- Public facade class coordinating concerns (parsing, validation, persistence)\n- Small pure functions for testability\n- No global state; dependency injection for filesystem I/O\n\n```python\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom pathlib import Path\nfrom typing import Protocol, Iterable\nimport json\n\nclass Store(Protocol):\n def write_text(self, path: Path, data: str) -> None: ...\n\nclass FSStore:\n def write_text(self, path: Path, data: str) -> None:\n path.parent.mkdir(parents=True, exist_ok=True)\n path.write_text(data, encoding=\"utf-8\")\n\n@dataclass(frozen=True, slots=True)\nclass Item:\n name: str\n qty: int\n\ndef parse_items(lines: Iterable[str]) -> list[Item]:\n out: list[Item] = []\n for i, line in enumerate(lines, 1):\n s = line.strip()\n if not s:\n continue\n obj = json.loads(s)\n if not isinstance(obj, dict):\n raise ValueError(f\"line {i}: expected object\")\n name = obj.get(\"name\")\n qty = obj.get(\"qty\")\n if not isinstance(name, str) or not name:\n raise ValueError(f\"line {i}: name must be str\")\n if not isinstance(qty, int) or qty < 0:\n raise ValueError(f\"line {i}: qty must be non-negative int\")\n out.append(Item(name, qty))\n return out\n\nclass InventoryWriter:\n def __init__(self, base_dir: Path, store: Store | None = None) -> None:\n self._base = base_dir\n self._store: Store = store or FSStore()\n\n def write(self, rel_path: str, items: list[Item]) -> Path:\n dst = (self._base / rel_path).resolve()\n base = self._base.resolve()\n if dst != base and base not in dst.parents:\n raise ValueError(\"unsafe path traversal\")\n payload = json.dumps([item.__dict__ for item in items], ensure_ascii=False)\n self._store.write_text(dst, payload)\n return dst\n```\n\n```python\nimport json\nfrom pathlib import Path\nimport pytest\nfrom module_under_test import InventoryWriter, parse_items\n\ndef test_parse_items_valid():\n lines = [json.dumps({\"name\":\"x\",\"qty\":1})]\n assert parse_items(lines)[0].name == \"x\"\n\ndef test_writer_blocks_traversal(tmp_path: Path):\n w = InventoryWriter(tmp_path)\n with pytest.raises(ValueError):\n w.write(\"../evil.json\", [])\n```", "source": "WithinUsAI/python_GOD_coder_100k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Refactor to modern typed Python with immutability and tests.\n\nFile: nm8_m8wi.py\n```python\nclass Rd0D0Zw9:\n def __init__(self, name, values):\n self.name = name\n self.values = list(values)\n def add(self, v):\n self.values.append(v)\n def mean(self):\n s = 0\n for x in self.values:\n s += x\n return s / len(self.values)\n```\n\nReturn full new nm8_m8wi.py and test_nm8_m8wi.py.\n\n# nm8_m8wi.py\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom typing import Iterable, Tuple\n\n@dataclass(frozen=True)\nclass Rd0D0Zw9:\n name: str\n values: Tuple[float, ...]\n\n @staticmethod\n def create(name: str, values: Iterable[float]) -> \"Rd0D0Zw9\":\n vals = tuple(float(v) for v in values)\n if not vals:\n raise ValueError(\"values must be non-empty\")\n return Rd0D0Zw9(name=name, values=vals)\n\n def add(self, v: float) -> \"Rd0D0Zw9\":\n return Rd0D0Zw9(name=self.name, values=self.values + (float(v),))\n\n def mean(self) -> float:\n return sum(self.values) / len(self.values)\n\n# test_nm8_m8wi.py\nimport pytest\nfrom nm8_m8wi import Rd0D0Zw9\n\ndef test_mean_and_add():\n c = Rd0D0Zw9.create(\"a\", [1, 2, 3])\n assert c.mean() == 2.0\n assert c.add(5).mean() == (1 + 2 + 3 + 5) / 4\n\ndef test_empty_raises():\n with pytest.raises(ValueError):\n Rd0D0Zw9.create(\"x\", [])", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: Repository domain: job scheduler\nPrimary language: Rust\nFramework/tooling: Tokio\nReported problem: mismatched API contract\nTask type: bug_fix\nDifficulty: hard\n\nProduce a complete professional engineering response:\n1. Diagnose the root cause.\n2. Provide the corrected implementation or patch.\n3. Add tests.\n4. Add verification commands.\n5. Note edge cases and any migration or rollback risk.\n\nRepository sketch:\nrepo/\n src/main.rs\n src/lib.rs\n src/service.rs\n src/store.rs\n tests/integration.rs\n Cargo.toml\n\nQuality target:\n- Minimal diff unless redesign is clearly required\n- Production-ready code\n- No placeholders\n- Secure defaults\n- Clear acceptance of failure cases\n\nFocus: Focus on complete implementation quality, patch correctness, tests, and production readiness.\n\nassistant: Diagnosis:\n- Root cause: the failure around mismatched API contract is caused by missing validation, weak edge-case handling, or unsafe lifecycle behavior in the current implementation.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```rust\nuse std::collections::HashMap;\n\npub fn normalize_payload(payload: HashMap) -> HashMap {\n payload\n .into_iter()\n .filter(|(_, v)| !v.trim().is_empty())\n .collect()\n}\n```\n\nTests:\n```rust\n#[test]\nfn normalize_payload_filters_empty_values() {\n use std::collections::HashMap;\n let mut payload = HashMap::new();\n payload.insert(\"id\".to_string(), \"7\".to_string());\n payload.insert(\"name\".to_string(), \"\".to_string());\n let out = normalize_payload(payload);\n assert!(out.contains_key(\"id\"));\n assert!(!out.contains_key(\"name\"));\n}\n```\n\nVerification:\n- `cargo test`\n- `cargo clippy -- -D warnings`\n\nEngineering notes:\n- Language: Rust\n- Framework/tooling: Tokio\n- Stack context: Airflow, dbt, DuckDB, MinIO, pytest\n- Domain: job scheduler\n- Task type: bug_fix\n- Difficulty: hard\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "Fix the bug and add pytest tests.\n\n```python\ndef f39420(n: int) -> int:\n # sum 1..n inclusive\n if n < 0: raise ValueError\n total = 0\n for k in range(n): # BUG\n total += k\n return total\n```\nReturn unified diffs for `m77060.py` and `test_m77060.py`.\n\n*** Begin Patch\n*** Update File: m77060.py\n@@\n def f39420(n: int) -> int:\n@@\n- for k in range(n): # BUG\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_m77060.py\n+import pytest\n+from m77060 import f39420\n+\n+def test_small():\n+ assert f39420(7) == 28\n+\n+def test_zero():\n+ assert f39420(0) == 0\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ f39420(-1)\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Build an elite-grade solution in the domain of gpu compute for scenario: inventory & ordering.\nPrimary language: sql.\nDifficulty: expert.\nConstraints: design for backward compatibility and migrations, document performance characteristics, include invariants and failure modes, include tests or verification strategy, make the interface contract explicit.\nComponent: component_awuhpws.\nAssume strict auditability and replayable history.\nTask: Define properties/invariants and implement property-based tests (or generative tests) with a reference model and edge-case generators.\n\nOutput: elite-grade engineering answer with contracts, edge cases, and verification.\nOutput: properties + reference model + generative tests.\n\n**Properties**\n- Idempotency: replayed command yields same result.\n- Monotonicity: versions only increase.\n- Conservation: for queues, produced items == consumed items (multiset) under no-loss assumption.\n\n**Approach**\n- Write a small reference model (pure function).\n- Generate random sequences of operations; compare implementation outputs to model.\n\n\nExpert checks: state-machine reasoning, concurrency stress, and upgrade/rollback validated.", "source": "WithinUsAI/Elite_GOD_Coder_100k"} {"text": "Refactor an existing codebase in social media to support offline-first sync cleanly.\nTarget platform: ML (PyTorch + serving).\nRequirements: propose new modules/layers, dependency boundaries, and migration plan.\nConstraints: must be secure-by-default, must be production-ready, must be performant under load, must include documentation/comments.\nDifficulty: easy. Assume untrusted input; validate everything.\n\nOutput: design + implementation guidance suitable for shipping.\nDeliverable: refactor plan + module boundaries.\n\n**Proposed modules**\n- `domain/` pure business logic (no I/O)\n- `adapters/` DB, cache, external APIs\n- `api/` request/response validation and routing\n- `observability/` logging/metrics/tracing\n- `tests/` unit + integration suites\n\n**Migration plan**\n1. Introduce new interfaces + adapters behind feature flags.\n2. Dual-write or read-compat layer if schema changes.\n3. Incremental cutover; deprecate legacy module.\n\nKey rule: dependencies flow inward; domain has no framework imports.\n\n\nChecks: input validation, tests, and safe defaults included.", "source": "WithinUsAI/GOD_Coder_100k"} {"text": "Write pytest tests for `f77754`.\n\n```python\ndef f77754(a: int, b: int) -> int:\n return a*a + b*b\n```\nInclude edge cases and a property-style check.\n\n```python\nimport random\nfrom m96822 import f77754\n\ndef test_known():\n assert f77754(3,4) == 25\n\ndef test_zero():\n assert f77754(0,0) == 0\n\ndef test_property_nonnegative():\n for _ in range(200):\n a=random.randint(-50,50)\n b=random.randint(-50,50)\n assert f77754(a,b) >= 0\n```", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: System domain: data pipeline\nStack: Rust, Axum, SQLx, Redis, Tokio, Docker\nCross-layer incident: CI failures after dependency upgrade\nTask type: cache_consistency_patch\nDifficulty: hard\n\nSolve this as a complete-project engineer.\nOutput must include:\n- root cause across layers\n- final implementation patch\n- tests touching at least two layers\n- deployment or observability note\n- verification commands\n\nRepository sketch:\nrepo/\n cmd/server/main.go\n internal/service/service.go\n internal/store/store.go\n internal/api/api.go\n service_test.go\n go.mod\n\nFocus: Focus on multi-layer debugging across frontend, backend, database, CI, caching, and deployment.\n\nassistant: Diagnosis:\n- Root cause: CI failures after dependency upgrade crosses service boundaries, so the fix must align code, contracts, tests, and deployment behavior.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```go\npackage service\n\nimport \"fmt\"\n\nfunc NormalizePayload(payload map[string]any) map[string]any {\n\tout := make(map[string]any)\n\tfor k, v := range payload {\n\t\tif v == nil {\n\t\t\tcontinue\n\t\t}\n\t\tout[k] = v\n\t}\n\treturn out\n}\n\nfunc Handle(payload map[string]any) (map[string]any, error) {\n\tclean := NormalizePayload(payload)\n\tif _, ok := clean[\"id\"]; !ok {\n\t\treturn nil, fmt.Errorf(\"missing id\")\n\t}\n\treturn map[string]any{\"ok\": true, \"data\": clean}, nil\n}\n```\n\nTests:\n```go\npackage service\n\nimport \"testing\"\n\nfunc TestHandle(t *testing.T) {\n\tgot, err := Handle(map[string]any{\"id\": 7, \"name\": \"ok\", \"unused\": nil})\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tif got[\"ok\"] != true {\n\t\tt.Fatalf(\"expected ok=true\")\n\t}\n\tif _, err := Handle(map[string]any{\"name\": \"x\"}); err == nil {\n\t\tt.Fatalf(\"expected missing id error\")\n\t}\n}\n```\n\nVerification:\n- `go test ./...`\n- `go vet ./...`\n\nEngineering notes:\n- Language: Go\n- Framework/tooling: net/http\n- Stack context: Rust, Axum, SQLx, Redis, Tokio, Docker\n- Domain: data pipeline\n- Task type: cache_consistency_patch\n- Difficulty: hard\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "Debug and fix a subtle production bug related to audit logs in a fraud detection service.\nTarget platform: CI (GitHub Actions).\nRequirements: identify root cause, provide patch, and add regression tests.\nConstraints: must include tests, must be performant under load, must be production-ready.\nDifficulty: medium. Assume PII must be protected.\n\nOutput: production-oriented blueprint with code where appropriate.\nDeliverable: production-grade reference implementation (FastAPI) + tests.\n\n```python\n# app.py\nfrom __future__ import annotations\n\nimport hashlib\nimport json\nfrom dataclasses import dataclass\nfrom datetime import datetime, timezone\nfrom typing import Any, Optional\n\nfrom fastapi import FastAPI, Header, HTTPException\nfrom pydantic import BaseModel, Field\n\napp = FastAPI(title=\"Idempotent API\")\n\nclass CreateReq(BaseModel):\n tenant_id: str = Field(min_length=1)\n amount_cents: int = Field(ge=0)\n currency: str = Field(min_length=3, max_length=3)\n\nclass CreateResp(BaseModel):\n id: str\n created_at: str\n echo: CreateReq\n\n@dataclass\nclass _IdempoEntry:\n request_hash: str\n response_json: str\n\n# In production: Postgres table with UNIQUE(tenant_id, key)\n_IDEMPO: dict[tuple[str, str], _IdempoEntry] = {}\n\ndef _hash_req(req: CreateReq) -> str:\n raw = req.model_dump_json()\n return hashlib.sha256(raw.encode(\"utf-8\")).hexdigest()\n\n@app.post(\"/v1/payments\", response_model=CreateResp)\ndef create_payment(\n req: CreateReq,\n idempotency_key: Optional[str] = Header(default=None, alias=\"Idempotency-Key\"),\n) -> Any:\n if not idempotency_key:\n raise HTTPException(status_code=400, detail=\"Missing Idempotency-Key\")\n if len(idempotency_key) > 128:\n raise HTTPException(status_code=400, detail=\"Idempotency-Key too long\")\n\n key = (req.tenant_id, idempotency_key)\n rh = _hash_req(req)\n\n existing = _IDEMPO.get(key)\n if existing:\n if existing.request_hash != rh:\n raise HTTPException(status_code=409, detail=\"Idempotency-Key reuse with different payload\")\n return json.loads(existing.response_json)\n\n # Create new payment (stubbed)\n pid = hashlib.md5(f\"{req.tenant_id}:{idempotency_key}\".encode()).hexdigest()\n resp = CreateResp(\n id=pid,\n created_at=datetime.now(timezone.utc).isoformat(),\n echo=req,\n )\n _IDEMPO[key] = _IdempoEntry(request_hash=rh, response_json=resp.model_dump_json())\n return resp\n```\n\n```python\n# test_app.py (pytest)\nfrom fastapi.testclient import TestClient\nfrom app import app\n\nclient = TestClient(app)\n\ndef test_idempotent_replay():\n headers = {\"Idempotency-Key\": \"abc\"}\n body = {\"tenant_id\":\"t1\",\"amount_cents\":100,\"currency\":\"USD\"}\n r1 = client.post(\"/v1/payments\", json=body, headers=headers)\n r2 = client.post(\"/v1/payments\", json=body, headers=headers)\n assert r1.status_code == 200 and r2.status_code == 200\n assert r1.json() == r2.json()\n\ndef test_payload_conflict():\n headers = {\"Idempotency-Key\": \"abc\"}\n b1 = {\"tenant_id\":\"t1\",\"amount_cents\":100,\"currency\":\"USD\"}\n b2 = {\"tenant_id\":\"t1\",\"amount_cents\":200,\"currency\":\"USD\"}\n assert client.post(\"/v1/payments\", json=b1, headers=headers).status_code == 200\n assert client.post(\"/v1/payments\", json=b2, headers=headers).status_code == 409\n```\n\nNotes:\n- Replace in-memory store with a DB table and transaction.\n- Store response + request hash to detect key reuse with different payload.\n\n\nChecks: input validation, tests, and safe defaults included.", "source": "WithinUsAI/GOD_Coder_100k"} {"text": "Task type: kernel_syscall_design\nScenario: identity and access\nDomain focus: stream processing\nPrimary language: cpp\nDifficulty: expert+\nScale/SLO: 99.99% availability\nComponent: component_rtfbxqjh\nConstraints: include deterministic replay plan, include performance model and limits, include backward compatibility and migration plan, assume adversarial inputs; validate everything, explicit contracts and invariants, include failure modes and recovery\nAssume weekly network partitions.\nDeliverable: Design a safe syscall/API boundary: ABI, validation, error codes, and compatibility; include tests and fuzz plan.\n\nOutput: elite engineering answer optimized for correctness, performance, and operability.\n**Contract**\n- Inputs validated at the boundary; explicit error taxonomy.\n- Idempotency for side effects via request_id; deterministic replay.\n- Backward compatibility: additive changes by default; versioned breaking changes.\n**Invariants**\n- Safety: state transitions preserve invariants; no partial commit leaks.\n- Liveness: under bounded faults and stable network, progress occurs.\n- Determinism: replay of the same event log yields identical outputs.\n**Failure modes & recovery**\n- Crash during commit: WAL replay completes or transaction aborts; no torn writes.\n- Data corruption: checksums + scrubber; quarantine and rebuild from replicas/snapshots.\n- Duplicate requests: de-duplicate by (tenant, request_id) returning cached response.\n**Security posture (defensive)**\n- Threat model: auth/authz, injection, replay/abuse, supply chain.\n- Least privilege; secrets in managed store; audit logs for sensitive ops.\n- Input normalization, parameterized queries, path traversal protections.\n**Verification strategy**\n- Fuzzing of parsers/framers/validators with corpus seeds.\n- Property tests against a pure reference model (state machine).\n- Deterministic simulation with fault injection (crash/partition/latency).\n\n**Snippet**\n```text\nImplementation sketch: factor pure state-machine core; adapters for I/O; add deterministic replay log.\n```\nExpert+ checks: mechanized invariants (or exhaustive model checking), adversarial fuzzing, and multi-region failure drills.", "source": "WithinUsAI/Omega_Genesis_Coder_100k"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: Language: SQL\nFramework/tooling: DuckDB\nDomain: benchmark harness\nLogic challenge: N+1 query explosion\nTask type: misleading_symptom_debug\nDifficulty: hard\n\nReturn a rigorous engineering answer:\n- identify the hidden root cause or logical failure\n- present the corrected implementation\n- add tests that prove the fix\n- list verification commands\n- explain why naive fixes are insufficient when relevant\n\nRepository sketch:\nrepo/\n migrations/\n 001_init.sql\n 002_add_index.sql\n queries/\n report.sql\n tests/\n report_cases.md\n\nFocus: Focus on ambiguity, misleading symptoms, hidden root causes, and high-stakes debugging.\n\nassistant: Diagnosis:\n- Hidden root cause: N+1 query explosion presents misleading symptoms, so the patch must target the actual logic boundary rather than the first visible failure.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```sql\nWITH ranked AS (\n SELECT\n user_id,\n created_at,\n amount,\n ROW_NUMBER() OVER (PARTITION BY user_id ORDER BY created_at DESC, id DESC) AS rn\n FROM orders\n)\nSELECT user_id, created_at, amount\nFROM ranked\nWHERE rn = 1;\n```\n\nTests:\n```sql\n-- Correctness checks:\n-- 1) multiple rows per user\n-- 2) identical timestamps require deterministic tie-breaker\n-- 3) null values handled by business rules\n```\n\nVerification:\n- `run migration checks`\n- `run query correctness cases`\n\nEngineering notes:\n- Language: SQL\n- Framework/tooling: DuckDB\n- Stack context: FastAPI, PostgreSQL, Redis, Celery, pytest, Docker\n- Domain: benchmark harness\n- Task type: misleading_symptom_debug\n- Difficulty: hard\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "Design CI/CD for a education service delivering background jobs.\nTarget platform: web (React + TypeScript).\nRequirements: pipelines, checks, artifact strategy, deployments, and rollbacks.\nConstraints: must include tests, must be observable (logs/metrics/traces), must be secure-by-default.\nDifficulty: hard. Include rollback strategy.\n\nOutput: engineering-grade answer with edge cases covered.\nDeliverable: CI/CD pipeline (GitHub Actions) with quality gates.\n\n```yaml\nname: ci\non:\n pull_request:\n push:\n branches: [main]\n\njobs:\n test:\n runs-on: ubuntu-latest\n steps:\n - uses: actions/checkout@v4\n - uses: actions/setup-python@v5\n with:\n python-version: \"3.11\"\n - run: python -m pip install -U pip\n - run: pip install -r requirements.txt\n - run: pip install -r requirements-dev.txt\n - run: ruff check .\n - run: mypy .\n - run: pytest -q --maxfail=1 --disable-warnings\n\n docker:\n needs: test\n runs-on: ubuntu-latest\n steps:\n - uses: actions/checkout@v4\n - uses: docker/setup-buildx-action@v3\n - run: docker build -t app:${{ github.sha }} .\n```\n\nDeployment strategy:\n- main → build → deploy to staging → smoke tests → canary to prod.\n- Rollback: redeploy previous image + DB migration rollback plan.\n\n\nHard-mode checks: concurrency safety, idempotency, and rollback validated; add chaos tests where feasible.", "source": "WithinUsAI/GOD_Coder_100k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Refactor to modern typed Python with immutability and tests.\n\nFile: inuu6xz.py\n```python\nclass Facy37B3Aed:\n def __init__(self, name, values):\n self.name = name\n self.values = list(values)\n def add(self, v):\n self.values.append(v)\n def mean(self):\n s = 0\n for x in self.values:\n s += x\n return s / len(self.values)\n```\n\nReturn full new inuu6xz.py and test_inuu6xz.py.\n\n# inuu6xz.py\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom typing import Iterable, Tuple\n\n@dataclass(frozen=True)\nclass Facy37B3Aed:\n name: str\n values: Tuple[float, ...]\n\n @staticmethod\n def create(name: str, values: Iterable[float]) -> \"Facy37B3Aed\":\n vals = tuple(float(v) for v in values)\n if not vals:\n raise ValueError(\"values must be non-empty\")\n return Facy37B3Aed(name=name, values=vals)\n\n def add(self, v: float) -> \"Facy37B3Aed\":\n return Facy37B3Aed(name=self.name, values=self.values + (float(v),))\n\n def mean(self) -> float:\n return sum(self.values) / len(self.values)\n\n# test_inuu6xz.py\nimport pytest\nfrom inuu6xz import Facy37B3Aed\n\ndef test_mean_and_add():\n c = Facy37B3Aed.create(\"a\", [1, 2, 3])\n assert c.mean() == 2.0\n assert c.add(5).mean() == (1 + 2 + 3 + 5) / 4\n\ndef test_empty_raises():\n with pytest.raises(ValueError):\n Facy37B3Aed.create(\"x\", [])", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Task type: gpu_serving_pipeline\nScenario: rate limit gateway\nDomain focus: static analysis\nPrimary language: python\nDifficulty: expert+\nScale/SLO: 100k RPS peak\nComponent: component_cunudzbj\nConstraints: include security threat model (defensive only), include deterministic replay plan, include test vectors and fuzz strategy, avoid data races and undefined behavior, assume adversarial inputs; validate everything\nAssume tight memory budget and cold-start constraints.\nDeliverable: Design a GPU inference serving pipeline: batching, scheduling, memory management, tail-latency control, and monitoring.\n\nOutput: rigorous design + invariants + verification plan + implementation sketch.\n**Contract**\n- Inputs validated at the boundary; explicit error taxonomy.\n- Idempotency for side effects via request_id; deterministic replay.\n- Backward compatibility: additive changes by default; versioned breaking changes.\n**Invariants**\n- Isolation: tenant boundary enforced; no cross-tenant reads/writes.\n- Determinism: replay of the same event log yields identical outputs.\n- Liveness: under bounded faults and stable network, progress occurs.\n**Failure modes & recovery**\n- Data corruption: checksums + scrubber; quarantine and rebuild from replicas/snapshots.\n- Network partition: minority cannot commit; clients receive retriable errors.\n- Duplicate requests: de-duplicate by (tenant, request_id) returning cached response.\n**Security posture (defensive)**\n- Threat model: auth/authz, injection, replay/abuse, supply chain.\n- Least privilege; secrets in managed store; audit logs for sensitive ops.\n- Input normalization, parameterized queries, path traversal protections.\n**Verification strategy**\n- Canary + shadow traffic; invariants checked in production via assertions/metrics.\n- Property tests against a pure reference model (state machine).\n- Fuzzing of parsers/framers/validators with corpus seeds.\n\n**Snippet**\n```text\nImplementation sketch: factor pure state-machine core; adapters for I/O; add deterministic replay log.\n```\nExpert+ checks: mechanized invariants (or exhaustive model checking), adversarial fuzzing, and multi-region failure drills.", "source": "WithinUsAI/Omega_Genesis_Coder_100k"} {"text": "Build an elite-grade solution in the domain of distributed systems for scenario: inventory & ordering.\nPrimary language: python.\nDifficulty: hard.\nConstraints: include invariants and failure modes, document performance characteristics, make the interface contract explicit, design for backward compatibility and migrations.\nComponent: component_kcbxvng.\nAssume cold-start and memory limits are tight.\nTask: Implement or outline a storage/indexing subsystem (LSM/B-Tree, WAL, snapshots). Include transaction/consistency considerations and benchmark plan.\n\nOutput: elite-grade engineering answer with contracts, edge cases, and verification.\nOutput: storage design + WAL + compaction + benchmarks.\n\n**Design**\n- WAL (append-only) for durability; fsync policy configurable.\n- Memtable (in-memory) → flush to immutable SSTables.\n- LSM compaction tiers; bloom filters per SSTable for point-lookups.\n- Manifest tracks SSTable set; atomic pointer swap on updates.\n\n**Correctness**\n- Crash recovery: replay WAL to rebuild memtable; manifest ensures last consistent set.\n- Reads: merge memtable + SSTables newest→oldest; tombstones override older values.\n\n**Bench plan**\n- Workloads: write-heavy, read-heavy, mixed; measure p50/p95 latency and write amplification.\n- Track compaction debt and space amplification.\n\n**Test plan**\n- Fuzz crash points: kill after WAL append / after manifest update; verify invariants on restart.\n\n\nHard checks: failure injection tests and performance regressions gated.", "source": "WithinUsAI/Elite_GOD_Coder_100k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Fix a bug and add tests.\n\nFile: jm0inqxlt.py\n```python\ndef o1b7sigobk6(n: int) -> int:\n \"\"\"Sum 1..n inclusive.\"\"\"\n if n < 0:\n raise ValueError(\"n must be non-negative\")\n total = 0\n for k in range(n): # BUG: should include n\n total += k\n return total\n```\n\nReturn unified diffs for jm0inqxlt.py and test_jm0inqxlt.py (pytest).\n\n*** Begin Patch\n*** Update File: jm0inqxlt.py\n@@\n def o1b7sigobk6(n: int) -> int:\n@@\n total = 0\n- for k in range(n): # BUG: should include n\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_jm0inqxlt.py\n+import pytest\n+from jm0inqxlt import o1b7sigobk6\n+\n+def test_zero():\n+ assert o1b7sigobk6(0) == 0\n+\n+def test_one():\n+ assert o1b7sigobk6(1) == 1\n+\n+def test_small():\n+ assert o1b7sigobk6(7) == 28\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ o1b7sigobk6(-1)\n+\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Build an elite-grade solution in the domain of distributed systems for scenario: job scheduler.\nPrimary language: rust.\nDifficulty: hard.\nConstraints: include invariants and failure modes, design for backward compatibility and migrations, include tests or verification strategy.\nComponent: component_qprhufp.\nAssume compliance requires data deletion with proofs.\nTask: Design an application-level protocol (framing, retries, timeouts, backpressure). Provide client/server skeleton and test vectors.\n\nOutput: rigorous solution with invariants, failure modes, and performance notes.\nOutput: protocol framing + retry policy + client/server skeleton.\n\n**Framing**\n- Length-prefixed: uint32_be length + payload\n- Payload: msgpack/json; include request_id, type, and optional checksum\n\n**Reliability**\n- Retries only for idempotent ops; exponential backoff + jitter.\n- Timeouts: connect, read, overall; enforce max in-flight to provide backpressure.\n\n**Test vectors**\n- Corrupted length / truncated frame rejected\n- Duplicate request_id returns cached response\n- Slowloris protection by read deadlines\n\n\nHard checks: failure injection tests and performance regressions gated.", "source": "WithinUsAI/Elite_GOD_Coder_100k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Refactor to modern typed Python with immutability and tests.\n\nFile: eoilozcb.py\n```python\nclass Hk48Zy:\n def __init__(self, name, values):\n self.name = name\n self.values = list(values)\n def add(self, v):\n self.values.append(v)\n def mean(self):\n s = 0\n for x in self.values:\n s += x\n return s / len(self.values)\n```\n\nReturn full new eoilozcb.py and test_eoilozcb.py.\n\n# eoilozcb.py\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom typing import Iterable, Tuple\n\n@dataclass(frozen=True)\nclass Hk48Zy:\n name: str\n values: Tuple[float, ...]\n\n @staticmethod\n def create(name: str, values: Iterable[float]) -> \"Hk48Zy\":\n vals = tuple(float(v) for v in values)\n if not vals:\n raise ValueError(\"values must be non-empty\")\n return Hk48Zy(name=name, values=vals)\n\n def add(self, v: float) -> \"Hk48Zy\":\n return Hk48Zy(name=self.name, values=self.values + (float(v),))\n\n def mean(self) -> float:\n return sum(self.values) / len(self.values)\n\n# test_eoilozcb.py\nimport pytest\nfrom eoilozcb import Hk48Zy\n\ndef test_mean_and_add():\n c = Hk48Zy.create(\"a\", [1, 2, 3])\n assert c.mean() == 2.0\n assert c.add(5).mean() == (1 + 2 + 3 + 5) / 4\n\ndef test_empty_raises():\n with pytest.raises(ValueError):\n Hk48Zy.create(\"x\", [])", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Fix a bug and add tests.\n\nFile: ceb7hm7jwf.py\n```python\ndef a0dmj_1bpb9e(n: int) -> int:\n \"\"\"Sum 1..n inclusive.\"\"\"\n if n < 0:\n raise ValueError(\"n must be non-negative\")\n total = 0\n for k in range(n): # BUG: should include n\n total += k\n return total\n```\n\nReturn unified diffs for ceb7hm7jwf.py and test_ceb7hm7jwf.py (pytest).\n\n*** Begin Patch\n*** Update File: ceb7hm7jwf.py\n@@\n def a0dmj_1bpb9e(n: int) -> int:\n@@\n total = 0\n- for k in range(n): # BUG: should include n\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_ceb7hm7jwf.py\n+import pytest\n+from ceb7hm7jwf import a0dmj_1bpb9e\n+\n+def test_zero():\n+ assert a0dmj_1bpb9e(0) == 0\n+\n+def test_one():\n+ assert a0dmj_1bpb9e(1) == 1\n+\n+def test_small():\n+ assert a0dmj_1bpb9e(7) == 28\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ a0dmj_1bpb9e(-1)\n+\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Task type: lockfree_primitive\nScenario: real-time notification hub\nDomain focus: stream processing\nPrimary language: cpp\nDifficulty: hard\nScale/SLO: 1M msgs/min\nComponent: component_kyuzrcvu\nConstraints: explicit contracts and invariants, include test vectors and fuzz strategy, include backward compatibility and migration plan, include deterministic replay plan, include performance model and limits, include verification strategy, assume adversarial inputs; validate everything\nAssume tight memory budget and cold-start constraints.\nDeliverable: Design a lock-free primitive with memory ordering reasoning and stress tests (no UB).\n\nOutput: contract-first solution with failure modes, security posture, and test/verification strategy.\n**Contract**\n- Inputs validated at the boundary; explicit error taxonomy.\n- Idempotency for side effects via request_id; deterministic replay.\n- Backward compatibility: additive changes by default; versioned breaking changes.\n**Invariants**\n- Safety: state transitions preserve invariants; no partial commit leaks.\n- Liveness: under bounded faults and stable network, progress occurs.\n- Isolation: tenant boundary enforced; no cross-tenant reads/writes.\n**Failure modes & recovery**\n- Network partition: minority cannot commit; clients receive retriable errors.\n- Data corruption: checksums + scrubber; quarantine and rebuild from replicas/snapshots.\n- Duplicate requests: de-duplicate by (tenant, request_id) returning cached response.\n**Security posture (defensive)**\n- Threat model: auth/authz, injection, replay/abuse, supply chain.\n- Least privilege; secrets in managed store; audit logs for sensitive ops.\n- Input normalization, parameterized queries, path traversal protections.\n**Verification strategy**\n- Fuzzing of parsers/framers/validators with corpus seeds.\n- Deterministic simulation with fault injection (crash/partition/latency).\n- Canary + shadow traffic; invariants checked in production via assertions/metrics.\n\n**Snippet**\n```rust\n// Skeleton: SPSC ring buffer with acquire/release (outline)\nuse std::sync::atomic::{AtomicUsize, Ordering};\n\npub struct Ring {\n buf: Vec>,\n head: AtomicUsize,\n tail: AtomicUsize,\n cap: usize,\n}\n\n// Correctness sketch: producer uses Release on tail store, consumer uses Acquire on tail load.\n```\n\nHard checks: fault injection tests gate merges; perf thresholds enforced in CI.", "source": "WithinUsAI/Omega_Genesis_Coder_100k"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: Language: Go\nFramework/tooling: Gin\nDomain: auth service\nLogic challenge: monorepo toolchain skew\nTask type: transaction_integrity_fix\nDifficulty: hard\n\nReturn a rigorous engineering answer:\n- identify the hidden root cause or logical failure\n- present the corrected implementation\n- add tests that prove the fix\n- list verification commands\n- explain why naive fixes are insufficient when relevant\n\nRepository sketch:\nrepo/\n cmd/server/main.go\n internal/service/service.go\n internal/store/store.go\n internal/api/api.go\n service_test.go\n go.mod\n\nFocus: Focus on ambiguity, misleading symptoms, hidden root causes, and high-stakes debugging.\n\nassistant: Diagnosis:\n- Hidden root cause: monorepo toolchain skew presents misleading symptoms, so the patch must target the actual logic boundary rather than the first visible failure.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```go\npackage service\n\nimport \"fmt\"\n\nfunc NormalizePayload(payload map[string]any) map[string]any {\n\tout := make(map[string]any)\n\tfor k, v := range payload {\n\t\tif v == nil {\n\t\t\tcontinue\n\t\t}\n\t\tout[k] = v\n\t}\n\treturn out\n}\n\nfunc Handle(payload map[string]any) (map[string]any, error) {\n\tclean := NormalizePayload(payload)\n\tif _, ok := clean[\"id\"]; !ok {\n\t\treturn nil, fmt.Errorf(\"missing id\")\n\t}\n\treturn map[string]any{\"ok\": true, \"data\": clean}, nil\n}\n```\n\nTests:\n```go\npackage service\n\nimport \"testing\"\n\nfunc TestHandle(t *testing.T) {\n\tgot, err := Handle(map[string]any{\"id\": 7, \"name\": \"ok\", \"unused\": nil})\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tif got[\"ok\"] != true {\n\t\tt.Fatalf(\"expected ok=true\")\n\t}\n\tif _, err := Handle(map[string]any{\"name\": \"x\"}); err == nil {\n\t\tt.Fatalf(\"expected missing id error\")\n\t}\n}\n```\n\nVerification:\n- `go test ./...`\n- `go vet ./...`\n\nEngineering notes:\n- Language: Go\n- Framework/tooling: Gin\n- Stack context: FastAPI, PostgreSQL, Redis, Celery, pytest, Docker\n- Domain: auth service\n- Task type: transaction_integrity_fix\n- Difficulty: hard\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "Debug and fix a subtle production bug related to role-based access control in a content moderation service.\nTarget platform: CI (GitHub Actions).\nRequirements: identify root cause, provide patch, and add regression tests.\nConstraints: must include tests, must be performant under load, must be secure-by-default, must be production-ready, must be easy to extend.\nDifficulty: expert. Assume PII must be protected.\n\nOutput: production-oriented blueprint with code where appropriate.\nDeliverable: production-grade reference implementation (FastAPI) + tests.\n\n```python\n# app.py\nfrom __future__ import annotations\n\nimport hashlib\nimport json\nfrom dataclasses import dataclass\nfrom datetime import datetime, timezone\nfrom typing import Any, Optional\n\nfrom fastapi import FastAPI, Header, HTTPException\nfrom pydantic import BaseModel, Field\n\napp = FastAPI(title=\"Idempotent API\")\n\nclass CreateReq(BaseModel):\n tenant_id: str = Field(min_length=1)\n amount_cents: int = Field(ge=0)\n currency: str = Field(min_length=3, max_length=3)\n\nclass CreateResp(BaseModel):\n id: str\n created_at: str\n echo: CreateReq\n\n@dataclass\nclass _IdempoEntry:\n request_hash: str\n response_json: str\n\n# In production: Postgres table with UNIQUE(tenant_id, key)\n_IDEMPO: dict[tuple[str, str], _IdempoEntry] = {}\n\ndef _hash_req(req: CreateReq) -> str:\n raw = req.model_dump_json()\n return hashlib.sha256(raw.encode(\"utf-8\")).hexdigest()\n\n@app.post(\"/v1/payments\", response_model=CreateResp)\ndef create_payment(\n req: CreateReq,\n idempotency_key: Optional[str] = Header(default=None, alias=\"Idempotency-Key\"),\n) -> Any:\n if not idempotency_key:\n raise HTTPException(status_code=400, detail=\"Missing Idempotency-Key\")\n if len(idempotency_key) > 128:\n raise HTTPException(status_code=400, detail=\"Idempotency-Key too long\")\n\n key = (req.tenant_id, idempotency_key)\n rh = _hash_req(req)\n\n existing = _IDEMPO.get(key)\n if existing:\n if existing.request_hash != rh:\n raise HTTPException(status_code=409, detail=\"Idempotency-Key reuse with different payload\")\n return json.loads(existing.response_json)\n\n # Create new payment (stubbed)\n pid = hashlib.md5(f\"{req.tenant_id}:{idempotency_key}\".encode()).hexdigest()\n resp = CreateResp(\n id=pid,\n created_at=datetime.now(timezone.utc).isoformat(),\n echo=req,\n )\n _IDEMPO[key] = _IdempoEntry(request_hash=rh, response_json=resp.model_dump_json())\n return resp\n```\n\n```python\n# test_app.py (pytest)\nfrom fastapi.testclient import TestClient\nfrom app import app\n\nclient = TestClient(app)\n\ndef test_idempotent_replay():\n headers = {\"Idempotency-Key\": \"abc\"}\n body = {\"tenant_id\":\"t1\",\"amount_cents\":100,\"currency\":\"USD\"}\n r1 = client.post(\"/v1/payments\", json=body, headers=headers)\n r2 = client.post(\"/v1/payments\", json=body, headers=headers)\n assert r1.status_code == 200 and r2.status_code == 200\n assert r1.json() == r2.json()\n\ndef test_payload_conflict():\n headers = {\"Idempotency-Key\": \"abc\"}\n b1 = {\"tenant_id\":\"t1\",\"amount_cents\":100,\"currency\":\"USD\"}\n b2 = {\"tenant_id\":\"t1\",\"amount_cents\":200,\"currency\":\"USD\"}\n assert client.post(\"/v1/payments\", json=b1, headers=headers).status_code == 200\n assert client.post(\"/v1/payments\", json=b2, headers=headers).status_code == 409\n```\n\nNotes:\n- Replace in-memory store with a DB table and transaction.\n- Store response + request hash to detect key reuse with different payload.\n\n\nHard-mode checks: concurrency safety, idempotency, and rollback validated; add chaos tests where feasible.", "source": "WithinUsAI/GOD_Coder_100k"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: Language: C#\nFramework/tooling: NUnit\nDomain: job scheduler\nLogic challenge: stale cache invalidation\nTask type: multi_file_migration_repair\nDifficulty: hard\n\nReturn a rigorous engineering answer:\n- identify the hidden root cause or logical failure\n- present the corrected implementation\n- add tests that prove the fix\n- list verification commands\n- explain why naive fixes are insufficient when relevant\n\nRepository sketch:\nrepo/\n src/App/Program.cs\n src/App/Service.cs\n tests/App.Tests/ServiceTests.cs\n App.sln\n\nFocus: Focus on staff-level problem solving with multi-file patches, rollout implications, performance and security tradeoffs.\n\nassistant: Diagnosis:\n- Staff-level diagnosis: stale cache invalidation impacts correctness, operability, and future maintenance, so the fix must be minimal where possible but complete where necessary.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```csharp\nusing System;\nusing System.Collections.Generic;\n\npublic static class RequestHandler\n{\n public static Dictionary HandleRequest(Dictionary payload)\n {\n var clean = new Dictionary();\n foreach (var entry in payload)\n {\n if (entry.Value != null)\n clean[entry.Key.Trim()] = entry.Value;\n }\n if (!clean.ContainsKey(\"id\"))\n throw new ArgumentException(\"missing id\");\n return new Dictionary\n {\n [\"ok\"] = true,\n [\"data\"] = clean\n };\n }\n}\n```\n\nTests:\n```csharp\nusing System;\nusing System.Collections.Generic;\nusing Xunit;\n\npublic class RequestHandlerTests\n{\n [Fact]\n public void RequiresId()\n {\n Assert.Throws(() => RequestHandler.HandleRequest(new Dictionary { [\"name\"] = \"x\" }));\n }\n}\n```\n\nVerification:\n- `dotnet test`\n- `dotnet build`\n\nEngineering notes:\n- Language: C#\n- Framework/tooling: NUnit\n- Stack context: GitHub Actions, Docker Compose, Kubernetes, Terraform\n- Domain: job scheduler\n- Task type: multi_file_migration_repair\n- Difficulty: hard\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: Language: TypeScript\nFramework/tooling: Node.js\nDomain: auth service\nLogic challenge: broken pagination cursor\nTask type: state_machine_patch\nDifficulty: hard\n\nReturn a rigorous engineering answer:\n- identify the hidden root cause or logical failure\n- present the corrected implementation\n- add tests that prove the fix\n- list verification commands\n- explain why naive fixes are insufficient when relevant\n\nRepository sketch:\nrepo/\n src/\n api.ts\n service.ts\n schema.ts\n tests/\n api.test.ts\n package.json\n\nFocus: Focus on strong structured logic with edge cases, data validation, and concurrency safety.\n\nassistant: Diagnosis:\n- Root cause: the failure around broken pagination cursor is caused by missing validation, weak edge-case handling, or unsafe lifecycle behavior in the current implementation.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```ts\ntype Payload = Record;\n\nexport function normalizePayload(payload: Payload): Payload {\n if (!payload || typeof payload !== \"object\" || Array.isArray(payload)) {\n throw new TypeError(\"payload must be a plain object\");\n }\n return Object.fromEntries(\n Object.entries(payload)\n .filter(([, value]) => value !== null && value !== undefined)\n .map(([key, value]) => [String(key).trim(), value])\n );\n}\n\nexport function handleBrokenPaginationCursor(payload: Payload) {\n const clean = normalizePayload(payload);\n if (!(\"id\" in clean)) {\n return { ok: false, data: {}, error: \"missing id\" };\n }\n return { ok: true, data: clean, error: null };\n}\n```\n\nTests:\n```ts\nimport { describe, it, expect } from \"vitest\";\nimport { handleBrokenPaginationCursor } from \"../src/service\";\n\ndescribe(\"handler\", () => {\n it(\"accepts valid input\", () => {\n expect(handleBrokenPaginationCursor({ id: 7, name: \"ok\", unused: null })).toEqual({\n ok: true,\n data: { id: 7, name: \"ok\" },\n error: null\n });\n });\n\n it(\"rejects missing id\", () => {\n expect(handleBrokenPaginationCursor({ name: \"x\" }).error).toMatch(/missing id/);\n });\n});\n```\n\nVerification:\n- `npm test`\n- `npm run typecheck`\n- `npm run lint`\n\nEngineering notes:\n- Language: TypeScript\n- Framework/tooling: Node.js\n- Stack context: Next.js, Node.js, Prisma, PostgreSQL, Playwright, Docker\n- Domain: auth service\n- Task type: state_machine_patch\n- Difficulty: hard\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "Implement a web feature for logistics: idempotent payments.\nTarget platform: web (React + TypeScript).\nRequirements: accessible UI, API integration, and tests.\nConstraints: must be performant under load, must include clear error handling, must include tests, must include type hints where applicable, must be easy to extend.\nDifficulty: expert. Assume schema evolves frequently; design for migrations.\n\nOutput: actionable implementation and verification artifacts.\nDeliverable: accessible React + TypeScript feature skeleton with tests.\n\n```tsx\n// Feature.tsx\nimport React, { useEffect, useMemo, useState } from \"react\";\n\ntype Item = { id: string; label: string };\n\nexport function Feature({ fetchItems }: { fetchItems: () => Promise }) {\n const [items, setItems] = useState([]);\n const [q, setQ] = useState(\"\");\n const filtered = useMemo(\n () => items.filter(i => i.label.toLowerCase().includes(q.toLowerCase())),\n [items, q]\n );\n\n useEffect(() => {\n let cancelled = false;\n fetchItems().then(xs => { if (!cancelled) setItems(xs); });\n return () => { cancelled = true; };\n }, [fetchItems]);\n\n return (\n
\n \n
    \n {filtered.map(i =>
  • {i.label}
  • )}\n
\n
\n );\n}\n```\n\n```tsx\n// Feature.test.tsx (vitest + testing-library)\nimport { render, screen } from \"@testing-library/react\";\nimport userEvent from \"@testing-library/user-event\";\nimport { Feature } from \"./Feature\";\n\ntest(\"filters items\", async () => {\n const fetchItems = async () => [{ id:\"1\", label:\"Alpha\" }, { id:\"2\", label:\"Beta\" }];\n render();\n expect(await screen.findByText(\"Alpha\")).toBeInTheDocument();\n await userEvent.type(screen.getByLabelText(\"Search\"), \"be\");\n expect(screen.queryByText(\"Alpha\")).toBeNull();\n expect(screen.getByText(\"Beta\")).toBeInTheDocument();\n});\n```\n\n\nHard-mode checks: concurrency safety, idempotency, and rollback validated; add chaos tests where feasible.", "source": "WithinUsAI/GOD_Coder_100k"} {"text": "Task type: runtime_gc\nScenario: rate limit gateway\nDomain focus: stream processing\nPrimary language: typescript\nDifficulty: hard\nScale/SLO: 99.99% availability\nComponent: component_enhcgerj\nConstraints: avoid data races and undefined behavior, include test vectors and fuzz strategy, explicit contracts and invariants, include failure modes and recovery, include verification strategy\nAssume hostile inputs and targeted abuse patterns.\nDeliverable: Design a GC/runtime component (mark-sweep/arena/RC hybrid); include pause-time strategy and tests.\n\nOutput: contract-first solution with failure modes, security posture, and test/verification strategy.\n**Contract**\n- Inputs validated at the boundary; explicit error taxonomy.\n- Idempotency for side effects via request_id; deterministic replay.\n- Backward compatibility: additive changes by default; versioned breaking changes.\n**Invariants**\n- Safety: state transitions preserve invariants; no partial commit leaks.\n- Isolation: tenant boundary enforced; no cross-tenant reads/writes.\n- Determinism: replay of the same event log yields identical outputs.\n**Failure modes & recovery**\n- Crash during commit: WAL replay completes or transaction aborts; no torn writes.\n- Data corruption: checksums + scrubber; quarantine and rebuild from replicas/snapshots.\n- Network partition: minority cannot commit; clients receive retriable errors.\n**Security posture (defensive)**\n- Threat model: auth/authz, injection, replay/abuse, supply chain.\n- Least privilege; secrets in managed store; audit logs for sensitive ops.\n- Input normalization, parameterized queries, path traversal protections.\n**Verification strategy**\n- Fuzzing of parsers/framers/validators with corpus seeds.\n- Property tests against a pure reference model (state machine).\n- Deterministic simulation with fault injection (crash/partition/latency).\n\n**Snippet**\n```text\nImplementation sketch: factor pure state-machine core; adapters for I/O; add deterministic replay log.\n```\nHard checks: fault injection tests gate merges; perf thresholds enforced in CI.", "source": "WithinUsAI/Omega_Genesis_Coder_100k"} {"text": "Fix the bug and add pytest tests.\n\n```python\ndef f27260(n: int) -> int:\n # sum 1..n inclusive\n if n < 0: raise ValueError\n total = 0\n for k in range(n): # BUG\n total += k\n return total\n```\nReturn unified diffs for `m18180.py` and `test_m18180.py`.\n\n*** Begin Patch\n*** Update File: m18180.py\n@@\n def f27260(n: int) -> int:\n@@\n- for k in range(n): # BUG\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_m18180.py\n+import pytest\n+from m18180 import f27260\n+\n+def test_small():\n+ assert f27260(7) == 28\n+\n+def test_zero():\n+ assert f27260(0) == 0\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ f27260(-1)\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Build an elite-grade solution in the domain of sre/observability for scenario: time-series metrics.\nPrimary language: python.\nDifficulty: medium.\nConstraints: include tests or verification strategy, avoid undefined behavior and data races, assume untrusted inputs; validate and sanitize.\nComponent: component_xbpbllz.\nAssume schema changes every sprint; must be backward compatible.\nTask: Provide a cross-language reference (API contract + implementation in two languages) and compatibility tests.\n\nOutput: elite-grade engineering answer with contracts, edge cases, and verification.\nOutput: API contract + two implementations + compat tests.\n\n**Contract**\n- JSON schema for request/response; strict field validation; explicit version.\n\n**Example**\n- Implement validator + handler in Python and TypeScript.\n- Compatibility tests: same inputs produce equivalent outputs; reject unknown fields when in strict mode.\n\n\nChecks: boundary validation and deterministic behavior verified.", "source": "WithinUsAI/Elite_GOD_Coder_100k"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: Repository domain: benchmark harness\nPrimary language: C#\nFramework/tooling: NUnit\nReported problem: S3-compatible upload inconsistency\nTask type: feature_delivery\nDifficulty: hard\n\nProduce a complete professional engineering response:\n1. Diagnose the root cause.\n2. Provide the corrected implementation or patch.\n3. Add tests.\n4. Add verification commands.\n5. Note edge cases and any migration or rollback risk.\n\nRepository sketch:\nrepo/\n src/App/Program.cs\n src/App/Service.cs\n tests/App.Tests/ServiceTests.cs\n App.sln\n\nQuality target:\n- Minimal diff unless redesign is clearly required\n- Production-ready code\n- No placeholders\n- Secure defaults\n- Clear acceptance of failure cases\n\nFocus: Focus on complete implementation quality, patch correctness, tests, and production readiness.\n\nassistant: Diagnosis:\n- Root cause: the failure around S3-compatible upload inconsistency is caused by missing validation, weak edge-case handling, or unsafe lifecycle behavior in the current implementation.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```csharp\nusing System;\nusing System.Collections.Generic;\n\npublic static class RequestHandler\n{\n public static Dictionary HandleRequest(Dictionary payload)\n {\n var clean = new Dictionary();\n foreach (var entry in payload)\n {\n if (entry.Value != null)\n clean[entry.Key.Trim()] = entry.Value;\n }\n if (!clean.ContainsKey(\"id\"))\n throw new ArgumentException(\"missing id\");\n return new Dictionary\n {\n [\"ok\"] = true,\n [\"data\"] = clean\n };\n }\n}\n```\n\nTests:\n```csharp\nusing System;\nusing System.Collections.Generic;\nusing Xunit;\n\npublic class RequestHandlerTests\n{\n [Fact]\n public void RequiresId()\n {\n Assert.Throws(() => RequestHandler.HandleRequest(new Dictionary { [\"name\"] = \"x\" }));\n }\n}\n```\n\nVerification:\n- `dotnet test`\n- `dotnet build`\n\nEngineering notes:\n- Language: C#\n- Framework/tooling: NUnit\n- Stack context: GitHub Actions, Docker Compose, Kubernetes, Terraform\n- Domain: benchmark harness\n- Task type: feature_delivery\n- Difficulty: hard\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: Language: C#\nFramework/tooling: EF Core\nDomain: notification service\nLogic challenge: partial checkpoint corruption\nTask type: performance_bottleneck_patch\nDifficulty: hard\n\nReturn a rigorous engineering answer:\n- identify the hidden root cause or logical failure\n- present the corrected implementation\n- add tests that prove the fix\n- list verification commands\n- explain why naive fixes are insufficient when relevant\n\nRepository sketch:\nrepo/\n src/App/Program.cs\n src/App/Service.cs\n tests/App.Tests/ServiceTests.cs\n App.sln\n\nFocus: Focus on ambiguity, misleading symptoms, hidden root causes, and high-stakes debugging.\n\nassistant: Diagnosis:\n- Hidden root cause: partial checkpoint corruption presents misleading symptoms, so the patch must target the actual logic boundary rather than the first visible failure.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```csharp\nusing System;\nusing System.Collections.Generic;\n\npublic static class RequestHandler\n{\n public static Dictionary HandleRequest(Dictionary payload)\n {\n var clean = new Dictionary();\n foreach (var entry in payload)\n {\n if (entry.Value != null)\n clean[entry.Key.Trim()] = entry.Value;\n }\n if (!clean.ContainsKey(\"id\"))\n throw new ArgumentException(\"missing id\");\n return new Dictionary\n {\n [\"ok\"] = true,\n [\"data\"] = clean\n };\n }\n}\n```\n\nTests:\n```csharp\nusing System;\nusing System.Collections.Generic;\nusing Xunit;\n\npublic class RequestHandlerTests\n{\n [Fact]\n public void RequiresId()\n {\n Assert.Throws(() => RequestHandler.HandleRequest(new Dictionary { [\"name\"] = \"x\" }));\n }\n}\n```\n\nVerification:\n- `dotnet test`\n- `dotnet build`\n\nEngineering notes:\n- Language: C#\n- Framework/tooling: EF Core\n- Stack context: ASP.NET Core, SQL Server, EF Core, xUnit, Docker\n- Domain: notification service\n- Task type: performance_bottleneck_patch\n- Difficulty: hard\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Optimize while preserving behavior.\n\nFile: wb67kvkyzdy.py\n```python\ndef lfk5zup2aa5(xs):\n out = []\n for x in xs:\n if x not in out:\n out.append(x)\n return out\n```\n\nRequirements: preserve first-seen order; O(n) average; add types + docstring.\n\n# wb67kvkyzdy.py\nfrom __future__ import annotations\nfrom typing import Iterable, List, Set, TypeVar\n\nT = TypeVar(\"T\")\n\ndef lfk5zup2aa5(xs: Iterable[T]) -> List[T]:\n \"\"\"Return unique items preserving first-seen order.\"\"\"\n seen: Set[T] = set()\n out: List[T] = []\n for x in xs:\n if x in seen:\n continue\n seen.add(x)\n out.append(x)\n return out", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Optimize while preserving behavior.\n\nFile: uvi51rh.py\n```python\ndef h_hefq(xs):\n out = []\n for x in xs:\n if x not in out:\n out.append(x)\n return out\n```\n\nRequirements: preserve first-seen order; O(n) average; add types + docstring.\n\n# uvi51rh.py\nfrom __future__ import annotations\nfrom typing import Iterable, List, Set, TypeVar\n\nT = TypeVar(\"T\")\n\ndef h_hefq(xs: Iterable[T]) -> List[T]:\n \"\"\"Return unique items preserving first-seen order.\"\"\"\n seen: Set[T] = set()\n out: List[T] = []\n for x in xs:\n if x in seen:\n continue\n seen.add(x)\n out.append(x)\n return out", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Refactor to typed, mostly-immutable Python and add minimal tests.\n\n```python\nclass C28010:\n def __init__(self, values): self.values=list(values)\n def mean(self): return sum(self.values)/len(self.values)\n```\nReturn `m86770.py` and `test_m86770.py`.\n\n```python\n# m86770.py\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom typing import Iterable, Tuple\n\n@dataclass(frozen=True)\nclass C28010:\n values: Tuple[float, ...]\n\n @staticmethod\n def create(values: Iterable[float]) -> \"C28010\":\n vals = tuple(float(v) for v in values)\n if not vals: raise ValueError(\"empty\")\n return C28010(vals)\n\n def mean(self) -> float:\n return sum(self.values)/len(self.values)\n```\n\n```python\n# test_m86770.py\nimport pytest\nfrom m86770 import C28010\n\ndef test_mean():\n assert C28010.create([1,2,3]).mean() == 2.0\ndef test_empty():\n with pytest.raises(ValueError):\n C28010.create([])\n```", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Refactor a Python module used for configuration loading into a clean, extensible design.\nRequirements: outline the new architecture briefly, then provide the refactored code and tests.\nConstraints: must be easy to extend, must provide clear error messages.\nDifficulty: easy. Guarantee deterministic output ordering.\n\nDeliverable: corrected code and verification tests.\nArchitecture:\n- Public facade class coordinating concerns (parsing, validation, persistence)\n- Small pure functions for testability\n- No global state; dependency injection for filesystem I/O\n\n```python\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom pathlib import Path\nfrom typing import Protocol, Iterable\nimport json\n\nclass Store(Protocol):\n def write_text(self, path: Path, data: str) -> None: ...\n\nclass FSStore:\n def write_text(self, path: Path, data: str) -> None:\n path.parent.mkdir(parents=True, exist_ok=True)\n path.write_text(data, encoding=\"utf-8\")\n\n@dataclass(frozen=True, slots=True)\nclass Item:\n name: str\n qty: int\n\ndef parse_items(lines: Iterable[str]) -> list[Item]:\n out: list[Item] = []\n for i, line in enumerate(lines, 1):\n s = line.strip()\n if not s:\n continue\n obj = json.loads(s)\n if not isinstance(obj, dict):\n raise ValueError(f\"line {i}: expected object\")\n name = obj.get(\"name\")\n qty = obj.get(\"qty\")\n if not isinstance(name, str) or not name:\n raise ValueError(f\"line {i}: name must be str\")\n if not isinstance(qty, int) or qty < 0:\n raise ValueError(f\"line {i}: qty must be non-negative int\")\n out.append(Item(name, qty))\n return out\n\nclass InventoryWriter:\n def __init__(self, base_dir: Path, store: Store | None = None) -> None:\n self._base = base_dir\n self._store: Store = store or FSStore()\n\n def write(self, rel_path: str, items: list[Item]) -> Path:\n dst = (self._base / rel_path).resolve()\n base = self._base.resolve()\n if dst != base and base not in dst.parents:\n raise ValueError(\"unsafe path traversal\")\n payload = json.dumps([item.__dict__ for item in items], ensure_ascii=False)\n self._store.write_text(dst, payload)\n return dst\n```\n\n```python\nimport json\nfrom pathlib import Path\nimport pytest\nfrom module_under_test import InventoryWriter, parse_items\n\ndef test_parse_items_valid():\n lines = [json.dumps({\"name\":\"x\",\"qty\":1})]\n assert parse_items(lines)[0].name == \"x\"\n\ndef test_writer_blocks_traversal(tmp_path: Path):\n w = InventoryWriter(tmp_path)\n with pytest.raises(ValueError):\n w.write(\"../evil.json\", [])\n```", "source": "WithinUsAI/python_GOD_coder_100k"} {"text": "Create a comprehensive test plan and automated tests for rate limiting in a e-commerce product.\nTarget platform: infra (Docker + Kubernetes).\nRequirements: unit/integration tests, edge cases, load tests strategy, and CI gates.\nConstraints: must be performant under load, must include type hints where applicable, must be easy to extend.\nDifficulty: hard. Assume 10k RPS peak traffic.\n\nOutput: design + implementation guidance suitable for shipping.\nDeliverable: test plan + automation guidance.\n\n**Unit tests**\n- Validation: malformed payloads rejected with correct codes.\n- AuthZ: tenant boundary enforced.\n- Idempotency: replay returns same response; conflicting reuse yields 409.\n\n**Integration tests**\n- DB transaction behavior; unique constraints.\n- Cache behavior: correctness under concurrent requests.\n\n**Load tests**\n- 10k RPS target: measure p95 latency, error rate, saturation.\n\n**CI gates**\n- Lint + typecheck + unit tests required.\n- Coverage threshold for critical modules.\n- Block merge on flaky test detection.\n\n\nHard-mode checks: concurrency safety, idempotency, and rollback validated; add chaos tests where feasible.", "source": "WithinUsAI/GOD_Coder_100k"} {"text": "Optimize while preserving behavior and order.\n\n```python\ndef f38864(xs):\n out=[]\n for x in xs:\n if x not in out: out.append(x)\n return out\n```\nReturn `m05552.py` with types and O(n) average.\n\n```python\n# m05552.py\nfrom __future__ import annotations\nfrom typing import Iterable, List, Set, TypeVar\nT=TypeVar(\"T\")\n\ndef f38864(xs: Iterable[T]) -> List[T]:\n \"\"\"Unique items preserving first-seen order.\"\"\"\n seen: Set[T]=set()\n out: List[T]=[]\n for x in xs:\n if x in seen: continue\n seen.add(x); out.append(x)\n return out\n```", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: Project domain: document processing API\nImplementation stack: Rust, Axum, SQLx, Redis, Tokio, Docker\nSoftware delivery problem: migration ordering failure\nTask type: test_strategy_implementation\nDifficulty: hard\n\nReturn a complete delivery-grade response with:\n- diagnosis or design reasoning\n- implementation\n- test plan or tests\n- rollout plan\n- rollback or compatibility note\n- verification commands\n\nRepository sketch:\nrepo/\n cmd/server/main.go\n internal/service/service.go\n internal/store/store.go\n internal/api/api.go\n service_test.go\n go.mod\n\nFocus: Focus on shipping production software with rollout safety, acceptance criteria, telemetry, and maintenance quality.\n\nassistant: Diagnosis:\n- Root cause or delivery blocker: migration ordering failure needs both implementation work and a safe shipping plan.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```go\npackage service\n\nimport \"fmt\"\n\nfunc NormalizePayload(payload map[string]any) map[string]any {\n\tout := make(map[string]any)\n\tfor k, v := range payload {\n\t\tif v == nil {\n\t\t\tcontinue\n\t\t}\n\t\tout[k] = v\n\t}\n\treturn out\n}\n\nfunc Handle(payload map[string]any) (map[string]any, error) {\n\tclean := NormalizePayload(payload)\n\tif _, ok := clean[\"id\"]; !ok {\n\t\treturn nil, fmt.Errorf(\"missing id\")\n\t}\n\treturn map[string]any{\"ok\": true, \"data\": clean}, nil\n}\n```\n\nTests:\n```go\npackage service\n\nimport \"testing\"\n\nfunc TestHandle(t *testing.T) {\n\tgot, err := Handle(map[string]any{\"id\": 7, \"name\": \"ok\", \"unused\": nil})\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tif got[\"ok\"] != true {\n\t\tt.Fatalf(\"expected ok=true\")\n\t}\n\tif _, err := Handle(map[string]any{\"name\": \"x\"}); err == nil {\n\t\tt.Fatalf(\"expected missing id error\")\n\t}\n}\n```\n\nVerification:\n- `go test ./...`\n- `go vet ./...`\n\nEngineering notes:\n- Language: Go\n- Framework/tooling: net/http\n- Stack context: Rust, Axum, SQLx, Redis, Tokio, Docker\n- Domain: document processing API\n- Task type: test_strategy_implementation\n- Difficulty: hard\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Refactor to modern typed Python with immutability and tests.\n\nFile: yori1x04z.py\n```python\nclass Usp6T5Ef:\n def __init__(self, name, values):\n self.name = name\n self.values = list(values)\n def add(self, v):\n self.values.append(v)\n def mean(self):\n s = 0\n for x in self.values:\n s += x\n return s / len(self.values)\n```\n\nReturn full new yori1x04z.py and test_yori1x04z.py.\n\n# yori1x04z.py\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom typing import Iterable, Tuple\n\n@dataclass(frozen=True)\nclass Usp6T5Ef:\n name: str\n values: Tuple[float, ...]\n\n @staticmethod\n def create(name: str, values: Iterable[float]) -> \"Usp6T5Ef\":\n vals = tuple(float(v) for v in values)\n if not vals:\n raise ValueError(\"values must be non-empty\")\n return Usp6T5Ef(name=name, values=vals)\n\n def add(self, v: float) -> \"Usp6T5Ef\":\n return Usp6T5Ef(name=self.name, values=self.values + (float(v),))\n\n def mean(self) -> float:\n return sum(self.values) / len(self.values)\n\n# test_yori1x04z.py\nimport pytest\nfrom yori1x04z import Usp6T5Ef\n\ndef test_mean_and_add():\n c = Usp6T5Ef.create(\"a\", [1, 2, 3])\n assert c.mean() == 2.0\n assert c.add(5).mean() == (1 + 2 + 3 + 5) / 4\n\ndef test_empty_raises():\n with pytest.raises(ValueError):\n Usp6T5Ef.create(\"x\", [])", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Refactor to modern typed Python with immutability and tests.\n\nFile: tcxad06c.py\n```python\nclass L7Gx96F:\n def __init__(self, name, values):\n self.name = name\n self.values = list(values)\n def add(self, v):\n self.values.append(v)\n def mean(self):\n s = 0\n for x in self.values:\n s += x\n return s / len(self.values)\n```\n\nReturn full new tcxad06c.py and test_tcxad06c.py.\n\n# tcxad06c.py\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom typing import Iterable, Tuple\n\n@dataclass(frozen=True)\nclass L7Gx96F:\n name: str\n values: Tuple[float, ...]\n\n @staticmethod\n def create(name: str, values: Iterable[float]) -> \"L7Gx96F\":\n vals = tuple(float(v) for v in values)\n if not vals:\n raise ValueError(\"values must be non-empty\")\n return L7Gx96F(name=name, values=vals)\n\n def add(self, v: float) -> \"L7Gx96F\":\n return L7Gx96F(name=self.name, values=self.values + (float(v),))\n\n def mean(self) -> float:\n return sum(self.values) / len(self.values)\n\n# test_tcxad06c.py\nimport pytest\nfrom tcxad06c import L7Gx96F\n\ndef test_mean_and_add():\n c = L7Gx96F.create(\"a\", [1, 2, 3])\n assert c.mean() == 2.0\n assert c.add(5).mean() == (1 + 2 + 3 + 5) / 4\n\ndef test_empty_raises():\n with pytest.raises(ValueError):\n L7Gx96F.create(\"x\", [])", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Fix a bug and add tests.\n\nFile: zpqtaoeqda.py\n```python\ndef aahldu_7hvn(n: int) -> int:\n \"\"\"Sum 1..n inclusive.\"\"\"\n if n < 0:\n raise ValueError(\"n must be non-negative\")\n total = 0\n for k in range(n): # BUG: should include n\n total += k\n return total\n```\n\nReturn unified diffs for zpqtaoeqda.py and test_zpqtaoeqda.py (pytest).\n\n*** Begin Patch\n*** Update File: zpqtaoeqda.py\n@@\n def aahldu_7hvn(n: int) -> int:\n@@\n total = 0\n- for k in range(n): # BUG: should include n\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_zpqtaoeqda.py\n+import pytest\n+from zpqtaoeqda import aahldu_7hvn\n+\n+def test_zero():\n+ assert aahldu_7hvn(0) == 0\n+\n+def test_one():\n+ assert aahldu_7hvn(1) == 1\n+\n+def test_small():\n+ assert aahldu_7hvn(7) == 28\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ aahldu_7hvn(-1)\n+\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Build an elite-grade solution in the domain of gpu compute for scenario: rate limiting gateway.\nPrimary language: sql.\nDifficulty: medium.\nConstraints: assume untrusted inputs; validate and sanitize, include tests or verification strategy, provide rollout and rollback guidance, avoid undefined behavior and data races, make the interface contract explicit.\nComponent: component_wyiqsfz.\nAssume schema changes every sprint; must be backward compatible.\nTask: Write a precise interface contract, list invariants, and provide a lightweight formal/spec-style description (pseudo-TLA+/state machine) plus reference implementation skeleton and tests.\n\nOutput: production blueprint plus correctness arguments and test strategy.\nOutput: contract + invariants + spec + reference skeleton.\n\n**Interface contract**\n- Commands: `Put(key, value, expected_version?)`, `Get(key)`, `Delete(key, expected_version?)`\n- Responses: `Ok(version, value?)`, `NotFound`, `Conflict(current_version)`, `InvalidInput`\n- Idempotency: client supplies `request_id`; server must de-duplicate per (tenant_id, request_id).\n\n**Invariants**\n1. Monotonic version per key (strictly increases on successful writes).\n2. Reads return latest committed value for a given consistency level.\n3. Exactly-once effect for a given `request_id` (at-most-once execution + replay response).\n4. Tenant isolation: keys are scoped by tenant_id.\n\n**State machine (pseudo)**\nState:\n- store: map[(tenant,key)] -> (version:int, value:bytes|tombstone)\n- seen: map[(tenant,request_id)] -> response\nTransition Put:\n- if request_id in seen: return seen[...]\n- validate input; if expected_version set and != current version -> Conflict\n- version' = version + 1; store[...] := (version', value); seen[...] := Ok(version', value)\n\n**Reference skeleton (Python)**\n```python\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom typing import Dict, Optional, Tuple\n\nclass Conflict(Exception): pass\nclass InvalidInput(ValueError): pass\n\n@dataclass(frozen=True, slots=True)\nclass Value:\n version: int\n data: Optional[bytes] # None == tombstone\n\n@dataclass(frozen=True, slots=True)\nclass Reply:\n kind: str\n version: Optional[int] = None\n data: Optional[bytes] = None\n\nclass KV:\n def __init__(self) -> None:\n self._store: Dict[Tuple[str,str], Value] = {}\n self._seen: Dict[Tuple[str,str], Reply] = {}\n\n def put(self, tenant: str, request_id: str, key: str, data: bytes, expected_version: Optional[int]=None) -> Reply:\n if not tenant or not request_id or not key:\n raise InvalidInput(\"tenant/request_id/key required\")\n de = self._seen.get((tenant, request_id))\n if de: \n return de\n cur = self._store.get((tenant, key), Value(0, None))\n if expected_version is not None and expected_version != cur.version:\n r = Reply(\"conflict\", version=cur.version)\n self._seen[(tenant, request_id)] = r\n return r\n nxt = Value(cur.version + 1, data)\n self._store[(tenant, key)] = nxt\n r = Reply(\"ok\", version=nxt.version)\n self._seen[(tenant, request_id)] = r\n return r\n```\n\n**Tests**\n- Determinism: same request_id → same reply.\n- Conflict detection and version monotonicity.\n\n\nChecks: boundary validation and deterministic behavior verified.", "source": "WithinUsAI/Elite_GOD_Coder_100k"} {"text": "Fix the bug and add pytest tests.\n\n```python\ndef f60322(n: int) -> int:\n # sum 1..n inclusive\n if n < 0: raise ValueError\n total = 0\n for k in range(n): # BUG\n total += k\n return total\n```\nReturn unified diffs for `m80046.py` and `test_m80046.py`.\n\n*** Begin Patch\n*** Update File: m80046.py\n@@\n def f60322(n: int) -> int:\n@@\n- for k in range(n): # BUG\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_m80046.py\n+import pytest\n+from m80046 import f60322\n+\n+def test_small():\n+ assert f60322(7) == 28\n+\n+def test_zero():\n+ assert f60322(0) == 0\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ f60322(-1)\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Write a thorough test suite for a Python component used for file synchronization.\nRequirements: cover edge cases, invalid inputs, and behavior invariants.\nConstraints: must include docstrings, stdlib-only, must be easy to extend, must include type hints.\nDifficulty: easy. Provide helpful exceptions with actionable messages.\n\nDeliverable: corrected code and verification tests.\n```python\n# tests (pytest-style) for a module providing: normalize(), parse_lines(), compute_stats()\nimport math\nimport pytest\n\ndef test_normalize_idempotent(module_under_test):\n x = \" A\\tB \"\n assert module_under_test.normalize(module_under_test.normalize(x)) == module_under_test.normalize(x)\n\ndef test_parse_lines_rejects_invalid(module_under_test):\n with pytest.raises(ValueError):\n module_under_test.parse_lines([\"\", \"???\", None]) # type: ignore[arg-type]\n\ndef test_compute_stats_basic(module_under_test):\n data = [1, 2, 3, 4]\n s = module_under_test.compute_stats(data)\n assert s.count == 4\n assert s.total == 10\n assert math.isclose(s.mean, 2.5)\n```", "source": "WithinUsAI/python_GOD_coder_100k"} {"text": "Build an elite-grade solution in the domain of compilers for scenario: rate limiting gateway.\nPrimary language: go.\nDifficulty: hard.\nConstraints: assume untrusted inputs; validate and sanitize, provide rollout and rollback guidance, document performance characteristics, include tests or verification strategy.\nComponent: component_xhvlawl.\nAssume 50k RPS and p99 < 250ms.\nTask: Design a replication/consistency approach (e.g., leader-based, quorum reads/writes). Provide message flows, failure handling, and a minimal reference implementation skeleton.\n\nOutput: elite-grade engineering answer with contracts, edge cases, and verification.\nOutput: replication design + failure handling + minimal skeleton.\n\n**Model**\n- Leader-based replication with term + log index.\n- Quorum acks for durability: write committed when majority acks.\n- Read options: leader-read (linearizable) or quorum-read (monotonic if using read-index).\n\n**Message flow (write)**\n1. Client → Leader: Put(request_id, payload)\n2. Leader appends to log, sends AppendEntries to followers\n3. Followers append + ack\n4. On majority ack: commit index advances; apply to state machine; respond to client\n\n**Failure modes**\n- Leader crash: new election; uncommitted entries may be rolled back.\n- Partition: minority side cannot commit.\n- Duplicate requests: deduplicate by request_id stored in state.\n\n**Skeleton (Go pseudo)**\n```go\ntype Entry struct { Term uint64; Index uint64; Cmd []byte }\ntype Node struct {\n id int\n term uint64\n log []Entry\n commit uint64\n seen map[string][]byte // request_id -> response\n}\n```\n\n**Verification**\n- Invariant: committed index never decreases.\n- Property: if a write is committed, all future leaders contain it.\n- Test with simulated partitions and crash/restart.\n\n\nHard checks: failure injection tests and performance regressions gated.", "source": "WithinUsAI/Elite_GOD_Coder_100k"} {"text": "Refactor to typed, mostly-immutable Python and add minimal tests.\n\n```python\nclass C80045:\n def __init__(self, values): self.values=list(values)\n def mean(self): return sum(self.values)/len(self.values)\n```\nReturn `m98465.py` and `test_m98465.py`.\n\n```python\n# m98465.py\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom typing import Iterable, Tuple\n\n@dataclass(frozen=True)\nclass C80045:\n values: Tuple[float, ...]\n\n @staticmethod\n def create(values: Iterable[float]) -> \"C80045\":\n vals = tuple(float(v) for v in values)\n if not vals: raise ValueError(\"empty\")\n return C80045(vals)\n\n def mean(self) -> float:\n return sum(self.values)/len(self.values)\n```\n\n```python\n# test_m98465.py\nimport pytest\nfrom m98465 import C80045\n\ndef test_mean():\n assert C80045.create([1,2,3]).mean() == 2.0\ndef test_empty():\n with pytest.raises(ValueError):\n C80045.create([])\n```", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Refactor a Python module used for data modeling into a clean, extensible design.\nRequirements: outline the new architecture briefly, then provide the refactored code and tests.\nConstraints: must be memory-efficient, stdlib-only, must include type hints.\nDifficulty: expert. Handle empty inputs and malformed records gracefully.\n\nDeliverable: API + reference implementation + tests.\nArchitecture:\n- Public facade class coordinating concerns (parsing, validation, persistence)\n- Small pure functions for testability\n- No global state; dependency injection for filesystem I/O\n\n```python\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom pathlib import Path\nfrom typing import Protocol, Iterable\nimport json\n\nclass Store(Protocol):\n def write_text(self, path: Path, data: str) -> None: ...\n\nclass FSStore:\n def write_text(self, path: Path, data: str) -> None:\n path.parent.mkdir(parents=True, exist_ok=True)\n path.write_text(data, encoding=\"utf-8\")\n\n@dataclass(frozen=True, slots=True)\nclass Item:\n name: str\n qty: int\n\ndef parse_items(lines: Iterable[str]) -> list[Item]:\n out: list[Item] = []\n for i, line in enumerate(lines, 1):\n s = line.strip()\n if not s:\n continue\n obj = json.loads(s)\n if not isinstance(obj, dict):\n raise ValueError(f\"line {i}: expected object\")\n name = obj.get(\"name\")\n qty = obj.get(\"qty\")\n if not isinstance(name, str) or not name:\n raise ValueError(f\"line {i}: name must be str\")\n if not isinstance(qty, int) or qty < 0:\n raise ValueError(f\"line {i}: qty must be non-negative int\")\n out.append(Item(name, qty))\n return out\n\nclass InventoryWriter:\n def __init__(self, base_dir: Path, store: Store | None = None) -> None:\n self._base = base_dir\n self._store: Store = store or FSStore()\n\n def write(self, rel_path: str, items: list[Item]) -> Path:\n dst = (self._base / rel_path).resolve()\n base = self._base.resolve()\n if dst != base and base not in dst.parents:\n raise ValueError(\"unsafe path traversal\")\n payload = json.dumps([item.__dict__ for item in items], ensure_ascii=False)\n self._store.write_text(dst, payload)\n return dst\n```\n\n```python\nimport json\nfrom pathlib import Path\nimport pytest\nfrom module_under_test import InventoryWriter, parse_items\n\ndef test_parse_items_valid():\n lines = [json.dumps({\"name\":\"x\",\"qty\":1})]\n assert parse_items(lines)[0].name == \"x\"\n\ndef test_writer_blocks_traversal(tmp_path: Path):\n w = InventoryWriter(tmp_path)\n with pytest.raises(ValueError):\n w.write(\"../evil.json\", [])\n```", "source": "WithinUsAI/python_GOD_coder_100k"} {"text": "Task type: storage_engine\nScenario: document indexing pipeline\nDomain focus: zero-downtime migrations\nPrimary language: go\nDifficulty: expert\nScale/SLO: 10k RPS peak\nComponent: component_azacooao\nConstraints: include failure modes and recovery, include backward compatibility and migration plan, include performance model and limits, include deterministic replay plan, assume adversarial inputs; validate everything, explicit contracts and invariants\nAssume tight memory budget and cold-start constraints.\nDeliverable: Design a storage engine subsystem (WAL, snapshots, compaction). Include crash recovery invariants and a benchmark plan.\n\nOutput: rigorous design + invariants + verification plan + implementation sketch.\n**Contract**\n- Inputs validated at the boundary; explicit error taxonomy.\n- Idempotency for side effects via request_id; deterministic replay.\n- Backward compatibility: additive changes by default; versioned breaking changes.\n**Invariants**\n- Determinism: replay of the same event log yields identical outputs.\n- Liveness: under bounded faults and stable network, progress occurs.\n- Isolation: tenant boundary enforced; no cross-tenant reads/writes.\n**Failure modes & recovery**\n- Network partition: minority cannot commit; clients receive retriable errors.\n- Data corruption: checksums + scrubber; quarantine and rebuild from replicas/snapshots.\n- Duplicate requests: de-duplicate by (tenant, request_id) returning cached response.\n**Security posture (defensive)**\n- Threat model: auth/authz, injection, replay/abuse, supply chain.\n- Least privilege; secrets in managed store; audit logs for sensitive ops.\n- Input normalization, parameterized queries, path traversal protections.\n**Verification strategy**\n- Deterministic simulation with fault injection (crash/partition/latency).\n- Canary + shadow traffic; invariants checked in production via assertions/metrics.\n- Fuzzing of parsers/framers/validators with corpus seeds.\n\n**Snippet**\n```text\nImplementation sketch: factor pure state-machine core; adapters for I/O; add deterministic replay log.\n```\nExpert checks: state-machine proof sketch + model checking; upgrade/rollback rehearsed.", "source": "WithinUsAI/Omega_Genesis_Coder_100k"} {"text": "Refactor to typed, mostly-immutable Python and add minimal tests.\n\n```python\nclass C69218:\n def __init__(self, values): self.values=list(values)\n def mean(self): return sum(self.values)/len(self.values)\n```\nReturn `m43786.py` and `test_m43786.py`.\n\n```python\n# m43786.py\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom typing import Iterable, Tuple\n\n@dataclass(frozen=True)\nclass C69218:\n values: Tuple[float, ...]\n\n @staticmethod\n def create(values: Iterable[float]) -> \"C69218\":\n vals = tuple(float(v) for v in values)\n if not vals: raise ValueError(\"empty\")\n return C69218(vals)\n\n def mean(self) -> float:\n return sum(self.values)/len(self.values)\n```\n\n```python\n# test_m43786.py\nimport pytest\nfrom m43786 import C69218\n\ndef test_mean():\n assert C69218.create([1,2,3]).mean() == 2.0\ndef test_empty():\n with pytest.raises(ValueError):\n C69218.create([])\n```", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Fix a bug and add tests.\n\nFile: r3ark1y.py\n```python\ndef ug3e5l_vm_(n: int) -> int:\n \"\"\"Sum 1..n inclusive.\"\"\"\n if n < 0:\n raise ValueError(\"n must be non-negative\")\n total = 0\n for k in range(n): # BUG: should include n\n total += k\n return total\n```\n\nReturn unified diffs for r3ark1y.py and test_r3ark1y.py (pytest).\n\n*** Begin Patch\n*** Update File: r3ark1y.py\n@@\n def ug3e5l_vm_(n: int) -> int:\n@@\n total = 0\n- for k in range(n): # BUG: should include n\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_r3ark1y.py\n+import pytest\n+from r3ark1y import ug3e5l_vm_\n+\n+def test_zero():\n+ assert ug3e5l_vm_(0) == 0\n+\n+def test_one():\n+ assert ug3e5l_vm_(1) == 1\n+\n+def test_small():\n+ assert ug3e5l_vm_(7) == 28\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ ug3e5l_vm_(-1)\n+\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: Language: C++\nFramework/tooling: Boost\nDomain: observability collector\nLogic challenge: race condition on worker shutdown\nTask type: concurrency_fix\nDifficulty: medium\n\nReturn a rigorous engineering answer:\n- identify the hidden root cause or logical failure\n- present the corrected implementation\n- add tests that prove the fix\n- list verification commands\n- explain why naive fixes are insufficient when relevant\n\nRepository sketch:\nrepo/\n src/main.cpp\n src/service.cpp\n include/service.h\n tests/test_service.cpp\n CMakeLists.txt\n\nFocus: Focus on strong structured logic with edge cases, data validation, and concurrency safety.\n\nassistant: Diagnosis:\n- Root cause: the failure around race condition on worker shutdown is caused by missing validation, weak edge-case handling, or unsafe lifecycle behavior in the current implementation.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```cpp\n#include \n#include \n\nusing Payload = std::unordered_map;\n\nPayload normalize_payload(const Payload& in) {\n Payload out;\n for (const auto& [k, v] : in) {\n if (!v.empty()) out[k] = v;\n }\n return out;\n}\n```\n\nTests:\n```cpp\nTEST_CASE(\"normalize_payload filters empty values\") {\n Payload in{{\"id\",\"7\"},{\"name\",\"\"}};\n auto out = normalize_payload(in);\n REQUIRE(out.count(\"id\") == 1);\n REQUIRE(out.count(\"name\") == 0);\n}\n```\n\nVerification:\n- `cmake --build build`\n- `ctest --test-dir build`\n\nEngineering notes:\n- Language: C++\n- Framework/tooling: Boost\n- Stack context: Go, Gin, PostgreSQL, gRPC, Prometheus, Docker\n- Domain: observability collector\n- Task type: concurrency_fix\n- Difficulty: medium\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: Repository domain: developer platform\nPrimary language: Java\nFramework/tooling: Gradle\nReported problem: race condition on worker shutdown\nTask type: bug_fix\nDifficulty: medium\n\nProduce a complete professional engineering response:\n1. Diagnose the root cause.\n2. Provide the corrected implementation or patch.\n3. Add tests.\n4. Add verification commands.\n5. Note edge cases and any migration or rollback risk.\n\nRepository sketch:\nrepo/\n src/main/java/com/acme/App.java\n src/main/java/com/acme/Service.java\n src/test/java/com/acme/AppTest.java\n pom.xml\n\nQuality target:\n- Minimal diff unless redesign is clearly required\n- Production-ready code\n- No placeholders\n- Secure defaults\n- Clear acceptance of failure cases\n\nFocus: Focus on complete implementation quality, patch correctness, tests, and production readiness.\n\nassistant: Diagnosis:\n- Root cause: the failure around race condition on worker shutdown is caused by missing validation, weak edge-case handling, or unsafe lifecycle behavior in the current implementation.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```java\nimport java.util.HashMap;\nimport java.util.Map;\n\npublic final class RequestHandler {\n public static Map handleRequest(Map payload) {\n Map clean = new HashMap<>();\n for (Map.Entry entry : payload.entrySet()) {\n if (entry.getValue() != null) clean.put(entry.getKey().trim(), entry.getValue());\n }\n if (!clean.containsKey(\"id\")) throw new IllegalArgumentException(\"missing id\");\n return Map.of(\"ok\", true, \"data\", clean);\n }\n}\n```\n\nTests:\n```java\nimport static org.junit.jupiter.api.Assertions.*;\nimport java.util.Map;\nimport org.junit.jupiter.api.Test;\n\nclass RequestHandlerTest {\n @Test\n void requiresId() {\n assertThrows(IllegalArgumentException.class, () -> RequestHandler.handleRequest(Map.of(\"name\", \"x\")));\n }\n}\n```\n\nVerification:\n- `./gradlew test`\n- `mvn test`\n\nEngineering notes:\n- Language: Java\n- Framework/tooling: Gradle\n- Stack context: Go, Gin, PostgreSQL, gRPC, Prometheus, Docker\n- Domain: developer platform\n- Task type: bug_fix\n- Difficulty: medium\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "Task type: storage_engine\nScenario: streaming ETL\nDomain focus: secure enclaves (defensive)\nPrimary language: bash\nDifficulty: expert\nScale/SLO: 10k RPS peak\nComponent: component_qymwygqx\nConstraints: include performance model and limits, explicit contracts and invariants, include test vectors and fuzz strategy, assume adversarial inputs; validate everything, avoid data races and undefined behavior, include security threat model (defensive only)\nAssume weekly network partitions.\nDeliverable: Design a storage engine subsystem (WAL, snapshots, compaction). Include crash recovery invariants and a benchmark plan.\n\nOutput: contract-first solution with failure modes, security posture, and test/verification strategy.\n**Contract**\n- Inputs validated at the boundary; explicit error taxonomy.\n- Idempotency for side effects via request_id; deterministic replay.\n- Backward compatibility: additive changes by default; versioned breaking changes.\n**Invariants**\n- Isolation: tenant boundary enforced; no cross-tenant reads/writes.\n- Determinism: replay of the same event log yields identical outputs.\n- Safety: state transitions preserve invariants; no partial commit leaks.\n**Failure modes & recovery**\n- Network partition: minority cannot commit; clients receive retriable errors.\n- Duplicate requests: de-duplicate by (tenant, request_id) returning cached response.\n- Data corruption: checksums + scrubber; quarantine and rebuild from replicas/snapshots.\n**Security posture (defensive)**\n- Threat model: auth/authz, injection, replay/abuse, supply chain.\n- Least privilege; secrets in managed store; audit logs for sensitive ops.\n- Input normalization, parameterized queries, path traversal protections.\n**Verification strategy**\n- Deterministic simulation with fault injection (crash/partition/latency).\n- Canary + shadow traffic; invariants checked in production via assertions/metrics.\n- Fuzzing of parsers/framers/validators with corpus seeds.\n\n**Snippet**\n```text\nImplementation sketch: factor pure state-machine core; adapters for I/O; add deterministic replay log.\n```\nExpert checks: state-machine proof sketch + model checking; upgrade/rollback rehearsed.", "source": "WithinUsAI/Omega_Genesis_Coder_100k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Optimize while preserving behavior.\n\nFile: uwe83my.py\n```python\ndef jow04yifdc_q(xs):\n out = []\n for x in xs:\n if x not in out:\n out.append(x)\n return out\n```\n\nRequirements: preserve first-seen order; O(n) average; add types + docstring.\n\n# uwe83my.py\nfrom __future__ import annotations\nfrom typing import Iterable, List, Set, TypeVar\n\nT = TypeVar(\"T\")\n\ndef jow04yifdc_q(xs: Iterable[T]) -> List[T]:\n \"\"\"Return unique items preserving first-seen order.\"\"\"\n seen: Set[T] = set()\n out: List[T] = []\n for x in xs:\n if x in seen:\n continue\n seen.add(x)\n out.append(x)\n return out", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Add a clear docstring and type hints to this function:\n\n```python\ndef f39517(s):\n return ''.join(x for x in s if x.isalnum()).lower()\n```\n\n```python\nfrom __future__ import annotations\n\ndef f39517(s: str) -> str:\n \"\"\"Normalize a string: keep only alphanumerics and lowercase the result.\"\"\"\n return \"\".join(ch for ch in s if ch.isalnum()).lower()\n```", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Task type: gpu_serving_pipeline\nScenario: multi-tenant event ingestion\nDomain focus: model checking\nPrimary language: bash\nDifficulty: expert\nScale/SLO: 50 TB/day ingestion\nComponent: component_fpowqkkz\nConstraints: include deterministic replay plan, include security threat model (defensive only), include performance model and limits, include failure modes and recovery, avoid data races and undefined behavior, include verification strategy\nAssume hostile inputs and targeted abuse patterns.\nDeliverable: Design a GPU inference serving pipeline: batching, scheduling, memory management, tail-latency control, and monitoring.\n\nOutput: elite engineering answer optimized for correctness, performance, and operability.\n**Contract**\n- Inputs validated at the boundary; explicit error taxonomy.\n- Idempotency for side effects via request_id; deterministic replay.\n- Backward compatibility: additive changes by default; versioned breaking changes.\n**Invariants**\n- Isolation: tenant boundary enforced; no cross-tenant reads/writes.\n- Liveness: under bounded faults and stable network, progress occurs.\n- Safety: state transitions preserve invariants; no partial commit leaks.\n**Failure modes & recovery**\n- Crash during commit: WAL replay completes or transaction aborts; no torn writes.\n- Network partition: minority cannot commit; clients receive retriable errors.\n- Duplicate requests: de-duplicate by (tenant, request_id) returning cached response.\n**Security posture (defensive)**\n- Threat model: auth/authz, injection, replay/abuse, supply chain.\n- Least privilege; secrets in managed store; audit logs for sensitive ops.\n- Input normalization, parameterized queries, path traversal protections.\n**Verification strategy**\n- Fuzzing of parsers/framers/validators with corpus seeds.\n- Canary + shadow traffic; invariants checked in production via assertions/metrics.\n- Deterministic simulation with fault injection (crash/partition/latency).\n\n**Snippet**\n```text\nImplementation sketch: factor pure state-machine core; adapters for I/O; add deterministic replay log.\n```\nExpert checks: state-machine proof sketch + model checking; upgrade/rollback rehearsed.", "source": "WithinUsAI/Omega_Genesis_Coder_100k"} {"text": "Add a clear docstring and type hints to this function:\n\n```python\ndef f59023(s):\n return ''.join(x for x in s if x.isalnum()).lower()\n```\n\n```python\nfrom __future__ import annotations\n\ndef f59023(s: str) -> str:\n \"\"\"Normalize a string: keep only alphanumerics and lowercase the result.\"\"\"\n return \"\".join(ch for ch in s if ch.isalnum()).lower()\n```", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: Repository domain: search service\nPrimary language: C#\nFramework/tooling: ASP.NET Core\nReported problem: build reproducibility failure\nTask type: api_endpoint_work\nDifficulty: medium\n\nProduce a complete professional engineering response:\n1. Diagnose the root cause.\n2. Provide the corrected implementation or patch.\n3. Add tests.\n4. Add verification commands.\n5. Note edge cases and any migration or rollback risk.\n\nRepository sketch:\nrepo/\n src/App/Program.cs\n src/App/Service.cs\n tests/App.Tests/ServiceTests.cs\n App.sln\n\nQuality target:\n- Minimal diff unless redesign is clearly required\n- Production-ready code\n- No placeholders\n- Secure defaults\n- Clear acceptance of failure cases\n\nFocus: Focus on complete implementation quality, patch correctness, tests, and production readiness.\n\nassistant: Diagnosis:\n- Root cause: the failure around build reproducibility failure is caused by missing validation, weak edge-case handling, or unsafe lifecycle behavior in the current implementation.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```csharp\nusing System;\nusing System.Collections.Generic;\n\npublic static class RequestHandler\n{\n public static Dictionary HandleRequest(Dictionary payload)\n {\n var clean = new Dictionary();\n foreach (var entry in payload)\n {\n if (entry.Value != null)\n clean[entry.Key.Trim()] = entry.Value;\n }\n if (!clean.ContainsKey(\"id\"))\n throw new ArgumentException(\"missing id\");\n return new Dictionary\n {\n [\"ok\"] = true,\n [\"data\"] = clean\n };\n }\n}\n```\n\nTests:\n```csharp\nusing System;\nusing System.Collections.Generic;\nusing Xunit;\n\npublic class RequestHandlerTests\n{\n [Fact]\n public void RequiresId()\n {\n Assert.Throws(() => RequestHandler.HandleRequest(new Dictionary { [\"name\"] = \"x\" }));\n }\n}\n```\n\nVerification:\n- `dotnet test`\n- `dotnet build`\n\nEngineering notes:\n- Language: C#\n- Framework/tooling: ASP.NET Core\n- Stack context: FastAPI, PostgreSQL, Redis, Celery, pytest, Docker\n- Domain: search service\n- Task type: api_endpoint_work\n- Difficulty: medium\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "Optimize while preserving behavior and order.\n\n```python\ndef f62322(xs):\n out=[]\n for x in xs:\n if x not in out: out.append(x)\n return out\n```\nReturn `m66046.py` with types and O(n) average.\n\n```python\n# m66046.py\nfrom __future__ import annotations\nfrom typing import Iterable, List, Set, TypeVar\nT=TypeVar(\"T\")\n\ndef f62322(xs: Iterable[T]) -> List[T]:\n \"\"\"Unique items preserving first-seen order.\"\"\"\n seen: Set[T]=set()\n out: List[T]=[]\n for x in xs:\n if x in seen: continue\n seen.add(x); out.append(x)\n return out\n```", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Refactor to modern typed Python with immutability and tests.\n\nFile: g6gbnyk.py\n```python\nclass Ft1A303:\n def __init__(self, name, values):\n self.name = name\n self.values = list(values)\n def add(self, v):\n self.values.append(v)\n def mean(self):\n s = 0\n for x in self.values:\n s += x\n return s / len(self.values)\n```\n\nReturn full new g6gbnyk.py and test_g6gbnyk.py.\n\n# g6gbnyk.py\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom typing import Iterable, Tuple\n\n@dataclass(frozen=True)\nclass Ft1A303:\n name: str\n values: Tuple[float, ...]\n\n @staticmethod\n def create(name: str, values: Iterable[float]) -> \"Ft1A303\":\n vals = tuple(float(v) for v in values)\n if not vals:\n raise ValueError(\"values must be non-empty\")\n return Ft1A303(name=name, values=vals)\n\n def add(self, v: float) -> \"Ft1A303\":\n return Ft1A303(name=self.name, values=self.values + (float(v),))\n\n def mean(self) -> float:\n return sum(self.values) / len(self.values)\n\n# test_g6gbnyk.py\nimport pytest\nfrom g6gbnyk import Ft1A303\n\ndef test_mean_and_add():\n c = Ft1A303.create(\"a\", [1, 2, 3])\n assert c.mean() == 2.0\n assert c.add(5).mean() == (1 + 2 + 3 + 5) / 4\n\ndef test_empty_raises():\n with pytest.raises(ValueError):\n Ft1A303.create(\"x\", [])", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: System domain: developer platform\nStack: ASP.NET Core, SQL Server, EF Core, xUnit, Docker\nCross-layer incident: migration ordering failure\nTask type: observability_debug_fix\nDifficulty: hard\n\nSolve this as a complete-project engineer.\nOutput must include:\n- root cause across layers\n- final implementation patch\n- tests touching at least two layers\n- deployment or observability note\n- verification commands\n\nRepository sketch:\nrepo/\n app/\n api.py\n service.py\n models.py\n tests/\n test_api.py\n pyproject.toml\n\nFocus: Focus on multi-layer debugging across frontend, backend, database, CI, caching, and deployment.\n\nassistant: Diagnosis:\n- Root cause: migration ordering failure crosses service boundaries, so the fix must align code, contracts, tests, and deployment behavior.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```python\nfrom __future__ import annotations\n\nfrom dataclasses import dataclass\nfrom typing import Any\n\n@dataclass\nclass ServiceResult:\n ok: bool\n data: dict[str, Any]\n error: str | None = None\n\ndef normalize_payload(payload: dict[str, Any]) -> dict[str, Any]:\n if not isinstance(payload, dict):\n raise TypeError(\"payload must be a dict\")\n clean: dict[str, Any] = {}\n for key, value in payload.items():\n if value is None:\n continue\n clean[str(key).strip()] = value\n return clean\n\ndef handle_migration_ordering_failure(payload: dict[str, Any]) -> ServiceResult:\n clean = normalize_payload(payload)\n if \"id\" not in clean:\n return ServiceResult(ok=False, data={}, error=\"missing id\")\n return ServiceResult(ok=True, data=clean)\n```\n\nTests:\n```python\nimport pytest\nfrom app.service import handle_jwt_refresh_token_rotation as handler\n\ndef test_handler_accepts_valid_payload():\n result = handler({\"id\": 7, \"name\": \"ok\", \"unused\": None})\n assert result.ok is True\n assert result.data == {\"id\": 7, \"name\": \"ok\"}\n\ndef test_handler_rejects_missing_id():\n result = handler({\"name\": \"x\"})\n assert result.ok is False\n assert result.error == \"missing id\"\n```\n\nVerification:\n- `pytest -q`\n- `ruff check .`\n- `python -m compileall .`\n\nEngineering notes:\n- Language: Python\n- Framework/tooling: SQLAlchemy\n- Stack context: ASP.NET Core, SQL Server, EF Core, xUnit, Docker\n- Domain: developer platform\n- Task type: observability_debug_fix\n- Difficulty: hard\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Fix a bug and add tests.\n\nFile: b0uzth.py\n```python\ndef t9rvn52p_r0d(n: int) -> int:\n \"\"\"Sum 1..n inclusive.\"\"\"\n if n < 0:\n raise ValueError(\"n must be non-negative\")\n total = 0\n for k in range(n): # BUG: should include n\n total += k\n return total\n```\n\nReturn unified diffs for b0uzth.py and test_b0uzth.py (pytest).\n\n*** Begin Patch\n*** Update File: b0uzth.py\n@@\n def t9rvn52p_r0d(n: int) -> int:\n@@\n total = 0\n- for k in range(n): # BUG: should include n\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_b0uzth.py\n+import pytest\n+from b0uzth import t9rvn52p_r0d\n+\n+def test_zero():\n+ assert t9rvn52p_r0d(0) == 0\n+\n+def test_one():\n+ assert t9rvn52p_r0d(1) == 1\n+\n+def test_small():\n+ assert t9rvn52p_r0d(7) == 28\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ t9rvn52p_r0d(-1)\n+\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Fix a bug and add tests.\n\nFile: tgri1k4.py\n```python\ndef m4yz1qu8(n: int) -> int:\n \"\"\"Sum 1..n inclusive.\"\"\"\n if n < 0:\n raise ValueError(\"n must be non-negative\")\n total = 0\n for k in range(n): # BUG: should include n\n total += k\n return total\n```\n\nReturn unified diffs for tgri1k4.py and test_tgri1k4.py (pytest).\n\n*** Begin Patch\n*** Update File: tgri1k4.py\n@@\n def m4yz1qu8(n: int) -> int:\n@@\n total = 0\n- for k in range(n): # BUG: should include n\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_tgri1k4.py\n+import pytest\n+from tgri1k4 import m4yz1qu8\n+\n+def test_zero():\n+ assert m4yz1qu8(0) == 0\n+\n+def test_one():\n+ assert m4yz1qu8(1) == 1\n+\n+def test_small():\n+ assert m4yz1qu8(7) == 28\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ m4yz1qu8(-1)\n+\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Build an elite-grade solution in the domain of compilers for scenario: rate limiting gateway.\nPrimary language: rust.\nDifficulty: hard.\nConstraints: include invariants and failure modes, provide rollout and rollback guidance, avoid undefined behavior and data races, include tests or verification strategy, assume untrusted inputs; validate and sanitize.\nComponent: component_qtuctbq.\nAssume cold-start and memory limits are tight.\nTask: Define a small DSL, implement tokenizer/parser, IR, and a codegen or interpreter. Include tests and complexity notes.\n\nOutput: elite-grade engineering answer with contracts, edge cases, and verification.\nOutput: DSL + parser + IR + interpreter/codegen + tests.\n\n**DSL**\n- Expressions: integers, identifiers, `+ - * /`, let-binding: `let x = expr in expr`\n- Example: `let x = 2+3 in x*10`\n\n**Pipeline**\n1. Tokenize\n2. Parse into AST\n3. Lower into IR (stack ops) or interpret AST directly\n\n**Reference (Rust-style outline)**\n- `enum Expr { Int(i64), Var(String), Bin(Op, Box, Box), Let(String, Box, Box) }`\n- Parser: Pratt or recursive descent.\n\n**Tests**\n- Golden tests for parse trees.\n- Property: pretty-print(parse(x)) round-trips for a corpus.\n- Eval tests for precedence and scoping.\n\n\nHard checks: failure injection tests and performance regressions gated.", "source": "WithinUsAI/Elite_GOD_Coder_100k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Produce an offline-first self-evolving code assistant architecture named `rjms_ms`.\nMust include: module layout, patch-safety policy, evaluation gates (tests/lint/types), versioned memory index.\n\nArchitecture: `rjms_ms` (offline-first, self-evolving)\n\nModules\n- core/loop.py: evolve → validate → accept/reject (bounded iterations)\n- patching/: diff builder, safe apply, atomic writes, rollback points\n- policy/: allowlist paths, deny globs (.git/, __pycache__/, binaries), patch size caps\n- signals/: parse pytest/ruff/mypy into normalized findings\n- memory/index.jsonl: append-only snapshots (hashes, metrics, rationale)\n\nSafety gates\n- refuse path traversal/symlink escapes; never edit binaries\n- accept only if tests/lint/types stay green or improve", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Refactor to modern typed Python with immutability and tests.\n\nFile: gzk0danih62j.py\n```python\nclass F8Wdu5Io:\n def __init__(self, name, values):\n self.name = name\n self.values = list(values)\n def add(self, v):\n self.values.append(v)\n def mean(self):\n s = 0\n for x in self.values:\n s += x\n return s / len(self.values)\n```\n\nReturn full new gzk0danih62j.py and test_gzk0danih62j.py.\n\n# gzk0danih62j.py\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom typing import Iterable, Tuple\n\n@dataclass(frozen=True)\nclass F8Wdu5Io:\n name: str\n values: Tuple[float, ...]\n\n @staticmethod\n def create(name: str, values: Iterable[float]) -> \"F8Wdu5Io\":\n vals = tuple(float(v) for v in values)\n if not vals:\n raise ValueError(\"values must be non-empty\")\n return F8Wdu5Io(name=name, values=vals)\n\n def add(self, v: float) -> \"F8Wdu5Io\":\n return F8Wdu5Io(name=self.name, values=self.values + (float(v),))\n\n def mean(self) -> float:\n return sum(self.values) / len(self.values)\n\n# test_gzk0danih62j.py\nimport pytest\nfrom gzk0danih62j import F8Wdu5Io\n\ndef test_mean_and_add():\n c = F8Wdu5Io.create(\"a\", [1, 2, 3])\n assert c.mean() == 2.0\n assert c.add(5).mean() == (1 + 2 + 3 + 5) / 4\n\ndef test_empty_raises():\n with pytest.raises(ValueError):\n F8Wdu5Io.create(\"x\", [])", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Fix a subtle bug in a Python module used for event dispatching.\nRequirements: explain root cause briefly, provide corrected code, and add regression tests.\nConstraints: must be easy to extend, must avoid global state, stdlib-only, must include tests.\nDifficulty: easy. Ensure the API is testable via dependency injection.\n\nDeliverable: implementation + tests.\n```python\nfrom __future__ import annotations\n\nfrom dataclasses import dataclass\nfrom pathlib import Path\nfrom typing import Iterable\nimport json\n\n\nclass ValidationError(ValueError):\n \"\"\"Raised when input validation fails.\"\"\"\n\n\ndef safe_join(base: Path, *parts: str) -> Path:\n \"\"\"Join paths while preventing traversal outside base.\"\"\"\n b = base.resolve()\n p = (b / Path(*parts)).resolve()\n if p != b and b not in p.parents:\n raise ValidationError(f\"unsafe path: {p}\")\n return p\n\n\n@dataclass(frozen=True, slots=True)\nclass Record:\n key: str\n value: int\n\n\ndef parse_jsonl(lines: Iterable[str]) -> list[Record]:\n out: list[Record] = []\n for idx, line in enumerate(lines, 1):\n s = line.strip()\n if not s:\n continue\n try:\n obj = json.loads(s)\n except json.JSONDecodeError as e:\n raise ValidationError(f\"line {idx}: invalid json\") from e\n if not isinstance(obj, dict):\n raise ValidationError(f\"line {idx}: expected object\")\n key = obj.get(\"key\")\n val = obj.get(\"value\")\n if not isinstance(key, str) or not key:\n raise ValidationError(f\"line {idx}: key must be non-empty str\")\n if not isinstance(val, int):\n raise ValidationError(f\"line {idx}: value must be int\")\n out.append(Record(key, val))\n return out\n\n\ndef write_jsonl(base: Path, rel: str, records: Iterable[Record]) -> Path:\n base.mkdir(parents=True, exist_ok=True)\n dst = safe_join(base, rel)\n dst.parent.mkdir(parents=True, exist_ok=True)\n with dst.open(\"w\", encoding=\"utf-8\", newline=\"\\n\") as f:\n for r in records:\n f.write(json.dumps({\"key\": r.key, \"value\": r.value}, ensure_ascii=False) + \"\\n\")\n return dst\n```\n\n```python\n# tests (pytest-style)\nimport json\nfrom pathlib import Path\nimport pytest\nfrom module_under_test import ValidationError, Record, parse_jsonl, write_jsonl\n\ndef test_parse_ok():\n lines = [json.dumps({\"key\":\"a\",\"value\":1}), json.dumps({\"key\":\"b\",\"value\":2})]\n assert parse_jsonl(lines) == [Record(\"a\",1), Record(\"b\",2)]\n\ndef test_parse_rejects_bad_json():\n with pytest.raises(ValidationError):\n parse_jsonl([\"{not json}\"])\n\ndef test_safe_join_blocks_traversal(tmp_path: Path):\n with pytest.raises(ValidationError):\n write_jsonl(tmp_path, \"../x.jsonl\", [Record(\"a\",1)])\n```", "source": "WithinUsAI/python_GOD_coder_100k"} {"text": "Write secure, defensive Python code for ETL pipelines.\nRequirements: input validation, safe file handling, prevent path traversal, include tests.\nConstraints: stdlib-only, must handle Windows paths safely, must be memory-efficient, must avoid global state.\nDifficulty: expert. Include a small CLI example if relevant.\n\nDeliverable: implementation + tests.\n```python\nfrom __future__ import annotations\n\nfrom dataclasses import dataclass\nfrom pathlib import Path\nfrom typing import Iterable\nimport json\n\n\nclass ValidationError(ValueError):\n \"\"\"Raised when input validation fails.\"\"\"\n\n\ndef safe_join(base: Path, *parts: str) -> Path:\n \"\"\"Join paths while preventing traversal outside base.\"\"\"\n b = base.resolve()\n p = (b / Path(*parts)).resolve()\n if p != b and b not in p.parents:\n raise ValidationError(f\"unsafe path: {p}\")\n return p\n\n\n@dataclass(frozen=True, slots=True)\nclass Record:\n key: str\n value: int\n\n\ndef parse_jsonl(lines: Iterable[str]) -> list[Record]:\n out: list[Record] = []\n for idx, line in enumerate(lines, 1):\n s = line.strip()\n if not s:\n continue\n try:\n obj = json.loads(s)\n except json.JSONDecodeError as e:\n raise ValidationError(f\"line {idx}: invalid json\") from e\n if not isinstance(obj, dict):\n raise ValidationError(f\"line {idx}: expected object\")\n key = obj.get(\"key\")\n val = obj.get(\"value\")\n if not isinstance(key, str) or not key:\n raise ValidationError(f\"line {idx}: key must be non-empty str\")\n if not isinstance(val, int):\n raise ValidationError(f\"line {idx}: value must be int\")\n out.append(Record(key, val))\n return out\n\n\ndef write_jsonl(base: Path, rel: str, records: Iterable[Record]) -> Path:\n base.mkdir(parents=True, exist_ok=True)\n dst = safe_join(base, rel)\n dst.parent.mkdir(parents=True, exist_ok=True)\n with dst.open(\"w\", encoding=\"utf-8\", newline=\"\\n\") as f:\n for r in records:\n f.write(json.dumps({\"key\": r.key, \"value\": r.value}, ensure_ascii=False) + \"\\n\")\n return dst\n```\n\n```python\n# tests (pytest-style)\nimport json\nfrom pathlib import Path\nimport pytest\nfrom module_under_test import ValidationError, Record, parse_jsonl, write_jsonl\n\ndef test_parse_ok():\n lines = [json.dumps({\"key\":\"a\",\"value\":1}), json.dumps({\"key\":\"b\",\"value\":2})]\n assert parse_jsonl(lines) == [Record(\"a\",1), Record(\"b\",2)]\n\ndef test_parse_rejects_bad_json():\n with pytest.raises(ValidationError):\n parse_jsonl([\"{not json}\"])\n\ndef test_safe_join_blocks_traversal(tmp_path: Path):\n with pytest.raises(ValidationError):\n write_jsonl(tmp_path, \"../x.jsonl\", [Record(\"a\",1)])\n```", "source": "WithinUsAI/python_GOD_coder_100k"} {"text": "Fix the bug and add pytest tests.\n\n```python\ndef f31094(n: int) -> int:\n # sum 1..n inclusive\n if n < 0: raise ValueError\n total = 0\n for k in range(n): # BUG\n total += k\n return total\n```\nReturn unified diffs for `m04442.py` and `test_m04442.py`.\n\n*** Begin Patch\n*** Update File: m04442.py\n@@\n def f31094(n: int) -> int:\n@@\n- for k in range(n): # BUG\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_m04442.py\n+import pytest\n+from m04442 import f31094\n+\n+def test_small():\n+ assert f31094(7) == 28\n+\n+def test_zero():\n+ assert f31094(0) == 0\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ f31094(-1)\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Fix a bug and add tests.\n\nFile: uc4_9_2y_sw.py\n```python\ndef pxexosuznuwz(n: int) -> int:\n \"\"\"Sum 1..n inclusive.\"\"\"\n if n < 0:\n raise ValueError(\"n must be non-negative\")\n total = 0\n for k in range(n): # BUG: should include n\n total += k\n return total\n```\n\nReturn unified diffs for uc4_9_2y_sw.py and test_uc4_9_2y_sw.py (pytest).\n\n*** Begin Patch\n*** Update File: uc4_9_2y_sw.py\n@@\n def pxexosuznuwz(n: int) -> int:\n@@\n total = 0\n- for k in range(n): # BUG: should include n\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_uc4_9_2y_sw.py\n+import pytest\n+from uc4_9_2y_sw import pxexosuznuwz\n+\n+def test_zero():\n+ assert pxexosuznuwz(0) == 0\n+\n+def test_one():\n+ assert pxexosuznuwz(1) == 1\n+\n+def test_small():\n+ assert pxexosuznuwz(7) == 28\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ pxexosuznuwz(-1)\n+\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Fix a bug and add tests.\n\nFile: chs34fe72.py\n```python\ndef fs9rar(n: int) -> int:\n \"\"\"Sum 1..n inclusive.\"\"\"\n if n < 0:\n raise ValueError(\"n must be non-negative\")\n total = 0\n for k in range(n): # BUG: should include n\n total += k\n return total\n```\n\nReturn unified diffs for chs34fe72.py and test_chs34fe72.py (pytest).\n\n*** Begin Patch\n*** Update File: chs34fe72.py\n@@\n def fs9rar(n: int) -> int:\n@@\n total = 0\n- for k in range(n): # BUG: should include n\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_chs34fe72.py\n+import pytest\n+from chs34fe72 import fs9rar\n+\n+def test_zero():\n+ assert fs9rar(0) == 0\n+\n+def test_one():\n+ assert fs9rar(1) == 1\n+\n+def test_small():\n+ assert fs9rar(7) == 28\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ fs9rar(-1)\n+\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Fix the bug and add pytest tests.\n\n```python\ndef f76442(n: int) -> int:\n # sum 1..n inclusive\n if n < 0: raise ValueError\n total = 0\n for k in range(n): # BUG\n total += k\n return total\n```\nReturn unified diffs for `m25206.py` and `test_m25206.py`.\n\n*** Begin Patch\n*** Update File: m25206.py\n@@\n def f76442(n: int) -> int:\n@@\n- for k in range(n): # BUG\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_m25206.py\n+import pytest\n+from m25206 import f76442\n+\n+def test_small():\n+ assert f76442(7) == 28\n+\n+def test_zero():\n+ assert f76442(0) == 0\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ f76442(-1)\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Task type: network_protocol\nScenario: edge sync\nDomain focus: data lineage & governance\nPrimary language: rust\nDifficulty: hard\nScale/SLO: 99.99% availability\nComponent: component_auffpewc\nConstraints: include backward compatibility and migration plan, include verification strategy, assume adversarial inputs; validate everything, explicit contracts and invariants, include test vectors and fuzz strategy\nAssume strict auditability and replayable history.\nDeliverable: Design an application protocol: framing, retries, backpressure, timeouts; include client/server skeleton and test vectors.\n\nOutput: rigorous design + invariants + verification plan + implementation sketch.\n**Contract**\n- Inputs validated at the boundary; explicit error taxonomy.\n- Idempotency for side effects via request_id; deterministic replay.\n- Backward compatibility: additive changes by default; versioned breaking changes.\n**Invariants**\n- Liveness: under bounded faults and stable network, progress occurs.\n- Safety: state transitions preserve invariants; no partial commit leaks.\n- Determinism: replay of the same event log yields identical outputs.\n**Failure modes & recovery**\n- Data corruption: checksums + scrubber; quarantine and rebuild from replicas/snapshots.\n- Network partition: minority cannot commit; clients receive retriable errors.\n- Duplicate requests: de-duplicate by (tenant, request_id) returning cached response.\n**Security posture (defensive)**\n- Threat model: auth/authz, injection, replay/abuse, supply chain.\n- Least privilege; secrets in managed store; audit logs for sensitive ops.\n- Input normalization, parameterized queries, path traversal protections.\n**Verification strategy**\n- Deterministic simulation with fault injection (crash/partition/latency).\n- Fuzzing of parsers/framers/validators with corpus seeds.\n- Property tests against a pure reference model (state machine).\n\n**Snippet**\n```text\nImplementation sketch: factor pure state-machine core; adapters for I/O; add deterministic replay log.\n```\nHard checks: fault injection tests gate merges; perf thresholds enforced in CI.", "source": "WithinUsAI/Omega_Genesis_Coder_100k"} {"text": "Refactor to typed, mostly-immutable Python and add minimal tests.\n\n```python\nclass C78909:\n def __init__(self, values): self.values=list(values)\n def mean(self): return sum(self.values)/len(self.values)\n```\nReturn `m82993.py` and `test_m82993.py`.\n\n```python\n# m82993.py\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom typing import Iterable, Tuple\n\n@dataclass(frozen=True)\nclass C78909:\n values: Tuple[float, ...]\n\n @staticmethod\n def create(values: Iterable[float]) -> \"C78909\":\n vals = tuple(float(v) for v in values)\n if not vals: raise ValueError(\"empty\")\n return C78909(vals)\n\n def mean(self) -> float:\n return sum(self.values)/len(self.values)\n```\n\n```python\n# test_m82993.py\nimport pytest\nfrom m82993 import C78909\n\ndef test_mean():\n assert C78909.create([1,2,3]).mean() == 2.0\ndef test_empty():\n with pytest.raises(ValueError):\n C78909.create([])\n```", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Add a clear docstring and type hints to this function:\n\n```python\ndef f86120(s):\n return ''.join(x for x in s if x.isalnum()).lower()\n```\n\n```python\nfrom __future__ import annotations\n\ndef f86120(s: str) -> str:\n \"\"\"Normalize a string: keep only alphanumerics and lowercase the result.\"\"\"\n return \"\".join(ch for ch in s if ch.isalnum()).lower()\n```", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Build an elite-grade solution in the domain of distributed systems for scenario: payment processing.\nPrimary language: go.\nDifficulty: medium.\nConstraints: make the interface contract explicit, document performance characteristics, design for backward compatibility and migrations, include invariants and failure modes.\nComponent: component_syyrnbe.\nAssume cold-start and memory limits are tight.\nTask: Implement or outline a storage/indexing subsystem (LSM/B-Tree, WAL, snapshots). Include transaction/consistency considerations and benchmark plan.\n\nOutput: rigorous solution with invariants, failure modes, and performance notes.\nOutput: storage design + WAL + compaction + benchmarks.\n\n**Design**\n- WAL (append-only) for durability; fsync policy configurable.\n- Memtable (in-memory) → flush to immutable SSTables.\n- LSM compaction tiers; bloom filters per SSTable for point-lookups.\n- Manifest tracks SSTable set; atomic pointer swap on updates.\n\n**Correctness**\n- Crash recovery: replay WAL to rebuild memtable; manifest ensures last consistent set.\n- Reads: merge memtable + SSTables newest→oldest; tombstones override older values.\n\n**Bench plan**\n- Workloads: write-heavy, read-heavy, mixed; measure p50/p95 latency and write amplification.\n- Track compaction debt and space amplification.\n\n**Test plan**\n- Fuzz crash points: kill after WAL append / after manifest update; verify invariants on restart.\n\n\nChecks: boundary validation and deterministic behavior verified.", "source": "WithinUsAI/Elite_GOD_Coder_100k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Optimize while preserving behavior.\n\nFile: crd_hzaih5c.py\n```python\ndef nmdbxf8h(xs):\n out = []\n for x in xs:\n if x not in out:\n out.append(x)\n return out\n```\n\nRequirements: preserve first-seen order; O(n) average; add types + docstring.\n\n# crd_hzaih5c.py\nfrom __future__ import annotations\nfrom typing import Iterable, List, Set, TypeVar\n\nT = TypeVar(\"T\")\n\ndef nmdbxf8h(xs: Iterable[T]) -> List[T]:\n \"\"\"Return unique items preserving first-seen order.\"\"\"\n seen: Set[T] = set()\n out: List[T] = []\n for x in xs:\n if x in seen:\n continue\n seen.add(x)\n out.append(x)\n return out", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: Language: C#\nFramework/tooling: NUnit\nDomain: model serving gateway\nLogic challenge: unsafe deserialization\nTask type: multi_service_security_patch\nDifficulty: hard\n\nReturn a rigorous engineering answer:\n- identify the hidden root cause or logical failure\n- present the corrected implementation\n- add tests that prove the fix\n- list verification commands\n- explain why naive fixes are insufficient when relevant\n\nRepository sketch:\nrepo/\n src/App/Program.cs\n src/App/Service.cs\n tests/App.Tests/ServiceTests.cs\n App.sln\n\nFocus: Focus on staff-level problem solving with multi-file patches, rollout implications, performance and security tradeoffs.\n\nassistant: Diagnosis:\n- Staff-level diagnosis: unsafe deserialization impacts correctness, operability, and future maintenance, so the fix must be minimal where possible but complete where necessary.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```csharp\nusing System;\nusing System.Collections.Generic;\n\npublic static class RequestHandler\n{\n public static Dictionary HandleRequest(Dictionary payload)\n {\n var clean = new Dictionary();\n foreach (var entry in payload)\n {\n if (entry.Value != null)\n clean[entry.Key.Trim()] = entry.Value;\n }\n if (!clean.ContainsKey(\"id\"))\n throw new ArgumentException(\"missing id\");\n return new Dictionary\n {\n [\"ok\"] = true,\n [\"data\"] = clean\n };\n }\n}\n```\n\nTests:\n```csharp\nusing System;\nusing System.Collections.Generic;\nusing Xunit;\n\npublic class RequestHandlerTests\n{\n [Fact]\n public void RequiresId()\n {\n Assert.Throws(() => RequestHandler.HandleRequest(new Dictionary { [\"name\"] = \"x\" }));\n }\n}\n```\n\nVerification:\n- `dotnet test`\n- `dotnet build`\n\nEngineering notes:\n- Language: C#\n- Framework/tooling: NUnit\n- Stack context: Go, Gin, PostgreSQL, gRPC, Prometheus, Docker\n- Domain: model serving gateway\n- Task type: multi_service_security_patch\n- Difficulty: hard\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Refactor to modern typed Python with immutability and tests.\n\nFile: bnq1fh3un9.py\n```python\nclass Mm3Sr9:\n def __init__(self, name, values):\n self.name = name\n self.values = list(values)\n def add(self, v):\n self.values.append(v)\n def mean(self):\n s = 0\n for x in self.values:\n s += x\n return s / len(self.values)\n```\n\nReturn full new bnq1fh3un9.py and test_bnq1fh3un9.py.\n\n# bnq1fh3un9.py\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom typing import Iterable, Tuple\n\n@dataclass(frozen=True)\nclass Mm3Sr9:\n name: str\n values: Tuple[float, ...]\n\n @staticmethod\n def create(name: str, values: Iterable[float]) -> \"Mm3Sr9\":\n vals = tuple(float(v) for v in values)\n if not vals:\n raise ValueError(\"values must be non-empty\")\n return Mm3Sr9(name=name, values=vals)\n\n def add(self, v: float) -> \"Mm3Sr9\":\n return Mm3Sr9(name=self.name, values=self.values + (float(v),))\n\n def mean(self) -> float:\n return sum(self.values) / len(self.values)\n\n# test_bnq1fh3un9.py\nimport pytest\nfrom bnq1fh3un9 import Mm3Sr9\n\ndef test_mean_and_add():\n c = Mm3Sr9.create(\"a\", [1, 2, 3])\n assert c.mean() == 2.0\n assert c.add(5).mean() == (1 + 2 + 3 + 5) / 4\n\ndef test_empty_raises():\n with pytest.raises(ValueError):\n Mm3Sr9.create(\"x\", [])", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Task type: gpu_serving_pipeline\nScenario: payment ledger\nDomain focus: constraint solving\nPrimary language: bash\nDifficulty: expert+\nScale/SLO: multi-region active-active\nComponent: component_khkuusdy\nConstraints: include security threat model (defensive only), include test vectors and fuzz strategy, include failure modes and recovery, include backward compatibility and migration plan, avoid data races and undefined behavior\nAssume hostile inputs and targeted abuse patterns.\nDeliverable: Design a GPU inference serving pipeline: batching, scheduling, memory management, tail-latency control, and monitoring.\n\nOutput: contract-first solution with failure modes, security posture, and test/verification strategy.\n**Contract**\n- Inputs validated at the boundary; explicit error taxonomy.\n- Idempotency for side effects via request_id; deterministic replay.\n- Backward compatibility: additive changes by default; versioned breaking changes.\n**Invariants**\n- Safety: state transitions preserve invariants; no partial commit leaks.\n- Isolation: tenant boundary enforced; no cross-tenant reads/writes.\n- Determinism: replay of the same event log yields identical outputs.\n**Failure modes & recovery**\n- Crash during commit: WAL replay completes or transaction aborts; no torn writes.\n- Duplicate requests: de-duplicate by (tenant, request_id) returning cached response.\n- Data corruption: checksums + scrubber; quarantine and rebuild from replicas/snapshots.\n**Security posture (defensive)**\n- Threat model: auth/authz, injection, replay/abuse, supply chain.\n- Least privilege; secrets in managed store; audit logs for sensitive ops.\n- Input normalization, parameterized queries, path traversal protections.\n**Verification strategy**\n- Fuzzing of parsers/framers/validators with corpus seeds.\n- Deterministic simulation with fault injection (crash/partition/latency).\n- Canary + shadow traffic; invariants checked in production via assertions/metrics.\n\n**Snippet**\n```text\nImplementation sketch: factor pure state-machine core; adapters for I/O; add deterministic replay log.\n```\nExpert+ checks: mechanized invariants (or exhaustive model checking), adversarial fuzzing, and multi-region failure drills.", "source": "WithinUsAI/Omega_Genesis_Coder_100k"} {"text": "Add a clear docstring and type hints to this function:\n\n```python\ndef f19926(s):\n return ''.join(x for x in s if x.isalnum()).lower()\n```\n\n```python\nfrom __future__ import annotations\n\ndef f19926(s: str) -> str:\n \"\"\"Normalize a string: keep only alphanumerics and lowercase the result.\"\"\"\n return \"\".join(ch for ch in s if ch.isalnum()).lower()\n```", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Build an elite-grade solution in the domain of databases for scenario: inventory & ordering.\nPrimary language: typescript.\nDifficulty: expert.\nConstraints: avoid undefined behavior and data races, include tests or verification strategy, include invariants and failure modes, make the interface contract explicit.\nComponent: component_eozrots.\nAssume compliance requires data deletion with proofs.\nTask: Provide SLOs, alerting, dashboards, runbooks, and incident playbook. Include chaos testing and safe rollout strategy.\n\nOutput: production blueprint plus correctness arguments and test strategy.\nOutput: SLOs + alerts + runbooks + chaos strategy.\n\n**SLOs**\n- Availability: 99.9% monthly\n- Latency: p95 < 200ms, p99 < 400ms\n- Error rate: < 0.1%\n\n**Alerts**\n- Burn-rate alerts for SLOs (fast/slow windows)\n- Saturation: CPU, memory, queue depth, DB connections\n- Dependency health: cache hit rate drop, downstream timeouts\n\n**Runbooks**\n- Triage: identify blast radius, feature-flag rollback, capacity mitigation\n- Post-incident: timeline, contributing factors, action items\n\n**Chaos**\n- Inject latency, partial outages, and restarts in staging; verify steady-state SLOs.\n\n\nExpert checks: state-machine reasoning, concurrency stress, and upgrade/rollback validated.", "source": "WithinUsAI/Elite_GOD_Coder_100k"} {"text": "Write pytest tests for `f91315`.\n\n```python\ndef f91315(a: int, b: int) -> int:\n return a*a + b*b\n```\nInclude edge cases and a property-style check.\n\n```python\nimport random\nfrom m13045 import f91315\n\ndef test_known():\n assert f91315(3,4) == 25\n\ndef test_zero():\n assert f91315(0,0) == 0\n\ndef test_property_nonnegative():\n for _ in range(200):\n a=random.randint(-50,50)\n b=random.randint(-50,50)\n assert f91315(a,b) >= 0\n```", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: Language: Rust\nFramework/tooling: cargo test\nDomain: document processing API\nLogic challenge: monorepo toolchain skew\nTask type: algorithmic_correctness\nDifficulty: medium\n\nReturn a rigorous engineering answer:\n- identify the hidden root cause or logical failure\n- present the corrected implementation\n- add tests that prove the fix\n- list verification commands\n- explain why naive fixes are insufficient when relevant\n\nRepository sketch:\nrepo/\n src/main.rs\n src/lib.rs\n src/service.rs\n src/store.rs\n tests/integration.rs\n Cargo.toml\n\nFocus: Focus on strong structured logic with edge cases, data validation, and concurrency safety.\n\nassistant: Diagnosis:\n- Root cause: the failure around monorepo toolchain skew is caused by missing validation, weak edge-case handling, or unsafe lifecycle behavior in the current implementation.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```rust\nuse std::collections::HashMap;\n\npub fn normalize_payload(payload: HashMap) -> HashMap {\n payload\n .into_iter()\n .filter(|(_, v)| !v.trim().is_empty())\n .collect()\n}\n```\n\nTests:\n```rust\n#[test]\nfn normalize_payload_filters_empty_values() {\n use std::collections::HashMap;\n let mut payload = HashMap::new();\n payload.insert(\"id\".to_string(), \"7\".to_string());\n payload.insert(\"name\".to_string(), \"\".to_string());\n let out = normalize_payload(payload);\n assert!(out.contains_key(\"id\"));\n assert!(!out.contains_key(\"name\"));\n}\n```\n\nVerification:\n- `cargo test`\n- `cargo clippy -- -D warnings`\n\nEngineering notes:\n- Language: Rust\n- Framework/tooling: cargo test\n- Stack context: ASP.NET Core, SQL Server, EF Core, xUnit, Docker\n- Domain: document processing API\n- Task type: algorithmic_correctness\n- Difficulty: medium\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Fix a bug and add tests.\n\nFile: zxabcyf6sx2v.py\n```python\ndef ytcauzriyh81(n: int) -> int:\n \"\"\"Sum 1..n inclusive.\"\"\"\n if n < 0:\n raise ValueError(\"n must be non-negative\")\n total = 0\n for k in range(n): # BUG: should include n\n total += k\n return total\n```\n\nReturn unified diffs for zxabcyf6sx2v.py and test_zxabcyf6sx2v.py (pytest).\n\n*** Begin Patch\n*** Update File: zxabcyf6sx2v.py\n@@\n def ytcauzriyh81(n: int) -> int:\n@@\n total = 0\n- for k in range(n): # BUG: should include n\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_zxabcyf6sx2v.py\n+import pytest\n+from zxabcyf6sx2v import ytcauzriyh81\n+\n+def test_zero():\n+ assert ytcauzriyh81(0) == 0\n+\n+def test_one():\n+ assert ytcauzriyh81(1) == 1\n+\n+def test_small():\n+ assert ytcauzriyh81(7) == 28\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ ytcauzriyh81(-1)\n+\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Refactor to typed, mostly-immutable Python and add minimal tests.\n\n```python\nclass C76585:\n def __init__(self, values): self.values=list(values)\n def mean(self): return sum(self.values)/len(self.values)\n```\nReturn `m52045.py` and `test_m52045.py`.\n\n```python\n# m52045.py\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom typing import Iterable, Tuple\n\n@dataclass(frozen=True)\nclass C76585:\n values: Tuple[float, ...]\n\n @staticmethod\n def create(values: Iterable[float]) -> \"C76585\":\n vals = tuple(float(v) for v in values)\n if not vals: raise ValueError(\"empty\")\n return C76585(vals)\n\n def mean(self) -> float:\n return sum(self.values)/len(self.values)\n```\n\n```python\n# test_m52045.py\nimport pytest\nfrom m52045 import C76585\n\ndef test_mean():\n assert C76585.create([1,2,3]).mean() == 2.0\ndef test_empty():\n with pytest.raises(ValueError):\n C76585.create([])\n```", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Perform a code review for a social media PR implementing rate limiting.\nTarget platform: mobile (iOS Swift).\nRequirements: list critical issues, improvements, and provide an improved patch excerpt.\nConstraints: must be production-ready, must include type hints where applicable, must avoid global state.\nDifficulty: expert. Include rollback strategy.\n\nOutput: design + implementation guidance suitable for shipping.\nDeliverable: code review findings + improved patch excerpt.\n\n**Critical issues**\n1. Missing input validation at boundary; potential unexpected exceptions.\n2. No idempotency / retry safety for side-effecting endpoint.\n3. No tests for edge cases (empty input, duplicates, timeouts).\n4. Observability gaps: no request_id correlation, no metrics.\n\n**Improvements**\n- Add strict validation and explicit error responses.\n- Add idempotency key support for create endpoints.\n- Add unit + integration tests with CI gating.\n- Add structured logs and basic metrics.\n\nPatch excerpt (illustrative):\n```python\nif not idem_key:\n raise HTTPException(400, \"Missing Idempotency-Key\")\n```\n\n\nHard-mode checks: concurrency safety, idempotency, and rollback validated; add chaos tests where feasible.", "source": "WithinUsAI/GOD_Coder_100k"} {"text": "Build an elite-grade solution in the domain of security engineering (defensive) for scenario: chat messaging.\nPrimary language: rust.\nDifficulty: medium.\nConstraints: avoid undefined behavior and data races, assume untrusted inputs; validate and sanitize, make the interface contract explicit, include tests or verification strategy.\nComponent: component_phfwjqj.\nAssume crash-only design; recovery must be deterministic.\nTask: Design an application-level protocol (framing, retries, timeouts, backpressure). Provide client/server skeleton and test vectors.\n\nOutput: production blueprint plus correctness arguments and test strategy.\nOutput: protocol framing + retry policy + client/server skeleton.\n\n**Framing**\n- Length-prefixed: uint32_be length + payload\n- Payload: msgpack/json; include request_id, type, and optional checksum\n\n**Reliability**\n- Retries only for idempotent ops; exponential backoff + jitter.\n- Timeouts: connect, read, overall; enforce max in-flight to provide backpressure.\n\n**Test vectors**\n- Corrupted length / truncated frame rejected\n- Duplicate request_id returns cached response\n- Slowloris protection by read deadlines\n\n\nChecks: boundary validation and deterministic behavior verified.", "source": "WithinUsAI/Elite_GOD_Coder_100k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Refactor to modern typed Python with immutability and tests.\n\nFile: fwvwny.py\n```python\nclass Vn48Pjah1:\n def __init__(self, name, values):\n self.name = name\n self.values = list(values)\n def add(self, v):\n self.values.append(v)\n def mean(self):\n s = 0\n for x in self.values:\n s += x\n return s / len(self.values)\n```\n\nReturn full new fwvwny.py and test_fwvwny.py.\n\n# fwvwny.py\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom typing import Iterable, Tuple\n\n@dataclass(frozen=True)\nclass Vn48Pjah1:\n name: str\n values: Tuple[float, ...]\n\n @staticmethod\n def create(name: str, values: Iterable[float]) -> \"Vn48Pjah1\":\n vals = tuple(float(v) for v in values)\n if not vals:\n raise ValueError(\"values must be non-empty\")\n return Vn48Pjah1(name=name, values=vals)\n\n def add(self, v: float) -> \"Vn48Pjah1\":\n return Vn48Pjah1(name=self.name, values=self.values + (float(v),))\n\n def mean(self) -> float:\n return sum(self.values) / len(self.values)\n\n# test_fwvwny.py\nimport pytest\nfrom fwvwny import Vn48Pjah1\n\ndef test_mean_and_add():\n c = Vn48Pjah1.create(\"a\", [1, 2, 3])\n assert c.mean() == 2.0\n assert c.add(5).mean() == (1 + 2 + 3 + 5) / 4\n\ndef test_empty_raises():\n with pytest.raises(ValueError):\n Vn48Pjah1.create(\"x\", [])", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Produce an offline-first self-evolving code assistant architecture named `rtdor2ii6hj4`.\nMust include: module layout, patch-safety policy, evaluation gates (tests/lint/types), versioned memory index.\n\nArchitecture: `rtdor2ii6hj4` (offline-first, self-evolving)\n\nModules\n- core/loop.py: evolve → validate → accept/reject (bounded iterations)\n- patching/: diff builder, safe apply, atomic writes, rollback points\n- policy/: allowlist paths, deny globs (.git/, __pycache__/, binaries), patch size caps\n- signals/: parse pytest/ruff/mypy into normalized findings\n- memory/index.jsonl: append-only snapshots (hashes, metrics, rationale)\n\nSafety gates\n- refuse path traversal/symlink escapes; never edit binaries\n- accept only if tests/lint/types stay green or improve", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Fix a bug and add tests.\n\nFile: fbyqso63mqa.py\n```python\ndef hj80yi(n: int) -> int:\n \"\"\"Sum 1..n inclusive.\"\"\"\n if n < 0:\n raise ValueError(\"n must be non-negative\")\n total = 0\n for k in range(n): # BUG: should include n\n total += k\n return total\n```\n\nReturn unified diffs for fbyqso63mqa.py and test_fbyqso63mqa.py (pytest).\n\n*** Begin Patch\n*** Update File: fbyqso63mqa.py\n@@\n def hj80yi(n: int) -> int:\n@@\n total = 0\n- for k in range(n): # BUG: should include n\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_fbyqso63mqa.py\n+import pytest\n+from fbyqso63mqa import hj80yi\n+\n+def test_zero():\n+ assert hj80yi(0) == 0\n+\n+def test_one():\n+ assert hj80yi(1) == 1\n+\n+def test_small():\n+ assert hj80yi(7) == 28\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ hj80yi(-1)\n+\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Build an elite-grade solution in the domain of high-performance services for scenario: event ingestion.\nPrimary language: go.\nDifficulty: hard.\nConstraints: document performance characteristics, design for backward compatibility and migrations, include tests or verification strategy.\nComponent: component_rcgxtlj.\nAssume schema changes every sprint; must be backward compatible.\nTask: Optimize a hot path with profiling-driven approach; propose micro/meso optimizations, and supply a benchmark harness with acceptance thresholds.\n\nOutput: production blueprint plus correctness arguments and test strategy.\nOutput: profiling-first optimization + benchmark harness.\n\n**Plan**\n1. Establish baseline with microbench + representative dataset.\n2. Profile (CPU, allocations, syscalls).\n3. Apply optimizations: reduce allocations, reuse buffers, batch I/O, vectorize parsing where safe.\n4. Validate with regression suite and perf thresholds.\n\n**Benchmark guidance**\n- Use p50/p95 and throughput; pin CPU frequency if possible.\n- Acceptance: p95 improves ≥ X% with no correctness regressions.\n\n\nHard checks: failure injection tests and performance regressions gated.", "source": "WithinUsAI/Elite_GOD_Coder_100k"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: Project domain: repo automation\nImplementation stack: ASP.NET Core, SQL Server, EF Core, xUnit, Docker\nSoftware delivery problem: monorepo toolchain skew\nTask type: prd_to_patch\nDifficulty: hard\n\nReturn a complete delivery-grade response with:\n- diagnosis or design reasoning\n- implementation\n- test plan or tests\n- rollout plan\n- rollback or compatibility note\n- verification commands\n\nRepository sketch:\nrepo/\n src/main.cpp\n src/service.cpp\n include/service.h\n tests/test_service.cpp\n CMakeLists.txt\n\nFocus: Focus on shipping production software with rollout safety, acceptance criteria, telemetry, and maintenance quality.\n\nassistant: Diagnosis:\n- Root cause or delivery blocker: monorepo toolchain skew needs both implementation work and a safe shipping plan.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```cpp\n#include \n#include \n\nusing Payload = std::unordered_map;\n\nPayload normalize_payload(const Payload& in) {\n Payload out;\n for (const auto& [k, v] : in) {\n if (!v.empty()) out[k] = v;\n }\n return out;\n}\n```\n\nTests:\n```cpp\nTEST_CASE(\"normalize_payload filters empty values\") {\n Payload in{{\"id\",\"7\"},{\"name\",\"\"}};\n auto out = normalize_payload(in);\n REQUIRE(out.count(\"id\") == 1);\n REQUIRE(out.count(\"name\") == 0);\n}\n```\n\nVerification:\n- `cmake --build build`\n- `ctest --test-dir build`\n\nEngineering notes:\n- Language: C++\n- Framework/tooling: Catch2\n- Stack context: ASP.NET Core, SQL Server, EF Core, xUnit, Docker\n- Domain: repo automation\n- Task type: prd_to_patch\n- Difficulty: hard\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "Refactor a Python module used for data modeling into a clean, extensible design.\nRequirements: outline the new architecture briefly, then provide the refactored code and tests.\nConstraints: must be streaming-friendly, must include docstrings, must avoid global state, stdlib-only.\nDifficulty: easy. Avoid quadratic behavior on large inputs.\n\nDeliverable: production-ready reference solution.\nArchitecture:\n- Public facade class coordinating concerns (parsing, validation, persistence)\n- Small pure functions for testability\n- No global state; dependency injection for filesystem I/O\n\n```python\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom pathlib import Path\nfrom typing import Protocol, Iterable\nimport json\n\nclass Store(Protocol):\n def write_text(self, path: Path, data: str) -> None: ...\n\nclass FSStore:\n def write_text(self, path: Path, data: str) -> None:\n path.parent.mkdir(parents=True, exist_ok=True)\n path.write_text(data, encoding=\"utf-8\")\n\n@dataclass(frozen=True, slots=True)\nclass Item:\n name: str\n qty: int\n\ndef parse_items(lines: Iterable[str]) -> list[Item]:\n out: list[Item] = []\n for i, line in enumerate(lines, 1):\n s = line.strip()\n if not s:\n continue\n obj = json.loads(s)\n if not isinstance(obj, dict):\n raise ValueError(f\"line {i}: expected object\")\n name = obj.get(\"name\")\n qty = obj.get(\"qty\")\n if not isinstance(name, str) or not name:\n raise ValueError(f\"line {i}: name must be str\")\n if not isinstance(qty, int) or qty < 0:\n raise ValueError(f\"line {i}: qty must be non-negative int\")\n out.append(Item(name, qty))\n return out\n\nclass InventoryWriter:\n def __init__(self, base_dir: Path, store: Store | None = None) -> None:\n self._base = base_dir\n self._store: Store = store or FSStore()\n\n def write(self, rel_path: str, items: list[Item]) -> Path:\n dst = (self._base / rel_path).resolve()\n base = self._base.resolve()\n if dst != base and base not in dst.parents:\n raise ValueError(\"unsafe path traversal\")\n payload = json.dumps([item.__dict__ for item in items], ensure_ascii=False)\n self._store.write_text(dst, payload)\n return dst\n```\n\n```python\nimport json\nfrom pathlib import Path\nimport pytest\nfrom module_under_test import InventoryWriter, parse_items\n\ndef test_parse_items_valid():\n lines = [json.dumps({\"name\":\"x\",\"qty\":1})]\n assert parse_items(lines)[0].name == \"x\"\n\ndef test_writer_blocks_traversal(tmp_path: Path):\n w = InventoryWriter(tmp_path)\n with pytest.raises(ValueError):\n w.write(\"../evil.json\", [])\n```", "source": "WithinUsAI/python_GOD_coder_100k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Optimize while preserving behavior.\n\nFile: oce6zrxizsr.py\n```python\ndef sxt5d8g2ur(xs):\n out = []\n for x in xs:\n if x not in out:\n out.append(x)\n return out\n```\n\nRequirements: preserve first-seen order; O(n) average; add types + docstring.\n\n# oce6zrxizsr.py\nfrom __future__ import annotations\nfrom typing import Iterable, List, Set, TypeVar\n\nT = TypeVar(\"T\")\n\ndef sxt5d8g2ur(xs: Iterable[T]) -> List[T]:\n \"\"\"Return unique items preserving first-seen order.\"\"\"\n seen: Set[T] = set()\n out: List[T] = []\n for x in xs:\n if x in seen:\n continue\n seen.add(x)\n out.append(x)\n return out", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Implement a concurrent Python solution for CLI tooling.\nRequirements: choose appropriate concurrency model, handle cancellation/timeouts, include tests.\nConstraints: must be easy to extend, must be memory-efficient.\nDifficulty: expert. Support both Windows and POSIX paths correctly.\n\nDeliverable: corrected code and verification tests.\n```python\nfrom __future__ import annotations\nimport asyncio\nfrom dataclasses import dataclass\nfrom typing import Awaitable, Callable, Iterable, Optional\n\n@dataclass(frozen=True, slots=True)\nclass JobResult:\n ok: bool\n value: Optional[int]\n error: Optional[str]\n\nasync def run_bounded(\n factories: Iterable[Callable[[], Awaitable[int]]],\n *,\n limit: int = 10,\n timeout_s: float = 5.0,\n) -> list[JobResult]:\n if limit <= 0:\n raise ValueError(\"limit must be > 0\")\n sem = asyncio.Semaphore(limit)\n results: list[JobResult] = []\n\n async def one(factory: Callable[[], Awaitable[int]]) -> None:\n async with sem:\n try:\n v = await asyncio.wait_for(factory(), timeout=timeout_s)\n results.append(JobResult(True, v, None))\n except Exception as e:\n results.append(JobResult(False, None, str(e)))\n\n tasks = [asyncio.create_task(one(f)) for f in factories]\n try:\n await asyncio.gather(*tasks)\n finally:\n for t in tasks:\n if not t.done():\n t.cancel()\n return results\n```\n\n```python\nimport asyncio\nimport pytest\nfrom module_under_test import run_bounded\n\n@pytest.mark.asyncio\nasync def test_run_bounded_collects():\n async def work(x: int) -> int:\n await asyncio.sleep(0.01)\n return x\n fs = [(lambda i=i: work(i)) for i in range(30)]\n out = await run_bounded(fs, limit=5, timeout_s=1.0)\n assert len(out) == 30\n assert all(r.ok for r in out)\n```", "source": "WithinUsAI/python_GOD_coder_100k"} {"text": "Refactor to typed, mostly-immutable Python and add minimal tests.\n\n```python\nclass C59945:\n def __init__(self, values): self.values=list(values)\n def mean(self): return sum(self.values)/len(self.values)\n```\nReturn `m50765.py` and `test_m50765.py`.\n\n```python\n# m50765.py\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom typing import Iterable, Tuple\n\n@dataclass(frozen=True)\nclass C59945:\n values: Tuple[float, ...]\n\n @staticmethod\n def create(values: Iterable[float]) -> \"C59945\":\n vals = tuple(float(v) for v in values)\n if not vals: raise ValueError(\"empty\")\n return C59945(vals)\n\n def mean(self) -> float:\n return sum(self.values)/len(self.values)\n```\n\n```python\n# test_m50765.py\nimport pytest\nfrom m50765 import C59945\n\ndef test_mean():\n assert C59945.create([1,2,3]).mean() == 2.0\ndef test_empty():\n with pytest.raises(ValueError):\n C59945.create([])\n```", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Improve typing and robustness of a Python module used for rate limiting.\nRequirements: provide type-safe APIs (generics/protocols where appropriate) and include tests.\nConstraints: must include type hints, must provide clear error messages, must be easy to extend.\nDifficulty: expert. Ensure the API is testable via dependency injection.\n\nDeliverable: API + reference implementation + tests.\n```python\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom typing import Callable, Generic, Iterable, Protocol, TypeVar\n\nT = TypeVar(\"T\")\nR = TypeVar(\"R\")\n\nclass Mapper(Protocol[T, R]):\n def __call__(self, x: T) -> R: ...\n\n@dataclass(frozen=True, slots=True)\nclass Batch(Generic[T]):\n items: tuple[T, ...]\n\ndef map_batch(batch: Batch[T], fn: Mapper[T, R]) -> Batch[R]:\n return Batch(items=tuple(fn(x) for x in batch.items))\n\ndef chunked(xs: Iterable[T], size: int) -> Iterable[Batch[T]]:\n if size <= 0:\n raise ValueError(\"size must be > 0\")\n buf: list[T] = []\n for x in xs:\n buf.append(x)\n if len(buf) == size:\n yield Batch(items=tuple(buf))\n buf.clear()\n if buf:\n yield Batch(items=tuple(buf))\n```\n\n```python\nimport pytest\nfrom module_under_test import Batch, map_batch, chunked\n\ndef test_map_batch():\n b = Batch(items=(1,2,3))\n assert map_batch(b, lambda x: x*2).items == (2,4,6)\n\ndef test_chunked():\n out = list(chunked([1,2,3,4,5], 2))\n assert [b.items for b in out] == [(1,2),(3,4),(5,)]\n```", "source": "WithinUsAI/python_GOD_coder_100k"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: Language: Rust\nFramework/tooling: SQLx\nDomain: payments platform\nLogic challenge: migration ordering failure\nTask type: security_logic_interaction\nDifficulty: hard\n\nReturn a rigorous engineering answer:\n- identify the hidden root cause or logical failure\n- present the corrected implementation\n- add tests that prove the fix\n- list verification commands\n- explain why naive fixes are insufficient when relevant\n\nRepository sketch:\nrepo/\n src/main.rs\n src/lib.rs\n src/service.rs\n src/store.rs\n tests/integration.rs\n Cargo.toml\n\nFocus: Focus on ambiguity, misleading symptoms, hidden root causes, and high-stakes debugging.\n\nassistant: Diagnosis:\n- Hidden root cause: migration ordering failure presents misleading symptoms, so the patch must target the actual logic boundary rather than the first visible failure.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```rust\nuse std::collections::HashMap;\n\npub fn normalize_payload(payload: HashMap) -> HashMap {\n payload\n .into_iter()\n .filter(|(_, v)| !v.trim().is_empty())\n .collect()\n}\n```\n\nTests:\n```rust\n#[test]\nfn normalize_payload_filters_empty_values() {\n use std::collections::HashMap;\n let mut payload = HashMap::new();\n payload.insert(\"id\".to_string(), \"7\".to_string());\n payload.insert(\"name\".to_string(), \"\".to_string());\n let out = normalize_payload(payload);\n assert!(out.contains_key(\"id\"));\n assert!(!out.contains_key(\"name\"));\n}\n```\n\nVerification:\n- `cargo test`\n- `cargo clippy -- -D warnings`\n\nEngineering notes:\n- Language: Rust\n- Framework/tooling: SQLx\n- Stack context: Airflow, dbt, DuckDB, MinIO, pytest\n- Domain: payments platform\n- Task type: security_logic_interaction\n- Difficulty: hard\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Refactor to modern typed Python with immutability and tests.\n\nFile: ifkg2g.py\n```python\nclass Bhr4Eg12P8Q:\n def __init__(self, name, values):\n self.name = name\n self.values = list(values)\n def add(self, v):\n self.values.append(v)\n def mean(self):\n s = 0\n for x in self.values:\n s += x\n return s / len(self.values)\n```\n\nReturn full new ifkg2g.py and test_ifkg2g.py.\n\n# ifkg2g.py\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom typing import Iterable, Tuple\n\n@dataclass(frozen=True)\nclass Bhr4Eg12P8Q:\n name: str\n values: Tuple[float, ...]\n\n @staticmethod\n def create(name: str, values: Iterable[float]) -> \"Bhr4Eg12P8Q\":\n vals = tuple(float(v) for v in values)\n if not vals:\n raise ValueError(\"values must be non-empty\")\n return Bhr4Eg12P8Q(name=name, values=vals)\n\n def add(self, v: float) -> \"Bhr4Eg12P8Q\":\n return Bhr4Eg12P8Q(name=self.name, values=self.values + (float(v),))\n\n def mean(self) -> float:\n return sum(self.values) / len(self.values)\n\n# test_ifkg2g.py\nimport pytest\nfrom ifkg2g import Bhr4Eg12P8Q\n\ndef test_mean_and_add():\n c = Bhr4Eg12P8Q.create(\"a\", [1, 2, 3])\n assert c.mean() == 2.0\n assert c.add(5).mean() == (1 + 2 + 3 + 5) / 4\n\ndef test_empty_raises():\n with pytest.raises(ValueError):\n Bhr4Eg12P8Q.create(\"x\", [])", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: Language: JavaScript\nFramework/tooling: React\nDomain: team dashboard\nLogic challenge: JWT refresh token rotation\nTask type: algorithmic_correctness\nDifficulty: medium\n\nReturn a rigorous engineering answer:\n- identify the hidden root cause or logical failure\n- present the corrected implementation\n- add tests that prove the fix\n- list verification commands\n- explain why naive fixes are insufficient when relevant\n\nRepository sketch:\nrepo/\n src/\n api.js\n service.js\n utils.js\n tests/\n api.test.js\n package.json\n\nFocus: Focus on strong structured logic with edge cases, data validation, and concurrency safety.\n\nassistant: Diagnosis:\n- Root cause: the failure around JWT refresh token rotation is caused by missing validation, weak edge-case handling, or unsafe lifecycle behavior in the current implementation.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```javascript\ntype Payload = Record;\n\nexport function normalizePayload(payload: Payload): Payload {\n if (!payload || typeof payload !== \"object\" || Array.isArray(payload)) {\n throw new TypeError(\"payload must be a plain object\");\n }\n return Object.fromEntries(\n Object.entries(payload)\n .filter(([, value]) => value !== null && value !== undefined)\n .map(([key, value]) => [String(key).trim(), value])\n );\n}\n\nexport function handleJwtRefreshTokenRotation(payload: Payload) {\n const clean = normalizePayload(payload);\n if (!(\"id\" in clean)) {\n return { ok: false, data: {}, error: \"missing id\" };\n }\n return { ok: true, data: clean, error: null };\n}\n```\n\nTests:\n```javascript\nimport { describe, it, expect } from \"vitest\";\nimport { handleJwtRefreshTokenRotation } from \"../src/service\";\n\ndescribe(\"handler\", () => {\n it(\"accepts valid input\", () => {\n expect(handleJwtRefreshTokenRotation({ id: 7, name: \"ok\", unused: null })).toEqual({\n ok: true,\n data: { id: 7, name: \"ok\" },\n error: null\n });\n });\n\n it(\"rejects missing id\", () => {\n expect(handleJwtRefreshTokenRotation({ name: \"x\" }).error).toMatch(/missing id/);\n });\n});\n```\n\nVerification:\n- `npm test`\n- `npm run lint`\n\nEngineering notes:\n- Language: JavaScript\n- Framework/tooling: React\n- Stack context: ASP.NET Core, SQL Server, EF Core, xUnit, Docker\n- Domain: team dashboard\n- Task type: algorithmic_correctness\n- Difficulty: medium\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "Refactor to typed, mostly-immutable Python and add minimal tests.\n\n```python\nclass C42929:\n def __init__(self, values): self.values=list(values)\n def mean(self): return sum(self.values)/len(self.values)\n```\nReturn `m72533.py` and `test_m72533.py`.\n\n```python\n# m72533.py\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom typing import Iterable, Tuple\n\n@dataclass(frozen=True)\nclass C42929:\n values: Tuple[float, ...]\n\n @staticmethod\n def create(values: Iterable[float]) -> \"C42929\":\n vals = tuple(float(v) for v in values)\n if not vals: raise ValueError(\"empty\")\n return C42929(vals)\n\n def mean(self) -> float:\n return sum(self.values)/len(self.values)\n```\n\n```python\n# test_m72533.py\nimport pytest\nfrom m72533 import C42929\n\ndef test_mean():\n assert C42929.create([1,2,3]).mean() == 2.0\ndef test_empty():\n with pytest.raises(ValueError):\n C42929.create([])\n```", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Fix the bug and add pytest tests.\n\n```python\ndef f26944(n: int) -> int:\n # sum 1..n inclusive\n if n < 0: raise ValueError\n total = 0\n for k in range(n): # BUG\n total += k\n return total\n```\nReturn unified diffs for `m60992.py` and `test_m60992.py`.\n\n*** Begin Patch\n*** Update File: m60992.py\n@@\n def f26944(n: int) -> int:\n@@\n- for k in range(n): # BUG\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_m60992.py\n+import pytest\n+from m60992 import f26944\n+\n+def test_small():\n+ assert f26944(7) == 28\n+\n+def test_zero():\n+ assert f26944(0) == 0\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ f26944(-1)\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Write a thorough test suite for a Python component used for file synchronization.\nRequirements: cover edge cases, invalid inputs, and behavior invariants.\nConstraints: must handle Windows paths safely, must provide clear error messages.\nDifficulty: expert. Handle empty inputs and malformed records gracefully.\n\nDeliverable: implementation + tests.\n```python\n# tests (pytest-style) for a module providing: normalize(), parse_lines(), compute_stats()\nimport math\nimport pytest\n\ndef test_normalize_idempotent(module_under_test):\n x = \" A\\tB \"\n assert module_under_test.normalize(module_under_test.normalize(x)) == module_under_test.normalize(x)\n\ndef test_parse_lines_rejects_invalid(module_under_test):\n with pytest.raises(ValueError):\n module_under_test.parse_lines([\"\", \"???\", None]) # type: ignore[arg-type]\n\ndef test_compute_stats_basic(module_under_test):\n data = [1, 2, 3, 4]\n s = module_under_test.compute_stats(data)\n assert s.count == 4\n assert s.total == 10\n assert math.isclose(s.mean, 2.5)\n```", "source": "WithinUsAI/python_GOD_coder_100k"} {"text": "Task type: mechanized_spec\nScenario: identity and access\nDomain focus: secure enclaves (defensive)\nPrimary language: lean\nDifficulty: expert+\nScale/SLO: 99.99% availability\nComponent: component_ivelxffu\nConstraints: include deterministic replay plan, explicit contracts and invariants, include backward compatibility and migration plan, include performance model and limits, include failure modes and recovery\nAssume schema changes every sprint; must be backward compatible.\nDeliverable: Provide a mechanized-style spec outline (Lean-like), key definitions, and a proof plan. Include executable reference code skeleton and tests.\n\nOutput: elite engineering answer optimized for correctness, performance, and operability.\n**Contract**\n- Inputs validated at the boundary; explicit error taxonomy.\n- Idempotency for side effects via request_id; deterministic replay.\n- Backward compatibility: additive changes by default; versioned breaking changes.\n**Invariants**\n- Determinism: replay of the same event log yields identical outputs.\n- Liveness: under bounded faults and stable network, progress occurs.\n- Safety: state transitions preserve invariants; no partial commit leaks.\n**Failure modes & recovery**\n- Duplicate requests: de-duplicate by (tenant, request_id) returning cached response.\n- Crash during commit: WAL replay completes or transaction aborts; no torn writes.\n- Network partition: minority cannot commit; clients receive retriable errors.\n**Security posture (defensive)**\n- Threat model: auth/authz, injection, replay/abuse, supply chain.\n- Least privilege; secrets in managed store; audit logs for sensitive ops.\n- Input normalization, parameterized queries, path traversal protections.\n**Verification strategy**\n- Deterministic simulation with fault injection (crash/partition/latency).\n- Fuzzing of parsers/framers/validators with corpus seeds.\n- Property tests against a pure reference model (state machine).\n\n**Snippet**\n```lean\n-- Pseudo-Lean outline\nstructure State where\n ver : Nat\n val : Option ByteArray\n\ndef invariant (s : State) : Prop := True\n\ntheorem step_preserves_invariant :\n ∀ s, invariant s → ∀ s', Step s s' → invariant s' := by\n intro s hs s' hstep\n -- proof plan: case analysis on transition; trivial here\n trivial\n```\n\nExpert+ checks: mechanized invariants (or exhaustive model checking), adversarial fuzzing, and multi-region failure drills.", "source": "WithinUsAI/Omega_Genesis_Coder_100k"} {"text": "Add a clear docstring and type hints to this function:\n\n```python\ndef f88275(s):\n return ''.join(x for x in s if x.isalnum()).lower()\n```\n\n```python\nfrom __future__ import annotations\n\ndef f88275(s: str) -> str:\n \"\"\"Normalize a string: keep only alphanumerics and lowercase the result.\"\"\"\n return \"\".join(ch for ch in s if ch.isalnum()).lower()\n```", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Build an elite-grade solution in the domain of stream processing for scenario: inventory & ordering.\nPrimary language: rust.\nDifficulty: hard.\nConstraints: assume untrusted inputs; validate and sanitize, include tests or verification strategy, avoid undefined behavior and data races.\nComponent: component_luqpwon.\nAssume compliance requires data deletion with proofs.\nTask: Design an application-level protocol (framing, retries, timeouts, backpressure). Provide client/server skeleton and test vectors.\n\nOutput: elite-grade engineering answer with contracts, edge cases, and verification.\nOutput: protocol framing + retry policy + client/server skeleton.\n\n**Framing**\n- Length-prefixed: uint32_be length + payload\n- Payload: msgpack/json; include request_id, type, and optional checksum\n\n**Reliability**\n- Retries only for idempotent ops; exponential backoff + jitter.\n- Timeouts: connect, read, overall; enforce max in-flight to provide backpressure.\n\n**Test vectors**\n- Corrupted length / truncated frame rejected\n- Duplicate request_id returns cached response\n- Slowloris protection by read deadlines\n\n\nHard checks: failure injection tests and performance regressions gated.", "source": "WithinUsAI/Elite_GOD_Coder_100k"} {"text": "Fix the bug and add pytest tests.\n\n```python\ndef f08332(n: int) -> int:\n # sum 1..n inclusive\n if n < 0: raise ValueError\n total = 0\n for k in range(n): # BUG\n total += k\n return total\n```\nReturn unified diffs for `m15476.py` and `test_m15476.py`.\n\n*** Begin Patch\n*** Update File: m15476.py\n@@\n def f08332(n: int) -> int:\n@@\n- for k in range(n): # BUG\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_m15476.py\n+import pytest\n+from m15476 import f08332\n+\n+def test_small():\n+ assert f08332(7) == 28\n+\n+def test_zero():\n+ assert f08332(0) == 0\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ f08332(-1)\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Implement a concurrent Python solution for CLI tooling.\nRequirements: choose appropriate concurrency model, handle cancellation/timeouts, include tests.\nConstraints: must be memory-efficient, must be easy to extend, must include type hints.\nDifficulty: medium. Handle empty inputs and malformed records gracefully.\n\nDeliverable: API + reference implementation + tests.\n```python\nfrom __future__ import annotations\nimport asyncio\nfrom dataclasses import dataclass\nfrom typing import Awaitable, Callable, Iterable, Optional\n\n@dataclass(frozen=True, slots=True)\nclass JobResult:\n ok: bool\n value: Optional[int]\n error: Optional[str]\n\nasync def run_bounded(\n factories: Iterable[Callable[[], Awaitable[int]]],\n *,\n limit: int = 10,\n timeout_s: float = 5.0,\n) -> list[JobResult]:\n if limit <= 0:\n raise ValueError(\"limit must be > 0\")\n sem = asyncio.Semaphore(limit)\n results: list[JobResult] = []\n\n async def one(factory: Callable[[], Awaitable[int]]) -> None:\n async with sem:\n try:\n v = await asyncio.wait_for(factory(), timeout=timeout_s)\n results.append(JobResult(True, v, None))\n except Exception as e:\n results.append(JobResult(False, None, str(e)))\n\n tasks = [asyncio.create_task(one(f)) for f in factories]\n try:\n await asyncio.gather(*tasks)\n finally:\n for t in tasks:\n if not t.done():\n t.cancel()\n return results\n```\n\n```python\nimport asyncio\nimport pytest\nfrom module_under_test import run_bounded\n\n@pytest.mark.asyncio\nasync def test_run_bounded_collects():\n async def work(x: int) -> int:\n await asyncio.sleep(0.01)\n return x\n fs = [(lambda i=i: work(i)) for i in range(30)]\n out = await run_bounded(fs, limit=5, timeout_s=1.0)\n assert len(out) == 30\n assert all(r.ok for r in out)\n```", "source": "WithinUsAI/python_GOD_coder_100k"} {"text": "Task type: mechanized_spec\nScenario: edge sync\nDomain focus: large-scale ML systems\nPrimary language: lean\nDifficulty: hard\nScale/SLO: 10k RPS peak\nComponent: component_pxwfnjyj\nConstraints: assume adversarial inputs; validate everything, include backward compatibility and migration plan, explicit contracts and invariants, include performance model and limits, include verification strategy, include deterministic replay plan, include failure modes and recovery\nAssume strict auditability and replayable history.\nDeliverable: Provide a mechanized-style spec outline (Lean-like), key definitions, and a proof plan. Include executable reference code skeleton and tests.\n\nOutput: contract-first solution with failure modes, security posture, and test/verification strategy.\n**Contract**\n- Inputs validated at the boundary; explicit error taxonomy.\n- Idempotency for side effects via request_id; deterministic replay.\n- Backward compatibility: additive changes by default; versioned breaking changes.\n**Invariants**\n- Isolation: tenant boundary enforced; no cross-tenant reads/writes.\n- Safety: state transitions preserve invariants; no partial commit leaks.\n- Liveness: under bounded faults and stable network, progress occurs.\n**Failure modes & recovery**\n- Crash during commit: WAL replay completes or transaction aborts; no torn writes.\n- Network partition: minority cannot commit; clients receive retriable errors.\n- Data corruption: checksums + scrubber; quarantine and rebuild from replicas/snapshots.\n**Security posture (defensive)**\n- Threat model: auth/authz, injection, replay/abuse, supply chain.\n- Least privilege; secrets in managed store; audit logs for sensitive ops.\n- Input normalization, parameterized queries, path traversal protections.\n**Verification strategy**\n- Property tests against a pure reference model (state machine).\n- Canary + shadow traffic; invariants checked in production via assertions/metrics.\n- Fuzzing of parsers/framers/validators with corpus seeds.\n\n**Snippet**\n```lean\n-- Pseudo-Lean outline\nstructure State where\n ver : Nat\n val : Option ByteArray\n\ndef invariant (s : State) : Prop := True\n\ntheorem step_preserves_invariant :\n ∀ s, invariant s → ∀ s', Step s s' → invariant s' := by\n intro s hs s' hstep\n -- proof plan: case analysis on transition; trivial here\n trivial\n```\n\nHard checks: fault injection tests gate merges; perf thresholds enforced in CI.", "source": "WithinUsAI/Omega_Genesis_Coder_100k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Fix a bug and add tests.\n\nFile: b_rysn13k.py\n```python\ndef w455jyc(n: int) -> int:\n \"\"\"Sum 1..n inclusive.\"\"\"\n if n < 0:\n raise ValueError(\"n must be non-negative\")\n total = 0\n for k in range(n): # BUG: should include n\n total += k\n return total\n```\n\nReturn unified diffs for b_rysn13k.py and test_b_rysn13k.py (pytest).\n\n*** Begin Patch\n*** Update File: b_rysn13k.py\n@@\n def w455jyc(n: int) -> int:\n@@\n total = 0\n- for k in range(n): # BUG: should include n\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_b_rysn13k.py\n+import pytest\n+from b_rysn13k import w455jyc\n+\n+def test_zero():\n+ assert w455jyc(0) == 0\n+\n+def test_one():\n+ assert w455jyc(1) == 1\n+\n+def test_small():\n+ assert w455jyc(7) == 28\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ w455jyc(-1)\n+\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Refactor a Python module used for configuration loading into a clean, extensible design.\nRequirements: outline the new architecture briefly, then provide the refactored code and tests.\nConstraints: must handle Windows paths safely, stdlib-only, must be memory-efficient.\nDifficulty: hard. Include a small CLI example if relevant.\n\nDeliverable: API + reference implementation + tests.\nArchitecture:\n- Public facade class coordinating concerns (parsing, validation, persistence)\n- Small pure functions for testability\n- No global state; dependency injection for filesystem I/O\n\n```python\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom pathlib import Path\nfrom typing import Protocol, Iterable\nimport json\n\nclass Store(Protocol):\n def write_text(self, path: Path, data: str) -> None: ...\n\nclass FSStore:\n def write_text(self, path: Path, data: str) -> None:\n path.parent.mkdir(parents=True, exist_ok=True)\n path.write_text(data, encoding=\"utf-8\")\n\n@dataclass(frozen=True, slots=True)\nclass Item:\n name: str\n qty: int\n\ndef parse_items(lines: Iterable[str]) -> list[Item]:\n out: list[Item] = []\n for i, line in enumerate(lines, 1):\n s = line.strip()\n if not s:\n continue\n obj = json.loads(s)\n if not isinstance(obj, dict):\n raise ValueError(f\"line {i}: expected object\")\n name = obj.get(\"name\")\n qty = obj.get(\"qty\")\n if not isinstance(name, str) or not name:\n raise ValueError(f\"line {i}: name must be str\")\n if not isinstance(qty, int) or qty < 0:\n raise ValueError(f\"line {i}: qty must be non-negative int\")\n out.append(Item(name, qty))\n return out\n\nclass InventoryWriter:\n def __init__(self, base_dir: Path, store: Store | None = None) -> None:\n self._base = base_dir\n self._store: Store = store or FSStore()\n\n def write(self, rel_path: str, items: list[Item]) -> Path:\n dst = (self._base / rel_path).resolve()\n base = self._base.resolve()\n if dst != base and base not in dst.parents:\n raise ValueError(\"unsafe path traversal\")\n payload = json.dumps([item.__dict__ for item in items], ensure_ascii=False)\n self._store.write_text(dst, payload)\n return dst\n```\n\n```python\nimport json\nfrom pathlib import Path\nimport pytest\nfrom module_under_test import InventoryWriter, parse_items\n\ndef test_parse_items_valid():\n lines = [json.dumps({\"name\":\"x\",\"qty\":1})]\n assert parse_items(lines)[0].name == \"x\"\n\ndef test_writer_blocks_traversal(tmp_path: Path):\n w = InventoryWriter(tmp_path)\n with pytest.raises(ValueError):\n w.write(\"../evil.json\", [])\n```", "source": "WithinUsAI/python_GOD_coder_100k"} {"text": "Refactor to typed, mostly-immutable Python and add minimal tests.\n\n```python\nclass C84706:\n def __init__(self, values): self.values=list(values)\n def mean(self): return sum(self.values)/len(self.values)\n```\nReturn `m60362.py` and `test_m60362.py`.\n\n```python\n# m60362.py\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom typing import Iterable, Tuple\n\n@dataclass(frozen=True)\nclass C84706:\n values: Tuple[float, ...]\n\n @staticmethod\n def create(values: Iterable[float]) -> \"C84706\":\n vals = tuple(float(v) for v in values)\n if not vals: raise ValueError(\"empty\")\n return C84706(vals)\n\n def mean(self) -> float:\n return sum(self.values)/len(self.values)\n```\n\n```python\n# test_m60362.py\nimport pytest\nfrom m60362 import C84706\n\ndef test_mean():\n assert C84706.create([1,2,3]).mean() == 2.0\ndef test_empty():\n with pytest.raises(ValueError):\n C84706.create([])\n```", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Fix a bug and add tests.\n\nFile: zttzajk.py\n```python\ndef bdf5mzaww(n: int) -> int:\n \"\"\"Sum 1..n inclusive.\"\"\"\n if n < 0:\n raise ValueError(\"n must be non-negative\")\n total = 0\n for k in range(n): # BUG: should include n\n total += k\n return total\n```\n\nReturn unified diffs for zttzajk.py and test_zttzajk.py (pytest).\n\n*** Begin Patch\n*** Update File: zttzajk.py\n@@\n def bdf5mzaww(n: int) -> int:\n@@\n total = 0\n- for k in range(n): # BUG: should include n\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_zttzajk.py\n+import pytest\n+from zttzajk import bdf5mzaww\n+\n+def test_zero():\n+ assert bdf5mzaww(0) == 0\n+\n+def test_one():\n+ assert bdf5mzaww(1) == 1\n+\n+def test_small():\n+ assert bdf5mzaww(7) == 28\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ bdf5mzaww(-1)\n+\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Add a clear docstring and type hints to this function:\n\n```python\ndef f46527(s):\n return ''.join(x for x in s if x.isalnum()).lower()\n```\n\n```python\nfrom __future__ import annotations\n\ndef f46527(s: str) -> str:\n \"\"\"Normalize a string: keep only alphanumerics and lowercase the result.\"\"\"\n return \"\".join(ch for ch in s if ch.isalnum()).lower()\n```", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Fix the bug and add pytest tests.\n\n```python\ndef f13967(n: int) -> int:\n # sum 1..n inclusive\n if n < 0: raise ValueError\n total = 0\n for k in range(n): # BUG\n total += k\n return total\n```\nReturn unified diffs for `m16281.py` and `test_m16281.py`.\n\n*** Begin Patch\n*** Update File: m16281.py\n@@\n def f13967(n: int) -> int:\n@@\n- for k in range(n): # BUG\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_m16281.py\n+import pytest\n+from m16281 import f13967\n+\n+def test_small():\n+ assert f13967(7) == 28\n+\n+def test_zero():\n+ assert f13967(0) == 0\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ f13967(-1)\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: Language: Rust\nFramework/tooling: Serde\nDomain: notification service\nLogic challenge: transaction boundary bug\nTask type: monorepo_toolchain_recovery\nDifficulty: expert\n\nReturn a rigorous engineering answer:\n- identify the hidden root cause or logical failure\n- present the corrected implementation\n- add tests that prove the fix\n- list verification commands\n- explain why naive fixes are insufficient when relevant\n\nRepository sketch:\nrepo/\n src/main.rs\n src/lib.rs\n src/service.rs\n src/store.rs\n tests/integration.rs\n Cargo.toml\n\nFocus: Focus on staff-level problem solving with multi-file patches, rollout implications, performance and security tradeoffs.\n\nassistant: Diagnosis:\n- Staff-level diagnosis: transaction boundary bug impacts correctness, operability, and future maintenance, so the fix must be minimal where possible but complete where necessary.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```rust\nuse std::collections::HashMap;\n\npub fn normalize_payload(payload: HashMap) -> HashMap {\n payload\n .into_iter()\n .filter(|(_, v)| !v.trim().is_empty())\n .collect()\n}\n```\n\nTests:\n```rust\n#[test]\nfn normalize_payload_filters_empty_values() {\n use std::collections::HashMap;\n let mut payload = HashMap::new();\n payload.insert(\"id\".to_string(), \"7\".to_string());\n payload.insert(\"name\".to_string(), \"\".to_string());\n let out = normalize_payload(payload);\n assert!(out.contains_key(\"id\"));\n assert!(!out.contains_key(\"name\"));\n}\n```\n\nVerification:\n- `cargo test`\n- `cargo clippy -- -D warnings`\n\nEngineering notes:\n- Language: Rust\n- Framework/tooling: Serde\n- Stack context: GitHub Actions, Docker Compose, Kubernetes, Terraform\n- Domain: notification service\n- Task type: monorepo_toolchain_recovery\n- Difficulty: expert\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "Refactor to typed, mostly-immutable Python and add minimal tests.\n\n```python\nclass C60226:\n def __init__(self, values): self.values=list(values)\n def mean(self): return sum(self.values)/len(self.values)\n```\nReturn `m35402.py` and `test_m35402.py`.\n\n```python\n# m35402.py\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom typing import Iterable, Tuple\n\n@dataclass(frozen=True)\nclass C60226:\n values: Tuple[float, ...]\n\n @staticmethod\n def create(values: Iterable[float]) -> \"C60226\":\n vals = tuple(float(v) for v in values)\n if not vals: raise ValueError(\"empty\")\n return C60226(vals)\n\n def mean(self) -> float:\n return sum(self.values)/len(self.values)\n```\n\n```python\n# test_m35402.py\nimport pytest\nfrom m35402 import C60226\n\ndef test_mean():\n assert C60226.create([1,2,3]).mean() == 2.0\ndef test_empty():\n with pytest.raises(ValueError):\n C60226.create([])\n```", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Build an elite-grade solution in the domain of operating systems for scenario: analytics pipeline.\nPrimary language: sql.\nDifficulty: medium.\nConstraints: assume untrusted inputs; validate and sanitize, include tests or verification strategy, document performance characteristics, design for backward compatibility and migrations, provide rollout and rollback guidance.\nComponent: component_ndvgaku.\nAssume schema changes every sprint; must be backward compatible.\nTask: Optimize a hot path with profiling-driven approach; propose micro/meso optimizations, and supply a benchmark harness with acceptance thresholds.\n\nOutput: elite-grade engineering answer with contracts, edge cases, and verification.\nOutput: profiling-first optimization + benchmark harness.\n\n**Plan**\n1. Establish baseline with microbench + representative dataset.\n2. Profile (CPU, allocations, syscalls).\n3. Apply optimizations: reduce allocations, reuse buffers, batch I/O, vectorize parsing where safe.\n4. Validate with regression suite and perf thresholds.\n\n**Benchmark guidance**\n- Use p50/p95 and throughput; pin CPU frequency if possible.\n- Acceptance: p95 improves ≥ X% with no correctness regressions.\n\n\nChecks: boundary validation and deterministic behavior verified.", "source": "WithinUsAI/Elite_GOD_Coder_100k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Refactor to modern typed Python with immutability and tests.\n\nFile: ai40g3mp1.py\n```python\nclass Solnjp96Hl:\n def __init__(self, name, values):\n self.name = name\n self.values = list(values)\n def add(self, v):\n self.values.append(v)\n def mean(self):\n s = 0\n for x in self.values:\n s += x\n return s / len(self.values)\n```\n\nReturn full new ai40g3mp1.py and test_ai40g3mp1.py.\n\n# ai40g3mp1.py\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom typing import Iterable, Tuple\n\n@dataclass(frozen=True)\nclass Solnjp96Hl:\n name: str\n values: Tuple[float, ...]\n\n @staticmethod\n def create(name: str, values: Iterable[float]) -> \"Solnjp96Hl\":\n vals = tuple(float(v) for v in values)\n if not vals:\n raise ValueError(\"values must be non-empty\")\n return Solnjp96Hl(name=name, values=vals)\n\n def add(self, v: float) -> \"Solnjp96Hl\":\n return Solnjp96Hl(name=self.name, values=self.values + (float(v),))\n\n def mean(self) -> float:\n return sum(self.values) / len(self.values)\n\n# test_ai40g3mp1.py\nimport pytest\nfrom ai40g3mp1 import Solnjp96Hl\n\ndef test_mean_and_add():\n c = Solnjp96Hl.create(\"a\", [1, 2, 3])\n assert c.mean() == 2.0\n assert c.add(5).mean() == (1 + 2 + 3 + 5) / 4\n\ndef test_empty_raises():\n with pytest.raises(ValueError):\n Solnjp96Hl.create(\"x\", [])", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Fix a bug and add tests.\n\nFile: g8wmp40z.py\n```python\ndef urgtwd646(n: int) -> int:\n \"\"\"Sum 1..n inclusive.\"\"\"\n if n < 0:\n raise ValueError(\"n must be non-negative\")\n total = 0\n for k in range(n): # BUG: should include n\n total += k\n return total\n```\n\nReturn unified diffs for g8wmp40z.py and test_g8wmp40z.py (pytest).\n\n*** Begin Patch\n*** Update File: g8wmp40z.py\n@@\n def urgtwd646(n: int) -> int:\n@@\n total = 0\n- for k in range(n): # BUG: should include n\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_g8wmp40z.py\n+import pytest\n+from g8wmp40z import urgtwd646\n+\n+def test_zero():\n+ assert urgtwd646(0) == 0\n+\n+def test_one():\n+ assert urgtwd646(1) == 1\n+\n+def test_small():\n+ assert urgtwd646(7) == 28\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ urgtwd646(-1)\n+\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Task type: ml_system_design\nScenario: multi-tenant event ingestion\nDomain focus: static analysis\nPrimary language: go\nDifficulty: hard\nScale/SLO: 50 TB/day ingestion\nComponent: component_aedfopnj\nConstraints: include deterministic replay plan, assume adversarial inputs; validate everything, explicit contracts and invariants, include test vectors and fuzz strategy, include backward compatibility and migration plan, include security threat model (defensive only), avoid data races and undefined behavior\nAssume tight memory budget and cold-start constraints.\nDeliverable: Design end-to-end ML system: data contracts, training, evaluation, registry, serving, monitoring, and rollback.\n\nOutput: rigorous design + invariants + verification plan + implementation sketch.\n**Contract**\n- Inputs validated at the boundary; explicit error taxonomy.\n- Idempotency for side effects via request_id; deterministic replay.\n- Backward compatibility: additive changes by default; versioned breaking changes.\n**Invariants**\n- Determinism: replay of the same event log yields identical outputs.\n- Safety: state transitions preserve invariants; no partial commit leaks.\n- Isolation: tenant boundary enforced; no cross-tenant reads/writes.\n**Failure modes & recovery**\n- Network partition: minority cannot commit; clients receive retriable errors.\n- Data corruption: checksums + scrubber; quarantine and rebuild from replicas/snapshots.\n- Duplicate requests: de-duplicate by (tenant, request_id) returning cached response.\n**Security posture (defensive)**\n- Threat model: auth/authz, injection, replay/abuse, supply chain.\n- Least privilege; secrets in managed store; audit logs for sensitive ops.\n- Input normalization, parameterized queries, path traversal protections.\n**Verification strategy**\n- Property tests against a pure reference model (state machine).\n- Canary + shadow traffic; invariants checked in production via assertions/metrics.\n- Fuzzing of parsers/framers/validators with corpus seeds.\n\n**Snippet**\n```text\nImplementation sketch: factor pure state-machine core; adapters for I/O; add deterministic replay log.\n```\nHard checks: fault injection tests gate merges; perf thresholds enforced in CI.", "source": "WithinUsAI/Omega_Genesis_Coder_100k"} {"text": "Create a small, production-ready Python package for time series.\nRequirements: include module code, CLI entrypoint, logging, and a minimal pyproject.toml.\nConstraints: must include tests, must be streaming-friendly, must avoid global state, stdlib-only.\nDifficulty: easy. Ensure the API is testable via dependency injection.\n\nDeliverable: API + reference implementation + tests.\nPackage layout:\n- mypkg/core.py\n- mypkg/cli.py\n- pyproject.toml\n\n```python\n# mypkg/core.py\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom typing import Iterable\nimport logging\n\nlog = logging.getLogger(__name__)\n\n@dataclass(frozen=True, slots=True)\nclass Result:\n total: int\n count: int\n\ndef aggregate(values: Iterable[int]) -> Result:\n total = 0\n count = 0\n for v in values:\n if not isinstance(v, int):\n raise TypeError(\"values must be ints\")\n total += v\n count += 1\n log.debug(\"aggregate count=%s total=%s\", count, total)\n return Result(total, count)\n```\n\n```python\n# mypkg/cli.py\nfrom __future__ import annotations\nimport argparse\nimport logging\nimport sys\nfrom .core import aggregate\n\ndef main(argv: list[str] | None = None) -> int:\n p = argparse.ArgumentParser(prog=\"mypkg\")\n p.add_argument(\"--log-level\", default=\"WARNING\")\n args = p.parse_args(argv)\n logging.basicConfig(level=getattr(logging, args.log_level.upper(), logging.WARNING))\n data: list[int] = []\n for line in sys.stdin:\n line = line.strip()\n if line:\n data.append(int(line))\n r = aggregate(data)\n print(f\"count={r.count} total={r.total}\")\n return 0\n```\n\n```toml\n# pyproject.toml\n[project]\nname = \"mypkg\"\nversion = \"0.1.0\"\nrequires-python = \">=3.10\"\n\n[project.scripts]\nmypkg = \"mypkg.cli:main\"\n```", "source": "WithinUsAI/python_GOD_coder_100k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Fix a bug and add tests.\n\nFile: dhojtyj7q.py\n```python\ndef itr_8xw4csxt(n: int) -> int:\n \"\"\"Sum 1..n inclusive.\"\"\"\n if n < 0:\n raise ValueError(\"n must be non-negative\")\n total = 0\n for k in range(n): # BUG: should include n\n total += k\n return total\n```\n\nReturn unified diffs for dhojtyj7q.py and test_dhojtyj7q.py (pytest).\n\n*** Begin Patch\n*** Update File: dhojtyj7q.py\n@@\n def itr_8xw4csxt(n: int) -> int:\n@@\n total = 0\n- for k in range(n): # BUG: should include n\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_dhojtyj7q.py\n+import pytest\n+from dhojtyj7q import itr_8xw4csxt\n+\n+def test_zero():\n+ assert itr_8xw4csxt(0) == 0\n+\n+def test_one():\n+ assert itr_8xw4csxt(1) == 1\n+\n+def test_small():\n+ assert itr_8xw4csxt(7) == 28\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ itr_8xw4csxt(-1)\n+\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: Project stack: Spring Boot, PostgreSQL, JUnit, Gradle, Docker, GitHub Actions\nLanguage: JavaScript\nDependency challenge: multi-tenant access leak\nTask type: migration_patch\nDifficulty: medium\n\nFix this as a senior engineer.\nRequired:\n- identify the version or compatibility failure mode\n- produce the corrected config/code/build patch\n- explain rollback-safe migration notes\n- add regression tests or reproducibility checks\n- include concrete verification commands\n\nRepository sketch:\nrepo/\n src/\n api.js\n service.js\n utils.js\n tests/\n api.test.js\n package.json\n\nFocus: Focus on versioning, migrations, lockfiles, runtime compatibility, and secure dependency handling.\n\nassistant: Diagnosis:\n- Root cause: the issue around multi-tenant access leak is a dependency, migration, or runtime-compatibility mismatch that needs a rollback-safe patch.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```javascript\ntype Payload = Record;\n\nexport function normalizePayload(payload: Payload): Payload {\n if (!payload || typeof payload !== \"object\" || Array.isArray(payload)) {\n throw new TypeError(\"payload must be a plain object\");\n }\n return Object.fromEntries(\n Object.entries(payload)\n .filter(([, value]) => value !== null && value !== undefined)\n .map(([key, value]) => [String(key).trim(), value])\n );\n}\n\nexport function handleMultiTenantAccessLeak(payload: Payload) {\n const clean = normalizePayload(payload);\n if (!(\"id\" in clean)) {\n return { ok: false, data: {}, error: \"missing id\" };\n }\n return { ok: true, data: clean, error: null };\n}\n```\n\nTests:\n```javascript\nimport { describe, it, expect } from \"vitest\";\nimport { handleMultiTenantAccessLeak } from \"../src/service\";\n\ndescribe(\"handler\", () => {\n it(\"accepts valid input\", () => {\n expect(handleMultiTenantAccessLeak({ id: 7, name: \"ok\", unused: null })).toEqual({\n ok: true,\n data: { id: 7, name: \"ok\" },\n error: null\n });\n });\n\n it(\"rejects missing id\", () => {\n expect(handleMultiTenantAccessLeak({ name: \"x\" }).error).toMatch(/missing id/);\n });\n});\n```\n\nVerification:\n- `npm test`\n- `npm run lint`\n\nEngineering notes:\n- Language: JavaScript\n- Framework/tooling: Express\n- Stack context: Spring Boot, PostgreSQL, JUnit, Gradle, Docker, GitHub Actions\n- Domain: model serving gateway\n- Task type: migration_patch\n- Difficulty: medium\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "Build an elite-grade solution in the domain of operating systems for scenario: edge sync.\nPrimary language: go.\nDifficulty: medium.\nConstraints: assume untrusted inputs; validate and sanitize, avoid undefined behavior and data races, make the interface contract explicit, include invariants and failure modes, document performance characteristics.\nComponent: component_fhetroz.\nAssume crash-only design; recovery must be deterministic.\nTask: Define a small DSL, implement tokenizer/parser, IR, and a codegen or interpreter. Include tests and complexity notes.\n\nOutput: production blueprint plus correctness arguments and test strategy.\nOutput: DSL + parser + IR + interpreter/codegen + tests.\n\n**DSL**\n- Expressions: integers, identifiers, `+ - * /`, let-binding: `let x = expr in expr`\n- Example: `let x = 2+3 in x*10`\n\n**Pipeline**\n1. Tokenize\n2. Parse into AST\n3. Lower into IR (stack ops) or interpret AST directly\n\n**Reference (Rust-style outline)**\n- `enum Expr { Int(i64), Var(String), Bin(Op, Box, Box), Let(String, Box, Box) }`\n- Parser: Pratt or recursive descent.\n\n**Tests**\n- Golden tests for parse trees.\n- Property: pretty-print(parse(x)) round-trips for a corpus.\n- Eval tests for precedence and scoping.\n\n\nChecks: boundary validation and deterministic behavior verified.", "source": "WithinUsAI/Elite_GOD_Coder_100k"} {"text": "Build an elite-grade solution in the domain of compilers for scenario: payment processing.\nPrimary language: bash.\nDifficulty: hard.\nConstraints: include invariants and failure modes, assume untrusted inputs; validate and sanitize, provide rollout and rollback guidance.\nComponent: component_snzlbbt.\nAssume 50k RPS and p99 < 250ms.\nTask: Provide SLOs, alerting, dashboards, runbooks, and incident playbook. Include chaos testing and safe rollout strategy.\n\nOutput: elite-grade engineering answer with contracts, edge cases, and verification.\nOutput: SLOs + alerts + runbooks + chaos strategy.\n\n**SLOs**\n- Availability: 99.9% monthly\n- Latency: p95 < 200ms, p99 < 400ms\n- Error rate: < 0.1%\n\n**Alerts**\n- Burn-rate alerts for SLOs (fast/slow windows)\n- Saturation: CPU, memory, queue depth, DB connections\n- Dependency health: cache hit rate drop, downstream timeouts\n\n**Runbooks**\n- Triage: identify blast radius, feature-flag rollback, capacity mitigation\n- Post-incident: timeline, contributing factors, action items\n\n**Chaos**\n- Inject latency, partial outages, and restarts in staging; verify steady-state SLOs.\n\n\nHard checks: failure injection tests and performance regressions gated.", "source": "WithinUsAI/Elite_GOD_Coder_100k"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: Language: Python\nFramework/tooling: Celery\nDomain: artifact registry\nLogic challenge: partial checkpoint corruption\nTask type: transaction_integrity_fix\nDifficulty: hard\n\nReturn a rigorous engineering answer:\n- identify the hidden root cause or logical failure\n- present the corrected implementation\n- add tests that prove the fix\n- list verification commands\n- explain why naive fixes are insufficient when relevant\n\nRepository sketch:\nrepo/\n app/\n api.py\n service.py\n models.py\n tests/\n test_api.py\n pyproject.toml\n\nFocus: Focus on ambiguity, misleading symptoms, hidden root causes, and high-stakes debugging.\n\nassistant: Diagnosis:\n- Hidden root cause: partial checkpoint corruption presents misleading symptoms, so the patch must target the actual logic boundary rather than the first visible failure.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```python\nfrom __future__ import annotations\n\nfrom dataclasses import dataclass\nfrom typing import Any\n\n@dataclass\nclass ServiceResult:\n ok: bool\n data: dict[str, Any]\n error: str | None = None\n\ndef normalize_payload(payload: dict[str, Any]) -> dict[str, Any]:\n if not isinstance(payload, dict):\n raise TypeError(\"payload must be a dict\")\n clean: dict[str, Any] = {}\n for key, value in payload.items():\n if value is None:\n continue\n clean[str(key).strip()] = value\n return clean\n\ndef handle_partial_checkpoint_corruption(payload: dict[str, Any]) -> ServiceResult:\n clean = normalize_payload(payload)\n if \"id\" not in clean:\n return ServiceResult(ok=False, data={}, error=\"missing id\")\n return ServiceResult(ok=True, data=clean)\n```\n\nTests:\n```python\nimport pytest\nfrom app.service import handle_jwt_refresh_token_rotation as handler\n\ndef test_handler_accepts_valid_payload():\n result = handler({\"id\": 7, \"name\": \"ok\", \"unused\": None})\n assert result.ok is True\n assert result.data == {\"id\": 7, \"name\": \"ok\"}\n\ndef test_handler_rejects_missing_id():\n result = handler({\"name\": \"x\"})\n assert result.ok is False\n assert result.error == \"missing id\"\n```\n\nVerification:\n- `pytest -q`\n- `ruff check .`\n- `python -m compileall .`\n\nEngineering notes:\n- Language: Python\n- Framework/tooling: Celery\n- Stack context: FastAPI, PostgreSQL, Redis, Celery, pytest, Docker\n- Domain: artifact registry\n- Task type: transaction_integrity_fix\n- Difficulty: hard\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "Refactor a Python module used for file synchronization into a clean, extensible design.\nRequirements: outline the new architecture briefly, then provide the refactored code and tests.\nConstraints: must avoid global state, must provide clear error messages, stdlib-only, must handle Windows paths safely.\nDifficulty: expert. Guarantee deterministic output ordering.\n\nDeliverable: production-ready reference solution.\nArchitecture:\n- Public facade class coordinating concerns (parsing, validation, persistence)\n- Small pure functions for testability\n- No global state; dependency injection for filesystem I/O\n\n```python\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom pathlib import Path\nfrom typing import Protocol, Iterable\nimport json\n\nclass Store(Protocol):\n def write_text(self, path: Path, data: str) -> None: ...\n\nclass FSStore:\n def write_text(self, path: Path, data: str) -> None:\n path.parent.mkdir(parents=True, exist_ok=True)\n path.write_text(data, encoding=\"utf-8\")\n\n@dataclass(frozen=True, slots=True)\nclass Item:\n name: str\n qty: int\n\ndef parse_items(lines: Iterable[str]) -> list[Item]:\n out: list[Item] = []\n for i, line in enumerate(lines, 1):\n s = line.strip()\n if not s:\n continue\n obj = json.loads(s)\n if not isinstance(obj, dict):\n raise ValueError(f\"line {i}: expected object\")\n name = obj.get(\"name\")\n qty = obj.get(\"qty\")\n if not isinstance(name, str) or not name:\n raise ValueError(f\"line {i}: name must be str\")\n if not isinstance(qty, int) or qty < 0:\n raise ValueError(f\"line {i}: qty must be non-negative int\")\n out.append(Item(name, qty))\n return out\n\nclass InventoryWriter:\n def __init__(self, base_dir: Path, store: Store | None = None) -> None:\n self._base = base_dir\n self._store: Store = store or FSStore()\n\n def write(self, rel_path: str, items: list[Item]) -> Path:\n dst = (self._base / rel_path).resolve()\n base = self._base.resolve()\n if dst != base and base not in dst.parents:\n raise ValueError(\"unsafe path traversal\")\n payload = json.dumps([item.__dict__ for item in items], ensure_ascii=False)\n self._store.write_text(dst, payload)\n return dst\n```\n\n```python\nimport json\nfrom pathlib import Path\nimport pytest\nfrom module_under_test import InventoryWriter, parse_items\n\ndef test_parse_items_valid():\n lines = [json.dumps({\"name\":\"x\",\"qty\":1})]\n assert parse_items(lines)[0].name == \"x\"\n\ndef test_writer_blocks_traversal(tmp_path: Path):\n w = InventoryWriter(tmp_path)\n with pytest.raises(ValueError):\n w.write(\"../evil.json\", [])\n```", "source": "WithinUsAI/python_GOD_coder_100k"} {"text": "Refactor to typed, mostly-immutable Python and add minimal tests.\n\n```python\nclass C15564:\n def __init__(self, values): self.values=list(values)\n def mean(self): return sum(self.values)/len(self.values)\n```\nReturn `m70428.py` and `test_m70428.py`.\n\n```python\n# m70428.py\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom typing import Iterable, Tuple\n\n@dataclass(frozen=True)\nclass C15564:\n values: Tuple[float, ...]\n\n @staticmethod\n def create(values: Iterable[float]) -> \"C15564\":\n vals = tuple(float(v) for v in values)\n if not vals: raise ValueError(\"empty\")\n return C15564(vals)\n\n def mean(self) -> float:\n return sum(self.values)/len(self.values)\n```\n\n```python\n# test_m70428.py\nimport pytest\nfrom m70428 import C15564\n\ndef test_mean():\n assert C15564.create([1,2,3]).mean() == 2.0\ndef test_empty():\n with pytest.raises(ValueError):\n C15564.create([])\n```", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: Project stack: FastAPI, PostgreSQL, Redis, Celery, pytest, Docker\nLanguage: C#\nDependency challenge: dead-letter queue replay\nTask type: build_reproducibility_fix\nDifficulty: medium\n\nFix this as a senior engineer.\nRequired:\n- identify the version or compatibility failure mode\n- produce the corrected config/code/build patch\n- explain rollback-safe migration notes\n- add regression tests or reproducibility checks\n- include concrete verification commands\n\nRepository sketch:\nrepo/\n src/App/Program.cs\n src/App/Service.cs\n tests/App.Tests/ServiceTests.cs\n App.sln\n\nFocus: Focus on versioning, migrations, lockfiles, runtime compatibility, and secure dependency handling.\n\nassistant: Diagnosis:\n- Root cause: the issue around dead-letter queue replay is a dependency, migration, or runtime-compatibility mismatch that needs a rollback-safe patch.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```csharp\nusing System;\nusing System.Collections.Generic;\n\npublic static class RequestHandler\n{\n public static Dictionary HandleRequest(Dictionary payload)\n {\n var clean = new Dictionary();\n foreach (var entry in payload)\n {\n if (entry.Value != null)\n clean[entry.Key.Trim()] = entry.Value;\n }\n if (!clean.ContainsKey(\"id\"))\n throw new ArgumentException(\"missing id\");\n return new Dictionary\n {\n [\"ok\"] = true,\n [\"data\"] = clean\n };\n }\n}\n```\n\nTests:\n```csharp\nusing System;\nusing System.Collections.Generic;\nusing Xunit;\n\npublic class RequestHandlerTests\n{\n [Fact]\n public void RequiresId()\n {\n Assert.Throws(() => RequestHandler.HandleRequest(new Dictionary { [\"name\"] = \"x\" }));\n }\n}\n```\n\nVerification:\n- `dotnet test`\n- `dotnet build`\n\nEngineering notes:\n- Language: C#\n- Framework/tooling: xUnit\n- Stack context: FastAPI, PostgreSQL, Redis, Celery, pytest, Docker\n- Domain: developer platform\n- Task type: build_reproducibility_fix\n- Difficulty: medium\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Refactor to modern typed Python with immutability and tests.\n\nFile: x51a5vcxx6.py\n```python\nclass Qcffi6Buk:\n def __init__(self, name, values):\n self.name = name\n self.values = list(values)\n def add(self, v):\n self.values.append(v)\n def mean(self):\n s = 0\n for x in self.values:\n s += x\n return s / len(self.values)\n```\n\nReturn full new x51a5vcxx6.py and test_x51a5vcxx6.py.\n\n# x51a5vcxx6.py\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom typing import Iterable, Tuple\n\n@dataclass(frozen=True)\nclass Qcffi6Buk:\n name: str\n values: Tuple[float, ...]\n\n @staticmethod\n def create(name: str, values: Iterable[float]) -> \"Qcffi6Buk\":\n vals = tuple(float(v) for v in values)\n if not vals:\n raise ValueError(\"values must be non-empty\")\n return Qcffi6Buk(name=name, values=vals)\n\n def add(self, v: float) -> \"Qcffi6Buk\":\n return Qcffi6Buk(name=self.name, values=self.values + (float(v),))\n\n def mean(self) -> float:\n return sum(self.values) / len(self.values)\n\n# test_x51a5vcxx6.py\nimport pytest\nfrom x51a5vcxx6 import Qcffi6Buk\n\ndef test_mean_and_add():\n c = Qcffi6Buk.create(\"a\", [1, 2, 3])\n assert c.mean() == 2.0\n assert c.add(5).mean() == (1 + 2 + 3 + 5) / 4\n\ndef test_empty_raises():\n with pytest.raises(ValueError):\n Qcffi6Buk.create(\"x\", [])", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Refactor to typed, mostly-immutable Python and add minimal tests.\n\n```python\nclass C87662:\n def __init__(self, values): self.values=list(values)\n def mean(self): return sum(self.values)/len(self.values)\n```\nReturn `m75974.py` and `test_m75974.py`.\n\n```python\n# m75974.py\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom typing import Iterable, Tuple\n\n@dataclass(frozen=True)\nclass C87662:\n values: Tuple[float, ...]\n\n @staticmethod\n def create(values: Iterable[float]) -> \"C87662\":\n vals = tuple(float(v) for v in values)\n if not vals: raise ValueError(\"empty\")\n return C87662(vals)\n\n def mean(self) -> float:\n return sum(self.values)/len(self.values)\n```\n\n```python\n# test_m75974.py\nimport pytest\nfrom m75974 import C87662\n\ndef test_mean():\n assert C87662.create([1,2,3]).mean() == 2.0\ndef test_empty():\n with pytest.raises(ValueError):\n C87662.create([])\n```", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Produce an offline-first self-evolving code assistant architecture named `zyza4jm6z9p`.\nMust include: module layout, patch-safety policy, evaluation gates (tests/lint/types), versioned memory index.\n\nArchitecture: `zyza4jm6z9p` (offline-first, self-evolving)\n\nModules\n- core/loop.py: evolve → validate → accept/reject (bounded iterations)\n- patching/: diff builder, safe apply, atomic writes, rollback points\n- policy/: allowlist paths, deny globs (.git/, __pycache__/, binaries), patch size caps\n- signals/: parse pytest/ruff/mypy into normalized findings\n- memory/index.jsonl: append-only snapshots (hashes, metrics, rationale)\n\nSafety gates\n- refuse path traversal/symlink escapes; never edit binaries\n- accept only if tests/lint/types stay green or improve", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Task type: sre_incident_sim\nScenario: payment ledger\nDomain focus: kernel primitives\nPrimary language: typescript\nDifficulty: hard\nScale/SLO: 1M msgs/min\nComponent: component_zmoebujo\nConstraints: include test vectors and fuzz strategy, include failure modes and recovery, include performance model and limits, explicit contracts and invariants, include deterministic replay plan, include verification strategy, include security threat model (defensive only)\nAssume tight memory budget and cold-start constraints.\nDeliverable: Provide incident simulation: SLOs, alerts, runbooks, and game-day plan; include postmortem template.\n\nOutput: contract-first solution with failure modes, security posture, and test/verification strategy.\n**Contract**\n- Inputs validated at the boundary; explicit error taxonomy.\n- Idempotency for side effects via request_id; deterministic replay.\n- Backward compatibility: additive changes by default; versioned breaking changes.\n**Invariants**\n- Safety: state transitions preserve invariants; no partial commit leaks.\n- Determinism: replay of the same event log yields identical outputs.\n- Isolation: tenant boundary enforced; no cross-tenant reads/writes.\n**Failure modes & recovery**\n- Network partition: minority cannot commit; clients receive retriable errors.\n- Data corruption: checksums + scrubber; quarantine and rebuild from replicas/snapshots.\n- Crash during commit: WAL replay completes or transaction aborts; no torn writes.\n**Security posture (defensive)**\n- Threat model: auth/authz, injection, replay/abuse, supply chain.\n- Least privilege; secrets in managed store; audit logs for sensitive ops.\n- Input normalization, parameterized queries, path traversal protections.\n**Verification strategy**\n- Property tests against a pure reference model (state machine).\n- Deterministic simulation with fault injection (crash/partition/latency).\n- Fuzzing of parsers/framers/validators with corpus seeds.\n\n**Snippet**\n```text\nImplementation sketch: factor pure state-machine core; adapters for I/O; add deterministic replay log.\n```\nHard checks: fault injection tests gate merges; perf thresholds enforced in CI.", "source": "WithinUsAI/Omega_Genesis_Coder_100k"} {"text": "Build an elite-grade solution in the domain of security engineering (defensive) for scenario: feature flagging.\nPrimary language: go.\nDifficulty: hard.\nConstraints: make the interface contract explicit, document performance characteristics, provide rollout and rollback guidance, include invariants and failure modes, design for backward compatibility and migrations.\nComponent: component_xpltjms.\nAssume partial network partitions occur weekly.\nTask: Implement a concurrency primitive or subsystem (lock-free queue, thread pool, async runtime component). Explain memory ordering and correctness arguments; include stress tests.\n\nOutput: production blueprint plus correctness arguments and test strategy.\nOutput: correctness-focused concurrency primitive + stress tests.\n\n**Primitive**\n- Bounded MPMC queue with backpressure (blocking push/pop) OR lock-free SPSC ring buffer.\n\n**Correctness notes**\n- For lock-free: use acquire/release semantics on head/tail indices.\n- Avoid ABA by monotonic counters; ring index = counter % capacity.\n\n**Stress tests**\n- Multi-thread producers/consumers; assert item multiset preserved.\n- Use time-bounded randomized schedules; detect deadlocks.\n\n\nHard checks: failure injection tests and performance regressions gated.", "source": "WithinUsAI/Elite_GOD_Coder_100k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Produce an offline-first self-evolving code assistant architecture named `nr8bkfpqz`.\nMust include: module layout, patch-safety policy, evaluation gates (tests/lint/types), versioned memory index.\n\nArchitecture: `nr8bkfpqz` (offline-first, self-evolving)\n\nModules\n- core/loop.py: evolve → validate → accept/reject (bounded iterations)\n- patching/: diff builder, safe apply, atomic writes, rollback points\n- policy/: allowlist paths, deny globs (.git/, __pycache__/, binaries), patch size caps\n- signals/: parse pytest/ruff/mypy into normalized findings\n- memory/index.jsonl: append-only snapshots (hashes, metrics, rationale)\n\nSafety gates\n- refuse path traversal/symlink escapes; never edit binaries\n- accept only if tests/lint/types stay green or improve", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Optimize while preserving behavior.\n\nFile: x2_mp_33m.py\n```python\ndef g0kvcqr0yo(xs):\n out = []\n for x in xs:\n if x not in out:\n out.append(x)\n return out\n```\n\nRequirements: preserve first-seen order; O(n) average; add types + docstring.\n\n# x2_mp_33m.py\nfrom __future__ import annotations\nfrom typing import Iterable, List, Set, TypeVar\n\nT = TypeVar(\"T\")\n\ndef g0kvcqr0yo(xs: Iterable[T]) -> List[T]:\n \"\"\"Return unique items preserving first-seen order.\"\"\"\n seen: Set[T] = set()\n out: List[T] = []\n for x in xs:\n if x in seen:\n continue\n seen.add(x)\n out.append(x)\n return out", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Fix the bug and add pytest tests.\n\n```python\ndef f12401(n: int) -> int:\n # sum 1..n inclusive\n if n < 0: raise ValueError\n total = 0\n for k in range(n): # BUG\n total += k\n return total\n```\nReturn unified diffs for `m30343.py` and `test_m30343.py`.\n\n*** Begin Patch\n*** Update File: m30343.py\n@@\n def f12401(n: int) -> int:\n@@\n- for k in range(n): # BUG\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_m30343.py\n+import pytest\n+from m30343 import f12401\n+\n+def test_small():\n+ assert f12401(7) == 28\n+\n+def test_zero():\n+ assert f12401(0) == 0\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ f12401(-1)\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Build an elite-grade solution in the domain of high-performance services for scenario: chat messaging.\nPrimary language: rust.\nDifficulty: hard.\nConstraints: provide rollout and rollback guidance, avoid undefined behavior and data races, assume untrusted inputs; validate and sanitize, make the interface contract explicit.\nComponent: component_mrmsqpt.\nAssume strict auditability and replayable history.\nTask: Write a precise interface contract, list invariants, and provide a lightweight formal/spec-style description (pseudo-TLA+/state machine) plus reference implementation skeleton and tests.\n\nOutput: rigorous solution with invariants, failure modes, and performance notes.\nOutput: contract + invariants + spec + reference skeleton.\n\n**Interface contract**\n- Commands: `Put(key, value, expected_version?)`, `Get(key)`, `Delete(key, expected_version?)`\n- Responses: `Ok(version, value?)`, `NotFound`, `Conflict(current_version)`, `InvalidInput`\n- Idempotency: client supplies `request_id`; server must de-duplicate per (tenant_id, request_id).\n\n**Invariants**\n1. Monotonic version per key (strictly increases on successful writes).\n2. Reads return latest committed value for a given consistency level.\n3. Exactly-once effect for a given `request_id` (at-most-once execution + replay response).\n4. Tenant isolation: keys are scoped by tenant_id.\n\n**State machine (pseudo)**\nState:\n- store: map[(tenant,key)] -> (version:int, value:bytes|tombstone)\n- seen: map[(tenant,request_id)] -> response\nTransition Put:\n- if request_id in seen: return seen[...]\n- validate input; if expected_version set and != current version -> Conflict\n- version' = version + 1; store[...] := (version', value); seen[...] := Ok(version', value)\n\n**Reference skeleton (Python)**\n```python\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom typing import Dict, Optional, Tuple\n\nclass Conflict(Exception): pass\nclass InvalidInput(ValueError): pass\n\n@dataclass(frozen=True, slots=True)\nclass Value:\n version: int\n data: Optional[bytes] # None == tombstone\n\n@dataclass(frozen=True, slots=True)\nclass Reply:\n kind: str\n version: Optional[int] = None\n data: Optional[bytes] = None\n\nclass KV:\n def __init__(self) -> None:\n self._store: Dict[Tuple[str,str], Value] = {}\n self._seen: Dict[Tuple[str,str], Reply] = {}\n\n def put(self, tenant: str, request_id: str, key: str, data: bytes, expected_version: Optional[int]=None) -> Reply:\n if not tenant or not request_id or not key:\n raise InvalidInput(\"tenant/request_id/key required\")\n de = self._seen.get((tenant, request_id))\n if de: \n return de\n cur = self._store.get((tenant, key), Value(0, None))\n if expected_version is not None and expected_version != cur.version:\n r = Reply(\"conflict\", version=cur.version)\n self._seen[(tenant, request_id)] = r\n return r\n nxt = Value(cur.version + 1, data)\n self._store[(tenant, key)] = nxt\n r = Reply(\"ok\", version=nxt.version)\n self._seen[(tenant, request_id)] = r\n return r\n```\n\n**Tests**\n- Determinism: same request_id → same reply.\n- Conflict detection and version monotonicity.\n\n\nHard checks: failure injection tests and performance regressions gated.", "source": "WithinUsAI/Elite_GOD_Coder_100k"} {"text": "Task type: perf_microarchitecture\nScenario: graph query service\nDomain focus: secure enclaves (defensive)\nPrimary language: python\nDifficulty: hard\nScale/SLO: p99 < 50ms\nComponent: component_rewlgoqa\nConstraints: include performance model and limits, include verification strategy, explicit contracts and invariants, include test vectors and fuzz strategy, include backward compatibility and migration plan, avoid data races and undefined behavior, include deterministic replay plan\nAssume schema changes every sprint; must be backward compatible.\nDeliverable: Provide performance engineering plan: profiling, hot-path redesign, cache behavior assumptions, and microbench harness.\n\nOutput: elite engineering answer optimized for correctness, performance, and operability.\n**Contract**\n- Inputs validated at the boundary; explicit error taxonomy.\n- Idempotency for side effects via request_id; deterministic replay.\n- Backward compatibility: additive changes by default; versioned breaking changes.\n**Invariants**\n- Determinism: replay of the same event log yields identical outputs.\n- Liveness: under bounded faults and stable network, progress occurs.\n- Safety: state transitions preserve invariants; no partial commit leaks.\n**Failure modes & recovery**\n- Data corruption: checksums + scrubber; quarantine and rebuild from replicas/snapshots.\n- Network partition: minority cannot commit; clients receive retriable errors.\n- Duplicate requests: de-duplicate by (tenant, request_id) returning cached response.\n**Security posture (defensive)**\n- Threat model: auth/authz, injection, replay/abuse, supply chain.\n- Least privilege; secrets in managed store; audit logs for sensitive ops.\n- Input normalization, parameterized queries, path traversal protections.\n**Verification strategy**\n- Property tests against a pure reference model (state machine).\n- Fuzzing of parsers/framers/validators with corpus seeds.\n- Canary + shadow traffic; invariants checked in production via assertions/metrics.\n\n**Snippet**\n```text\nImplementation sketch: factor pure state-machine core; adapters for I/O; add deterministic replay log.\n```\nHard checks: fault injection tests gate merges; perf thresholds enforced in CI.", "source": "WithinUsAI/Omega_Genesis_Coder_100k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Optimize while preserving behavior.\n\nFile: nj_rf02x.py\n```python\ndef wtxxdyttll(xs):\n out = []\n for x in xs:\n if x not in out:\n out.append(x)\n return out\n```\n\nRequirements: preserve first-seen order; O(n) average; add types + docstring.\n\n# nj_rf02x.py\nfrom __future__ import annotations\nfrom typing import Iterable, List, Set, TypeVar\n\nT = TypeVar(\"T\")\n\ndef wtxxdyttll(xs: Iterable[T]) -> List[T]:\n \"\"\"Return unique items preserving first-seen order.\"\"\"\n seen: Set[T] = set()\n out: List[T] = []\n for x in xs:\n if x in seen:\n continue\n seen.add(x)\n out.append(x)\n return out", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Optimize while preserving behavior and order.\n\n```python\ndef f15726(xs):\n out=[]\n for x in xs:\n if x not in out: out.append(x)\n return out\n```\nReturn `m30818.py` with types and O(n) average.\n\n```python\n# m30818.py\nfrom __future__ import annotations\nfrom typing import Iterable, List, Set, TypeVar\nT=TypeVar(\"T\")\n\ndef f15726(xs: Iterable[T]) -> List[T]:\n \"\"\"Unique items preserving first-seen order.\"\"\"\n seen: Set[T]=set()\n out: List[T]=[]\n for x in xs:\n if x in seen: continue\n seen.add(x); out.append(x)\n return out\n```", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Fix a bug and add tests.\n\nFile: c_6mr3.py\n```python\ndef dyujybl6xq_0(n: int) -> int:\n \"\"\"Sum 1..n inclusive.\"\"\"\n if n < 0:\n raise ValueError(\"n must be non-negative\")\n total = 0\n for k in range(n): # BUG: should include n\n total += k\n return total\n```\n\nReturn unified diffs for c_6mr3.py and test_c_6mr3.py (pytest).\n\n*** Begin Patch\n*** Update File: c_6mr3.py\n@@\n def dyujybl6xq_0(n: int) -> int:\n@@\n total = 0\n- for k in range(n): # BUG: should include n\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_c_6mr3.py\n+import pytest\n+from c_6mr3 import dyujybl6xq_0\n+\n+def test_zero():\n+ assert dyujybl6xq_0(0) == 0\n+\n+def test_one():\n+ assert dyujybl6xq_0(1) == 1\n+\n+def test_small():\n+ assert dyujybl6xq_0(7) == 28\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ dyujybl6xq_0(-1)\n+\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Build an elite-grade solution in the domain of stream processing for scenario: inventory & ordering.\nPrimary language: python.\nDifficulty: hard.\nConstraints: document performance characteristics, provide rollout and rollback guidance, avoid undefined behavior and data races, include invariants and failure modes, make the interface contract explicit.\nComponent: component_viynlbd.\nAssume cold-start and memory limits are tight.\nTask: Implement a concurrency primitive or subsystem (lock-free queue, thread pool, async runtime component). Explain memory ordering and correctness arguments; include stress tests.\n\nOutput: elite-grade engineering answer with contracts, edge cases, and verification.\nOutput: correctness-focused concurrency primitive + stress tests.\n\n**Primitive**\n- Bounded MPMC queue with backpressure (blocking push/pop) OR lock-free SPSC ring buffer.\n\n**Correctness notes**\n- For lock-free: use acquire/release semantics on head/tail indices.\n- Avoid ABA by monotonic counters; ring index = counter % capacity.\n\n**Stress tests**\n- Multi-thread producers/consumers; assert item multiset preserved.\n- Use time-bounded randomized schedules; detect deadlocks.\n\n\nHard checks: failure injection tests and performance regressions gated.", "source": "WithinUsAI/Elite_GOD_Coder_100k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Fix a bug and add tests.\n\nFile: r2p_jm32wmr.py\n```python\ndef w31z1i5n3oj6(n: int) -> int:\n \"\"\"Sum 1..n inclusive.\"\"\"\n if n < 0:\n raise ValueError(\"n must be non-negative\")\n total = 0\n for k in range(n): # BUG: should include n\n total += k\n return total\n```\n\nReturn unified diffs for r2p_jm32wmr.py and test_r2p_jm32wmr.py (pytest).\n\n*** Begin Patch\n*** Update File: r2p_jm32wmr.py\n@@\n def w31z1i5n3oj6(n: int) -> int:\n@@\n total = 0\n- for k in range(n): # BUG: should include n\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_r2p_jm32wmr.py\n+import pytest\n+from r2p_jm32wmr import w31z1i5n3oj6\n+\n+def test_zero():\n+ assert w31z1i5n3oj6(0) == 0\n+\n+def test_one():\n+ assert w31z1i5n3oj6(1) == 1\n+\n+def test_small():\n+ assert w31z1i5n3oj6(7) == 28\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ w31z1i5n3oj6(-1)\n+\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Write pytest tests for `f21735`.\n\n```python\ndef f21735(a: int, b: int) -> int:\n return a*a + b*b\n```\nInclude edge cases and a property-style check.\n\n```python\nimport random\nfrom m03105 import f21735\n\ndef test_known():\n assert f21735(3,4) == 25\n\ndef test_zero():\n assert f21735(0,0) == 0\n\ndef test_property_nonnegative():\n for _ in range(200):\n a=random.randint(-50,50)\n b=random.randint(-50,50)\n assert f21735(a,b) >= 0\n```", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Create a comprehensive test plan and automated tests for idempotent payments in a content moderation product.\nTarget platform: backend (Go).\nRequirements: unit/integration tests, edge cases, load tests strategy, and CI gates.\nConstraints: must include type hints where applicable, must include clear error handling, must be production-ready, must include tests.\nDifficulty: easy. Assume PII must be protected.\n\nOutput: production-oriented blueprint with code where appropriate.\nDeliverable: test plan + automation guidance.\n\n**Unit tests**\n- Validation: malformed payloads rejected with correct codes.\n- AuthZ: tenant boundary enforced.\n- Idempotency: replay returns same response; conflicting reuse yields 409.\n\n**Integration tests**\n- DB transaction behavior; unique constraints.\n- Cache behavior: correctness under concurrent requests.\n\n**Load tests**\n- 10k RPS target: measure p95 latency, error rate, saturation.\n\n**CI gates**\n- Lint + typecheck + unit tests required.\n- Coverage threshold for critical modules.\n- Block merge on flaky test detection.\n\n\nChecks: input validation, tests, and safe defaults included.", "source": "WithinUsAI/GOD_Coder_100k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Optimize while preserving behavior.\n\nFile: jcfxujt2anwi.py\n```python\ndef b5xpyy_(xs):\n out = []\n for x in xs:\n if x not in out:\n out.append(x)\n return out\n```\n\nRequirements: preserve first-seen order; O(n) average; add types + docstring.\n\n# jcfxujt2anwi.py\nfrom __future__ import annotations\nfrom typing import Iterable, List, Set, TypeVar\n\nT = TypeVar(\"T\")\n\ndef b5xpyy_(xs: Iterable[T]) -> List[T]:\n \"\"\"Return unique items preserving first-seen order.\"\"\"\n seen: Set[T] = set()\n out: List[T] = []\n for x in xs:\n if x in seen:\n continue\n seen.add(x)\n out.append(x)\n return out", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Task type: storage_engine\nScenario: real-time notification hub\nDomain focus: distributed storage\nPrimary language: bash\nDifficulty: expert+\nScale/SLO: 1M msgs/min\nComponent: component_zlxpbgid\nConstraints: avoid data races and undefined behavior, explicit contracts and invariants, assume adversarial inputs; validate everything, include verification strategy, include backward compatibility and migration plan\nAssume weekly network partitions.\nDeliverable: Design a storage engine subsystem (WAL, snapshots, compaction). Include crash recovery invariants and a benchmark plan.\n\nOutput: elite engineering answer optimized for correctness, performance, and operability.\n**Contract**\n- Inputs validated at the boundary; explicit error taxonomy.\n- Idempotency for side effects via request_id; deterministic replay.\n- Backward compatibility: additive changes by default; versioned breaking changes.\n**Invariants**\n- Safety: state transitions preserve invariants; no partial commit leaks.\n- Determinism: replay of the same event log yields identical outputs.\n- Liveness: under bounded faults and stable network, progress occurs.\n**Failure modes & recovery**\n- Network partition: minority cannot commit; clients receive retriable errors.\n- Duplicate requests: de-duplicate by (tenant, request_id) returning cached response.\n- Data corruption: checksums + scrubber; quarantine and rebuild from replicas/snapshots.\n**Security posture (defensive)**\n- Threat model: auth/authz, injection, replay/abuse, supply chain.\n- Least privilege; secrets in managed store; audit logs for sensitive ops.\n- Input normalization, parameterized queries, path traversal protections.\n**Verification strategy**\n- Canary + shadow traffic; invariants checked in production via assertions/metrics.\n- Fuzzing of parsers/framers/validators with corpus seeds.\n- Deterministic simulation with fault injection (crash/partition/latency).\n\n**Snippet**\n```text\nImplementation sketch: factor pure state-machine core; adapters for I/O; add deterministic replay log.\n```\nExpert+ checks: mechanized invariants (or exhaustive model checking), adversarial fuzzing, and multi-region failure drills.", "source": "WithinUsAI/Omega_Genesis_Coder_100k"} {"text": "Add a clear docstring and type hints to this function:\n\n```python\ndef f25552(s):\n return ''.join(x for x in s if x.isalnum()).lower()\n```\n\n```python\nfrom __future__ import annotations\n\ndef f25552(s: str) -> str:\n \"\"\"Normalize a string: keep only alphanumerics and lowercase the result.\"\"\"\n return \"\".join(ch for ch in s if ch.isalnum()).lower()\n```", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Fix a bug and add tests.\n\nFile: m6jhj4f9kz.py\n```python\ndef rql88_ysenaw(n: int) -> int:\n \"\"\"Sum 1..n inclusive.\"\"\"\n if n < 0:\n raise ValueError(\"n must be non-negative\")\n total = 0\n for k in range(n): # BUG: should include n\n total += k\n return total\n```\n\nReturn unified diffs for m6jhj4f9kz.py and test_m6jhj4f9kz.py (pytest).\n\n*** Begin Patch\n*** Update File: m6jhj4f9kz.py\n@@\n def rql88_ysenaw(n: int) -> int:\n@@\n total = 0\n- for k in range(n): # BUG: should include n\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_m6jhj4f9kz.py\n+import pytest\n+from m6jhj4f9kz import rql88_ysenaw\n+\n+def test_zero():\n+ assert rql88_ysenaw(0) == 0\n+\n+def test_one():\n+ assert rql88_ysenaw(1) == 1\n+\n+def test_small():\n+ assert rql88_ysenaw(7) == 28\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ rql88_ysenaw(-1)\n+\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Write a thorough test suite for a Python component used for task scheduling.\nRequirements: cover edge cases, invalid inputs, and behavior invariants.\nConstraints: must include type hints, stdlib-only, must include tests, must include docstrings.\nDifficulty: hard. Ensure the API is testable via dependency injection.\n\nDeliverable: implementation + tests.\n```python\n# tests (pytest-style) for a module providing: normalize(), parse_lines(), compute_stats()\nimport math\nimport pytest\n\ndef test_normalize_idempotent(module_under_test):\n x = \" A\\tB \"\n assert module_under_test.normalize(module_under_test.normalize(x)) == module_under_test.normalize(x)\n\ndef test_parse_lines_rejects_invalid(module_under_test):\n with pytest.raises(ValueError):\n module_under_test.parse_lines([\"\", \"???\", None]) # type: ignore[arg-type]\n\ndef test_compute_stats_basic(module_under_test):\n data = [1, 2, 3, 4]\n s = module_under_test.compute_stats(data)\n assert s.count == 4\n assert s.total == 10\n assert math.isclose(s.mean, 2.5)\n```", "source": "WithinUsAI/python_GOD_coder_100k"} {"text": "Task type: distributed_algorithm\nScenario: edge sync\nDomain focus: real-time scheduling\nPrimary language: bash\nDifficulty: expert\nScale/SLO: p99 < 150ms\nComponent: component_foeynsnt\nConstraints: include deterministic replay plan, include test vectors and fuzz strategy, include failure modes and recovery, include verification strategy, assume adversarial inputs; validate everything\nAssume tight memory budget and cold-start constraints.\nDeliverable: Design an algorithm with message flows and correctness arguments (safety + liveness). Include failure handling and a minimal reference implementation skeleton.\n\nOutput: contract-first solution with failure modes, security posture, and test/verification strategy.\n**Contract**\n- Inputs validated at the boundary; explicit error taxonomy.\n- Idempotency for side effects via request_id; deterministic replay.\n- Backward compatibility: additive changes by default; versioned breaking changes.\n**Invariants**\n- Determinism: replay of the same event log yields identical outputs.\n- Safety: state transitions preserve invariants; no partial commit leaks.\n- Liveness: under bounded faults and stable network, progress occurs.\n**Failure modes & recovery**\n- Network partition: minority cannot commit; clients receive retriable errors.\n- Data corruption: checksums + scrubber; quarantine and rebuild from replicas/snapshots.\n- Duplicate requests: de-duplicate by (tenant, request_id) returning cached response.\n**Security posture (defensive)**\n- Threat model: auth/authz, injection, replay/abuse, supply chain.\n- Least privilege; secrets in managed store; audit logs for sensitive ops.\n- Input normalization, parameterized queries, path traversal protections.\n**Verification strategy**\n- Deterministic simulation with fault injection (crash/partition/latency).\n- Canary + shadow traffic; invariants checked in production via assertions/metrics.\n- Property tests against a pure reference model (state machine).\n\n**Snippet**\n```text\nImplementation sketch: factor pure state-machine core; adapters for I/O; add deterministic replay log.\n```\nExpert checks: state-machine proof sketch + model checking; upgrade/rollback rehearsed.", "source": "WithinUsAI/Omega_Genesis_Coder_100k"} {"text": "Refactor an existing codebase in gaming to support A/B experimentation cleanly.\nTarget platform: mobile (Android Kotlin).\nRequirements: propose new modules/layers, dependency boundaries, and migration plan.\nConstraints: must be easy to extend, must be observable (logs/metrics/traces), must include clear error handling.\nDifficulty: expert. Assume untrusted input; validate everything.\n\nOutput: design + implementation guidance suitable for shipping.\nDeliverable: refactor plan + module boundaries.\n\n**Proposed modules**\n- `domain/` pure business logic (no I/O)\n- `adapters/` DB, cache, external APIs\n- `api/` request/response validation and routing\n- `observability/` logging/metrics/tracing\n- `tests/` unit + integration suites\n\n**Migration plan**\n1. Introduce new interfaces + adapters behind feature flags.\n2. Dual-write or read-compat layer if schema changes.\n3. Incremental cutover; deprecate legacy module.\n\nKey rule: dependencies flow inward; domain has no framework imports.\n\n\nHard-mode checks: concurrency safety, idempotency, and rollback validated; add chaos tests where feasible.", "source": "WithinUsAI/GOD_Coder_100k"} {"text": "Task type: query_optimizer\nScenario: multi-tenant event ingestion\nDomain focus: stream processing\nPrimary language: rust\nDifficulty: expert+\nScale/SLO: multi-region active-active\nComponent: component_xseuirex\nConstraints: include failure modes and recovery, include deterministic replay plan, include verification strategy, explicit contracts and invariants, include performance model and limits\nAssume hostile inputs and targeted abuse patterns.\nDeliverable: Design a cost-based optimizer slice: logical rules, physical operators, and cost model. Include regression tests and query-plan explain examples.\n\nOutput: elite engineering answer optimized for correctness, performance, and operability.\n**Contract**\n- Inputs validated at the boundary; explicit error taxonomy.\n- Idempotency for side effects via request_id; deterministic replay.\n- Backward compatibility: additive changes by default; versioned breaking changes.\n**Invariants**\n- Safety: state transitions preserve invariants; no partial commit leaks.\n- Liveness: under bounded faults and stable network, progress occurs.\n- Isolation: tenant boundary enforced; no cross-tenant reads/writes.\n**Failure modes & recovery**\n- Crash during commit: WAL replay completes or transaction aborts; no torn writes.\n- Network partition: minority cannot commit; clients receive retriable errors.\n- Duplicate requests: de-duplicate by (tenant, request_id) returning cached response.\n**Security posture (defensive)**\n- Threat model: auth/authz, injection, replay/abuse, supply chain.\n- Least privilege; secrets in managed store; audit logs for sensitive ops.\n- Input normalization, parameterized queries, path traversal protections.\n**Verification strategy**\n- Canary + shadow traffic; invariants checked in production via assertions/metrics.\n- Property tests against a pure reference model (state machine).\n- Deterministic simulation with fault injection (crash/partition/latency).\n\n**Snippet**\n```python\n# Minimal cost model skeleton\nfrom dataclasses import dataclass\n\n@dataclass(frozen=True)\nclass Plan:\n op: str\n cost: float\n children: tuple[\"Plan\", ...] = ()\n\ndef choose_best(plans: list[Plan]) -> Plan:\n return min(plans, key=lambda p: p.cost)\n```\n\nExpert+ checks: mechanized invariants (or exhaustive model checking), adversarial fuzzing, and multi-region failure drills.", "source": "WithinUsAI/Omega_Genesis_Coder_100k"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: Language: JavaScript\nFramework/tooling: Jest\nDomain: job scheduler\nLogic challenge: timezone bug in reporting\nTask type: security_logic_interaction\nDifficulty: hard\n\nReturn a rigorous engineering answer:\n- identify the hidden root cause or logical failure\n- present the corrected implementation\n- add tests that prove the fix\n- list verification commands\n- explain why naive fixes are insufficient when relevant\n\nRepository sketch:\nrepo/\n src/\n api.js\n service.js\n utils.js\n tests/\n api.test.js\n package.json\n\nFocus: Focus on ambiguity, misleading symptoms, hidden root causes, and high-stakes debugging.\n\nassistant: Diagnosis:\n- Hidden root cause: timezone bug in reporting presents misleading symptoms, so the patch must target the actual logic boundary rather than the first visible failure.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```javascript\ntype Payload = Record;\n\nexport function normalizePayload(payload: Payload): Payload {\n if (!payload || typeof payload !== \"object\" || Array.isArray(payload)) {\n throw new TypeError(\"payload must be a plain object\");\n }\n return Object.fromEntries(\n Object.entries(payload)\n .filter(([, value]) => value !== null && value !== undefined)\n .map(([key, value]) => [String(key).trim(), value])\n );\n}\n\nexport function handleTimezoneBugInReporting(payload: Payload) {\n const clean = normalizePayload(payload);\n if (!(\"id\" in clean)) {\n return { ok: false, data: {}, error: \"missing id\" };\n }\n return { ok: true, data: clean, error: null };\n}\n```\n\nTests:\n```javascript\nimport { describe, it, expect } from \"vitest\";\nimport { handleTimezoneBugInReporting } from \"../src/service\";\n\ndescribe(\"handler\", () => {\n it(\"accepts valid input\", () => {\n expect(handleTimezoneBugInReporting({ id: 7, name: \"ok\", unused: null })).toEqual({\n ok: true,\n data: { id: 7, name: \"ok\" },\n error: null\n });\n });\n\n it(\"rejects missing id\", () => {\n expect(handleTimezoneBugInReporting({ name: \"x\" }).error).toMatch(/missing id/);\n });\n});\n```\n\nVerification:\n- `npm test`\n- `npm run lint`\n\nEngineering notes:\n- Language: JavaScript\n- Framework/tooling: Jest\n- Stack context: Airflow, dbt, DuckDB, MinIO, pytest\n- Domain: job scheduler\n- Task type: security_logic_interaction\n- Difficulty: hard\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "Optimize while preserving behavior and order.\n\n```python\ndef f40775(xs):\n out=[]\n for x in xs:\n if x not in out: out.append(x)\n return out\n```\nReturn `m05825.py` with types and O(n) average.\n\n```python\n# m05825.py\nfrom __future__ import annotations\nfrom typing import Iterable, List, Set, TypeVar\nT=TypeVar(\"T\")\n\ndef f40775(xs: Iterable[T]) -> List[T]:\n \"\"\"Unique items preserving first-seen order.\"\"\"\n seen: Set[T]=set()\n out: List[T]=[]\n for x in xs:\n if x in seen: continue\n seen.add(x); out.append(x)\n return out\n```", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Build an elite-grade solution in the domain of security engineering (defensive) for scenario: multi-tenant SaaS.\nPrimary language: python.\nDifficulty: medium.\nConstraints: assume untrusted inputs; validate and sanitize, include invariants and failure modes, document performance characteristics.\nComponent: component_camaqfi.\nAssume schema changes every sprint; must be backward compatible.\nTask: Implement a concurrency primitive or subsystem (lock-free queue, thread pool, async runtime component). Explain memory ordering and correctness arguments; include stress tests.\n\nOutput: elite-grade engineering answer with contracts, edge cases, and verification.\nOutput: correctness-focused concurrency primitive + stress tests.\n\n**Primitive**\n- Bounded MPMC queue with backpressure (blocking push/pop) OR lock-free SPSC ring buffer.\n\n**Correctness notes**\n- For lock-free: use acquire/release semantics on head/tail indices.\n- Avoid ABA by monotonic counters; ring index = counter % capacity.\n\n**Stress tests**\n- Multi-thread producers/consumers; assert item multiset preserved.\n- Use time-bounded randomized schedules; detect deadlocks.\n\n\nChecks: boundary validation and deterministic behavior verified.", "source": "WithinUsAI/Elite_GOD_Coder_100k"} {"text": "Write a thorough test suite for a Python component used for task scheduling.\nRequirements: cover edge cases, invalid inputs, and behavior invariants.\nConstraints: stdlib-only, must be memory-efficient, must provide clear error messages.\nDifficulty: expert. Guarantee deterministic output ordering.\n\nDeliverable: implementation + tests.\n```python\n# tests (pytest-style) for a module providing: normalize(), parse_lines(), compute_stats()\nimport math\nimport pytest\n\ndef test_normalize_idempotent(module_under_test):\n x = \" A\\tB \"\n assert module_under_test.normalize(module_under_test.normalize(x)) == module_under_test.normalize(x)\n\ndef test_parse_lines_rejects_invalid(module_under_test):\n with pytest.raises(ValueError):\n module_under_test.parse_lines([\"\", \"???\", None]) # type: ignore[arg-type]\n\ndef test_compute_stats_basic(module_under_test):\n data = [1, 2, 3, 4]\n s = module_under_test.compute_stats(data)\n assert s.count == 4\n assert s.total == 10\n assert math.isclose(s.mean, 2.5)\n```", "source": "WithinUsAI/python_GOD_coder_100k"} {"text": "Optimize while preserving behavior and order.\n\n```python\ndef f33357(xs):\n out=[]\n for x in xs:\n if x not in out: out.append(x)\n return out\n```\nReturn `m19051.py` with types and O(n) average.\n\n```python\n# m19051.py\nfrom __future__ import annotations\nfrom typing import Iterable, List, Set, TypeVar\nT=TypeVar(\"T\")\n\ndef f33357(xs: Iterable[T]) -> List[T]:\n \"\"\"Unique items preserving first-seen order.\"\"\"\n seen: Set[T]=set()\n out: List[T]=[]\n for x in xs:\n if x in seen: continue\n seen.add(x); out.append(x)\n return out\n```", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Fix a bug and add tests.\n\nFile: bidkpi3eyrhl.py\n```python\ndef gbmnga(n: int) -> int:\n \"\"\"Sum 1..n inclusive.\"\"\"\n if n < 0:\n raise ValueError(\"n must be non-negative\")\n total = 0\n for k in range(n): # BUG: should include n\n total += k\n return total\n```\n\nReturn unified diffs for bidkpi3eyrhl.py and test_bidkpi3eyrhl.py (pytest).\n\n*** Begin Patch\n*** Update File: bidkpi3eyrhl.py\n@@\n def gbmnga(n: int) -> int:\n@@\n total = 0\n- for k in range(n): # BUG: should include n\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_bidkpi3eyrhl.py\n+import pytest\n+from bidkpi3eyrhl import gbmnga\n+\n+def test_zero():\n+ assert gbmnga(0) == 0\n+\n+def test_one():\n+ assert gbmnga(1) == 1\n+\n+def test_small():\n+ assert gbmnga(7) == 28\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ gbmnga(-1)\n+\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Fix the bug and add pytest tests.\n\n```python\ndef f21069(n: int) -> int:\n # sum 1..n inclusive\n if n < 0: raise ValueError\n total = 0\n for k in range(n): # BUG\n total += k\n return total\n```\nReturn unified diffs for `m45867.py` and `test_m45867.py`.\n\n*** Begin Patch\n*** Update File: m45867.py\n@@\n def f21069(n: int) -> int:\n@@\n- for k in range(n): # BUG\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_m45867.py\n+import pytest\n+from m45867 import f21069\n+\n+def test_small():\n+ assert f21069(7) == 28\n+\n+def test_zero():\n+ assert f21069(0) == 0\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ f21069(-1)\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Task type: formal_proof_sketch\nScenario: document indexing pipeline\nDomain focus: data lineage & governance\nPrimary language: bash\nDifficulty: expert\nScale/SLO: 10k RPS peak\nComponent: component_xijvlbms\nConstraints: include performance model and limits, assume adversarial inputs; validate everything, include failure modes and recovery, include deterministic replay plan, include security threat model (defensive only), explicit contracts and invariants\nAssume schema changes every sprint; must be backward compatible.\nDeliverable: Provide a rigorous proof sketch for key invariants and show how to test/verify them in practice.\n\nOutput: elite engineering answer optimized for correctness, performance, and operability.\n**Contract**\n- Inputs validated at the boundary; explicit error taxonomy.\n- Idempotency for side effects via request_id; deterministic replay.\n- Backward compatibility: additive changes by default; versioned breaking changes.\n**Invariants**\n- Isolation: tenant boundary enforced; no cross-tenant reads/writes.\n- Liveness: under bounded faults and stable network, progress occurs.\n- Safety: state transitions preserve invariants; no partial commit leaks.\n**Failure modes & recovery**\n- Duplicate requests: de-duplicate by (tenant, request_id) returning cached response.\n- Network partition: minority cannot commit; clients receive retriable errors.\n- Data corruption: checksums + scrubber; quarantine and rebuild from replicas/snapshots.\n**Security posture (defensive)**\n- Threat model: auth/authz, injection, replay/abuse, supply chain.\n- Least privilege; secrets in managed store; audit logs for sensitive ops.\n- Input normalization, parameterized queries, path traversal protections.\n**Verification strategy**\n- Property tests against a pure reference model (state machine).\n- Fuzzing of parsers/framers/validators with corpus seeds.\n- Deterministic simulation with fault injection (crash/partition/latency).\n\n**Snippet**\n```text\nImplementation sketch: factor pure state-machine core; adapters for I/O; add deterministic replay log.\n```\nExpert checks: state-machine proof sketch + model checking; upgrade/rollback rehearsed.", "source": "WithinUsAI/Omega_Genesis_Coder_100k"} {"text": "Task type: ml_system_design\nScenario: streaming ETL\nDomain focus: formal verification\nPrimary language: sql\nDifficulty: hard\nScale/SLO: 100k RPS peak\nComponent: component_xnyhfhaq\nConstraints: include deterministic replay plan, include test vectors and fuzz strategy, avoid data races and undefined behavior, assume adversarial inputs; validate everything, explicit contracts and invariants, include failure modes and recovery, include performance model and limits\nAssume partial data corruption; include scrubbing strategy.\nDeliverable: Design end-to-end ML system: data contracts, training, evaluation, registry, serving, monitoring, and rollback.\n\nOutput: elite engineering answer optimized for correctness, performance, and operability.\n**Contract**\n- Inputs validated at the boundary; explicit error taxonomy.\n- Idempotency for side effects via request_id; deterministic replay.\n- Backward compatibility: additive changes by default; versioned breaking changes.\n**Invariants**\n- Determinism: replay of the same event log yields identical outputs.\n- Safety: state transitions preserve invariants; no partial commit leaks.\n- Liveness: under bounded faults and stable network, progress occurs.\n**Failure modes & recovery**\n- Duplicate requests: de-duplicate by (tenant, request_id) returning cached response.\n- Crash during commit: WAL replay completes or transaction aborts; no torn writes.\n- Network partition: minority cannot commit; clients receive retriable errors.\n**Security posture (defensive)**\n- Threat model: auth/authz, injection, replay/abuse, supply chain.\n- Least privilege; secrets in managed store; audit logs for sensitive ops.\n- Input normalization, parameterized queries, path traversal protections.\n**Verification strategy**\n- Property tests against a pure reference model (state machine).\n- Fuzzing of parsers/framers/validators with corpus seeds.\n- Deterministic simulation with fault injection (crash/partition/latency).\n\n**Snippet**\n```text\nImplementation sketch: factor pure state-machine core; adapters for I/O; add deterministic replay log.\n```\nHard checks: fault injection tests gate merges; perf thresholds enforced in CI.", "source": "WithinUsAI/Omega_Genesis_Coder_100k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Fix a bug and add tests.\n\nFile: mwg9fs.py\n```python\ndef soihm05_0(n: int) -> int:\n \"\"\"Sum 1..n inclusive.\"\"\"\n if n < 0:\n raise ValueError(\"n must be non-negative\")\n total = 0\n for k in range(n): # BUG: should include n\n total += k\n return total\n```\n\nReturn unified diffs for mwg9fs.py and test_mwg9fs.py (pytest).\n\n*** Begin Patch\n*** Update File: mwg9fs.py\n@@\n def soihm05_0(n: int) -> int:\n@@\n total = 0\n- for k in range(n): # BUG: should include n\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_mwg9fs.py\n+import pytest\n+from mwg9fs import soihm05_0\n+\n+def test_zero():\n+ assert soihm05_0(0) == 0\n+\n+def test_one():\n+ assert soihm05_0(1) == 1\n+\n+def test_small():\n+ assert soihm05_0(7) == 28\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ soihm05_0(-1)\n+\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Implement caching for a content moderation product.\nTarget platform: mobile (Android Kotlin).\nRequirements: provide production-ready code, configuration, and tests.\nConstraints: must include clear error handling, must avoid global state, must be observable (logs/metrics/traces).\nDifficulty: easy. Assume PII must be protected.\n\nOutput: actionable implementation and verification artifacts.\nDeliverable: production-grade reference implementation (FastAPI) + tests.\n\n```python\n# app.py\nfrom __future__ import annotations\n\nimport hashlib\nimport json\nfrom dataclasses import dataclass\nfrom datetime import datetime, timezone\nfrom typing import Any, Optional\n\nfrom fastapi import FastAPI, Header, HTTPException\nfrom pydantic import BaseModel, Field\n\napp = FastAPI(title=\"Idempotent API\")\n\nclass CreateReq(BaseModel):\n tenant_id: str = Field(min_length=1)\n amount_cents: int = Field(ge=0)\n currency: str = Field(min_length=3, max_length=3)\n\nclass CreateResp(BaseModel):\n id: str\n created_at: str\n echo: CreateReq\n\n@dataclass\nclass _IdempoEntry:\n request_hash: str\n response_json: str\n\n# In production: Postgres table with UNIQUE(tenant_id, key)\n_IDEMPO: dict[tuple[str, str], _IdempoEntry] = {}\n\ndef _hash_req(req: CreateReq) -> str:\n raw = req.model_dump_json()\n return hashlib.sha256(raw.encode(\"utf-8\")).hexdigest()\n\n@app.post(\"/v1/payments\", response_model=CreateResp)\ndef create_payment(\n req: CreateReq,\n idempotency_key: Optional[str] = Header(default=None, alias=\"Idempotency-Key\"),\n) -> Any:\n if not idempotency_key:\n raise HTTPException(status_code=400, detail=\"Missing Idempotency-Key\")\n if len(idempotency_key) > 128:\n raise HTTPException(status_code=400, detail=\"Idempotency-Key too long\")\n\n key = (req.tenant_id, idempotency_key)\n rh = _hash_req(req)\n\n existing = _IDEMPO.get(key)\n if existing:\n if existing.request_hash != rh:\n raise HTTPException(status_code=409, detail=\"Idempotency-Key reuse with different payload\")\n return json.loads(existing.response_json)\n\n # Create new payment (stubbed)\n pid = hashlib.md5(f\"{req.tenant_id}:{idempotency_key}\".encode()).hexdigest()\n resp = CreateResp(\n id=pid,\n created_at=datetime.now(timezone.utc).isoformat(),\n echo=req,\n )\n _IDEMPO[key] = _IdempoEntry(request_hash=rh, response_json=resp.model_dump_json())\n return resp\n```\n\n```python\n# test_app.py (pytest)\nfrom fastapi.testclient import TestClient\nfrom app import app\n\nclient = TestClient(app)\n\ndef test_idempotent_replay():\n headers = {\"Idempotency-Key\": \"abc\"}\n body = {\"tenant_id\":\"t1\",\"amount_cents\":100,\"currency\":\"USD\"}\n r1 = client.post(\"/v1/payments\", json=body, headers=headers)\n r2 = client.post(\"/v1/payments\", json=body, headers=headers)\n assert r1.status_code == 200 and r2.status_code == 200\n assert r1.json() == r2.json()\n\ndef test_payload_conflict():\n headers = {\"Idempotency-Key\": \"abc\"}\n b1 = {\"tenant_id\":\"t1\",\"amount_cents\":100,\"currency\":\"USD\"}\n b2 = {\"tenant_id\":\"t1\",\"amount_cents\":200,\"currency\":\"USD\"}\n assert client.post(\"/v1/payments\", json=b1, headers=headers).status_code == 200\n assert client.post(\"/v1/payments\", json=b2, headers=headers).status_code == 409\n```\n\nNotes:\n- Replace in-memory store with a DB table and transaction.\n- Store response + request hash to detect key reuse with different payload.\n\n\nChecks: input validation, tests, and safe defaults included.", "source": "WithinUsAI/GOD_Coder_100k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Fix a bug and add tests.\n\nFile: o98p_4ytum.py\n```python\ndef nk1lng(n: int) -> int:\n \"\"\"Sum 1..n inclusive.\"\"\"\n if n < 0:\n raise ValueError(\"n must be non-negative\")\n total = 0\n for k in range(n): # BUG: should include n\n total += k\n return total\n```\n\nReturn unified diffs for o98p_4ytum.py and test_o98p_4ytum.py (pytest).\n\n*** Begin Patch\n*** Update File: o98p_4ytum.py\n@@\n def nk1lng(n: int) -> int:\n@@\n total = 0\n- for k in range(n): # BUG: should include n\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_o98p_4ytum.py\n+import pytest\n+from o98p_4ytum import nk1lng\n+\n+def test_zero():\n+ assert nk1lng(0) == 0\n+\n+def test_one():\n+ assert nk1lng(1) == 1\n+\n+def test_small():\n+ assert nk1lng(7) == 28\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ nk1lng(-1)\n+\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Fix a bug and add tests.\n\nFile: b6p7px.py\n```python\ndef llfu25(n: int) -> int:\n \"\"\"Sum 1..n inclusive.\"\"\"\n if n < 0:\n raise ValueError(\"n must be non-negative\")\n total = 0\n for k in range(n): # BUG: should include n\n total += k\n return total\n```\n\nReturn unified diffs for b6p7px.py and test_b6p7px.py (pytest).\n\n*** Begin Patch\n*** Update File: b6p7px.py\n@@\n def llfu25(n: int) -> int:\n@@\n total = 0\n- for k in range(n): # BUG: should include n\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_b6p7px.py\n+import pytest\n+from b6p7px import llfu25\n+\n+def test_zero():\n+ assert llfu25(0) == 0\n+\n+def test_one():\n+ assert llfu25(1) == 1\n+\n+def test_small():\n+ assert llfu25(7) == 28\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ llfu25(-1)\n+\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Add a clear docstring and type hints to this function:\n\n```python\ndef f23374(s):\n return ''.join(x for x in s if x.isalnum()).lower()\n```\n\n```python\nfrom __future__ import annotations\n\ndef f23374(s: str) -> str:\n \"\"\"Normalize a string: keep only alphanumerics and lowercase the result.\"\"\"\n return \"\".join(ch for ch in s if ch.isalnum()).lower()\n```", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Build an elite-grade solution in the domain of distributed systems for scenario: event ingestion.\nPrimary language: typescript.\nDifficulty: hard.\nConstraints: design for backward compatibility and migrations, avoid undefined behavior and data races, provide rollout and rollback guidance, include tests or verification strategy, document performance characteristics.\nComponent: component_laziewi.\nAssume schema changes every sprint; must be backward compatible.\nTask: Provide SLOs, alerting, dashboards, runbooks, and incident playbook. Include chaos testing and safe rollout strategy.\n\nOutput: elite-grade engineering answer with contracts, edge cases, and verification.\nOutput: SLOs + alerts + runbooks + chaos strategy.\n\n**SLOs**\n- Availability: 99.9% monthly\n- Latency: p95 < 200ms, p99 < 400ms\n- Error rate: < 0.1%\n\n**Alerts**\n- Burn-rate alerts for SLOs (fast/slow windows)\n- Saturation: CPU, memory, queue depth, DB connections\n- Dependency health: cache hit rate drop, downstream timeouts\n\n**Runbooks**\n- Triage: identify blast radius, feature-flag rollback, capacity mitigation\n- Post-incident: timeline, contributing factors, action items\n\n**Chaos**\n- Inject latency, partial outages, and restarts in staging; verify steady-state SLOs.\n\n\nHard checks: failure injection tests and performance regressions gated.", "source": "WithinUsAI/Elite_GOD_Coder_100k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Produce an offline-first self-evolving code assistant architecture named `axx7l4s23`.\nMust include: module layout, patch-safety policy, evaluation gates (tests/lint/types), versioned memory index.\n\nArchitecture: `axx7l4s23` (offline-first, self-evolving)\n\nModules\n- core/loop.py: evolve → validate → accept/reject (bounded iterations)\n- patching/: diff builder, safe apply, atomic writes, rollback points\n- policy/: allowlist paths, deny globs (.git/, __pycache__/, binaries), patch size caps\n- signals/: parse pytest/ruff/mypy into normalized findings\n- memory/index.jsonl: append-only snapshots (hashes, metrics, rationale)\n\nSafety gates\n- refuse path traversal/symlink escapes; never edit binaries\n- accept only if tests/lint/types stay green or improve", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Task type: static_analyzer\nScenario: time-series metrics store\nDomain focus: kernel primitives\nPrimary language: go\nDifficulty: expert+\nScale/SLO: multi-region active-active\nComponent: component_wgxhxbdp\nConstraints: include failure modes and recovery, include security threat model (defensive only), include backward compatibility and migration plan, assume adversarial inputs; validate everything, include performance model and limits, include test vectors and fuzz strategy\nAssume schema changes every sprint; must be backward compatible.\nDeliverable: Design a static analyzer for a safety property (e.g., taint/SQLi prevention); include rule set, false-positive strategy, and tests.\n\nOutput: contract-first solution with failure modes, security posture, and test/verification strategy.\n**Contract**\n- Inputs validated at the boundary; explicit error taxonomy.\n- Idempotency for side effects via request_id; deterministic replay.\n- Backward compatibility: additive changes by default; versioned breaking changes.\n**Invariants**\n- Liveness: under bounded faults and stable network, progress occurs.\n- Isolation: tenant boundary enforced; no cross-tenant reads/writes.\n- Determinism: replay of the same event log yields identical outputs.\n**Failure modes & recovery**\n- Network partition: minority cannot commit; clients receive retriable errors.\n- Crash during commit: WAL replay completes or transaction aborts; no torn writes.\n- Duplicate requests: de-duplicate by (tenant, request_id) returning cached response.\n**Security posture (defensive)**\n- Threat model: auth/authz, injection, replay/abuse, supply chain.\n- Least privilege; secrets in managed store; audit logs for sensitive ops.\n- Input normalization, parameterized queries, path traversal protections.\n**Verification strategy**\n- Canary + shadow traffic; invariants checked in production via assertions/metrics.\n- Property tests against a pure reference model (state machine).\n- Deterministic simulation with fault injection (crash/partition/latency).\n\n**Snippet**\n```text\nImplementation sketch: factor pure state-machine core; adapters for I/O; add deterministic replay log.\n```\nExpert+ checks: mechanized invariants (or exhaustive model checking), adversarial fuzzing, and multi-region failure drills.", "source": "WithinUsAI/Omega_Genesis_Coder_100k"} {"text": "Task type: schema_evolution_contracts\nScenario: real-time notification hub\nDomain focus: secure enclaves (defensive)\nPrimary language: go\nDifficulty: hard\nScale/SLO: 10k RPS peak\nComponent: component_ppgvozvm\nConstraints: include deterministic replay plan, explicit contracts and invariants, include failure modes and recovery, include verification strategy, include security threat model (defensive only)\nAssume crash-only processes; recovery must be deterministic.\nDeliverable: Design schema evolution rules and compatibility tests; include migration plan and examples.\n\nOutput: elite engineering answer optimized for correctness, performance, and operability.\n**Contract**\n- Inputs validated at the boundary; explicit error taxonomy.\n- Idempotency for side effects via request_id; deterministic replay.\n- Backward compatibility: additive changes by default; versioned breaking changes.\n**Invariants**\n- Liveness: under bounded faults and stable network, progress occurs.\n- Safety: state transitions preserve invariants; no partial commit leaks.\n- Determinism: replay of the same event log yields identical outputs.\n**Failure modes & recovery**\n- Data corruption: checksums + scrubber; quarantine and rebuild from replicas/snapshots.\n- Network partition: minority cannot commit; clients receive retriable errors.\n- Duplicate requests: de-duplicate by (tenant, request_id) returning cached response.\n**Security posture (defensive)**\n- Threat model: auth/authz, injection, replay/abuse, supply chain.\n- Least privilege; secrets in managed store; audit logs for sensitive ops.\n- Input normalization, parameterized queries, path traversal protections.\n**Verification strategy**\n- Property tests against a pure reference model (state machine).\n- Fuzzing of parsers/framers/validators with corpus seeds.\n- Deterministic simulation with fault injection (crash/partition/latency).\n\n**Snippet**\n```text\nImplementation sketch: factor pure state-machine core; adapters for I/O; add deterministic replay log.\n```\nHard checks: fault injection tests gate merges; perf thresholds enforced in CI.", "source": "WithinUsAI/Omega_Genesis_Coder_100k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Fix a bug and add tests.\n\nFile: u66q2jv.py\n```python\ndef hl75bp4i73(n: int) -> int:\n \"\"\"Sum 1..n inclusive.\"\"\"\n if n < 0:\n raise ValueError(\"n must be non-negative\")\n total = 0\n for k in range(n): # BUG: should include n\n total += k\n return total\n```\n\nReturn unified diffs for u66q2jv.py and test_u66q2jv.py (pytest).\n\n*** Begin Patch\n*** Update File: u66q2jv.py\n@@\n def hl75bp4i73(n: int) -> int:\n@@\n total = 0\n- for k in range(n): # BUG: should include n\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_u66q2jv.py\n+import pytest\n+from u66q2jv import hl75bp4i73\n+\n+def test_zero():\n+ assert hl75bp4i73(0) == 0\n+\n+def test_one():\n+ assert hl75bp4i73(1) == 1\n+\n+def test_small():\n+ assert hl75bp4i73(7) == 28\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ hl75bp4i73(-1)\n+\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Refactor a Python module used for data modeling into a clean, extensible design.\nRequirements: outline the new architecture briefly, then provide the refactored code and tests.\nConstraints: must include docstrings, must provide clear error messages, must avoid global state, must be easy to extend.\nDifficulty: easy. Include a small CLI example if relevant.\n\nDeliverable: API + reference implementation + tests.\nArchitecture:\n- Public facade class coordinating concerns (parsing, validation, persistence)\n- Small pure functions for testability\n- No global state; dependency injection for filesystem I/O\n\n```python\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom pathlib import Path\nfrom typing import Protocol, Iterable\nimport json\n\nclass Store(Protocol):\n def write_text(self, path: Path, data: str) -> None: ...\n\nclass FSStore:\n def write_text(self, path: Path, data: str) -> None:\n path.parent.mkdir(parents=True, exist_ok=True)\n path.write_text(data, encoding=\"utf-8\")\n\n@dataclass(frozen=True, slots=True)\nclass Item:\n name: str\n qty: int\n\ndef parse_items(lines: Iterable[str]) -> list[Item]:\n out: list[Item] = []\n for i, line in enumerate(lines, 1):\n s = line.strip()\n if not s:\n continue\n obj = json.loads(s)\n if not isinstance(obj, dict):\n raise ValueError(f\"line {i}: expected object\")\n name = obj.get(\"name\")\n qty = obj.get(\"qty\")\n if not isinstance(name, str) or not name:\n raise ValueError(f\"line {i}: name must be str\")\n if not isinstance(qty, int) or qty < 0:\n raise ValueError(f\"line {i}: qty must be non-negative int\")\n out.append(Item(name, qty))\n return out\n\nclass InventoryWriter:\n def __init__(self, base_dir: Path, store: Store | None = None) -> None:\n self._base = base_dir\n self._store: Store = store or FSStore()\n\n def write(self, rel_path: str, items: list[Item]) -> Path:\n dst = (self._base / rel_path).resolve()\n base = self._base.resolve()\n if dst != base and base not in dst.parents:\n raise ValueError(\"unsafe path traversal\")\n payload = json.dumps([item.__dict__ for item in items], ensure_ascii=False)\n self._store.write_text(dst, payload)\n return dst\n```\n\n```python\nimport json\nfrom pathlib import Path\nimport pytest\nfrom module_under_test import InventoryWriter, parse_items\n\ndef test_parse_items_valid():\n lines = [json.dumps({\"name\":\"x\",\"qty\":1})]\n assert parse_items(lines)[0].name == \"x\"\n\ndef test_writer_blocks_traversal(tmp_path: Path):\n w = InventoryWriter(tmp_path)\n with pytest.raises(ValueError):\n w.write(\"../evil.json\", [])\n```", "source": "WithinUsAI/python_GOD_coder_100k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Refactor to modern typed Python with immutability and tests.\n\nFile: j0wha_1m_vve.py\n```python\nclass X0R78Q85:\n def __init__(self, name, values):\n self.name = name\n self.values = list(values)\n def add(self, v):\n self.values.append(v)\n def mean(self):\n s = 0\n for x in self.values:\n s += x\n return s / len(self.values)\n```\n\nReturn full new j0wha_1m_vve.py and test_j0wha_1m_vve.py.\n\n# j0wha_1m_vve.py\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom typing import Iterable, Tuple\n\n@dataclass(frozen=True)\nclass X0R78Q85:\n name: str\n values: Tuple[float, ...]\n\n @staticmethod\n def create(name: str, values: Iterable[float]) -> \"X0R78Q85\":\n vals = tuple(float(v) for v in values)\n if not vals:\n raise ValueError(\"values must be non-empty\")\n return X0R78Q85(name=name, values=vals)\n\n def add(self, v: float) -> \"X0R78Q85\":\n return X0R78Q85(name=self.name, values=self.values + (float(v),))\n\n def mean(self) -> float:\n return sum(self.values) / len(self.values)\n\n# test_j0wha_1m_vve.py\nimport pytest\nfrom j0wha_1m_vve import X0R78Q85\n\ndef test_mean_and_add():\n c = X0R78Q85.create(\"a\", [1, 2, 3])\n assert c.mean() == 2.0\n assert c.add(5).mean() == (1 + 2 + 3 + 5) / 4\n\ndef test_empty_raises():\n with pytest.raises(ValueError):\n X0R78Q85.create(\"x\", [])", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Task type: schema_evolution_contracts\nScenario: edge sync\nDomain focus: secure enclaves (defensive)\nPrimary language: go\nDifficulty: expert+\nScale/SLO: p99 < 150ms\nComponent: component_qvcpdvjr\nConstraints: include verification strategy, include deterministic replay plan, include failure modes and recovery, explicit contracts and invariants, include performance model and limits, include backward compatibility and migration plan, include security threat model (defensive only)\nAssume strict auditability and replayable history.\nDeliverable: Design schema evolution rules and compatibility tests; include migration plan and examples.\n\nOutput: elite engineering answer optimized for correctness, performance, and operability.\n**Contract**\n- Inputs validated at the boundary; explicit error taxonomy.\n- Idempotency for side effects via request_id; deterministic replay.\n- Backward compatibility: additive changes by default; versioned breaking changes.\n**Invariants**\n- Safety: state transitions preserve invariants; no partial commit leaks.\n- Liveness: under bounded faults and stable network, progress occurs.\n- Determinism: replay of the same event log yields identical outputs.\n**Failure modes & recovery**\n- Network partition: minority cannot commit; clients receive retriable errors.\n- Duplicate requests: de-duplicate by (tenant, request_id) returning cached response.\n- Crash during commit: WAL replay completes or transaction aborts; no torn writes.\n**Security posture (defensive)**\n- Threat model: auth/authz, injection, replay/abuse, supply chain.\n- Least privilege; secrets in managed store; audit logs for sensitive ops.\n- Input normalization, parameterized queries, path traversal protections.\n**Verification strategy**\n- Canary + shadow traffic; invariants checked in production via assertions/metrics.\n- Deterministic simulation with fault injection (crash/partition/latency).\n- Fuzzing of parsers/framers/validators with corpus seeds.\n\n**Snippet**\n```text\nImplementation sketch: factor pure state-machine core; adapters for I/O; add deterministic replay log.\n```\nExpert+ checks: mechanized invariants (or exhaustive model checking), adversarial fuzzing, and multi-region failure drills.", "source": "WithinUsAI/Omega_Genesis_Coder_100k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Refactor to modern typed Python with immutability and tests.\n\nFile: kp6ui20cqd.py\n```python\nclass Jcp9Qmd7N8:\n def __init__(self, name, values):\n self.name = name\n self.values = list(values)\n def add(self, v):\n self.values.append(v)\n def mean(self):\n s = 0\n for x in self.values:\n s += x\n return s / len(self.values)\n```\n\nReturn full new kp6ui20cqd.py and test_kp6ui20cqd.py.\n\n# kp6ui20cqd.py\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom typing import Iterable, Tuple\n\n@dataclass(frozen=True)\nclass Jcp9Qmd7N8:\n name: str\n values: Tuple[float, ...]\n\n @staticmethod\n def create(name: str, values: Iterable[float]) -> \"Jcp9Qmd7N8\":\n vals = tuple(float(v) for v in values)\n if not vals:\n raise ValueError(\"values must be non-empty\")\n return Jcp9Qmd7N8(name=name, values=vals)\n\n def add(self, v: float) -> \"Jcp9Qmd7N8\":\n return Jcp9Qmd7N8(name=self.name, values=self.values + (float(v),))\n\n def mean(self) -> float:\n return sum(self.values) / len(self.values)\n\n# test_kp6ui20cqd.py\nimport pytest\nfrom kp6ui20cqd import Jcp9Qmd7N8\n\ndef test_mean_and_add():\n c = Jcp9Qmd7N8.create(\"a\", [1, 2, 3])\n assert c.mean() == 2.0\n assert c.add(5).mean() == (1 + 2 + 3 + 5) / 4\n\ndef test_empty_raises():\n with pytest.raises(ValueError):\n Jcp9Qmd7N8.create(\"x\", [])", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Fix a bug and add tests.\n\nFile: eb0ta8y.py\n```python\ndef naa1xb(n: int) -> int:\n \"\"\"Sum 1..n inclusive.\"\"\"\n if n < 0:\n raise ValueError(\"n must be non-negative\")\n total = 0\n for k in range(n): # BUG: should include n\n total += k\n return total\n```\n\nReturn unified diffs for eb0ta8y.py and test_eb0ta8y.py (pytest).\n\n*** Begin Patch\n*** Update File: eb0ta8y.py\n@@\n def naa1xb(n: int) -> int:\n@@\n total = 0\n- for k in range(n): # BUG: should include n\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_eb0ta8y.py\n+import pytest\n+from eb0ta8y import naa1xb\n+\n+def test_zero():\n+ assert naa1xb(0) == 0\n+\n+def test_one():\n+ assert naa1xb(1) == 1\n+\n+def test_small():\n+ assert naa1xb(7) == 28\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ naa1xb(-1)\n+\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Design and implement an algorithm for data modeling.\nRequirements: define inputs/outputs, implement solution with complexity analysis, and include tests.\nConstraints: must be streaming-friendly, must include type hints, must handle Windows paths safely, must include docstrings.\nDifficulty: medium. Include a small CLI example if relevant.\n\nDeliverable: production-ready reference solution.\nProblem: compute rolling sums over events (ts:int,value:int) with window W seconds. Events may be out-of-order.\n\nComplexity: sorting O(n log n); window maintenance O(n); memory O(k).\n\n```python\nfrom __future__ import annotations\nfrom collections import deque\nfrom dataclasses import dataclass\nfrom typing import Iterable, List, Tuple\n\n@dataclass(frozen=True, slots=True)\nclass Event:\n ts: int\n value: int\n\ndef rolling_sum(events: Iterable[Event], window_s: int) -> List[Tuple[int,int]]:\n if window_s < 0:\n raise ValueError(\"window_s must be >= 0\")\n evs = sorted(events, key=lambda e: e.ts)\n q: deque[Event] = deque()\n s = 0\n out: List[Tuple[int,int]] = []\n for e in evs:\n q.append(e)\n s += e.value\n cutoff = e.ts - window_s\n while q and q[0].ts < cutoff:\n old = q.popleft()\n s -= old.value\n out.append((e.ts, s))\n return out\n```\n\n```python\nimport pytest\nfrom module_under_test import Event, rolling_sum\n\ndef test_rolling_sum():\n ev = [Event(10,1), Event(11,2), Event(20,5)]\n assert rolling_sum(ev, 5) == [(10,1),(11,3),(20,5)]\n```", "source": "WithinUsAI/python_GOD_coder_100k"} {"text": "Task type: program_synthesis_safe\nScenario: graph query service\nDomain focus: constraint solving\nPrimary language: python\nDifficulty: expert+\nScale/SLO: 99.99% availability\nComponent: component_cbdkkbdc\nConstraints: explicit contracts and invariants, include verification strategy, avoid data races and undefined behavior, include test vectors and fuzz strategy, include failure modes and recovery\nAssume hostile inputs and targeted abuse patterns.\nDeliverable: Design a program-synthesis workflow that generates code from specs safely; include guardrails and verification.\n\nOutput: rigorous design + invariants + verification plan + implementation sketch.\n**Contract**\n- Inputs validated at the boundary; explicit error taxonomy.\n- Idempotency for side effects via request_id; deterministic replay.\n- Backward compatibility: additive changes by default; versioned breaking changes.\n**Invariants**\n- Isolation: tenant boundary enforced; no cross-tenant reads/writes.\n- Safety: state transitions preserve invariants; no partial commit leaks.\n- Liveness: under bounded faults and stable network, progress occurs.\n**Failure modes & recovery**\n- Network partition: minority cannot commit; clients receive retriable errors.\n- Data corruption: checksums + scrubber; quarantine and rebuild from replicas/snapshots.\n- Crash during commit: WAL replay completes or transaction aborts; no torn writes.\n**Security posture (defensive)**\n- Threat model: auth/authz, injection, replay/abuse, supply chain.\n- Least privilege; secrets in managed store; audit logs for sensitive ops.\n- Input normalization, parameterized queries, path traversal protections.\n**Verification strategy**\n- Property tests against a pure reference model (state machine).\n- Canary + shadow traffic; invariants checked in production via assertions/metrics.\n- Deterministic simulation with fault injection (crash/partition/latency).\n\n**Snippet**\n```text\nImplementation sketch: factor pure state-machine core; adapters for I/O; add deterministic replay log.\n```\nExpert+ checks: mechanized invariants (or exhaustive model checking), adversarial fuzzing, and multi-region failure drills.", "source": "WithinUsAI/Omega_Genesis_Coder_100k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Optimize while preserving behavior.\n\nFile: eyecz22f5.py\n```python\ndef gfuwwbn1sxd(xs):\n out = []\n for x in xs:\n if x not in out:\n out.append(x)\n return out\n```\n\nRequirements: preserve first-seen order; O(n) average; add types + docstring.\n\n# eyecz22f5.py\nfrom __future__ import annotations\nfrom typing import Iterable, List, Set, TypeVar\n\nT = TypeVar(\"T\")\n\ndef gfuwwbn1sxd(xs: Iterable[T]) -> List[T]:\n \"\"\"Return unique items preserving first-seen order.\"\"\"\n seen: Set[T] = set()\n out: List[T] = []\n for x in xs:\n if x in seen:\n continue\n seen.add(x)\n out.append(x)\n return out", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Task type: gpu_serving_pipeline\nScenario: document indexing pipeline\nDomain focus: zero-downtime migrations\nPrimary language: bash\nDifficulty: expert\nScale/SLO: multi-region active-active\nComponent: component_puwtzacc\nConstraints: assume adversarial inputs; validate everything, include test vectors and fuzz strategy, include verification strategy, include security threat model (defensive only), include failure modes and recovery\nAssume weekly network partitions.\nDeliverable: Design a GPU inference serving pipeline: batching, scheduling, memory management, tail-latency control, and monitoring.\n\nOutput: elite engineering answer optimized for correctness, performance, and operability.\n**Contract**\n- Inputs validated at the boundary; explicit error taxonomy.\n- Idempotency for side effects via request_id; deterministic replay.\n- Backward compatibility: additive changes by default; versioned breaking changes.\n**Invariants**\n- Isolation: tenant boundary enforced; no cross-tenant reads/writes.\n- Liveness: under bounded faults and stable network, progress occurs.\n- Determinism: replay of the same event log yields identical outputs.\n**Failure modes & recovery**\n- Crash during commit: WAL replay completes or transaction aborts; no torn writes.\n- Duplicate requests: de-duplicate by (tenant, request_id) returning cached response.\n- Network partition: minority cannot commit; clients receive retriable errors.\n**Security posture (defensive)**\n- Threat model: auth/authz, injection, replay/abuse, supply chain.\n- Least privilege; secrets in managed store; audit logs for sensitive ops.\n- Input normalization, parameterized queries, path traversal protections.\n**Verification strategy**\n- Fuzzing of parsers/framers/validators with corpus seeds.\n- Canary + shadow traffic; invariants checked in production via assertions/metrics.\n- Deterministic simulation with fault injection (crash/partition/latency).\n\n**Snippet**\n```text\nImplementation sketch: factor pure state-machine core; adapters for I/O; add deterministic replay log.\n```\nExpert checks: state-machine proof sketch + model checking; upgrade/rollback rehearsed.", "source": "WithinUsAI/Omega_Genesis_Coder_100k"} {"text": "Refactor to typed, mostly-immutable Python and add minimal tests.\n\n```python\nclass C78175:\n def __init__(self, values): self.values=list(values)\n def mean(self): return sum(self.values)/len(self.values)\n```\nReturn `m44475.py` and `test_m44475.py`.\n\n```python\n# m44475.py\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom typing import Iterable, Tuple\n\n@dataclass(frozen=True)\nclass C78175:\n values: Tuple[float, ...]\n\n @staticmethod\n def create(values: Iterable[float]) -> \"C78175\":\n vals = tuple(float(v) for v in values)\n if not vals: raise ValueError(\"empty\")\n return C78175(vals)\n\n def mean(self) -> float:\n return sum(self.values)/len(self.values)\n```\n\n```python\n# test_m44475.py\nimport pytest\nfrom m44475 import C78175\n\ndef test_mean():\n assert C78175.create([1,2,3]).mean() == 2.0\ndef test_empty():\n with pytest.raises(ValueError):\n C78175.create([])\n```", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Implement a web feature for healthtech: background jobs.\nTarget platform: web (React + TypeScript).\nRequirements: accessible UI, API integration, and tests.\nConstraints: must be observable (logs/metrics/traces), must avoid global state, must include type hints where applicable.\nDifficulty: easy. Assume strict latency budget (p95 < 200ms).\n\nOutput: actionable implementation and verification artifacts.\nDeliverable: accessible React + TypeScript feature skeleton with tests.\n\n```tsx\n// Feature.tsx\nimport React, { useEffect, useMemo, useState } from \"react\";\n\ntype Item = { id: string; label: string };\n\nexport function Feature({ fetchItems }: { fetchItems: () => Promise }) {\n const [items, setItems] = useState([]);\n const [q, setQ] = useState(\"\");\n const filtered = useMemo(\n () => items.filter(i => i.label.toLowerCase().includes(q.toLowerCase())),\n [items, q]\n );\n\n useEffect(() => {\n let cancelled = false;\n fetchItems().then(xs => { if (!cancelled) setItems(xs); });\n return () => { cancelled = true; };\n }, [fetchItems]);\n\n return (\n
\n \n
    \n {filtered.map(i =>
  • {i.label}
  • )}\n
\n
\n );\n}\n```\n\n```tsx\n// Feature.test.tsx (vitest + testing-library)\nimport { render, screen } from \"@testing-library/react\";\nimport userEvent from \"@testing-library/user-event\";\nimport { Feature } from \"./Feature\";\n\ntest(\"filters items\", async () => {\n const fetchItems = async () => [{ id:\"1\", label:\"Alpha\" }, { id:\"2\", label:\"Beta\" }];\n render();\n expect(await screen.findByText(\"Alpha\")).toBeInTheDocument();\n await userEvent.type(screen.getByLabelText(\"Search\"), \"be\");\n expect(screen.queryByText(\"Alpha\")).toBeNull();\n expect(screen.getByText(\"Beta\")).toBeInTheDocument();\n});\n```\n\n\nChecks: input validation, tests, and safe defaults included.", "source": "WithinUsAI/GOD_Coder_100k"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: System domain: model serving gateway\nStack: Next.js, Node.js, Prisma, PostgreSQL, Playwright, Docker\nCross-layer incident: N+1 query explosion\nTask type: full_stack_bug_fix\nDifficulty: hard\n\nSolve this as a complete-project engineer.\nOutput must include:\n- root cause across layers\n- final implementation patch\n- tests touching at least two layers\n- deployment or observability note\n- verification commands\n\nRepository sketch:\nrepo/\n src/App/Program.cs\n src/App/Service.cs\n tests/App.Tests/ServiceTests.cs\n App.sln\n\nFocus: Focus on multi-layer debugging across frontend, backend, database, CI, caching, and deployment.\n\nassistant: Diagnosis:\n- Root cause: N+1 query explosion crosses service boundaries, so the fix must align code, contracts, tests, and deployment behavior.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```csharp\nusing System;\nusing System.Collections.Generic;\n\npublic static class RequestHandler\n{\n public static Dictionary HandleRequest(Dictionary payload)\n {\n var clean = new Dictionary();\n foreach (var entry in payload)\n {\n if (entry.Value != null)\n clean[entry.Key.Trim()] = entry.Value;\n }\n if (!clean.ContainsKey(\"id\"))\n throw new ArgumentException(\"missing id\");\n return new Dictionary\n {\n [\"ok\"] = true,\n [\"data\"] = clean\n };\n }\n}\n```\n\nTests:\n```csharp\nusing System;\nusing System.Collections.Generic;\nusing Xunit;\n\npublic class RequestHandlerTests\n{\n [Fact]\n public void RequiresId()\n {\n Assert.Throws(() => RequestHandler.HandleRequest(new Dictionary { [\"name\"] = \"x\" }));\n }\n}\n```\n\nVerification:\n- `dotnet test`\n- `dotnet build`\n\nEngineering notes:\n- Language: C#\n- Framework/tooling: ASP.NET Core\n- Stack context: Next.js, Node.js, Prisma, PostgreSQL, Playwright, Docker\n- Domain: model serving gateway\n- Task type: full_stack_bug_fix\n- Difficulty: hard\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: Language: Python\nFramework/tooling: SQLAlchemy\nDomain: payments platform\nLogic challenge: race condition on worker shutdown\nTask type: algorithmic_correctness\nDifficulty: hard\n\nReturn a rigorous engineering answer:\n- identify the hidden root cause or logical failure\n- present the corrected implementation\n- add tests that prove the fix\n- list verification commands\n- explain why naive fixes are insufficient when relevant\n\nRepository sketch:\nrepo/\n app/\n api.py\n service.py\n models.py\n tests/\n test_api.py\n pyproject.toml\n\nFocus: Focus on strong structured logic with edge cases, data validation, and concurrency safety.\n\nassistant: Diagnosis:\n- Root cause: the failure around race condition on worker shutdown is caused by missing validation, weak edge-case handling, or unsafe lifecycle behavior in the current implementation.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```python\nfrom __future__ import annotations\n\nfrom dataclasses import dataclass\nfrom typing import Any\n\n@dataclass\nclass ServiceResult:\n ok: bool\n data: dict[str, Any]\n error: str | None = None\n\ndef normalize_payload(payload: dict[str, Any]) -> dict[str, Any]:\n if not isinstance(payload, dict):\n raise TypeError(\"payload must be a dict\")\n clean: dict[str, Any] = {}\n for key, value in payload.items():\n if value is None:\n continue\n clean[str(key).strip()] = value\n return clean\n\ndef handle_race_condition_on_worker_shutdown(payload: dict[str, Any]) -> ServiceResult:\n clean = normalize_payload(payload)\n if \"id\" not in clean:\n return ServiceResult(ok=False, data={}, error=\"missing id\")\n return ServiceResult(ok=True, data=clean)\n```\n\nTests:\n```python\nimport pytest\nfrom app.service import handle_jwt_refresh_token_rotation as handler\n\ndef test_handler_accepts_valid_payload():\n result = handler({\"id\": 7, \"name\": \"ok\", \"unused\": None})\n assert result.ok is True\n assert result.data == {\"id\": 7, \"name\": \"ok\"}\n\ndef test_handler_rejects_missing_id():\n result = handler({\"name\": \"x\"})\n assert result.ok is False\n assert result.error == \"missing id\"\n```\n\nVerification:\n- `pytest -q`\n- `ruff check .`\n- `python -m compileall .`\n\nEngineering notes:\n- Language: Python\n- Framework/tooling: SQLAlchemy\n- Stack context: FastAPI, PostgreSQL, Redis, Celery, pytest, Docker\n- Domain: payments platform\n- Task type: algorithmic_correctness\n- Difficulty: hard\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Fix a bug and add tests.\n\nFile: z_c1fn6d2w.py\n```python\ndef q2w0tqfsqj(n: int) -> int:\n \"\"\"Sum 1..n inclusive.\"\"\"\n if n < 0:\n raise ValueError(\"n must be non-negative\")\n total = 0\n for k in range(n): # BUG: should include n\n total += k\n return total\n```\n\nReturn unified diffs for z_c1fn6d2w.py and test_z_c1fn6d2w.py (pytest).\n\n*** Begin Patch\n*** Update File: z_c1fn6d2w.py\n@@\n def q2w0tqfsqj(n: int) -> int:\n@@\n total = 0\n- for k in range(n): # BUG: should include n\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_z_c1fn6d2w.py\n+import pytest\n+from z_c1fn6d2w import q2w0tqfsqj\n+\n+def test_zero():\n+ assert q2w0tqfsqj(0) == 0\n+\n+def test_one():\n+ assert q2w0tqfsqj(1) == 1\n+\n+def test_small():\n+ assert q2w0tqfsqj(7) == 28\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ q2w0tqfsqj(-1)\n+\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: System domain: developer platform\nStack: Spring Boot, PostgreSQL, JUnit, Gradle, Docker, GitHub Actions\nCross-layer incident: rate-limit bypass\nTask type: auth_session_repair\nDifficulty: hard\n\nSolve this as a complete-project engineer.\nOutput must include:\n- root cause across layers\n- final implementation patch\n- tests touching at least two layers\n- deployment or observability note\n- verification commands\n\nRepository sketch:\nrepo/\n cmd/server/main.go\n internal/service/service.go\n internal/store/store.go\n internal/api/api.go\n service_test.go\n go.mod\n\nFocus: Focus on multi-layer debugging across frontend, backend, database, CI, caching, and deployment.\n\nassistant: Diagnosis:\n- Root cause: rate-limit bypass crosses service boundaries, so the fix must align code, contracts, tests, and deployment behavior.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```go\npackage service\n\nimport \"fmt\"\n\nfunc NormalizePayload(payload map[string]any) map[string]any {\n\tout := make(map[string]any)\n\tfor k, v := range payload {\n\t\tif v == nil {\n\t\t\tcontinue\n\t\t}\n\t\tout[k] = v\n\t}\n\treturn out\n}\n\nfunc Handle(payload map[string]any) (map[string]any, error) {\n\tclean := NormalizePayload(payload)\n\tif _, ok := clean[\"id\"]; !ok {\n\t\treturn nil, fmt.Errorf(\"missing id\")\n\t}\n\treturn map[string]any{\"ok\": true, \"data\": clean}, nil\n}\n```\n\nTests:\n```go\npackage service\n\nimport \"testing\"\n\nfunc TestHandle(t *testing.T) {\n\tgot, err := Handle(map[string]any{\"id\": 7, \"name\": \"ok\", \"unused\": nil})\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tif got[\"ok\"] != true {\n\t\tt.Fatalf(\"expected ok=true\")\n\t}\n\tif _, err := Handle(map[string]any{\"name\": \"x\"}); err == nil {\n\t\tt.Fatalf(\"expected missing id error\")\n\t}\n}\n```\n\nVerification:\n- `go test ./...`\n- `go vet ./...`\n\nEngineering notes:\n- Language: Go\n- Framework/tooling: net/http\n- Stack context: Spring Boot, PostgreSQL, JUnit, Gradle, Docker, GitHub Actions\n- Domain: developer platform\n- Task type: auth_session_repair\n- Difficulty: hard\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Optimize while preserving behavior.\n\nFile: jankv6skkr.py\n```python\ndef x3ip9he6nlm1(xs):\n out = []\n for x in xs:\n if x not in out:\n out.append(x)\n return out\n```\n\nRequirements: preserve first-seen order; O(n) average; add types + docstring.\n\n# jankv6skkr.py\nfrom __future__ import annotations\nfrom typing import Iterable, List, Set, TypeVar\n\nT = TypeVar(\"T\")\n\ndef x3ip9he6nlm1(xs: Iterable[T]) -> List[T]:\n \"\"\"Return unique items preserving first-seen order.\"\"\"\n seen: Set[T] = set()\n out: List[T] = []\n for x in xs:\n if x in seen:\n continue\n seen.add(x)\n out.append(x)\n return out", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Fix the bug and add pytest tests.\n\n```python\ndef f55979(n: int) -> int:\n # sum 1..n inclusive\n if n < 0: raise ValueError\n total = 0\n for k in range(n): # BUG\n total += k\n return total\n```\nReturn unified diffs for `m07997.py` and `test_m07997.py`.\n\n*** Begin Patch\n*** Update File: m07997.py\n@@\n def f55979(n: int) -> int:\n@@\n- for k in range(n): # BUG\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_m07997.py\n+import pytest\n+from m07997 import f55979\n+\n+def test_small():\n+ assert f55979(7) == 28\n+\n+def test_zero():\n+ assert f55979(0) == 0\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ f55979(-1)\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Refactor a Python module used for ETL pipelines into a clean, extensible design.\nRequirements: outline the new architecture briefly, then provide the refactored code and tests.\nConstraints: must include docstrings, must be streaming-friendly, must provide clear error messages, must handle Windows paths safely.\nDifficulty: easy. Provide helpful exceptions with actionable messages.\n\nDeliverable: production-ready reference solution.\nArchitecture:\n- Public facade class coordinating concerns (parsing, validation, persistence)\n- Small pure functions for testability\n- No global state; dependency injection for filesystem I/O\n\n```python\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom pathlib import Path\nfrom typing import Protocol, Iterable\nimport json\n\nclass Store(Protocol):\n def write_text(self, path: Path, data: str) -> None: ...\n\nclass FSStore:\n def write_text(self, path: Path, data: str) -> None:\n path.parent.mkdir(parents=True, exist_ok=True)\n path.write_text(data, encoding=\"utf-8\")\n\n@dataclass(frozen=True, slots=True)\nclass Item:\n name: str\n qty: int\n\ndef parse_items(lines: Iterable[str]) -> list[Item]:\n out: list[Item] = []\n for i, line in enumerate(lines, 1):\n s = line.strip()\n if not s:\n continue\n obj = json.loads(s)\n if not isinstance(obj, dict):\n raise ValueError(f\"line {i}: expected object\")\n name = obj.get(\"name\")\n qty = obj.get(\"qty\")\n if not isinstance(name, str) or not name:\n raise ValueError(f\"line {i}: name must be str\")\n if not isinstance(qty, int) or qty < 0:\n raise ValueError(f\"line {i}: qty must be non-negative int\")\n out.append(Item(name, qty))\n return out\n\nclass InventoryWriter:\n def __init__(self, base_dir: Path, store: Store | None = None) -> None:\n self._base = base_dir\n self._store: Store = store or FSStore()\n\n def write(self, rel_path: str, items: list[Item]) -> Path:\n dst = (self._base / rel_path).resolve()\n base = self._base.resolve()\n if dst != base and base not in dst.parents:\n raise ValueError(\"unsafe path traversal\")\n payload = json.dumps([item.__dict__ for item in items], ensure_ascii=False)\n self._store.write_text(dst, payload)\n return dst\n```\n\n```python\nimport json\nfrom pathlib import Path\nimport pytest\nfrom module_under_test import InventoryWriter, parse_items\n\ndef test_parse_items_valid():\n lines = [json.dumps({\"name\":\"x\",\"qty\":1})]\n assert parse_items(lines)[0].name == \"x\"\n\ndef test_writer_blocks_traversal(tmp_path: Path):\n w = InventoryWriter(tmp_path)\n with pytest.raises(ValueError):\n w.write(\"../evil.json\", [])\n```", "source": "WithinUsAI/python_GOD_coder_100k"} {"text": "Perform a code review for a healthtech PR implementing rate limiting.\nTarget platform: mobile (Android Kotlin).\nRequirements: list critical issues, improvements, and provide an improved patch excerpt.\nConstraints: must be observable (logs/metrics/traces), must avoid global state, must be secure-by-default.\nDifficulty: easy. Assume mobile clients are occasionally offline.\n\nOutput: design + implementation guidance suitable for shipping.\nDeliverable: code review findings + improved patch excerpt.\n\n**Critical issues**\n1. Missing input validation at boundary; potential unexpected exceptions.\n2. No idempotency / retry safety for side-effecting endpoint.\n3. No tests for edge cases (empty input, duplicates, timeouts).\n4. Observability gaps: no request_id correlation, no metrics.\n\n**Improvements**\n- Add strict validation and explicit error responses.\n- Add idempotency key support for create endpoints.\n- Add unit + integration tests with CI gating.\n- Add structured logs and basic metrics.\n\nPatch excerpt (illustrative):\n```python\nif not idem_key:\n raise HTTPException(400, \"Missing Idempotency-Key\")\n```\n\n\nChecks: input validation, tests, and safe defaults included.", "source": "WithinUsAI/GOD_Coder_100k"} {"text": "Task type: compiler_backend_ir\nScenario: real-time notification hub\nDomain focus: cryptography engineering (defensive)\nPrimary language: cpp\nDifficulty: expert\nScale/SLO: 99.99% availability\nComponent: component_hivmcouz\nConstraints: include failure modes and recovery, explicit contracts and invariants, include backward compatibility and migration plan, include security threat model (defensive only), include test vectors and fuzz strategy\nAssume partial data corruption; include scrubbing strategy.\nDeliverable: Design an IR and lowering pipeline; include an optimization pass and correctness checks. Provide minimal code skeleton and tests.\n\nOutput: contract-first solution with failure modes, security posture, and test/verification strategy.\n**Contract**\n- Inputs validated at the boundary; explicit error taxonomy.\n- Idempotency for side effects via request_id; deterministic replay.\n- Backward compatibility: additive changes by default; versioned breaking changes.\n**Invariants**\n- Safety: state transitions preserve invariants; no partial commit leaks.\n- Isolation: tenant boundary enforced; no cross-tenant reads/writes.\n- Determinism: replay of the same event log yields identical outputs.\n**Failure modes & recovery**\n- Duplicate requests: de-duplicate by (tenant, request_id) returning cached response.\n- Network partition: minority cannot commit; clients receive retriable errors.\n- Data corruption: checksums + scrubber; quarantine and rebuild from replicas/snapshots.\n**Security posture (defensive)**\n- Threat model: auth/authz, injection, replay/abuse, supply chain.\n- Least privilege; secrets in managed store; audit logs for sensitive ops.\n- Input normalization, parameterized queries, path traversal protections.\n**Verification strategy**\n- Canary + shadow traffic; invariants checked in production via assertions/metrics.\n- Property tests against a pure reference model (state machine).\n- Fuzzing of parsers/framers/validators with corpus seeds.\n\n**Snippet**\n```text\nImplementation sketch: factor pure state-machine core; adapters for I/O; add deterministic replay log.\n```\nExpert checks: state-machine proof sketch + model checking; upgrade/rollback rehearsed.", "source": "WithinUsAI/Omega_Genesis_Coder_100k"} {"text": "Fix the bug and add pytest tests.\n\n```python\ndef f67260(n: int) -> int:\n # sum 1..n inclusive\n if n < 0: raise ValueError\n total = 0\n for k in range(n): # BUG\n total += k\n return total\n```\nReturn unified diffs for `m38180.py` and `test_m38180.py`.\n\n*** Begin Patch\n*** Update File: m38180.py\n@@\n def f67260(n: int) -> int:\n@@\n- for k in range(n): # BUG\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_m38180.py\n+import pytest\n+from m38180 import f67260\n+\n+def test_small():\n+ assert f67260(7) == 28\n+\n+def test_zero():\n+ assert f67260(0) == 0\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ f67260(-1)\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Build an elite-grade solution in the domain of gpu compute for scenario: feature flagging.\nPrimary language: bash.\nDifficulty: medium.\nConstraints: avoid undefined behavior and data races, include tests or verification strategy, provide rollout and rollback guidance.\nComponent: component_mlczyqy.\nAssume partial network partitions occur weekly.\nTask: Write a precise interface contract, list invariants, and provide a lightweight formal/spec-style description (pseudo-TLA+/state machine) plus reference implementation skeleton and tests.\n\nOutput: rigorous solution with invariants, failure modes, and performance notes.\nOutput: contract + invariants + spec + reference skeleton.\n\n**Interface contract**\n- Commands: `Put(key, value, expected_version?)`, `Get(key)`, `Delete(key, expected_version?)`\n- Responses: `Ok(version, value?)`, `NotFound`, `Conflict(current_version)`, `InvalidInput`\n- Idempotency: client supplies `request_id`; server must de-duplicate per (tenant_id, request_id).\n\n**Invariants**\n1. Monotonic version per key (strictly increases on successful writes).\n2. Reads return latest committed value for a given consistency level.\n3. Exactly-once effect for a given `request_id` (at-most-once execution + replay response).\n4. Tenant isolation: keys are scoped by tenant_id.\n\n**State machine (pseudo)**\nState:\n- store: map[(tenant,key)] -> (version:int, value:bytes|tombstone)\n- seen: map[(tenant,request_id)] -> response\nTransition Put:\n- if request_id in seen: return seen[...]\n- validate input; if expected_version set and != current version -> Conflict\n- version' = version + 1; store[...] := (version', value); seen[...] := Ok(version', value)\n\n**Reference skeleton (Python)**\n```python\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom typing import Dict, Optional, Tuple\n\nclass Conflict(Exception): pass\nclass InvalidInput(ValueError): pass\n\n@dataclass(frozen=True, slots=True)\nclass Value:\n version: int\n data: Optional[bytes] # None == tombstone\n\n@dataclass(frozen=True, slots=True)\nclass Reply:\n kind: str\n version: Optional[int] = None\n data: Optional[bytes] = None\n\nclass KV:\n def __init__(self) -> None:\n self._store: Dict[Tuple[str,str], Value] = {}\n self._seen: Dict[Tuple[str,str], Reply] = {}\n\n def put(self, tenant: str, request_id: str, key: str, data: bytes, expected_version: Optional[int]=None) -> Reply:\n if not tenant or not request_id or not key:\n raise InvalidInput(\"tenant/request_id/key required\")\n de = self._seen.get((tenant, request_id))\n if de: \n return de\n cur = self._store.get((tenant, key), Value(0, None))\n if expected_version is not None and expected_version != cur.version:\n r = Reply(\"conflict\", version=cur.version)\n self._seen[(tenant, request_id)] = r\n return r\n nxt = Value(cur.version + 1, data)\n self._store[(tenant, key)] = nxt\n r = Reply(\"ok\", version=nxt.version)\n self._seen[(tenant, request_id)] = r\n return r\n```\n\n**Tests**\n- Determinism: same request_id → same reply.\n- Conflict detection and version monotonicity.\n\n\nChecks: boundary validation and deterministic behavior verified.", "source": "WithinUsAI/Elite_GOD_Coder_100k"} {"text": "Design a small, production-grade Python API for CLI tooling.\nRequirements: define data models and interfaces, implement reference version, include tests.\nConstraints: must be memory-efficient, must avoid global state, must be streaming-friendly.\nDifficulty: medium. Guarantee deterministic output ordering.\n\nDeliverable: API + reference implementation + tests.\nArchitecture:\n- Public facade class coordinating concerns (parsing, validation, persistence)\n- Small pure functions for testability\n- No global state; dependency injection for filesystem I/O\n\n```python\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom pathlib import Path\nfrom typing import Protocol, Iterable\nimport json\n\nclass Store(Protocol):\n def write_text(self, path: Path, data: str) -> None: ...\n\nclass FSStore:\n def write_text(self, path: Path, data: str) -> None:\n path.parent.mkdir(parents=True, exist_ok=True)\n path.write_text(data, encoding=\"utf-8\")\n\n@dataclass(frozen=True, slots=True)\nclass Item:\n name: str\n qty: int\n\ndef parse_items(lines: Iterable[str]) -> list[Item]:\n out: list[Item] = []\n for i, line in enumerate(lines, 1):\n s = line.strip()\n if not s:\n continue\n obj = json.loads(s)\n if not isinstance(obj, dict):\n raise ValueError(f\"line {i}: expected object\")\n name = obj.get(\"name\")\n qty = obj.get(\"qty\")\n if not isinstance(name, str) or not name:\n raise ValueError(f\"line {i}: name must be str\")\n if not isinstance(qty, int) or qty < 0:\n raise ValueError(f\"line {i}: qty must be non-negative int\")\n out.append(Item(name, qty))\n return out\n\nclass InventoryWriter:\n def __init__(self, base_dir: Path, store: Store | None = None) -> None:\n self._base = base_dir\n self._store: Store = store or FSStore()\n\n def write(self, rel_path: str, items: list[Item]) -> Path:\n dst = (self._base / rel_path).resolve()\n base = self._base.resolve()\n if dst != base and base not in dst.parents:\n raise ValueError(\"unsafe path traversal\")\n payload = json.dumps([item.__dict__ for item in items], ensure_ascii=False)\n self._store.write_text(dst, payload)\n return dst\n```\n\n```python\nimport json\nfrom pathlib import Path\nimport pytest\nfrom module_under_test import InventoryWriter, parse_items\n\ndef test_parse_items_valid():\n lines = [json.dumps({\"name\":\"x\",\"qty\":1})]\n assert parse_items(lines)[0].name == \"x\"\n\ndef test_writer_blocks_traversal(tmp_path: Path):\n w = InventoryWriter(tmp_path)\n with pytest.raises(ValueError):\n w.write(\"../evil.json\", [])\n```", "source": "WithinUsAI/python_GOD_coder_100k"} {"text": "Implement a concurrent Python solution for caching layer.\nRequirements: choose appropriate concurrency model, handle cancellation/timeouts, include tests.\nConstraints: must provide clear error messages, stdlib-only.\nDifficulty: hard. Handle empty inputs and malformed records gracefully.\n\nDeliverable: production-ready reference solution.\n```python\nfrom __future__ import annotations\nimport asyncio\nfrom dataclasses import dataclass\nfrom typing import Awaitable, Callable, Iterable, Optional\n\n@dataclass(frozen=True, slots=True)\nclass JobResult:\n ok: bool\n value: Optional[int]\n error: Optional[str]\n\nasync def run_bounded(\n factories: Iterable[Callable[[], Awaitable[int]]],\n *,\n limit: int = 10,\n timeout_s: float = 5.0,\n) -> list[JobResult]:\n if limit <= 0:\n raise ValueError(\"limit must be > 0\")\n sem = asyncio.Semaphore(limit)\n results: list[JobResult] = []\n\n async def one(factory: Callable[[], Awaitable[int]]) -> None:\n async with sem:\n try:\n v = await asyncio.wait_for(factory(), timeout=timeout_s)\n results.append(JobResult(True, v, None))\n except Exception as e:\n results.append(JobResult(False, None, str(e)))\n\n tasks = [asyncio.create_task(one(f)) for f in factories]\n try:\n await asyncio.gather(*tasks)\n finally:\n for t in tasks:\n if not t.done():\n t.cancel()\n return results\n```\n\n```python\nimport asyncio\nimport pytest\nfrom module_under_test import run_bounded\n\n@pytest.mark.asyncio\nasync def test_run_bounded_collects():\n async def work(x: int) -> int:\n await asyncio.sleep(0.01)\n return x\n fs = [(lambda i=i: work(i)) for i in range(30)]\n out = await run_bounded(fs, limit=5, timeout_s=1.0)\n assert len(out) == 30\n assert all(r.ok for r in out)\n```", "source": "WithinUsAI/python_GOD_coder_100k"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: Repository domain: job scheduler\nPrimary language: YAML\nFramework/tooling: Helm\nReported problem: migration ordering failure\nTask type: performance_patch\nDifficulty: medium\n\nProduce a complete professional engineering response:\n1. Diagnose the root cause.\n2. Provide the corrected implementation or patch.\n3. Add tests.\n4. Add verification commands.\n5. Note edge cases and any migration or rollback risk.\n\nRepository sketch:\nrepo/\n .github/workflows/ci.yml\n docker-compose.yml\n deploy/\n app.yaml\n\nQuality target:\n- Minimal diff unless redesign is clearly required\n- Production-ready code\n- No placeholders\n- Secure defaults\n- Clear acceptance of failure cases\n\nFocus: Focus on complete implementation quality, patch correctness, tests, and production readiness.\n\nassistant: Diagnosis:\n- Root cause: the failure around migration ordering failure is caused by missing validation, weak edge-case handling, or unsafe lifecycle behavior in the current implementation.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```yaml\nname: ci\non: [push, pull_request]\njobs:\n test:\n runs-on: ubuntu-latest\n steps:\n - uses: actions/checkout@v4\n - name: Validate\n run: echo \"validated\"\n```\n\nTests:\n```yaml\n# Verification:\n# - validate syntax\n# - run smoke workflow\n# - fail fast on broken config\n```\n\nVerification:\n- `validate workflow syntax`\n- `run CI smoke job`\n\nEngineering notes:\n- Language: YAML\n- Framework/tooling: Helm\n- Stack context: Airflow, dbt, DuckDB, MinIO, pytest\n- Domain: job scheduler\n- Task type: performance_patch\n- Difficulty: medium\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "Fix a subtle bug in a Python module used for configuration loading.\nRequirements: explain root cause briefly, provide corrected code, and add regression tests.\nConstraints: must provide clear error messages, must include tests.\nDifficulty: expert. Include a small CLI example if relevant.\n\nDeliverable: API + reference implementation + tests.\n```python\nfrom __future__ import annotations\n\nfrom dataclasses import dataclass\nfrom pathlib import Path\nfrom typing import Iterable\nimport json\n\n\nclass ValidationError(ValueError):\n \"\"\"Raised when input validation fails.\"\"\"\n\n\ndef safe_join(base: Path, *parts: str) -> Path:\n \"\"\"Join paths while preventing traversal outside base.\"\"\"\n b = base.resolve()\n p = (b / Path(*parts)).resolve()\n if p != b and b not in p.parents:\n raise ValidationError(f\"unsafe path: {p}\")\n return p\n\n\n@dataclass(frozen=True, slots=True)\nclass Record:\n key: str\n value: int\n\n\ndef parse_jsonl(lines: Iterable[str]) -> list[Record]:\n out: list[Record] = []\n for idx, line in enumerate(lines, 1):\n s = line.strip()\n if not s:\n continue\n try:\n obj = json.loads(s)\n except json.JSONDecodeError as e:\n raise ValidationError(f\"line {idx}: invalid json\") from e\n if not isinstance(obj, dict):\n raise ValidationError(f\"line {idx}: expected object\")\n key = obj.get(\"key\")\n val = obj.get(\"value\")\n if not isinstance(key, str) or not key:\n raise ValidationError(f\"line {idx}: key must be non-empty str\")\n if not isinstance(val, int):\n raise ValidationError(f\"line {idx}: value must be int\")\n out.append(Record(key, val))\n return out\n\n\ndef write_jsonl(base: Path, rel: str, records: Iterable[Record]) -> Path:\n base.mkdir(parents=True, exist_ok=True)\n dst = safe_join(base, rel)\n dst.parent.mkdir(parents=True, exist_ok=True)\n with dst.open(\"w\", encoding=\"utf-8\", newline=\"\\n\") as f:\n for r in records:\n f.write(json.dumps({\"key\": r.key, \"value\": r.value}, ensure_ascii=False) + \"\\n\")\n return dst\n```\n\n```python\n# tests (pytest-style)\nimport json\nfrom pathlib import Path\nimport pytest\nfrom module_under_test import ValidationError, Record, parse_jsonl, write_jsonl\n\ndef test_parse_ok():\n lines = [json.dumps({\"key\":\"a\",\"value\":1}), json.dumps({\"key\":\"b\",\"value\":2})]\n assert parse_jsonl(lines) == [Record(\"a\",1), Record(\"b\",2)]\n\ndef test_parse_rejects_bad_json():\n with pytest.raises(ValidationError):\n parse_jsonl([\"{not json}\"])\n\ndef test_safe_join_blocks_traversal(tmp_path: Path):\n with pytest.raises(ValidationError):\n write_jsonl(tmp_path, \"../x.jsonl\", [Record(\"a\",1)])\n```", "source": "WithinUsAI/python_GOD_coder_100k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Fix a bug and add tests.\n\nFile: a2hsh4ne_.py\n```python\ndef gn7u3jbowbk(n: int) -> int:\n \"\"\"Sum 1..n inclusive.\"\"\"\n if n < 0:\n raise ValueError(\"n must be non-negative\")\n total = 0\n for k in range(n): # BUG: should include n\n total += k\n return total\n```\n\nReturn unified diffs for a2hsh4ne_.py and test_a2hsh4ne_.py (pytest).\n\n*** Begin Patch\n*** Update File: a2hsh4ne_.py\n@@\n def gn7u3jbowbk(n: int) -> int:\n@@\n total = 0\n- for k in range(n): # BUG: should include n\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_a2hsh4ne_.py\n+import pytest\n+from a2hsh4ne_ import gn7u3jbowbk\n+\n+def test_zero():\n+ assert gn7u3jbowbk(0) == 0\n+\n+def test_one():\n+ assert gn7u3jbowbk(1) == 1\n+\n+def test_small():\n+ assert gn7u3jbowbk(7) == 28\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ gn7u3jbowbk(-1)\n+\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Implement a web feature for logistics: rate limiting.\nTarget platform: web (React + TypeScript).\nRequirements: accessible UI, API integration, and tests.\nConstraints: must be observable (logs/metrics/traces), must include tests, must include clear error handling, must be easy to extend, must be performant under load.\nDifficulty: easy. Assume PII must be protected.\n\nOutput: actionable implementation and verification artifacts.\nDeliverable: accessible React + TypeScript feature skeleton with tests.\n\n```tsx\n// Feature.tsx\nimport React, { useEffect, useMemo, useState } from \"react\";\n\ntype Item = { id: string; label: string };\n\nexport function Feature({ fetchItems }: { fetchItems: () => Promise }) {\n const [items, setItems] = useState([]);\n const [q, setQ] = useState(\"\");\n const filtered = useMemo(\n () => items.filter(i => i.label.toLowerCase().includes(q.toLowerCase())),\n [items, q]\n );\n\n useEffect(() => {\n let cancelled = false;\n fetchItems().then(xs => { if (!cancelled) setItems(xs); });\n return () => { cancelled = true; };\n }, [fetchItems]);\n\n return (\n
\n \n
    \n {filtered.map(i =>
  • {i.label}
  • )}\n
\n
\n );\n}\n```\n\n```tsx\n// Feature.test.tsx (vitest + testing-library)\nimport { render, screen } from \"@testing-library/react\";\nimport userEvent from \"@testing-library/user-event\";\nimport { Feature } from \"./Feature\";\n\ntest(\"filters items\", async () => {\n const fetchItems = async () => [{ id:\"1\", label:\"Alpha\" }, { id:\"2\", label:\"Beta\" }];\n render();\n expect(await screen.findByText(\"Alpha\")).toBeInTheDocument();\n await userEvent.type(screen.getByLabelText(\"Search\"), \"be\");\n expect(screen.queryByText(\"Alpha\")).toBeNull();\n expect(screen.getByText(\"Beta\")).toBeInTheDocument();\n});\n```\n\n\nChecks: input validation, tests, and safe defaults included.", "source": "WithinUsAI/GOD_Coder_100k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Refactor to modern typed Python with immutability and tests.\n\nFile: qvz6xg2z.py\n```python\nclass Dgkrth33Oc9:\n def __init__(self, name, values):\n self.name = name\n self.values = list(values)\n def add(self, v):\n self.values.append(v)\n def mean(self):\n s = 0\n for x in self.values:\n s += x\n return s / len(self.values)\n```\n\nReturn full new qvz6xg2z.py and test_qvz6xg2z.py.\n\n# qvz6xg2z.py\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom typing import Iterable, Tuple\n\n@dataclass(frozen=True)\nclass Dgkrth33Oc9:\n name: str\n values: Tuple[float, ...]\n\n @staticmethod\n def create(name: str, values: Iterable[float]) -> \"Dgkrth33Oc9\":\n vals = tuple(float(v) for v in values)\n if not vals:\n raise ValueError(\"values must be non-empty\")\n return Dgkrth33Oc9(name=name, values=vals)\n\n def add(self, v: float) -> \"Dgkrth33Oc9\":\n return Dgkrth33Oc9(name=self.name, values=self.values + (float(v),))\n\n def mean(self) -> float:\n return sum(self.values) / len(self.values)\n\n# test_qvz6xg2z.py\nimport pytest\nfrom qvz6xg2z import Dgkrth33Oc9\n\ndef test_mean_and_add():\n c = Dgkrth33Oc9.create(\"a\", [1, 2, 3])\n assert c.mean() == 2.0\n assert c.add(5).mean() == (1 + 2 + 3 + 5) / 4\n\ndef test_empty_raises():\n with pytest.raises(ValueError):\n Dgkrth33Oc9.create(\"x\", [])", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: Repository domain: benchmark harness\nPrimary language: SQL\nFramework/tooling: PostgreSQL\nReported problem: invalid rollback sequence\nTask type: test_repair\nDifficulty: hard\n\nProduce a complete professional engineering response:\n1. Diagnose the root cause.\n2. Provide the corrected implementation or patch.\n3. Add tests.\n4. Add verification commands.\n5. Note edge cases and any migration or rollback risk.\n\nRepository sketch:\nrepo/\n migrations/\n 001_init.sql\n 002_add_index.sql\n queries/\n report.sql\n tests/\n report_cases.md\n\nQuality target:\n- Minimal diff unless redesign is clearly required\n- Production-ready code\n- No placeholders\n- Secure defaults\n- Clear acceptance of failure cases\n\nFocus: Focus on complete implementation quality, patch correctness, tests, and production readiness.\n\nassistant: Diagnosis:\n- Root cause: the failure around invalid rollback sequence is caused by missing validation, weak edge-case handling, or unsafe lifecycle behavior in the current implementation.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```sql\nWITH ranked AS (\n SELECT\n user_id,\n created_at,\n amount,\n ROW_NUMBER() OVER (PARTITION BY user_id ORDER BY created_at DESC, id DESC) AS rn\n FROM orders\n)\nSELECT user_id, created_at, amount\nFROM ranked\nWHERE rn = 1;\n```\n\nTests:\n```sql\n-- Correctness checks:\n-- 1) multiple rows per user\n-- 2) identical timestamps require deterministic tie-breaker\n-- 3) null values handled by business rules\n```\n\nVerification:\n- `run migration checks`\n- `run query correctness cases`\n\nEngineering notes:\n- Language: SQL\n- Framework/tooling: PostgreSQL\n- Stack context: Go, Gin, PostgreSQL, gRPC, Prometheus, Docker\n- Domain: benchmark harness\n- Task type: test_repair\n- Difficulty: hard\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Fix a bug and add tests.\n\nFile: nslzag1.py\n```python\ndef doshds(n: int) -> int:\n \"\"\"Sum 1..n inclusive.\"\"\"\n if n < 0:\n raise ValueError(\"n must be non-negative\")\n total = 0\n for k in range(n): # BUG: should include n\n total += k\n return total\n```\n\nReturn unified diffs for nslzag1.py and test_nslzag1.py (pytest).\n\n*** Begin Patch\n*** Update File: nslzag1.py\n@@\n def doshds(n: int) -> int:\n@@\n total = 0\n- for k in range(n): # BUG: should include n\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_nslzag1.py\n+import pytest\n+from nslzag1 import doshds\n+\n+def test_zero():\n+ assert doshds(0) == 0\n+\n+def test_one():\n+ assert doshds(1) == 1\n+\n+def test_small():\n+ assert doshds(7) == 28\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ doshds(-1)\n+\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Fix the bug and add pytest tests.\n\n```python\ndef f75879(n: int) -> int:\n # sum 1..n inclusive\n if n < 0: raise ValueError\n total = 0\n for k in range(n): # BUG\n total += k\n return total\n```\nReturn unified diffs for `m53697.py` and `test_m53697.py`.\n\n*** Begin Patch\n*** Update File: m53697.py\n@@\n def f75879(n: int) -> int:\n@@\n- for k in range(n): # BUG\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_m53697.py\n+import pytest\n+from m53697 import f75879\n+\n+def test_small():\n+ assert f75879(7) == 28\n+\n+def test_zero():\n+ assert f75879(0) == 0\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ f75879(-1)\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Task type: query_optimizer\nScenario: payment ledger\nDomain focus: network protocols\nPrimary language: sql\nDifficulty: hard\nScale/SLO: multi-region active-active\nComponent: component_rbhadyfb\nConstraints: explicit contracts and invariants, avoid data races and undefined behavior, include performance model and limits, assume adversarial inputs; validate everything, include backward compatibility and migration plan, include verification strategy\nAssume weekly network partitions.\nDeliverable: Design a cost-based optimizer slice: logical rules, physical operators, and cost model. Include regression tests and query-plan explain examples.\n\nOutput: contract-first solution with failure modes, security posture, and test/verification strategy.\n**Contract**\n- Inputs validated at the boundary; explicit error taxonomy.\n- Idempotency for side effects via request_id; deterministic replay.\n- Backward compatibility: additive changes by default; versioned breaking changes.\n**Invariants**\n- Isolation: tenant boundary enforced; no cross-tenant reads/writes.\n- Safety: state transitions preserve invariants; no partial commit leaks.\n- Determinism: replay of the same event log yields identical outputs.\n**Failure modes & recovery**\n- Crash during commit: WAL replay completes or transaction aborts; no torn writes.\n- Duplicate requests: de-duplicate by (tenant, request_id) returning cached response.\n- Network partition: minority cannot commit; clients receive retriable errors.\n**Security posture (defensive)**\n- Threat model: auth/authz, injection, replay/abuse, supply chain.\n- Least privilege; secrets in managed store; audit logs for sensitive ops.\n- Input normalization, parameterized queries, path traversal protections.\n**Verification strategy**\n- Canary + shadow traffic; invariants checked in production via assertions/metrics.\n- Property tests against a pure reference model (state machine).\n- Deterministic simulation with fault injection (crash/partition/latency).\n\n**Snippet**\n```python\n# Minimal cost model skeleton\nfrom dataclasses import dataclass\n\n@dataclass(frozen=True)\nclass Plan:\n op: str\n cost: float\n children: tuple[\"Plan\", ...] = ()\n\ndef choose_best(plans: list[Plan]) -> Plan:\n return min(plans, key=lambda p: p.cost)\n```\n\nHard checks: fault injection tests gate merges; perf thresholds enforced in CI.", "source": "WithinUsAI/Omega_Genesis_Coder_100k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Optimize while preserving behavior.\n\nFile: jjfrku6.py\n```python\ndef a0wo26p_b(xs):\n out = []\n for x in xs:\n if x not in out:\n out.append(x)\n return out\n```\n\nRequirements: preserve first-seen order; O(n) average; add types + docstring.\n\n# jjfrku6.py\nfrom __future__ import annotations\nfrom typing import Iterable, List, Set, TypeVar\n\nT = TypeVar(\"T\")\n\ndef a0wo26p_b(xs: Iterable[T]) -> List[T]:\n \"\"\"Return unique items preserving first-seen order.\"\"\"\n seen: Set[T] = set()\n out: List[T] = []\n for x in xs:\n if x in seen:\n continue\n seen.add(x)\n out.append(x)\n return out", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: Repository domain: team dashboard\nPrimary language: Python\nFramework/tooling: Django\nReported problem: rate-limit bypass\nTask type: feature_delivery\nDifficulty: hard\n\nProduce a complete professional engineering response:\n1. Diagnose the root cause.\n2. Provide the corrected implementation or patch.\n3. Add tests.\n4. Add verification commands.\n5. Note edge cases and any migration or rollback risk.\n\nRepository sketch:\nrepo/\n app/\n api.py\n service.py\n models.py\n tests/\n test_api.py\n pyproject.toml\n\nQuality target:\n- Minimal diff unless redesign is clearly required\n- Production-ready code\n- No placeholders\n- Secure defaults\n- Clear acceptance of failure cases\n\nFocus: Focus on complete implementation quality, patch correctness, tests, and production readiness.\n\nassistant: Diagnosis:\n- Root cause: the failure around rate-limit bypass is caused by missing validation, weak edge-case handling, or unsafe lifecycle behavior in the current implementation.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```python\nfrom __future__ import annotations\n\nfrom dataclasses import dataclass\nfrom typing import Any\n\n@dataclass\nclass ServiceResult:\n ok: bool\n data: dict[str, Any]\n error: str | None = None\n\ndef normalize_payload(payload: dict[str, Any]) -> dict[str, Any]:\n if not isinstance(payload, dict):\n raise TypeError(\"payload must be a dict\")\n clean: dict[str, Any] = {}\n for key, value in payload.items():\n if value is None:\n continue\n clean[str(key).strip()] = value\n return clean\n\ndef handle_rate_limit_bypass(payload: dict[str, Any]) -> ServiceResult:\n clean = normalize_payload(payload)\n if \"id\" not in clean:\n return ServiceResult(ok=False, data={}, error=\"missing id\")\n return ServiceResult(ok=True, data=clean)\n```\n\nTests:\n```python\nimport pytest\nfrom app.service import handle_jwt_refresh_token_rotation as handler\n\ndef test_handler_accepts_valid_payload():\n result = handler({\"id\": 7, \"name\": \"ok\", \"unused\": None})\n assert result.ok is True\n assert result.data == {\"id\": 7, \"name\": \"ok\"}\n\ndef test_handler_rejects_missing_id():\n result = handler({\"name\": \"x\"})\n assert result.ok is False\n assert result.error == \"missing id\"\n```\n\nVerification:\n- `pytest -q`\n- `ruff check .`\n- `python -m compileall .`\n\nEngineering notes:\n- Language: Python\n- Framework/tooling: Django\n- Stack context: Go, Gin, PostgreSQL, gRPC, Prometheus, Docker\n- Domain: team dashboard\n- Task type: feature_delivery\n- Difficulty: hard\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: System domain: job scheduler\nStack: Next.js, Node.js, Prisma, PostgreSQL, Playwright, Docker\nCross-layer incident: websocket reconnect storm\nTask type: observability_debug_fix\nDifficulty: hard\n\nSolve this as a complete-project engineer.\nOutput must include:\n- root cause across layers\n- final implementation patch\n- tests touching at least two layers\n- deployment or observability note\n- verification commands\n\nRepository sketch:\nrepo/\n src/main/java/com/acme/App.java\n src/main/java/com/acme/Service.java\n src/test/java/com/acme/AppTest.java\n pom.xml\n\nFocus: Focus on multi-layer debugging across frontend, backend, database, CI, caching, and deployment.\n\nassistant: Diagnosis:\n- Root cause: websocket reconnect storm crosses service boundaries, so the fix must align code, contracts, tests, and deployment behavior.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```java\nimport java.util.HashMap;\nimport java.util.Map;\n\npublic final class RequestHandler {\n public static Map handleRequest(Map payload) {\n Map clean = new HashMap<>();\n for (Map.Entry entry : payload.entrySet()) {\n if (entry.getValue() != null) clean.put(entry.getKey().trim(), entry.getValue());\n }\n if (!clean.containsKey(\"id\")) throw new IllegalArgumentException(\"missing id\");\n return Map.of(\"ok\", true, \"data\", clean);\n }\n}\n```\n\nTests:\n```java\nimport static org.junit.jupiter.api.Assertions.*;\nimport java.util.Map;\nimport org.junit.jupiter.api.Test;\n\nclass RequestHandlerTest {\n @Test\n void requiresId() {\n assertThrows(IllegalArgumentException.class, () -> RequestHandler.handleRequest(Map.of(\"name\", \"x\")));\n }\n}\n```\n\nVerification:\n- `./gradlew test`\n- `mvn test`\n\nEngineering notes:\n- Language: Java\n- Framework/tooling: Maven\n- Stack context: Next.js, Node.js, Prisma, PostgreSQL, Playwright, Docker\n- Domain: job scheduler\n- Task type: observability_debug_fix\n- Difficulty: hard\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "Build an elite-grade solution in the domain of distributed systems for scenario: inventory & ordering.\nPrimary language: sql.\nDifficulty: expert.\nConstraints: avoid undefined behavior and data races, include tests or verification strategy, provide rollout and rollback guidance.\nComponent: component_snpsalc.\nAssume crash-only design; recovery must be deterministic.\nTask: Optimize a hot path with profiling-driven approach; propose micro/meso optimizations, and supply a benchmark harness with acceptance thresholds.\n\nOutput: production blueprint plus correctness arguments and test strategy.\nOutput: profiling-first optimization + benchmark harness.\n\n**Plan**\n1. Establish baseline with microbench + representative dataset.\n2. Profile (CPU, allocations, syscalls).\n3. Apply optimizations: reduce allocations, reuse buffers, batch I/O, vectorize parsing where safe.\n4. Validate with regression suite and perf thresholds.\n\n**Benchmark guidance**\n- Use p50/p95 and throughput; pin CPU frequency if possible.\n- Acceptance: p95 improves ≥ X% with no correctness regressions.\n\n\nExpert checks: state-machine reasoning, concurrency stress, and upgrade/rollback validated.", "source": "WithinUsAI/Elite_GOD_Coder_100k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Optimize while preserving behavior.\n\nFile: osfwyu.py\n```python\ndef rr5t13p5w(xs):\n out = []\n for x in xs:\n if x not in out:\n out.append(x)\n return out\n```\n\nRequirements: preserve first-seen order; O(n) average; add types + docstring.\n\n# osfwyu.py\nfrom __future__ import annotations\nfrom typing import Iterable, List, Set, TypeVar\n\nT = TypeVar(\"T\")\n\ndef rr5t13p5w(xs: Iterable[T]) -> List[T]:\n \"\"\"Return unique items preserving first-seen order.\"\"\"\n seen: Set[T] = set()\n out: List[T] = []\n for x in xs:\n if x in seen:\n continue\n seen.add(x)\n out.append(x)\n return out", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Fix a subtle bug in a Python module used for metrics aggregation.\nRequirements: explain root cause briefly, provide corrected code, and add regression tests.\nConstraints: must be memory-efficient, must include tests.\nDifficulty: expert. Include a small CLI example if relevant.\n\nDeliverable: API + reference implementation + tests.\n```python\nfrom __future__ import annotations\n\nfrom dataclasses import dataclass\nfrom pathlib import Path\nfrom typing import Iterable\nimport json\n\n\nclass ValidationError(ValueError):\n \"\"\"Raised when input validation fails.\"\"\"\n\n\ndef safe_join(base: Path, *parts: str) -> Path:\n \"\"\"Join paths while preventing traversal outside base.\"\"\"\n b = base.resolve()\n p = (b / Path(*parts)).resolve()\n if p != b and b not in p.parents:\n raise ValidationError(f\"unsafe path: {p}\")\n return p\n\n\n@dataclass(frozen=True, slots=True)\nclass Record:\n key: str\n value: int\n\n\ndef parse_jsonl(lines: Iterable[str]) -> list[Record]:\n out: list[Record] = []\n for idx, line in enumerate(lines, 1):\n s = line.strip()\n if not s:\n continue\n try:\n obj = json.loads(s)\n except json.JSONDecodeError as e:\n raise ValidationError(f\"line {idx}: invalid json\") from e\n if not isinstance(obj, dict):\n raise ValidationError(f\"line {idx}: expected object\")\n key = obj.get(\"key\")\n val = obj.get(\"value\")\n if not isinstance(key, str) or not key:\n raise ValidationError(f\"line {idx}: key must be non-empty str\")\n if not isinstance(val, int):\n raise ValidationError(f\"line {idx}: value must be int\")\n out.append(Record(key, val))\n return out\n\n\ndef write_jsonl(base: Path, rel: str, records: Iterable[Record]) -> Path:\n base.mkdir(parents=True, exist_ok=True)\n dst = safe_join(base, rel)\n dst.parent.mkdir(parents=True, exist_ok=True)\n with dst.open(\"w\", encoding=\"utf-8\", newline=\"\\n\") as f:\n for r in records:\n f.write(json.dumps({\"key\": r.key, \"value\": r.value}, ensure_ascii=False) + \"\\n\")\n return dst\n```\n\n```python\n# tests (pytest-style)\nimport json\nfrom pathlib import Path\nimport pytest\nfrom module_under_test import ValidationError, Record, parse_jsonl, write_jsonl\n\ndef test_parse_ok():\n lines = [json.dumps({\"key\":\"a\",\"value\":1}), json.dumps({\"key\":\"b\",\"value\":2})]\n assert parse_jsonl(lines) == [Record(\"a\",1), Record(\"b\",2)]\n\ndef test_parse_rejects_bad_json():\n with pytest.raises(ValidationError):\n parse_jsonl([\"{not json}\"])\n\ndef test_safe_join_blocks_traversal(tmp_path: Path):\n with pytest.raises(ValidationError):\n write_jsonl(tmp_path, \"../x.jsonl\", [Record(\"a\",1)])\n```", "source": "WithinUsAI/python_GOD_coder_100k"} {"text": "Build an elite-grade solution in the domain of security engineering (defensive) for scenario: payment processing.\nPrimary language: go.\nDifficulty: hard.\nConstraints: include invariants and failure modes, include tests or verification strategy, avoid undefined behavior and data races.\nComponent: component_zmhfatt.\nAssume partial network partitions occur weekly.\nTask: Implement a concurrency primitive or subsystem (lock-free queue, thread pool, async runtime component). Explain memory ordering and correctness arguments; include stress tests.\n\nOutput: rigorous solution with invariants, failure modes, and performance notes.\nOutput: correctness-focused concurrency primitive + stress tests.\n\n**Primitive**\n- Bounded MPMC queue with backpressure (blocking push/pop) OR lock-free SPSC ring buffer.\n\n**Correctness notes**\n- For lock-free: use acquire/release semantics on head/tail indices.\n- Avoid ABA by monotonic counters; ring index = counter % capacity.\n\n**Stress tests**\n- Multi-thread producers/consumers; assert item multiset preserved.\n- Use time-bounded randomized schedules; detect deadlocks.\n\n\nHard checks: failure injection tests and performance regressions gated.", "source": "WithinUsAI/Elite_GOD_Coder_100k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Produce an offline-first self-evolving code assistant architecture named `uxd088`.\nMust include: module layout, patch-safety policy, evaluation gates (tests/lint/types), versioned memory index.\n\nArchitecture: `uxd088` (offline-first, self-evolving)\n\nModules\n- core/loop.py: evolve → validate → accept/reject (bounded iterations)\n- patching/: diff builder, safe apply, atomic writes, rollback points\n- policy/: allowlist paths, deny globs (.git/, __pycache__/, binaries), patch size caps\n- signals/: parse pytest/ruff/mypy into normalized findings\n- memory/index.jsonl: append-only snapshots (hashes, metrics, rationale)\n\nSafety gates\n- refuse path traversal/symlink escapes; never edit binaries\n- accept only if tests/lint/types stay green or improve", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: Language: C#\nFramework/tooling: EF Core\nDomain: observability collector\nLogic challenge: idempotent retry design\nTask type: security_logic_interaction\nDifficulty: hard\n\nReturn a rigorous engineering answer:\n- identify the hidden root cause or logical failure\n- present the corrected implementation\n- add tests that prove the fix\n- list verification commands\n- explain why naive fixes are insufficient when relevant\n\nRepository sketch:\nrepo/\n src/App/Program.cs\n src/App/Service.cs\n tests/App.Tests/ServiceTests.cs\n App.sln\n\nFocus: Focus on ambiguity, misleading symptoms, hidden root causes, and high-stakes debugging.\n\nassistant: Diagnosis:\n- Hidden root cause: idempotent retry design presents misleading symptoms, so the patch must target the actual logic boundary rather than the first visible failure.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```csharp\nusing System;\nusing System.Collections.Generic;\n\npublic static class RequestHandler\n{\n public static Dictionary HandleRequest(Dictionary payload)\n {\n var clean = new Dictionary();\n foreach (var entry in payload)\n {\n if (entry.Value != null)\n clean[entry.Key.Trim()] = entry.Value;\n }\n if (!clean.ContainsKey(\"id\"))\n throw new ArgumentException(\"missing id\");\n return new Dictionary\n {\n [\"ok\"] = true,\n [\"data\"] = clean\n };\n }\n}\n```\n\nTests:\n```csharp\nusing System;\nusing System.Collections.Generic;\nusing Xunit;\n\npublic class RequestHandlerTests\n{\n [Fact]\n public void RequiresId()\n {\n Assert.Throws(() => RequestHandler.HandleRequest(new Dictionary { [\"name\"] = \"x\" }));\n }\n}\n```\n\nVerification:\n- `dotnet test`\n- `dotnet build`\n\nEngineering notes:\n- Language: C#\n- Framework/tooling: EF Core\n- Stack context: Next.js, Node.js, Prisma, PostgreSQL, Playwright, Docker\n- Domain: observability collector\n- Task type: security_logic_interaction\n- Difficulty: hard\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "Design and implement an algorithm for file synchronization.\nRequirements: define inputs/outputs, implement solution with complexity analysis, and include tests.\nConstraints: must provide clear error messages, must be easy to extend, stdlib-only, must include type hints.\nDifficulty: medium. Guarantee deterministic output ordering.\n\nDeliverable: corrected code and verification tests.\nProblem: compute rolling sums over events (ts:int,value:int) with window W seconds. Events may be out-of-order.\n\nComplexity: sorting O(n log n); window maintenance O(n); memory O(k).\n\n```python\nfrom __future__ import annotations\nfrom collections import deque\nfrom dataclasses import dataclass\nfrom typing import Iterable, List, Tuple\n\n@dataclass(frozen=True, slots=True)\nclass Event:\n ts: int\n value: int\n\ndef rolling_sum(events: Iterable[Event], window_s: int) -> List[Tuple[int,int]]:\n if window_s < 0:\n raise ValueError(\"window_s must be >= 0\")\n evs = sorted(events, key=lambda e: e.ts)\n q: deque[Event] = deque()\n s = 0\n out: List[Tuple[int,int]] = []\n for e in evs:\n q.append(e)\n s += e.value\n cutoff = e.ts - window_s\n while q and q[0].ts < cutoff:\n old = q.popleft()\n s -= old.value\n out.append((e.ts, s))\n return out\n```\n\n```python\nimport pytest\nfrom module_under_test import Event, rolling_sum\n\ndef test_rolling_sum():\n ev = [Event(10,1), Event(11,2), Event(20,5)]\n assert rolling_sum(ev, 5) == [(10,1),(11,3),(20,5)]\n```", "source": "WithinUsAI/python_GOD_coder_100k"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: Language: YAML\nFramework/tooling: Kubernetes\nDomain: feature flag service\nLogic challenge: partial checkpoint corruption\nTask type: multi_service_security_patch\nDifficulty: expert\n\nReturn a rigorous engineering answer:\n- identify the hidden root cause or logical failure\n- present the corrected implementation\n- add tests that prove the fix\n- list verification commands\n- explain why naive fixes are insufficient when relevant\n\nRepository sketch:\nrepo/\n .github/workflows/ci.yml\n docker-compose.yml\n deploy/\n app.yaml\n\nFocus: Focus on staff-level problem solving with multi-file patches, rollout implications, performance and security tradeoffs.\n\nassistant: Diagnosis:\n- Staff-level diagnosis: partial checkpoint corruption impacts correctness, operability, and future maintenance, so the fix must be minimal where possible but complete where necessary.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```yaml\nname: ci\non: [push, pull_request]\njobs:\n test:\n runs-on: ubuntu-latest\n steps:\n - uses: actions/checkout@v4\n - name: Validate\n run: echo \"validated\"\n```\n\nTests:\n```yaml\n# Verification:\n# - validate syntax\n# - run smoke workflow\n# - fail fast on broken config\n```\n\nVerification:\n- `validate workflow syntax`\n- `run CI smoke job`\n\nEngineering notes:\n- Language: YAML\n- Framework/tooling: Kubernetes\n- Stack context: Rust, Axum, SQLx, Redis, Tokio, Docker\n- Domain: feature flag service\n- Task type: multi_service_security_patch\n- Difficulty: expert\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "Create a small, production-ready Python package for metrics aggregation.\nRequirements: include module code, CLI entrypoint, logging, and a minimal pyproject.toml.\nConstraints: must handle Windows paths safely, must include tests.\nDifficulty: hard. Support both Windows and POSIX paths correctly.\n\nDeliverable: API + reference implementation + tests.\nPackage layout:\n- mypkg/core.py\n- mypkg/cli.py\n- pyproject.toml\n\n```python\n# mypkg/core.py\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom typing import Iterable\nimport logging\n\nlog = logging.getLogger(__name__)\n\n@dataclass(frozen=True, slots=True)\nclass Result:\n total: int\n count: int\n\ndef aggregate(values: Iterable[int]) -> Result:\n total = 0\n count = 0\n for v in values:\n if not isinstance(v, int):\n raise TypeError(\"values must be ints\")\n total += v\n count += 1\n log.debug(\"aggregate count=%s total=%s\", count, total)\n return Result(total, count)\n```\n\n```python\n# mypkg/cli.py\nfrom __future__ import annotations\nimport argparse\nimport logging\nimport sys\nfrom .core import aggregate\n\ndef main(argv: list[str] | None = None) -> int:\n p = argparse.ArgumentParser(prog=\"mypkg\")\n p.add_argument(\"--log-level\", default=\"WARNING\")\n args = p.parse_args(argv)\n logging.basicConfig(level=getattr(logging, args.log_level.upper(), logging.WARNING))\n data: list[int] = []\n for line in sys.stdin:\n line = line.strip()\n if line:\n data.append(int(line))\n r = aggregate(data)\n print(f\"count={r.count} total={r.total}\")\n return 0\n```\n\n```toml\n# pyproject.toml\n[project]\nname = \"mypkg\"\nversion = \"0.1.0\"\nrequires-python = \">=3.10\"\n\n[project.scripts]\nmypkg = \"mypkg.cli:main\"\n```", "source": "WithinUsAI/python_GOD_coder_100k"} {"text": "Build an elite-grade solution in the domain of high-performance services for scenario: analytics pipeline.\nPrimary language: bash.\nDifficulty: hard.\nConstraints: make the interface contract explicit, assume untrusted inputs; validate and sanitize, design for backward compatibility and migrations.\nComponent: component_ldsaalo.\nAssume schema changes every sprint; must be backward compatible.\nTask: Define properties/invariants and implement property-based tests (or generative tests) with a reference model and edge-case generators.\n\nOutput: production blueprint plus correctness arguments and test strategy.\nOutput: properties + reference model + generative tests.\n\n**Properties**\n- Idempotency: replayed command yields same result.\n- Monotonicity: versions only increase.\n- Conservation: for queues, produced items == consumed items (multiset) under no-loss assumption.\n\n**Approach**\n- Write a small reference model (pure function).\n- Generate random sequences of operations; compare implementation outputs to model.\n\n\nHard checks: failure injection tests and performance regressions gated.", "source": "WithinUsAI/Elite_GOD_Coder_100k"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: Language: YAML\nFramework/tooling: Helm\nDomain: feature flag service\nLogic challenge: dead-letter queue replay\nTask type: backwards_compatible_redesign\nDifficulty: hard\n\nReturn a rigorous engineering answer:\n- identify the hidden root cause or logical failure\n- present the corrected implementation\n- add tests that prove the fix\n- list verification commands\n- explain why naive fixes are insufficient when relevant\n\nRepository sketch:\nrepo/\n .github/workflows/ci.yml\n docker-compose.yml\n deploy/\n app.yaml\n\nFocus: Focus on staff-level problem solving with multi-file patches, rollout implications, performance and security tradeoffs.\n\nassistant: Diagnosis:\n- Staff-level diagnosis: dead-letter queue replay impacts correctness, operability, and future maintenance, so the fix must be minimal where possible but complete where necessary.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```yaml\nname: ci\non: [push, pull_request]\njobs:\n test:\n runs-on: ubuntu-latest\n steps:\n - uses: actions/checkout@v4\n - name: Validate\n run: echo \"validated\"\n```\n\nTests:\n```yaml\n# Verification:\n# - validate syntax\n# - run smoke workflow\n# - fail fast on broken config\n```\n\nVerification:\n- `validate workflow syntax`\n- `run CI smoke job`\n\nEngineering notes:\n- Language: YAML\n- Framework/tooling: Helm\n- Stack context: Next.js, Node.js, Prisma, PostgreSQL, Playwright, Docker\n- Domain: feature flag service\n- Task type: backwards_compatible_redesign\n- Difficulty: hard\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "Task type: storage_engine\nScenario: graph query service\nDomain focus: stream processing\nPrimary language: typescript\nDifficulty: expert\nScale/SLO: p99 < 50ms\nComponent: component_vmuhhwul\nConstraints: assume adversarial inputs; validate everything, include security threat model (defensive only), include backward compatibility and migration plan, include performance model and limits, include deterministic replay plan, include test vectors and fuzz strategy\nAssume schema changes every sprint; must be backward compatible.\nDeliverable: Design a storage engine subsystem (WAL, snapshots, compaction). Include crash recovery invariants and a benchmark plan.\n\nOutput: contract-first solution with failure modes, security posture, and test/verification strategy.\n**Contract**\n- Inputs validated at the boundary; explicit error taxonomy.\n- Idempotency for side effects via request_id; deterministic replay.\n- Backward compatibility: additive changes by default; versioned breaking changes.\n**Invariants**\n- Isolation: tenant boundary enforced; no cross-tenant reads/writes.\n- Safety: state transitions preserve invariants; no partial commit leaks.\n- Liveness: under bounded faults and stable network, progress occurs.\n**Failure modes & recovery**\n- Data corruption: checksums + scrubber; quarantine and rebuild from replicas/snapshots.\n- Crash during commit: WAL replay completes or transaction aborts; no torn writes.\n- Duplicate requests: de-duplicate by (tenant, request_id) returning cached response.\n**Security posture (defensive)**\n- Threat model: auth/authz, injection, replay/abuse, supply chain.\n- Least privilege; secrets in managed store; audit logs for sensitive ops.\n- Input normalization, parameterized queries, path traversal protections.\n**Verification strategy**\n- Deterministic simulation with fault injection (crash/partition/latency).\n- Fuzzing of parsers/framers/validators with corpus seeds.\n- Property tests against a pure reference model (state machine).\n\n**Snippet**\n```text\nImplementation sketch: factor pure state-machine core; adapters for I/O; add deterministic replay log.\n```\nExpert checks: state-machine proof sketch + model checking; upgrade/rollback rehearsed.", "source": "WithinUsAI/Omega_Genesis_Coder_100k"} {"text": "Task type: gpu_serving_pipeline\nScenario: payment ledger\nDomain focus: cryptography engineering (defensive)\nPrimary language: python\nDifficulty: hard\nScale/SLO: 100k RPS peak\nComponent: component_iwdwwuvw\nConstraints: explicit contracts and invariants, include backward compatibility and migration plan, include failure modes and recovery, avoid data races and undefined behavior, assume adversarial inputs; validate everything, include verification strategy\nAssume schema changes every sprint; must be backward compatible.\nDeliverable: Design a GPU inference serving pipeline: batching, scheduling, memory management, tail-latency control, and monitoring.\n\nOutput: rigorous design + invariants + verification plan + implementation sketch.\n**Contract**\n- Inputs validated at the boundary; explicit error taxonomy.\n- Idempotency for side effects via request_id; deterministic replay.\n- Backward compatibility: additive changes by default; versioned breaking changes.\n**Invariants**\n- Isolation: tenant boundary enforced; no cross-tenant reads/writes.\n- Safety: state transitions preserve invariants; no partial commit leaks.\n- Determinism: replay of the same event log yields identical outputs.\n**Failure modes & recovery**\n- Data corruption: checksums + scrubber; quarantine and rebuild from replicas/snapshots.\n- Duplicate requests: de-duplicate by (tenant, request_id) returning cached response.\n- Network partition: minority cannot commit; clients receive retriable errors.\n**Security posture (defensive)**\n- Threat model: auth/authz, injection, replay/abuse, supply chain.\n- Least privilege; secrets in managed store; audit logs for sensitive ops.\n- Input normalization, parameterized queries, path traversal protections.\n**Verification strategy**\n- Fuzzing of parsers/framers/validators with corpus seeds.\n- Property tests against a pure reference model (state machine).\n- Deterministic simulation with fault injection (crash/partition/latency).\n\n**Snippet**\n```text\nImplementation sketch: factor pure state-machine core; adapters for I/O; add deterministic replay log.\n```\nHard checks: fault injection tests gate merges; perf thresholds enforced in CI.", "source": "WithinUsAI/Omega_Genesis_Coder_100k"} {"text": "Task type: query_optimizer\nScenario: feature-flag evaluation\nDomain focus: formal verification\nPrimary language: bash\nDifficulty: expert\nScale/SLO: p99 < 150ms\nComponent: component_vmiciwlw\nConstraints: include backward compatibility and migration plan, include security threat model (defensive only), include performance model and limits, avoid data races and undefined behavior, include deterministic replay plan\nAssume tight memory budget and cold-start constraints.\nDeliverable: Design a cost-based optimizer slice: logical rules, physical operators, and cost model. Include regression tests and query-plan explain examples.\n\nOutput: contract-first solution with failure modes, security posture, and test/verification strategy.\n**Contract**\n- Inputs validated at the boundary; explicit error taxonomy.\n- Idempotency for side effects via request_id; deterministic replay.\n- Backward compatibility: additive changes by default; versioned breaking changes.\n**Invariants**\n- Liveness: under bounded faults and stable network, progress occurs.\n- Safety: state transitions preserve invariants; no partial commit leaks.\n- Determinism: replay of the same event log yields identical outputs.\n**Failure modes & recovery**\n- Data corruption: checksums + scrubber; quarantine and rebuild from replicas/snapshots.\n- Crash during commit: WAL replay completes or transaction aborts; no torn writes.\n- Duplicate requests: de-duplicate by (tenant, request_id) returning cached response.\n**Security posture (defensive)**\n- Threat model: auth/authz, injection, replay/abuse, supply chain.\n- Least privilege; secrets in managed store; audit logs for sensitive ops.\n- Input normalization, parameterized queries, path traversal protections.\n**Verification strategy**\n- Deterministic simulation with fault injection (crash/partition/latency).\n- Fuzzing of parsers/framers/validators with corpus seeds.\n- Property tests against a pure reference model (state machine).\n\n**Snippet**\n```python\n# Minimal cost model skeleton\nfrom dataclasses import dataclass\n\n@dataclass(frozen=True)\nclass Plan:\n op: str\n cost: float\n children: tuple[\"Plan\", ...] = ()\n\ndef choose_best(plans: list[Plan]) -> Plan:\n return min(plans, key=lambda p: p.cost)\n```\n\nExpert checks: state-machine proof sketch + model checking; upgrade/rollback rehearsed.", "source": "WithinUsAI/Omega_Genesis_Coder_100k"} {"text": "Build an elite-grade solution in the domain of distributed systems for scenario: feature flagging.\nPrimary language: go.\nDifficulty: medium.\nConstraints: make the interface contract explicit, document performance characteristics, include tests or verification strategy, design for backward compatibility and migrations.\nComponent: component_nhvocac.\nAssume crash-only design; recovery must be deterministic.\nTask: Provide threat model, secure-by-default design, and defensive implementation patterns. No offensive/exploit content; focus on prevention and detection.\n\nOutput: rigorous solution with invariants, failure modes, and performance notes.\nOutput: threat model + defensive design + detection.\n\n**Threat model**\n- Auth: token theft → short-lived tokens, rotation, audience checks\n- AuthZ: privilege escalation → centralized policy checks, tenant isolation tests\n- Input: injection → strict validation, parameterized queries, output encoding\n- Supply chain: dependencies → lockfiles, signature verification, SBOM\n\n**Defensive patterns**\n- Idempotency keys for side effects; replay-safe handlers\n- Secrets in managed store; never logs\n- Audit logging for sensitive ops; tamper-evident storage\n\n**Detection**\n- Alert on unusual auth failures, access pattern anomalies, and data exfil signals.\n\n\nChecks: boundary validation and deterministic behavior verified.", "source": "WithinUsAI/Elite_GOD_Coder_100k"} {"text": "Build an elite-grade solution in the domain of edge/IoT for scenario: inventory & ordering.\nPrimary language: rust.\nDifficulty: expert.\nConstraints: make the interface contract explicit, provide rollout and rollback guidance, assume untrusted inputs; validate and sanitize.\nComponent: component_leytpxr.\nAssume compliance requires data deletion with proofs.\nTask: Design an application-level protocol (framing, retries, timeouts, backpressure). Provide client/server skeleton and test vectors.\n\nOutput: production blueprint plus correctness arguments and test strategy.\nOutput: protocol framing + retry policy + client/server skeleton.\n\n**Framing**\n- Length-prefixed: uint32_be length + payload\n- Payload: msgpack/json; include request_id, type, and optional checksum\n\n**Reliability**\n- Retries only for idempotent ops; exponential backoff + jitter.\n- Timeouts: connect, read, overall; enforce max in-flight to provide backpressure.\n\n**Test vectors**\n- Corrupted length / truncated frame rejected\n- Duplicate request_id returns cached response\n- Slowloris protection by read deadlines\n\n\nExpert checks: state-machine reasoning, concurrency stress, and upgrade/rollback validated.", "source": "WithinUsAI/Elite_GOD_Coder_100k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Optimize while preserving behavior.\n\nFile: vnwax38bsh_.py\n```python\ndef rn3ptynyfk(xs):\n out = []\n for x in xs:\n if x not in out:\n out.append(x)\n return out\n```\n\nRequirements: preserve first-seen order; O(n) average; add types + docstring.\n\n# vnwax38bsh_.py\nfrom __future__ import annotations\nfrom typing import Iterable, List, Set, TypeVar\n\nT = TypeVar(\"T\")\n\ndef rn3ptynyfk(xs: Iterable[T]) -> List[T]:\n \"\"\"Return unique items preserving first-seen order.\"\"\"\n seen: Set[T] = set()\n out: List[T] = []\n for x in xs:\n if x in seen:\n continue\n seen.add(x)\n out.append(x)\n return out", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Produce an offline-first self-evolving code assistant architecture named `y9yzgv8mmdt0`.\nMust include: module layout, patch-safety policy, evaluation gates (tests/lint/types), versioned memory index.\n\nArchitecture: `y9yzgv8mmdt0` (offline-first, self-evolving)\n\nModules\n- core/loop.py: evolve → validate → accept/reject (bounded iterations)\n- patching/: diff builder, safe apply, atomic writes, rollback points\n- policy/: allowlist paths, deny globs (.git/, __pycache__/, binaries), patch size caps\n- signals/: parse pytest/ruff/mypy into normalized findings\n- memory/index.jsonl: append-only snapshots (hashes, metrics, rationale)\n\nSafety gates\n- refuse path traversal/symlink escapes; never edit binaries\n- accept only if tests/lint/types stay green or improve", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Task type: query_optimizer\nScenario: multi-tenant event ingestion\nDomain focus: high-frequency trading systems (safe engineering)\nPrimary language: sql\nDifficulty: hard\nScale/SLO: 1M msgs/min\nComponent: component_fjsffuhe\nConstraints: assume adversarial inputs; validate everything, include backward compatibility and migration plan, avoid data races and undefined behavior, include test vectors and fuzz strategy, include verification strategy, include deterministic replay plan\nAssume tight memory budget and cold-start constraints.\nDeliverable: Design a cost-based optimizer slice: logical rules, physical operators, and cost model. Include regression tests and query-plan explain examples.\n\nOutput: elite engineering answer optimized for correctness, performance, and operability.\n**Contract**\n- Inputs validated at the boundary; explicit error taxonomy.\n- Idempotency for side effects via request_id; deterministic replay.\n- Backward compatibility: additive changes by default; versioned breaking changes.\n**Invariants**\n- Liveness: under bounded faults and stable network, progress occurs.\n- Isolation: tenant boundary enforced; no cross-tenant reads/writes.\n- Determinism: replay of the same event log yields identical outputs.\n**Failure modes & recovery**\n- Crash during commit: WAL replay completes or transaction aborts; no torn writes.\n- Network partition: minority cannot commit; clients receive retriable errors.\n- Data corruption: checksums + scrubber; quarantine and rebuild from replicas/snapshots.\n**Security posture (defensive)**\n- Threat model: auth/authz, injection, replay/abuse, supply chain.\n- Least privilege; secrets in managed store; audit logs for sensitive ops.\n- Input normalization, parameterized queries, path traversal protections.\n**Verification strategy**\n- Fuzzing of parsers/framers/validators with corpus seeds.\n- Deterministic simulation with fault injection (crash/partition/latency).\n- Property tests against a pure reference model (state machine).\n\n**Snippet**\n```python\n# Minimal cost model skeleton\nfrom dataclasses import dataclass\n\n@dataclass(frozen=True)\nclass Plan:\n op: str\n cost: float\n children: tuple[\"Plan\", ...] = ()\n\ndef choose_best(plans: list[Plan]) -> Plan:\n return min(plans, key=lambda p: p.cost)\n```\n\nHard checks: fault injection tests gate merges; perf thresholds enforced in CI.", "source": "WithinUsAI/Omega_Genesis_Coder_100k"} {"text": "Refactor to typed, mostly-immutable Python and add minimal tests.\n\n```python\nclass C42770:\n def __init__(self, values): self.values=list(values)\n def mean(self): return sum(self.values)/len(self.values)\n```\nReturn `m03290.py` and `test_m03290.py`.\n\n```python\n# m03290.py\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom typing import Iterable, Tuple\n\n@dataclass(frozen=True)\nclass C42770:\n values: Tuple[float, ...]\n\n @staticmethod\n def create(values: Iterable[float]) -> \"C42770\":\n vals = tuple(float(v) for v in values)\n if not vals: raise ValueError(\"empty\")\n return C42770(vals)\n\n def mean(self) -> float:\n return sum(self.values)/len(self.values)\n```\n\n```python\n# test_m03290.py\nimport pytest\nfrom m03290 import C42770\n\ndef test_mean():\n assert C42770.create([1,2,3]).mean() == 2.0\ndef test_empty():\n with pytest.raises(ValueError):\n C42770.create([])\n```", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Build an elite-grade solution in the domain of networking for scenario: chat messaging.\nPrimary language: rust.\nDifficulty: hard.\nConstraints: provide rollout and rollback guidance, make the interface contract explicit, assume untrusted inputs; validate and sanitize.\nComponent: component_xebtkme.\nAssume 50k RPS and p99 < 250ms.\nTask: Define a small DSL, implement tokenizer/parser, IR, and a codegen or interpreter. Include tests and complexity notes.\n\nOutput: rigorous solution with invariants, failure modes, and performance notes.\nOutput: DSL + parser + IR + interpreter/codegen + tests.\n\n**DSL**\n- Expressions: integers, identifiers, `+ - * /`, let-binding: `let x = expr in expr`\n- Example: `let x = 2+3 in x*10`\n\n**Pipeline**\n1. Tokenize\n2. Parse into AST\n3. Lower into IR (stack ops) or interpret AST directly\n\n**Reference (Rust-style outline)**\n- `enum Expr { Int(i64), Var(String), Bin(Op, Box, Box), Let(String, Box, Box) }`\n- Parser: Pratt or recursive descent.\n\n**Tests**\n- Golden tests for parse trees.\n- Property: pretty-print(parse(x)) round-trips for a corpus.\n- Eval tests for precedence and scoping.\n\n\nHard checks: failure injection tests and performance regressions gated.", "source": "WithinUsAI/Elite_GOD_Coder_100k"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: Language: JavaScript\nFramework/tooling: Jest\nDomain: job scheduler\nLogic challenge: broken pagination cursor\nTask type: misleading_symptom_debug\nDifficulty: hard\n\nReturn a rigorous engineering answer:\n- identify the hidden root cause or logical failure\n- present the corrected implementation\n- add tests that prove the fix\n- list verification commands\n- explain why naive fixes are insufficient when relevant\n\nRepository sketch:\nrepo/\n src/\n api.js\n service.js\n utils.js\n tests/\n api.test.js\n package.json\n\nFocus: Focus on ambiguity, misleading symptoms, hidden root causes, and high-stakes debugging.\n\nassistant: Diagnosis:\n- Hidden root cause: broken pagination cursor presents misleading symptoms, so the patch must target the actual logic boundary rather than the first visible failure.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```javascript\ntype Payload = Record;\n\nexport function normalizePayload(payload: Payload): Payload {\n if (!payload || typeof payload !== \"object\" || Array.isArray(payload)) {\n throw new TypeError(\"payload must be a plain object\");\n }\n return Object.fromEntries(\n Object.entries(payload)\n .filter(([, value]) => value !== null && value !== undefined)\n .map(([key, value]) => [String(key).trim(), value])\n );\n}\n\nexport function handleBrokenPaginationCursor(payload: Payload) {\n const clean = normalizePayload(payload);\n if (!(\"id\" in clean)) {\n return { ok: false, data: {}, error: \"missing id\" };\n }\n return { ok: true, data: clean, error: null };\n}\n```\n\nTests:\n```javascript\nimport { describe, it, expect } from \"vitest\";\nimport { handleBrokenPaginationCursor } from \"../src/service\";\n\ndescribe(\"handler\", () => {\n it(\"accepts valid input\", () => {\n expect(handleBrokenPaginationCursor({ id: 7, name: \"ok\", unused: null })).toEqual({\n ok: true,\n data: { id: 7, name: \"ok\" },\n error: null\n });\n });\n\n it(\"rejects missing id\", () => {\n expect(handleBrokenPaginationCursor({ name: \"x\" }).error).toMatch(/missing id/);\n });\n});\n```\n\nVerification:\n- `npm test`\n- `npm run lint`\n\nEngineering notes:\n- Language: JavaScript\n- Framework/tooling: Jest\n- Stack context: Rust, Axum, SQLx, Redis, Tokio, Docker\n- Domain: job scheduler\n- Task type: misleading_symptom_debug\n- Difficulty: hard\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "Refactor to typed, mostly-immutable Python and add minimal tests.\n\n```python\nclass C47610:\n def __init__(self, values): self.values=list(values)\n def mean(self): return sum(self.values)/len(self.values)\n```\nReturn `m95970.py` and `test_m95970.py`.\n\n```python\n# m95970.py\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom typing import Iterable, Tuple\n\n@dataclass(frozen=True)\nclass C47610:\n values: Tuple[float, ...]\n\n @staticmethod\n def create(values: Iterable[float]) -> \"C47610\":\n vals = tuple(float(v) for v in values)\n if not vals: raise ValueError(\"empty\")\n return C47610(vals)\n\n def mean(self) -> float:\n return sum(self.values)/len(self.values)\n```\n\n```python\n# test_m95970.py\nimport pytest\nfrom m95970 import C47610\n\ndef test_mean():\n assert C47610.create([1,2,3]).mean() == 2.0\ndef test_empty():\n with pytest.raises(ValueError):\n C47610.create([])\n```", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: Language: C#\nFramework/tooling: xUnit\nDomain: notification service\nLogic challenge: broken pagination cursor\nTask type: performance_bottleneck_patch\nDifficulty: hard\n\nReturn a rigorous engineering answer:\n- identify the hidden root cause or logical failure\n- present the corrected implementation\n- add tests that prove the fix\n- list verification commands\n- explain why naive fixes are insufficient when relevant\n\nRepository sketch:\nrepo/\n src/App/Program.cs\n src/App/Service.cs\n tests/App.Tests/ServiceTests.cs\n App.sln\n\nFocus: Focus on ambiguity, misleading symptoms, hidden root causes, and high-stakes debugging.\n\nassistant: Diagnosis:\n- Hidden root cause: broken pagination cursor presents misleading symptoms, so the patch must target the actual logic boundary rather than the first visible failure.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```csharp\nusing System;\nusing System.Collections.Generic;\n\npublic static class RequestHandler\n{\n public static Dictionary HandleRequest(Dictionary payload)\n {\n var clean = new Dictionary();\n foreach (var entry in payload)\n {\n if (entry.Value != null)\n clean[entry.Key.Trim()] = entry.Value;\n }\n if (!clean.ContainsKey(\"id\"))\n throw new ArgumentException(\"missing id\");\n return new Dictionary\n {\n [\"ok\"] = true,\n [\"data\"] = clean\n };\n }\n}\n```\n\nTests:\n```csharp\nusing System;\nusing System.Collections.Generic;\nusing Xunit;\n\npublic class RequestHandlerTests\n{\n [Fact]\n public void RequiresId()\n {\n Assert.Throws(() => RequestHandler.HandleRequest(new Dictionary { [\"name\"] = \"x\" }));\n }\n}\n```\n\nVerification:\n- `dotnet test`\n- `dotnet build`\n\nEngineering notes:\n- Language: C#\n- Framework/tooling: xUnit\n- Stack context: Go, Gin, PostgreSQL, gRPC, Prometheus, Docker\n- Domain: notification service\n- Task type: performance_bottleneck_patch\n- Difficulty: hard\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "Task type: distributed_algorithm\nScenario: feature-flag evaluation\nDomain focus: query planning\nPrimary language: bash\nDifficulty: expert+\nScale/SLO: 50 TB/day ingestion\nComponent: component_fygrdtnk\nConstraints: avoid data races and undefined behavior, include test vectors and fuzz strategy, include failure modes and recovery, include backward compatibility and migration plan, include performance model and limits, include deterministic replay plan\nAssume schema changes every sprint; must be backward compatible.\nDeliverable: Design an algorithm with message flows and correctness arguments (safety + liveness). Include failure handling and a minimal reference implementation skeleton.\n\nOutput: contract-first solution with failure modes, security posture, and test/verification strategy.\n**Contract**\n- Inputs validated at the boundary; explicit error taxonomy.\n- Idempotency for side effects via request_id; deterministic replay.\n- Backward compatibility: additive changes by default; versioned breaking changes.\n**Invariants**\n- Isolation: tenant boundary enforced; no cross-tenant reads/writes.\n- Liveness: under bounded faults and stable network, progress occurs.\n- Safety: state transitions preserve invariants; no partial commit leaks.\n**Failure modes & recovery**\n- Data corruption: checksums + scrubber; quarantine and rebuild from replicas/snapshots.\n- Network partition: minority cannot commit; clients receive retriable errors.\n- Duplicate requests: de-duplicate by (tenant, request_id) returning cached response.\n**Security posture (defensive)**\n- Threat model: auth/authz, injection, replay/abuse, supply chain.\n- Least privilege; secrets in managed store; audit logs for sensitive ops.\n- Input normalization, parameterized queries, path traversal protections.\n**Verification strategy**\n- Property tests against a pure reference model (state machine).\n- Canary + shadow traffic; invariants checked in production via assertions/metrics.\n- Fuzzing of parsers/framers/validators with corpus seeds.\n\n**Snippet**\n```text\nImplementation sketch: factor pure state-machine core; adapters for I/O; add deterministic replay log.\n```\nExpert+ checks: mechanized invariants (or exhaustive model checking), adversarial fuzzing, and multi-region failure drills.", "source": "WithinUsAI/Omega_Genesis_Coder_100k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Fix a bug and add tests.\n\nFile: pscc0kghqa.py\n```python\ndef asbu2zx1kx8r(n: int) -> int:\n \"\"\"Sum 1..n inclusive.\"\"\"\n if n < 0:\n raise ValueError(\"n must be non-negative\")\n total = 0\n for k in range(n): # BUG: should include n\n total += k\n return total\n```\n\nReturn unified diffs for pscc0kghqa.py and test_pscc0kghqa.py (pytest).\n\n*** Begin Patch\n*** Update File: pscc0kghqa.py\n@@\n def asbu2zx1kx8r(n: int) -> int:\n@@\n total = 0\n- for k in range(n): # BUG: should include n\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_pscc0kghqa.py\n+import pytest\n+from pscc0kghqa import asbu2zx1kx8r\n+\n+def test_zero():\n+ assert asbu2zx1kx8r(0) == 0\n+\n+def test_one():\n+ assert asbu2zx1kx8r(1) == 1\n+\n+def test_small():\n+ assert asbu2zx1kx8r(7) == 28\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ asbu2zx1kx8r(-1)\n+\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Write pytest tests for `f30512`.\n\n```python\ndef f30512(a: int, b: int) -> int:\n return a*a + b*b\n```\nInclude edge cases and a property-style check.\n\n```python\nimport random\nfrom m47216 import f30512\n\ndef test_known():\n assert f30512(3,4) == 25\n\ndef test_zero():\n assert f30512(0,0) == 0\n\ndef test_property_nonnegative():\n for _ in range(200):\n a=random.randint(-50,50)\n b=random.randint(-50,50)\n assert f30512(a,b) >= 0\n```", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Optimize while preserving behavior.\n\nFile: ei60z2xraz_.py\n```python\ndef fw2co_b4(xs):\n out = []\n for x in xs:\n if x not in out:\n out.append(x)\n return out\n```\n\nRequirements: preserve first-seen order; O(n) average; add types + docstring.\n\n# ei60z2xraz_.py\nfrom __future__ import annotations\nfrom typing import Iterable, List, Set, TypeVar\n\nT = TypeVar(\"T\")\n\ndef fw2co_b4(xs: Iterable[T]) -> List[T]:\n \"\"\"Return unique items preserving first-seen order.\"\"\"\n seen: Set[T] = set()\n out: List[T] = []\n for x in xs:\n if x in seen:\n continue\n seen.add(x)\n out.append(x)\n return out", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: Language: JavaScript\nFramework/tooling: Node.js\nDomain: data pipeline\nLogic challenge: memory leak in AST cache\nTask type: transaction_integrity_fix\nDifficulty: hard\n\nReturn a rigorous engineering answer:\n- identify the hidden root cause or logical failure\n- present the corrected implementation\n- add tests that prove the fix\n- list verification commands\n- explain why naive fixes are insufficient when relevant\n\nRepository sketch:\nrepo/\n src/\n api.js\n service.js\n utils.js\n tests/\n api.test.js\n package.json\n\nFocus: Focus on ambiguity, misleading symptoms, hidden root causes, and high-stakes debugging.\n\nassistant: Diagnosis:\n- Hidden root cause: memory leak in AST cache presents misleading symptoms, so the patch must target the actual logic boundary rather than the first visible failure.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```javascript\ntype Payload = Record;\n\nexport function normalizePayload(payload: Payload): Payload {\n if (!payload || typeof payload !== \"object\" || Array.isArray(payload)) {\n throw new TypeError(\"payload must be a plain object\");\n }\n return Object.fromEntries(\n Object.entries(payload)\n .filter(([, value]) => value !== null && value !== undefined)\n .map(([key, value]) => [String(key).trim(), value])\n );\n}\n\nexport function handleMemoryLeakInAstCache(payload: Payload) {\n const clean = normalizePayload(payload);\n if (!(\"id\" in clean)) {\n return { ok: false, data: {}, error: \"missing id\" };\n }\n return { ok: true, data: clean, error: null };\n}\n```\n\nTests:\n```javascript\nimport { describe, it, expect } from \"vitest\";\nimport { handleMemoryLeakInAstCache } from \"../src/service\";\n\ndescribe(\"handler\", () => {\n it(\"accepts valid input\", () => {\n expect(handleMemoryLeakInAstCache({ id: 7, name: \"ok\", unused: null })).toEqual({\n ok: true,\n data: { id: 7, name: \"ok\" },\n error: null\n });\n });\n\n it(\"rejects missing id\", () => {\n expect(handleMemoryLeakInAstCache({ name: \"x\" }).error).toMatch(/missing id/);\n });\n});\n```\n\nVerification:\n- `npm test`\n- `npm run lint`\n\nEngineering notes:\n- Language: JavaScript\n- Framework/tooling: Node.js\n- Stack context: GitHub Actions, Docker Compose, Kubernetes, Terraform\n- Domain: data pipeline\n- Task type: transaction_integrity_fix\n- Difficulty: hard\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "Design a small, production-grade Python API for metrics aggregation.\nRequirements: define data models and interfaces, implement reference version, include tests.\nConstraints: must be memory-efficient, must be streaming-friendly, stdlib-only, must include type hints.\nDifficulty: medium. Handle empty inputs and malformed records gracefully.\n\nDeliverable: API + reference implementation + tests.\nArchitecture:\n- Public facade class coordinating concerns (parsing, validation, persistence)\n- Small pure functions for testability\n- No global state; dependency injection for filesystem I/O\n\n```python\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom pathlib import Path\nfrom typing import Protocol, Iterable\nimport json\n\nclass Store(Protocol):\n def write_text(self, path: Path, data: str) -> None: ...\n\nclass FSStore:\n def write_text(self, path: Path, data: str) -> None:\n path.parent.mkdir(parents=True, exist_ok=True)\n path.write_text(data, encoding=\"utf-8\")\n\n@dataclass(frozen=True, slots=True)\nclass Item:\n name: str\n qty: int\n\ndef parse_items(lines: Iterable[str]) -> list[Item]:\n out: list[Item] = []\n for i, line in enumerate(lines, 1):\n s = line.strip()\n if not s:\n continue\n obj = json.loads(s)\n if not isinstance(obj, dict):\n raise ValueError(f\"line {i}: expected object\")\n name = obj.get(\"name\")\n qty = obj.get(\"qty\")\n if not isinstance(name, str) or not name:\n raise ValueError(f\"line {i}: name must be str\")\n if not isinstance(qty, int) or qty < 0:\n raise ValueError(f\"line {i}: qty must be non-negative int\")\n out.append(Item(name, qty))\n return out\n\nclass InventoryWriter:\n def __init__(self, base_dir: Path, store: Store | None = None) -> None:\n self._base = base_dir\n self._store: Store = store or FSStore()\n\n def write(self, rel_path: str, items: list[Item]) -> Path:\n dst = (self._base / rel_path).resolve()\n base = self._base.resolve()\n if dst != base and base not in dst.parents:\n raise ValueError(\"unsafe path traversal\")\n payload = json.dumps([item.__dict__ for item in items], ensure_ascii=False)\n self._store.write_text(dst, payload)\n return dst\n```\n\n```python\nimport json\nfrom pathlib import Path\nimport pytest\nfrom module_under_test import InventoryWriter, parse_items\n\ndef test_parse_items_valid():\n lines = [json.dumps({\"name\":\"x\",\"qty\":1})]\n assert parse_items(lines)[0].name == \"x\"\n\ndef test_writer_blocks_traversal(tmp_path: Path):\n w = InventoryWriter(tmp_path)\n with pytest.raises(ValueError):\n w.write(\"../evil.json\", [])\n```", "source": "WithinUsAI/python_GOD_coder_100k"} {"text": "Add a clear docstring and type hints to this function:\n\n```python\ndef f51426(s):\n return ''.join(x for x in s if x.isalnum()).lower()\n```\n\n```python\nfrom __future__ import annotations\n\ndef f51426(s: str) -> str:\n \"\"\"Normalize a string: keep only alphanumerics and lowercase the result.\"\"\"\n return \"\".join(ch for ch in s if ch.isalnum()).lower()\n```", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Refactor an existing codebase in gaming to support event-driven workflows cleanly.\nTarget platform: ML (scikit + batch).\nRequirements: propose new modules/layers, dependency boundaries, and migration plan.\nConstraints: must include clear error handling, must be easy to extend, must be performant under load, must avoid global state, must be production-ready.\nDifficulty: easy. Assume strict latency budget (p95 < 200ms).\n\nOutput: actionable implementation and verification artifacts.\nDeliverable: refactor plan + module boundaries.\n\n**Proposed modules**\n- `domain/` pure business logic (no I/O)\n- `adapters/` DB, cache, external APIs\n- `api/` request/response validation and routing\n- `observability/` logging/metrics/tracing\n- `tests/` unit + integration suites\n\n**Migration plan**\n1. Introduce new interfaces + adapters behind feature flags.\n2. Dual-write or read-compat layer if schema changes.\n3. Incremental cutover; deprecate legacy module.\n\nKey rule: dependencies flow inward; domain has no framework imports.\n\n\nChecks: input validation, tests, and safe defaults included.", "source": "WithinUsAI/GOD_Coder_100k"} {"text": "Design and implement an algorithm for event dispatching.\nRequirements: define inputs/outputs, implement solution with complexity analysis, and include tests.\nConstraints: must be easy to extend, must avoid global state, must include tests.\nDifficulty: expert. Avoid quadratic behavior on large inputs.\n\nDeliverable: API + reference implementation + tests.\nProblem: compute rolling sums over events (ts:int,value:int) with window W seconds. Events may be out-of-order.\n\nComplexity: sorting O(n log n); window maintenance O(n); memory O(k).\n\n```python\nfrom __future__ import annotations\nfrom collections import deque\nfrom dataclasses import dataclass\nfrom typing import Iterable, List, Tuple\n\n@dataclass(frozen=True, slots=True)\nclass Event:\n ts: int\n value: int\n\ndef rolling_sum(events: Iterable[Event], window_s: int) -> List[Tuple[int,int]]:\n if window_s < 0:\n raise ValueError(\"window_s must be >= 0\")\n evs = sorted(events, key=lambda e: e.ts)\n q: deque[Event] = deque()\n s = 0\n out: List[Tuple[int,int]] = []\n for e in evs:\n q.append(e)\n s += e.value\n cutoff = e.ts - window_s\n while q and q[0].ts < cutoff:\n old = q.popleft()\n s -= old.value\n out.append((e.ts, s))\n return out\n```\n\n```python\nimport pytest\nfrom module_under_test import Event, rolling_sum\n\ndef test_rolling_sum():\n ev = [Event(10,1), Event(11,2), Event(20,5)]\n assert rolling_sum(ev, 5) == [(10,1),(11,3),(20,5)]\n```", "source": "WithinUsAI/python_GOD_coder_100k"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: Language: TypeScript\nFramework/tooling: Next.js\nDomain: observability collector\nLogic challenge: slow cold start\nTask type: concurrency_fix\nDifficulty: hard\n\nReturn a rigorous engineering answer:\n- identify the hidden root cause or logical failure\n- present the corrected implementation\n- add tests that prove the fix\n- list verification commands\n- explain why naive fixes are insufficient when relevant\n\nRepository sketch:\nrepo/\n src/\n api.ts\n service.ts\n schema.ts\n tests/\n api.test.ts\n package.json\n\nFocus: Focus on strong structured logic with edge cases, data validation, and concurrency safety.\n\nassistant: Diagnosis:\n- Root cause: the failure around slow cold start is caused by missing validation, weak edge-case handling, or unsafe lifecycle behavior in the current implementation.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```ts\ntype Payload = Record;\n\nexport function normalizePayload(payload: Payload): Payload {\n if (!payload || typeof payload !== \"object\" || Array.isArray(payload)) {\n throw new TypeError(\"payload must be a plain object\");\n }\n return Object.fromEntries(\n Object.entries(payload)\n .filter(([, value]) => value !== null && value !== undefined)\n .map(([key, value]) => [String(key).trim(), value])\n );\n}\n\nexport function handleSlowColdStart(payload: Payload) {\n const clean = normalizePayload(payload);\n if (!(\"id\" in clean)) {\n return { ok: false, data: {}, error: \"missing id\" };\n }\n return { ok: true, data: clean, error: null };\n}\n```\n\nTests:\n```ts\nimport { describe, it, expect } from \"vitest\";\nimport { handleSlowColdStart } from \"../src/service\";\n\ndescribe(\"handler\", () => {\n it(\"accepts valid input\", () => {\n expect(handleSlowColdStart({ id: 7, name: \"ok\", unused: null })).toEqual({\n ok: true,\n data: { id: 7, name: \"ok\" },\n error: null\n });\n });\n\n it(\"rejects missing id\", () => {\n expect(handleSlowColdStart({ name: \"x\" }).error).toMatch(/missing id/);\n });\n});\n```\n\nVerification:\n- `npm test`\n- `npm run typecheck`\n- `npm run lint`\n\nEngineering notes:\n- Language: TypeScript\n- Framework/tooling: Next.js\n- Stack context: FastAPI, PostgreSQL, Redis, Celery, pytest, Docker\n- Domain: observability collector\n- Task type: concurrency_fix\n- Difficulty: hard\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "Refactor to typed, mostly-immutable Python and add minimal tests.\n\n```python\nclass C16170:\n def __init__(self, values): self.values=list(values)\n def mean(self): return sum(self.values)/len(self.values)\n```\nReturn `m55090.py` and `test_m55090.py`.\n\n```python\n# m55090.py\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom typing import Iterable, Tuple\n\n@dataclass(frozen=True)\nclass C16170:\n values: Tuple[float, ...]\n\n @staticmethod\n def create(values: Iterable[float]) -> \"C16170\":\n vals = tuple(float(v) for v in values)\n if not vals: raise ValueError(\"empty\")\n return C16170(vals)\n\n def mean(self) -> float:\n return sum(self.values)/len(self.values)\n```\n\n```python\n# test_m55090.py\nimport pytest\nfrom m55090 import C16170\n\ndef test_mean():\n assert C16170.create([1,2,3]).mean() == 2.0\ndef test_empty():\n with pytest.raises(ValueError):\n C16170.create([])\n```", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Refactor to typed, mostly-immutable Python and add minimal tests.\n\n```python\nclass C99646:\n def __init__(self, values): self.values=list(values)\n def mean(self): return sum(self.values)/len(self.values)\n```\nReturn `m30742.py` and `test_m30742.py`.\n\n```python\n# m30742.py\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom typing import Iterable, Tuple\n\n@dataclass(frozen=True)\nclass C99646:\n values: Tuple[float, ...]\n\n @staticmethod\n def create(values: Iterable[float]) -> \"C99646\":\n vals = tuple(float(v) for v in values)\n if not vals: raise ValueError(\"empty\")\n return C99646(vals)\n\n def mean(self) -> float:\n return sum(self.values)/len(self.values)\n```\n\n```python\n# test_m30742.py\nimport pytest\nfrom m30742 import C99646\n\ndef test_mean():\n assert C99646.create([1,2,3]).mean() == 2.0\ndef test_empty():\n with pytest.raises(ValueError):\n C99646.create([])\n```", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: Project domain: data pipeline\nImplementation stack: Go, Gin, PostgreSQL, gRPC, Prometheus, Docker\nSoftware delivery problem: multi-tenant access leak\nTask type: prd_to_patch\nDifficulty: medium\n\nReturn a complete delivery-grade response with:\n- diagnosis or design reasoning\n- implementation\n- test plan or tests\n- rollout plan\n- rollback or compatibility note\n- verification commands\n\nRepository sketch:\nrepo/\n migrations/\n 001_init.sql\n 002_add_index.sql\n queries/\n report.sql\n tests/\n report_cases.md\n\nFocus: Focus on shipping production software with rollout safety, acceptance criteria, telemetry, and maintenance quality.\n\nassistant: Diagnosis:\n- Root cause or delivery blocker: multi-tenant access leak needs both implementation work and a safe shipping plan.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```sql\nWITH ranked AS (\n SELECT\n user_id,\n created_at,\n amount,\n ROW_NUMBER() OVER (PARTITION BY user_id ORDER BY created_at DESC, id DESC) AS rn\n FROM orders\n)\nSELECT user_id, created_at, amount\nFROM ranked\nWHERE rn = 1;\n```\n\nTests:\n```sql\n-- Correctness checks:\n-- 1) multiple rows per user\n-- 2) identical timestamps require deterministic tie-breaker\n-- 3) null values handled by business rules\n```\n\nVerification:\n- `run migration checks`\n- `run query correctness cases`\n\nEngineering notes:\n- Language: SQL\n- Framework/tooling: SQLite\n- Stack context: Go, Gin, PostgreSQL, gRPC, Prometheus, Docker\n- Domain: data pipeline\n- Task type: prd_to_patch\n- Difficulty: medium\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "Optimize a Python workflow for file synchronization.\nRequirements: provide an optimized implementation and a small benchmark harness.\nConstraints: must be memory-efficient, must be streaming-friendly, must include type hints.\nDifficulty: medium. Guarantee deterministic output ordering.\n\nDeliverable: API + reference implementation + tests.\nStrategy:\n- Avoid repeated parsing; precompile regex if needed; use local variables; stream processing.\n\n```python\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom typing import Iterable\nimport time\n\n@dataclass(frozen=True, slots=True)\nclass Stats:\n count: int\n total: int\n\ndef compute_stats_stream(values: Iterable[int]) -> Stats:\n c = 0\n t = 0\n for v in values:\n c += 1\n t += v\n return Stats(c, t)\n\ndef bench(n: int = 1_000_00) -> float:\n data = range(n)\n t0 = time.perf_counter()\n _ = compute_stats_stream(data)\n return time.perf_counter() - t0\n```\n\n```python\nfrom module_under_test import bench\ndef test_bench_runs_fast_enough():\n # Sanity: should run quickly on typical machines; adjust threshold for CI.\n assert bench(50_000) < 0.5\n```", "source": "WithinUsAI/python_GOD_coder_100k"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: Repository domain: auth service\nPrimary language: Rust\nFramework/tooling: Axum\nReported problem: streaming timeout handling\nTask type: api_endpoint_work\nDifficulty: medium\n\nProduce a complete professional engineering response:\n1. Diagnose the root cause.\n2. Provide the corrected implementation or patch.\n3. Add tests.\n4. Add verification commands.\n5. Note edge cases and any migration or rollback risk.\n\nRepository sketch:\nrepo/\n src/main.rs\n src/lib.rs\n src/service.rs\n src/store.rs\n tests/integration.rs\n Cargo.toml\n\nQuality target:\n- Minimal diff unless redesign is clearly required\n- Production-ready code\n- No placeholders\n- Secure defaults\n- Clear acceptance of failure cases\n\nFocus: Focus on complete implementation quality, patch correctness, tests, and production readiness.\n\nassistant: Diagnosis:\n- Root cause: the failure around streaming timeout handling is caused by missing validation, weak edge-case handling, or unsafe lifecycle behavior in the current implementation.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```rust\nuse std::collections::HashMap;\n\npub fn normalize_payload(payload: HashMap) -> HashMap {\n payload\n .into_iter()\n .filter(|(_, v)| !v.trim().is_empty())\n .collect()\n}\n```\n\nTests:\n```rust\n#[test]\nfn normalize_payload_filters_empty_values() {\n use std::collections::HashMap;\n let mut payload = HashMap::new();\n payload.insert(\"id\".to_string(), \"7\".to_string());\n payload.insert(\"name\".to_string(), \"\".to_string());\n let out = normalize_payload(payload);\n assert!(out.contains_key(\"id\"));\n assert!(!out.contains_key(\"name\"));\n}\n```\n\nVerification:\n- `cargo test`\n- `cargo clippy -- -D warnings`\n\nEngineering notes:\n- Language: Rust\n- Framework/tooling: Axum\n- Stack context: FastAPI, PostgreSQL, Redis, Celery, pytest, Docker\n- Domain: auth service\n- Task type: api_endpoint_work\n- Difficulty: medium\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "Add a clear docstring and type hints to this function:\n\n```python\ndef f44277(s):\n return ''.join(x for x in s if x.isalnum()).lower()\n```\n\n```python\nfrom __future__ import annotations\n\ndef f44277(s: str) -> str:\n \"\"\"Normalize a string: keep only alphanumerics and lowercase the result.\"\"\"\n return \"\".join(ch for ch in s if ch.isalnum()).lower()\n```", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Refactor to modern typed Python with immutability and tests.\n\nFile: mcvpxx1shmsg.py\n```python\nclass T3I8Ndus8Eo7:\n def __init__(self, name, values):\n self.name = name\n self.values = list(values)\n def add(self, v):\n self.values.append(v)\n def mean(self):\n s = 0\n for x in self.values:\n s += x\n return s / len(self.values)\n```\n\nReturn full new mcvpxx1shmsg.py and test_mcvpxx1shmsg.py.\n\n# mcvpxx1shmsg.py\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom typing import Iterable, Tuple\n\n@dataclass(frozen=True)\nclass T3I8Ndus8Eo7:\n name: str\n values: Tuple[float, ...]\n\n @staticmethod\n def create(name: str, values: Iterable[float]) -> \"T3I8Ndus8Eo7\":\n vals = tuple(float(v) for v in values)\n if not vals:\n raise ValueError(\"values must be non-empty\")\n return T3I8Ndus8Eo7(name=name, values=vals)\n\n def add(self, v: float) -> \"T3I8Ndus8Eo7\":\n return T3I8Ndus8Eo7(name=self.name, values=self.values + (float(v),))\n\n def mean(self) -> float:\n return sum(self.values) / len(self.values)\n\n# test_mcvpxx1shmsg.py\nimport pytest\nfrom mcvpxx1shmsg import T3I8Ndus8Eo7\n\ndef test_mean_and_add():\n c = T3I8Ndus8Eo7.create(\"a\", [1, 2, 3])\n assert c.mean() == 2.0\n assert c.add(5).mean() == (1 + 2 + 3 + 5) / 4\n\ndef test_empty_raises():\n with pytest.raises(ValueError):\n T3I8Ndus8Eo7.create(\"x\", [])", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Refactor to typed, mostly-immutable Python and add minimal tests.\n\n```python\nclass C81039:\n def __init__(self, values): self.values=list(values)\n def mean(self): return sum(self.values)/len(self.values)\n```\nReturn `m37003.py` and `test_m37003.py`.\n\n```python\n# m37003.py\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom typing import Iterable, Tuple\n\n@dataclass(frozen=True)\nclass C81039:\n values: Tuple[float, ...]\n\n @staticmethod\n def create(values: Iterable[float]) -> \"C81039\":\n vals = tuple(float(v) for v in values)\n if not vals: raise ValueError(\"empty\")\n return C81039(vals)\n\n def mean(self) -> float:\n return sum(self.values)/len(self.values)\n```\n\n```python\n# test_m37003.py\nimport pytest\nfrom m37003 import C81039\n\ndef test_mean():\n assert C81039.create([1,2,3]).mean() == 2.0\ndef test_empty():\n with pytest.raises(ValueError):\n C81039.create([])\n```", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Task type: mechanized_spec\nScenario: graph query service\nDomain focus: high-frequency trading systems (safe engineering)\nPrimary language: lean\nDifficulty: expert+\nScale/SLO: multi-region active-active\nComponent: component_wopdicwy\nConstraints: assume adversarial inputs; validate everything, include verification strategy, avoid data races and undefined behavior, include backward compatibility and migration plan, include deterministic replay plan, include failure modes and recovery\nAssume hostile inputs and targeted abuse patterns.\nDeliverable: Provide a mechanized-style spec outline (Lean-like), key definitions, and a proof plan. Include executable reference code skeleton and tests.\n\nOutput: rigorous design + invariants + verification plan + implementation sketch.\n**Contract**\n- Inputs validated at the boundary; explicit error taxonomy.\n- Idempotency for side effects via request_id; deterministic replay.\n- Backward compatibility: additive changes by default; versioned breaking changes.\n**Invariants**\n- Liveness: under bounded faults and stable network, progress occurs.\n- Safety: state transitions preserve invariants; no partial commit leaks.\n- Isolation: tenant boundary enforced; no cross-tenant reads/writes.\n**Failure modes & recovery**\n- Crash during commit: WAL replay completes or transaction aborts; no torn writes.\n- Duplicate requests: de-duplicate by (tenant, request_id) returning cached response.\n- Data corruption: checksums + scrubber; quarantine and rebuild from replicas/snapshots.\n**Security posture (defensive)**\n- Threat model: auth/authz, injection, replay/abuse, supply chain.\n- Least privilege; secrets in managed store; audit logs for sensitive ops.\n- Input normalization, parameterized queries, path traversal protections.\n**Verification strategy**\n- Fuzzing of parsers/framers/validators with corpus seeds.\n- Canary + shadow traffic; invariants checked in production via assertions/metrics.\n- Deterministic simulation with fault injection (crash/partition/latency).\n\n**Snippet**\n```lean\n-- Pseudo-Lean outline\nstructure State where\n ver : Nat\n val : Option ByteArray\n\ndef invariant (s : State) : Prop := True\n\ntheorem step_preserves_invariant :\n ∀ s, invariant s → ∀ s', Step s s' → invariant s' := by\n intro s hs s' hstep\n -- proof plan: case analysis on transition; trivial here\n trivial\n```\n\nExpert+ checks: mechanized invariants (or exhaustive model checking), adversarial fuzzing, and multi-region failure drills.", "source": "WithinUsAI/Omega_Genesis_Coder_100k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Refactor to modern typed Python with immutability and tests.\n\nFile: m6zvbgxou__.py\n```python\nclass F81Ppt0Mhak:\n def __init__(self, name, values):\n self.name = name\n self.values = list(values)\n def add(self, v):\n self.values.append(v)\n def mean(self):\n s = 0\n for x in self.values:\n s += x\n return s / len(self.values)\n```\n\nReturn full new m6zvbgxou__.py and test_m6zvbgxou__.py.\n\n# m6zvbgxou__.py\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom typing import Iterable, Tuple\n\n@dataclass(frozen=True)\nclass F81Ppt0Mhak:\n name: str\n values: Tuple[float, ...]\n\n @staticmethod\n def create(name: str, values: Iterable[float]) -> \"F81Ppt0Mhak\":\n vals = tuple(float(v) for v in values)\n if not vals:\n raise ValueError(\"values must be non-empty\")\n return F81Ppt0Mhak(name=name, values=vals)\n\n def add(self, v: float) -> \"F81Ppt0Mhak\":\n return F81Ppt0Mhak(name=self.name, values=self.values + (float(v),))\n\n def mean(self) -> float:\n return sum(self.values) / len(self.values)\n\n# test_m6zvbgxou__.py\nimport pytest\nfrom m6zvbgxou__ import F81Ppt0Mhak\n\ndef test_mean_and_add():\n c = F81Ppt0Mhak.create(\"a\", [1, 2, 3])\n assert c.mean() == 2.0\n assert c.add(5).mean() == (1 + 2 + 3 + 5) / 4\n\ndef test_empty_raises():\n with pytest.raises(ValueError):\n F81Ppt0Mhak.create(\"x\", [])", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Task type: distributed_algorithm\nScenario: graph query service\nDomain focus: large-scale ML systems\nPrimary language: typescript\nDifficulty: hard\nScale/SLO: p99 < 150ms\nComponent: component_paaecxyp\nConstraints: include performance model and limits, include security threat model (defensive only), include test vectors and fuzz strategy, include deterministic replay plan, include failure modes and recovery, explicit contracts and invariants\nAssume crash-only processes; recovery must be deterministic.\nDeliverable: Design an algorithm with message flows and correctness arguments (safety + liveness). Include failure handling and a minimal reference implementation skeleton.\n\nOutput: elite engineering answer optimized for correctness, performance, and operability.\n**Contract**\n- Inputs validated at the boundary; explicit error taxonomy.\n- Idempotency for side effects via request_id; deterministic replay.\n- Backward compatibility: additive changes by default; versioned breaking changes.\n**Invariants**\n- Liveness: under bounded faults and stable network, progress occurs.\n- Isolation: tenant boundary enforced; no cross-tenant reads/writes.\n- Determinism: replay of the same event log yields identical outputs.\n**Failure modes & recovery**\n- Crash during commit: WAL replay completes or transaction aborts; no torn writes.\n- Network partition: minority cannot commit; clients receive retriable errors.\n- Duplicate requests: de-duplicate by (tenant, request_id) returning cached response.\n**Security posture (defensive)**\n- Threat model: auth/authz, injection, replay/abuse, supply chain.\n- Least privilege; secrets in managed store; audit logs for sensitive ops.\n- Input normalization, parameterized queries, path traversal protections.\n**Verification strategy**\n- Property tests against a pure reference model (state machine).\n- Fuzzing of parsers/framers/validators with corpus seeds.\n- Deterministic simulation with fault injection (crash/partition/latency).\n\n**Snippet**\n```text\nImplementation sketch: factor pure state-machine core; adapters for I/O; add deterministic replay log.\n```\nHard checks: fault injection tests gate merges; perf thresholds enforced in CI.", "source": "WithinUsAI/Omega_Genesis_Coder_100k"} {"text": "Perform a code review for a fraud detection PR implementing offline-first sync.\nTarget platform: backend (Python FastAPI).\nRequirements: list critical issues, improvements, and provide an improved patch excerpt.\nConstraints: must include clear error handling, must be observable (logs/metrics/traces), must include type hints where applicable, must be production-ready, must be performant under load.\nDifficulty: medium. Include rollback strategy.\n\nOutput: production-oriented blueprint with code where appropriate.\nDeliverable: code review findings + improved patch excerpt.\n\n**Critical issues**\n1. Missing input validation at boundary; potential unexpected exceptions.\n2. No idempotency / retry safety for side-effecting endpoint.\n3. No tests for edge cases (empty input, duplicates, timeouts).\n4. Observability gaps: no request_id correlation, no metrics.\n\n**Improvements**\n- Add strict validation and explicit error responses.\n- Add idempotency key support for create endpoints.\n- Add unit + integration tests with CI gating.\n- Add structured logs and basic metrics.\n\nPatch excerpt (illustrative):\n```python\nif not idem_key:\n raise HTTPException(400, \"Missing Idempotency-Key\")\n```\n\n\nChecks: input validation, tests, and safe defaults included.", "source": "WithinUsAI/GOD_Coder_100k"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: Language: Bash\nFramework/tooling: curl\nDomain: model serving gateway\nLogic challenge: JWT refresh token rotation\nTask type: edge_case_hardening\nDifficulty: hard\n\nReturn a rigorous engineering answer:\n- identify the hidden root cause or logical failure\n- present the corrected implementation\n- add tests that prove the fix\n- list verification commands\n- explain why naive fixes are insufficient when relevant\n\nRepository sketch:\nrepo/\n scripts/\n run.sh\n deploy.sh\n tests/\n smoke.sh\n\nFocus: Focus on strong structured logic with edge cases, data validation, and concurrency safety.\n\nassistant: Diagnosis:\n- Root cause: the failure around JWT refresh token rotation is caused by missing validation, weak edge-case handling, or unsafe lifecycle behavior in the current implementation.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```bash\n#!/usr/bin/env bash\nset -euo pipefail\n\ninput=\"${1:-}\"\nif [[ -z \"$input\" ]]; then\n echo \"missing input\" >&2\n exit 1\nfi\n\nprintf '%s\n' \"$input\" | tr -d '\r'\n```\n\nTests:\n```bash\noutput=\"$(bash scripts/run.sh \"abc\")\"\ntest \"$output\" = \"abc\"\n```\n\nVerification:\n- `bash tests/smoke.sh`\n- `shellcheck scripts/*.sh`\n\nEngineering notes:\n- Language: Bash\n- Framework/tooling: curl\n- Stack context: GitHub Actions, Docker Compose, Kubernetes, Terraform\n- Domain: model serving gateway\n- Task type: edge_case_hardening\n- Difficulty: hard\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "Create a comprehensive test plan and automated tests for event-driven workflows in a document processing product.\nTarget platform: web (React + TypeScript).\nRequirements: unit/integration tests, edge cases, load tests strategy, and CI gates.\nConstraints: must include documentation/comments, must include type hints where applicable, must be secure-by-default.\nDifficulty: medium. Assume 10k RPS peak traffic.\n\nOutput: design + implementation guidance suitable for shipping.\nDeliverable: test plan + automation guidance.\n\n**Unit tests**\n- Validation: malformed payloads rejected with correct codes.\n- AuthZ: tenant boundary enforced.\n- Idempotency: replay returns same response; conflicting reuse yields 409.\n\n**Integration tests**\n- DB transaction behavior; unique constraints.\n- Cache behavior: correctness under concurrent requests.\n\n**Load tests**\n- 10k RPS target: measure p95 latency, error rate, saturation.\n\n**CI gates**\n- Lint + typecheck + unit tests required.\n- Coverage threshold for critical modules.\n- Block merge on flaky test detection.\n\n\nChecks: input validation, tests, and safe defaults included.", "source": "WithinUsAI/GOD_Coder_100k"} {"text": "Write secure, defensive Python code for ETL pipelines.\nRequirements: input validation, safe file handling, prevent path traversal, include tests.\nConstraints: must include tests, must be streaming-friendly, must handle Windows paths safely, must be easy to extend.\nDifficulty: hard. Guarantee deterministic output ordering.\n\nDeliverable: API + reference implementation + tests.\n```python\nfrom __future__ import annotations\n\nfrom dataclasses import dataclass\nfrom pathlib import Path\nfrom typing import Iterable\nimport json\n\n\nclass ValidationError(ValueError):\n \"\"\"Raised when input validation fails.\"\"\"\n\n\ndef safe_join(base: Path, *parts: str) -> Path:\n \"\"\"Join paths while preventing traversal outside base.\"\"\"\n b = base.resolve()\n p = (b / Path(*parts)).resolve()\n if p != b and b not in p.parents:\n raise ValidationError(f\"unsafe path: {p}\")\n return p\n\n\n@dataclass(frozen=True, slots=True)\nclass Record:\n key: str\n value: int\n\n\ndef parse_jsonl(lines: Iterable[str]) -> list[Record]:\n out: list[Record] = []\n for idx, line in enumerate(lines, 1):\n s = line.strip()\n if not s:\n continue\n try:\n obj = json.loads(s)\n except json.JSONDecodeError as e:\n raise ValidationError(f\"line {idx}: invalid json\") from e\n if not isinstance(obj, dict):\n raise ValidationError(f\"line {idx}: expected object\")\n key = obj.get(\"key\")\n val = obj.get(\"value\")\n if not isinstance(key, str) or not key:\n raise ValidationError(f\"line {idx}: key must be non-empty str\")\n if not isinstance(val, int):\n raise ValidationError(f\"line {idx}: value must be int\")\n out.append(Record(key, val))\n return out\n\n\ndef write_jsonl(base: Path, rel: str, records: Iterable[Record]) -> Path:\n base.mkdir(parents=True, exist_ok=True)\n dst = safe_join(base, rel)\n dst.parent.mkdir(parents=True, exist_ok=True)\n with dst.open(\"w\", encoding=\"utf-8\", newline=\"\\n\") as f:\n for r in records:\n f.write(json.dumps({\"key\": r.key, \"value\": r.value}, ensure_ascii=False) + \"\\n\")\n return dst\n```\n\n```python\n# tests (pytest-style)\nimport json\nfrom pathlib import Path\nimport pytest\nfrom module_under_test import ValidationError, Record, parse_jsonl, write_jsonl\n\ndef test_parse_ok():\n lines = [json.dumps({\"key\":\"a\",\"value\":1}), json.dumps({\"key\":\"b\",\"value\":2})]\n assert parse_jsonl(lines) == [Record(\"a\",1), Record(\"b\",2)]\n\ndef test_parse_rejects_bad_json():\n with pytest.raises(ValidationError):\n parse_jsonl([\"{not json}\"])\n\ndef test_safe_join_blocks_traversal(tmp_path: Path):\n with pytest.raises(ValidationError):\n write_jsonl(tmp_path, \"../x.jsonl\", [Record(\"a\",1)])\n```", "source": "WithinUsAI/python_GOD_coder_100k"} {"text": "Optimize while preserving behavior and order.\n\n```python\ndef f14507(xs):\n out=[]\n for x in xs:\n if x not in out: out.append(x)\n return out\n```\nReturn `m73501.py` with types and O(n) average.\n\n```python\n# m73501.py\nfrom __future__ import annotations\nfrom typing import Iterable, List, Set, TypeVar\nT=TypeVar(\"T\")\n\ndef f14507(xs: Iterable[T]) -> List[T]:\n \"\"\"Unique items preserving first-seen order.\"\"\"\n seen: Set[T]=set()\n out: List[T]=[]\n for x in xs:\n if x in seen: continue\n seen.add(x); out.append(x)\n return out\n```", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Provision infrastructure for a content moderation workload providing offline-first sync.\nTarget platform: data (SQL + Python).\nRequirements: IaC (Terraform or Kubernetes YAML), networking, secrets, autoscaling.\nConstraints: must be secure-by-default, must be production-ready, must be easy to extend.\nDifficulty: hard. Assume 10k RPS peak traffic.\n\nOutput: production-oriented blueprint with code where appropriate.\nDeliverable: Kubernetes deployment + basic security posture.\n\n```yaml\napiVersion: apps/v1\nkind: Deployment\nmetadata:\n name: app\nspec:\n replicas: 3\n selector:\n matchLabels: { app: app }\n template:\n metadata:\n labels: { app: app }\n spec:\n containers:\n - name: app\n image: app:latest\n ports: [{ containerPort: 8080 }]\n readinessProbe:\n httpGet: { path: /healthz, port: 8080 }\n resources:\n requests: { cpu: \"200m\", memory: \"256Mi\" }\n limits: { cpu: \"1\", memory: \"1Gi\" }\n```\n\nAdditions:\n- NetworkPolicy to restrict egress/ingress.\n- Secrets via external secret store; rotate regularly.\n- HPA for autoscaling; PodDisruptionBudget for availability.\n\n\nHard-mode checks: concurrency safety, idempotency, and rollback validated; add chaos tests where feasible.", "source": "WithinUsAI/GOD_Coder_100k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Refactor to modern typed Python with immutability and tests.\n\nFile: sd3qu97rrq.py\n```python\nclass Ngsmt2Grla5:\n def __init__(self, name, values):\n self.name = name\n self.values = list(values)\n def add(self, v):\n self.values.append(v)\n def mean(self):\n s = 0\n for x in self.values:\n s += x\n return s / len(self.values)\n```\n\nReturn full new sd3qu97rrq.py and test_sd3qu97rrq.py.\n\n# sd3qu97rrq.py\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom typing import Iterable, Tuple\n\n@dataclass(frozen=True)\nclass Ngsmt2Grla5:\n name: str\n values: Tuple[float, ...]\n\n @staticmethod\n def create(name: str, values: Iterable[float]) -> \"Ngsmt2Grla5\":\n vals = tuple(float(v) for v in values)\n if not vals:\n raise ValueError(\"values must be non-empty\")\n return Ngsmt2Grla5(name=name, values=vals)\n\n def add(self, v: float) -> \"Ngsmt2Grla5\":\n return Ngsmt2Grla5(name=self.name, values=self.values + (float(v),))\n\n def mean(self) -> float:\n return sum(self.values) / len(self.values)\n\n# test_sd3qu97rrq.py\nimport pytest\nfrom sd3qu97rrq import Ngsmt2Grla5\n\ndef test_mean_and_add():\n c = Ngsmt2Grla5.create(\"a\", [1, 2, 3])\n assert c.mean() == 2.0\n assert c.add(5).mean() == (1 + 2 + 3 + 5) / 4\n\ndef test_empty_raises():\n with pytest.raises(ValueError):\n Ngsmt2Grla5.create(\"x\", [])", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Implement idempotent payments for a content moderation product.\nTarget platform: infra (Docker + Kubernetes).\nRequirements: provide production-ready code, configuration, and tests.\nConstraints: must avoid global state, must be observable (logs/metrics/traces), must be easy to extend.\nDifficulty: easy. Assume PII must be protected.\n\nOutput: design + implementation guidance suitable for shipping.\nDeliverable: production-grade reference implementation (FastAPI) + tests.\n\n```python\n# app.py\nfrom __future__ import annotations\n\nimport hashlib\nimport json\nfrom dataclasses import dataclass\nfrom datetime import datetime, timezone\nfrom typing import Any, Optional\n\nfrom fastapi import FastAPI, Header, HTTPException\nfrom pydantic import BaseModel, Field\n\napp = FastAPI(title=\"Idempotent API\")\n\nclass CreateReq(BaseModel):\n tenant_id: str = Field(min_length=1)\n amount_cents: int = Field(ge=0)\n currency: str = Field(min_length=3, max_length=3)\n\nclass CreateResp(BaseModel):\n id: str\n created_at: str\n echo: CreateReq\n\n@dataclass\nclass _IdempoEntry:\n request_hash: str\n response_json: str\n\n# In production: Postgres table with UNIQUE(tenant_id, key)\n_IDEMPO: dict[tuple[str, str], _IdempoEntry] = {}\n\ndef _hash_req(req: CreateReq) -> str:\n raw = req.model_dump_json()\n return hashlib.sha256(raw.encode(\"utf-8\")).hexdigest()\n\n@app.post(\"/v1/payments\", response_model=CreateResp)\ndef create_payment(\n req: CreateReq,\n idempotency_key: Optional[str] = Header(default=None, alias=\"Idempotency-Key\"),\n) -> Any:\n if not idempotency_key:\n raise HTTPException(status_code=400, detail=\"Missing Idempotency-Key\")\n if len(idempotency_key) > 128:\n raise HTTPException(status_code=400, detail=\"Idempotency-Key too long\")\n\n key = (req.tenant_id, idempotency_key)\n rh = _hash_req(req)\n\n existing = _IDEMPO.get(key)\n if existing:\n if existing.request_hash != rh:\n raise HTTPException(status_code=409, detail=\"Idempotency-Key reuse with different payload\")\n return json.loads(existing.response_json)\n\n # Create new payment (stubbed)\n pid = hashlib.md5(f\"{req.tenant_id}:{idempotency_key}\".encode()).hexdigest()\n resp = CreateResp(\n id=pid,\n created_at=datetime.now(timezone.utc).isoformat(),\n echo=req,\n )\n _IDEMPO[key] = _IdempoEntry(request_hash=rh, response_json=resp.model_dump_json())\n return resp\n```\n\n```python\n# test_app.py (pytest)\nfrom fastapi.testclient import TestClient\nfrom app import app\n\nclient = TestClient(app)\n\ndef test_idempotent_replay():\n headers = {\"Idempotency-Key\": \"abc\"}\n body = {\"tenant_id\":\"t1\",\"amount_cents\":100,\"currency\":\"USD\"}\n r1 = client.post(\"/v1/payments\", json=body, headers=headers)\n r2 = client.post(\"/v1/payments\", json=body, headers=headers)\n assert r1.status_code == 200 and r2.status_code == 200\n assert r1.json() == r2.json()\n\ndef test_payload_conflict():\n headers = {\"Idempotency-Key\": \"abc\"}\n b1 = {\"tenant_id\":\"t1\",\"amount_cents\":100,\"currency\":\"USD\"}\n b2 = {\"tenant_id\":\"t1\",\"amount_cents\":200,\"currency\":\"USD\"}\n assert client.post(\"/v1/payments\", json=b1, headers=headers).status_code == 200\n assert client.post(\"/v1/payments\", json=b2, headers=headers).status_code == 409\n```\n\nNotes:\n- Replace in-memory store with a DB table and transaction.\n- Store response + request hash to detect key reuse with different payload.\n\n\nChecks: input validation, tests, and safe defaults included.", "source": "WithinUsAI/GOD_Coder_100k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Refactor to modern typed Python with immutability and tests.\n\nFile: aven7saci4l.py\n```python\nclass Zpfd05Boo:\n def __init__(self, name, values):\n self.name = name\n self.values = list(values)\n def add(self, v):\n self.values.append(v)\n def mean(self):\n s = 0\n for x in self.values:\n s += x\n return s / len(self.values)\n```\n\nReturn full new aven7saci4l.py and test_aven7saci4l.py.\n\n# aven7saci4l.py\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom typing import Iterable, Tuple\n\n@dataclass(frozen=True)\nclass Zpfd05Boo:\n name: str\n values: Tuple[float, ...]\n\n @staticmethod\n def create(name: str, values: Iterable[float]) -> \"Zpfd05Boo\":\n vals = tuple(float(v) for v in values)\n if not vals:\n raise ValueError(\"values must be non-empty\")\n return Zpfd05Boo(name=name, values=vals)\n\n def add(self, v: float) -> \"Zpfd05Boo\":\n return Zpfd05Boo(name=self.name, values=self.values + (float(v),))\n\n def mean(self) -> float:\n return sum(self.values) / len(self.values)\n\n# test_aven7saci4l.py\nimport pytest\nfrom aven7saci4l import Zpfd05Boo\n\ndef test_mean_and_add():\n c = Zpfd05Boo.create(\"a\", [1, 2, 3])\n assert c.mean() == 2.0\n assert c.add(5).mean() == (1 + 2 + 3 + 5) / 4\n\ndef test_empty_raises():\n with pytest.raises(ValueError):\n Zpfd05Boo.create(\"x\", [])", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Refactor an existing codebase in enterprise SaaS to support multi-tenant isolation cleanly.\nTarget platform: mobile (Android Kotlin).\nRequirements: propose new modules/layers, dependency boundaries, and migration plan.\nConstraints: must include clear error handling, must be performant under load, must include documentation/comments.\nDifficulty: easy. Assume untrusted input; validate everything.\n\nOutput: production-oriented blueprint with code where appropriate.\nDeliverable: refactor plan + module boundaries.\n\n**Proposed modules**\n- `domain/` pure business logic (no I/O)\n- `adapters/` DB, cache, external APIs\n- `api/` request/response validation and routing\n- `observability/` logging/metrics/tracing\n- `tests/` unit + integration suites\n\n**Migration plan**\n1. Introduce new interfaces + adapters behind feature flags.\n2. Dual-write or read-compat layer if schema changes.\n3. Incremental cutover; deprecate legacy module.\n\nKey rule: dependencies flow inward; domain has no framework imports.\n\n\nChecks: input validation, tests, and safe defaults included.", "source": "WithinUsAI/GOD_Coder_100k"} {"text": "Build an elite-grade solution in the domain of gpu compute for scenario: job scheduler.\nPrimary language: python.\nDifficulty: hard.\nConstraints: include invariants and failure modes, avoid undefined behavior and data races, provide rollout and rollback guidance, include tests or verification strategy, assume untrusted inputs; validate and sanitize.\nComponent: component_noujcoo.\nAssume partial network partitions occur weekly.\nTask: Define an API and evolving schema strategy (versioning, migrations, compatibility rules). Provide example schemas and validation tests.\n\nOutput: elite-grade engineering answer with contracts, edge cases, and verification.\nOutput: GPU pipeline design for throughput and tail-latency.\n\n**Pipeline**\n- Request batching with max batch size + max wait (e.g., 5ms) to control p99.\n- Separate CPU pre/post-processing threads; pin memory for transfers if available.\n- Model warmup; cache weights in VRAM; use concurrency limits.\n\n**Monitoring**\n- GPU utilization, queue wait time, batch size distribution, OOM events.\n\n**Fallback**\n- Graceful degradation to smaller batch size; circuit breaker on repeated OOM.\n\n\nHard checks: failure injection tests and performance regressions gated.", "source": "WithinUsAI/Elite_GOD_Coder_100k"} {"text": "Task type: tla_state_machine\nScenario: identity and access\nDomain focus: formal verification\nPrimary language: tla+\nDifficulty: hard\nScale/SLO: 100k RPS peak\nComponent: component_puwaeifd\nConstraints: include verification strategy, explicit contracts and invariants, assume adversarial inputs; validate everything, include deterministic replay plan, include test vectors and fuzz strategy\nAssume crash-only processes; recovery must be deterministic.\nDeliverable: Provide a TLA+-style state machine (pseudo), safety/liveness properties, and a model-checking strategy. Include an implementation sketch and test vectors.\n\nOutput: contract-first solution with failure modes, security posture, and test/verification strategy.\n**Contract**\n- Inputs validated at the boundary; explicit error taxonomy.\n- Idempotency for side effects via request_id; deterministic replay.\n- Backward compatibility: additive changes by default; versioned breaking changes.\n**Invariants**\n- Liveness: under bounded faults and stable network, progress occurs.\n- Safety: state transitions preserve invariants; no partial commit leaks.\n- Determinism: replay of the same event log yields identical outputs.\n**Failure modes & recovery**\n- Crash during commit: WAL replay completes or transaction aborts; no torn writes.\n- Duplicate requests: de-duplicate by (tenant, request_id) returning cached response.\n- Data corruption: checksums + scrubber; quarantine and rebuild from replicas/snapshots.\n**Security posture (defensive)**\n- Threat model: auth/authz, injection, replay/abuse, supply chain.\n- Least privilege; secrets in managed store; audit logs for sensitive ops.\n- Input normalization, parameterized queries, path traversal protections.\n**Verification strategy**\n- Property tests against a pure reference model (state machine).\n- Canary + shadow traffic; invariants checked in production via assertions/metrics.\n- Fuzzing of parsers/framers/validators with corpus seeds.\n\n**Snippet**\n```tla\nVARIABLES state, log, seen\n\nInit == state = [k \\in Keys |-> <<0, NULL>>] /\\ log = << >> /\\ seen = [r \\in ReqIds |-> NULL]\n\nPut(req, k, v) ==\n IF seen[req] # NULL THEN UNCHANGED <>\n ELSE\n LET ver == state[k][1] + 1 IN\n /\\ state' = [state EXCEPT ![k] = <>]\n /\\ log' = Append(log, <>)\n /\\ seen' = [seen EXCEPT ![req] = <<\"ok\", ver>>]\n\nSafety == \\A k \\in Keys: state[k][1] >= 0\n```\n\nHard checks: fault injection tests gate merges; perf thresholds enforced in CI.", "source": "WithinUsAI/Omega_Genesis_Coder_100k"} {"text": "Optimize while preserving behavior and order.\n\n```python\ndef f79495(xs):\n out=[]\n for x in xs:\n if x not in out: out.append(x)\n return out\n```\nReturn `m82785.py` with types and O(n) average.\n\n```python\n# m82785.py\nfrom __future__ import annotations\nfrom typing import Iterable, List, Set, TypeVar\nT=TypeVar(\"T\")\n\ndef f79495(xs: Iterable[T]) -> List[T]:\n \"\"\"Unique items preserving first-seen order.\"\"\"\n seen: Set[T]=set()\n out: List[T]=[]\n for x in xs:\n if x in seen: continue\n seen.add(x); out.append(x)\n return out\n```", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Build an elite-grade solution in the domain of security engineering (defensive) for scenario: chat messaging.\nPrimary language: python.\nDifficulty: hard.\nConstraints: design for backward compatibility and migrations, make the interface contract explicit, include tests or verification strategy.\nComponent: component_bclyqbj.\nAssume schema changes every sprint; must be backward compatible.\nTask: Define an API and evolving schema strategy (versioning, migrations, compatibility rules). Provide example schemas and validation tests.\n\nOutput: elite-grade engineering answer with contracts, edge cases, and verification.\nOutput: GPU pipeline design for throughput and tail-latency.\n\n**Pipeline**\n- Request batching with max batch size + max wait (e.g., 5ms) to control p99.\n- Separate CPU pre/post-processing threads; pin memory for transfers if available.\n- Model warmup; cache weights in VRAM; use concurrency limits.\n\n**Monitoring**\n- GPU utilization, queue wait time, batch size distribution, OOM events.\n\n**Fallback**\n- Graceful degradation to smaller batch size; circuit breaker on repeated OOM.\n\n\nHard checks: failure injection tests and performance regressions gated.", "source": "WithinUsAI/Elite_GOD_Coder_100k"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: Language: TypeScript\nFramework/tooling: Node.js\nDomain: feature flag service\nLogic challenge: N+1 query explosion\nTask type: multi_file_migration_repair\nDifficulty: expert\n\nReturn a rigorous engineering answer:\n- identify the hidden root cause or logical failure\n- present the corrected implementation\n- add tests that prove the fix\n- list verification commands\n- explain why naive fixes are insufficient when relevant\n\nRepository sketch:\nrepo/\n src/\n api.ts\n service.ts\n schema.ts\n tests/\n api.test.ts\n package.json\n\nFocus: Focus on staff-level problem solving with multi-file patches, rollout implications, performance and security tradeoffs.\n\nassistant: Diagnosis:\n- Staff-level diagnosis: N+1 query explosion impacts correctness, operability, and future maintenance, so the fix must be minimal where possible but complete where necessary.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```ts\ntype Payload = Record;\n\nexport function normalizePayload(payload: Payload): Payload {\n if (!payload || typeof payload !== \"object\" || Array.isArray(payload)) {\n throw new TypeError(\"payload must be a plain object\");\n }\n return Object.fromEntries(\n Object.entries(payload)\n .filter(([, value]) => value !== null && value !== undefined)\n .map(([key, value]) => [String(key).trim(), value])\n );\n}\n\nexport function handleN+1QueryExplosion(payload: Payload) {\n const clean = normalizePayload(payload);\n if (!(\"id\" in clean)) {\n return { ok: false, data: {}, error: \"missing id\" };\n }\n return { ok: true, data: clean, error: null };\n}\n```\n\nTests:\n```ts\nimport { describe, it, expect } from \"vitest\";\nimport { handleN+1QueryExplosion } from \"../src/service\";\n\ndescribe(\"handler\", () => {\n it(\"accepts valid input\", () => {\n expect(handleN+1QueryExplosion({ id: 7, name: \"ok\", unused: null })).toEqual({\n ok: true,\n data: { id: 7, name: \"ok\" },\n error: null\n });\n });\n\n it(\"rejects missing id\", () => {\n expect(handleN+1QueryExplosion({ name: \"x\" }).error).toMatch(/missing id/);\n });\n});\n```\n\nVerification:\n- `npm test`\n- `npm run typecheck`\n- `npm run lint`\n\nEngineering notes:\n- Language: TypeScript\n- Framework/tooling: Node.js\n- Stack context: Airflow, dbt, DuckDB, MinIO, pytest\n- Domain: feature flag service\n- Task type: multi_file_migration_repair\n- Difficulty: expert\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "Optimize while preserving behavior and order.\n\n```python\ndef f81718(xs):\n out=[]\n for x in xs:\n if x not in out: out.append(x)\n return out\n```\nReturn `m11674.py` with types and O(n) average.\n\n```python\n# m11674.py\nfrom __future__ import annotations\nfrom typing import Iterable, List, Set, TypeVar\nT=TypeVar(\"T\")\n\ndef f81718(xs: Iterable[T]) -> List[T]:\n \"\"\"Unique items preserving first-seen order.\"\"\"\n seen: Set[T]=set()\n out: List[T]=[]\n for x in xs:\n if x in seen: continue\n seen.add(x); out.append(x)\n return out\n```", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Fix a bug and add tests.\n\nFile: dnlwrh.py\n```python\ndef r3134snwl_(n: int) -> int:\n \"\"\"Sum 1..n inclusive.\"\"\"\n if n < 0:\n raise ValueError(\"n must be non-negative\")\n total = 0\n for k in range(n): # BUG: should include n\n total += k\n return total\n```\n\nReturn unified diffs for dnlwrh.py and test_dnlwrh.py (pytest).\n\n*** Begin Patch\n*** Update File: dnlwrh.py\n@@\n def r3134snwl_(n: int) -> int:\n@@\n total = 0\n- for k in range(n): # BUG: should include n\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_dnlwrh.py\n+import pytest\n+from dnlwrh import r3134snwl_\n+\n+def test_zero():\n+ assert r3134snwl_(0) == 0\n+\n+def test_one():\n+ assert r3134snwl_(1) == 1\n+\n+def test_small():\n+ assert r3134snwl_(7) == 28\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ r3134snwl_(-1)\n+\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Debug and fix a subtle production bug related to rate limiting in a IoT telemetry service.\nTarget platform: backend (Go).\nRequirements: identify root cause, provide patch, and add regression tests.\nConstraints: must include type hints where applicable, must include clear error handling, must include tests, must be secure-by-default, must avoid global state.\nDifficulty: expert. Assume GDPR-style deletion requests must be supported.\n\nOutput: design + implementation guidance suitable for shipping.\nDeliverable: production-grade reference implementation (FastAPI) + tests.\n\n```python\n# app.py\nfrom __future__ import annotations\n\nimport hashlib\nimport json\nfrom dataclasses import dataclass\nfrom datetime import datetime, timezone\nfrom typing import Any, Optional\n\nfrom fastapi import FastAPI, Header, HTTPException\nfrom pydantic import BaseModel, Field\n\napp = FastAPI(title=\"Idempotent API\")\n\nclass CreateReq(BaseModel):\n tenant_id: str = Field(min_length=1)\n amount_cents: int = Field(ge=0)\n currency: str = Field(min_length=3, max_length=3)\n\nclass CreateResp(BaseModel):\n id: str\n created_at: str\n echo: CreateReq\n\n@dataclass\nclass _IdempoEntry:\n request_hash: str\n response_json: str\n\n# In production: Postgres table with UNIQUE(tenant_id, key)\n_IDEMPO: dict[tuple[str, str], _IdempoEntry] = {}\n\ndef _hash_req(req: CreateReq) -> str:\n raw = req.model_dump_json()\n return hashlib.sha256(raw.encode(\"utf-8\")).hexdigest()\n\n@app.post(\"/v1/payments\", response_model=CreateResp)\ndef create_payment(\n req: CreateReq,\n idempotency_key: Optional[str] = Header(default=None, alias=\"Idempotency-Key\"),\n) -> Any:\n if not idempotency_key:\n raise HTTPException(status_code=400, detail=\"Missing Idempotency-Key\")\n if len(idempotency_key) > 128:\n raise HTTPException(status_code=400, detail=\"Idempotency-Key too long\")\n\n key = (req.tenant_id, idempotency_key)\n rh = _hash_req(req)\n\n existing = _IDEMPO.get(key)\n if existing:\n if existing.request_hash != rh:\n raise HTTPException(status_code=409, detail=\"Idempotency-Key reuse with different payload\")\n return json.loads(existing.response_json)\n\n # Create new payment (stubbed)\n pid = hashlib.md5(f\"{req.tenant_id}:{idempotency_key}\".encode()).hexdigest()\n resp = CreateResp(\n id=pid,\n created_at=datetime.now(timezone.utc).isoformat(),\n echo=req,\n )\n _IDEMPO[key] = _IdempoEntry(request_hash=rh, response_json=resp.model_dump_json())\n return resp\n```\n\n```python\n# test_app.py (pytest)\nfrom fastapi.testclient import TestClient\nfrom app import app\n\nclient = TestClient(app)\n\ndef test_idempotent_replay():\n headers = {\"Idempotency-Key\": \"abc\"}\n body = {\"tenant_id\":\"t1\",\"amount_cents\":100,\"currency\":\"USD\"}\n r1 = client.post(\"/v1/payments\", json=body, headers=headers)\n r2 = client.post(\"/v1/payments\", json=body, headers=headers)\n assert r1.status_code == 200 and r2.status_code == 200\n assert r1.json() == r2.json()\n\ndef test_payload_conflict():\n headers = {\"Idempotency-Key\": \"abc\"}\n b1 = {\"tenant_id\":\"t1\",\"amount_cents\":100,\"currency\":\"USD\"}\n b2 = {\"tenant_id\":\"t1\",\"amount_cents\":200,\"currency\":\"USD\"}\n assert client.post(\"/v1/payments\", json=b1, headers=headers).status_code == 200\n assert client.post(\"/v1/payments\", json=b2, headers=headers).status_code == 409\n```\n\nNotes:\n- Replace in-memory store with a DB table and transaction.\n- Store response + request hash to detect key reuse with different payload.\n\n\nHard-mode checks: concurrency safety, idempotency, and rollback validated; add chaos tests where feasible.", "source": "WithinUsAI/GOD_Coder_100k"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: Language: Bash\nFramework/tooling: curl\nDomain: artifact registry\nLogic challenge: schema drift during deployment\nTask type: multi_file_migration_repair\nDifficulty: expert\n\nReturn a rigorous engineering answer:\n- identify the hidden root cause or logical failure\n- present the corrected implementation\n- add tests that prove the fix\n- list verification commands\n- explain why naive fixes are insufficient when relevant\n\nRepository sketch:\nrepo/\n scripts/\n run.sh\n deploy.sh\n tests/\n smoke.sh\n\nFocus: Focus on staff-level problem solving with multi-file patches, rollout implications, performance and security tradeoffs.\n\nassistant: Diagnosis:\n- Staff-level diagnosis: schema drift during deployment impacts correctness, operability, and future maintenance, so the fix must be minimal where possible but complete where necessary.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```bash\n#!/usr/bin/env bash\nset -euo pipefail\n\ninput=\"${1:-}\"\nif [[ -z \"$input\" ]]; then\n echo \"missing input\" >&2\n exit 1\nfi\n\nprintf '%s\n' \"$input\" | tr -d '\r'\n```\n\nTests:\n```bash\noutput=\"$(bash scripts/run.sh \"abc\")\"\ntest \"$output\" = \"abc\"\n```\n\nVerification:\n- `bash tests/smoke.sh`\n- `shellcheck scripts/*.sh`\n\nEngineering notes:\n- Language: Bash\n- Framework/tooling: curl\n- Stack context: Rust, Axum, SQLx, Redis, Tokio, Docker\n- Domain: artifact registry\n- Task type: multi_file_migration_repair\n- Difficulty: expert\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: Language: Bash\nFramework/tooling: GNU coreutils\nDomain: payments platform\nLogic challenge: unsafe deserialization\nTask type: transaction_integrity_fix\nDifficulty: hard\n\nReturn a rigorous engineering answer:\n- identify the hidden root cause or logical failure\n- present the corrected implementation\n- add tests that prove the fix\n- list verification commands\n- explain why naive fixes are insufficient when relevant\n\nRepository sketch:\nrepo/\n scripts/\n run.sh\n deploy.sh\n tests/\n smoke.sh\n\nFocus: Focus on ambiguity, misleading symptoms, hidden root causes, and high-stakes debugging.\n\nassistant: Diagnosis:\n- Hidden root cause: unsafe deserialization presents misleading symptoms, so the patch must target the actual logic boundary rather than the first visible failure.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```bash\n#!/usr/bin/env bash\nset -euo pipefail\n\ninput=\"${1:-}\"\nif [[ -z \"$input\" ]]; then\n echo \"missing input\" >&2\n exit 1\nfi\n\nprintf '%s\n' \"$input\" | tr -d '\r'\n```\n\nTests:\n```bash\noutput=\"$(bash scripts/run.sh \"abc\")\"\ntest \"$output\" = \"abc\"\n```\n\nVerification:\n- `bash tests/smoke.sh`\n- `shellcheck scripts/*.sh`\n\nEngineering notes:\n- Language: Bash\n- Framework/tooling: GNU coreutils\n- Stack context: Spring Boot, PostgreSQL, JUnit, Gradle, Docker, GitHub Actions\n- Domain: payments platform\n- Task type: transaction_integrity_fix\n- Difficulty: hard\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "Debug and fix a subtle production bug related to background jobs in a fintech service.\nTarget platform: infra (Docker + Kubernetes).\nRequirements: identify root cause, provide patch, and add regression tests.\nConstraints: must be performant under load, must include documentation/comments, must be production-ready.\nDifficulty: easy. Assume strict latency budget (p95 < 200ms).\n\nOutput: design + implementation guidance suitable for shipping.\nDeliverable: production-grade reference implementation (FastAPI) + tests.\n\n```python\n# app.py\nfrom __future__ import annotations\n\nimport hashlib\nimport json\nfrom dataclasses import dataclass\nfrom datetime import datetime, timezone\nfrom typing import Any, Optional\n\nfrom fastapi import FastAPI, Header, HTTPException\nfrom pydantic import BaseModel, Field\n\napp = FastAPI(title=\"Idempotent API\")\n\nclass CreateReq(BaseModel):\n tenant_id: str = Field(min_length=1)\n amount_cents: int = Field(ge=0)\n currency: str = Field(min_length=3, max_length=3)\n\nclass CreateResp(BaseModel):\n id: str\n created_at: str\n echo: CreateReq\n\n@dataclass\nclass _IdempoEntry:\n request_hash: str\n response_json: str\n\n# In production: Postgres table with UNIQUE(tenant_id, key)\n_IDEMPO: dict[tuple[str, str], _IdempoEntry] = {}\n\ndef _hash_req(req: CreateReq) -> str:\n raw = req.model_dump_json()\n return hashlib.sha256(raw.encode(\"utf-8\")).hexdigest()\n\n@app.post(\"/v1/payments\", response_model=CreateResp)\ndef create_payment(\n req: CreateReq,\n idempotency_key: Optional[str] = Header(default=None, alias=\"Idempotency-Key\"),\n) -> Any:\n if not idempotency_key:\n raise HTTPException(status_code=400, detail=\"Missing Idempotency-Key\")\n if len(idempotency_key) > 128:\n raise HTTPException(status_code=400, detail=\"Idempotency-Key too long\")\n\n key = (req.tenant_id, idempotency_key)\n rh = _hash_req(req)\n\n existing = _IDEMPO.get(key)\n if existing:\n if existing.request_hash != rh:\n raise HTTPException(status_code=409, detail=\"Idempotency-Key reuse with different payload\")\n return json.loads(existing.response_json)\n\n # Create new payment (stubbed)\n pid = hashlib.md5(f\"{req.tenant_id}:{idempotency_key}\".encode()).hexdigest()\n resp = CreateResp(\n id=pid,\n created_at=datetime.now(timezone.utc).isoformat(),\n echo=req,\n )\n _IDEMPO[key] = _IdempoEntry(request_hash=rh, response_json=resp.model_dump_json())\n return resp\n```\n\n```python\n# test_app.py (pytest)\nfrom fastapi.testclient import TestClient\nfrom app import app\n\nclient = TestClient(app)\n\ndef test_idempotent_replay():\n headers = {\"Idempotency-Key\": \"abc\"}\n body = {\"tenant_id\":\"t1\",\"amount_cents\":100,\"currency\":\"USD\"}\n r1 = client.post(\"/v1/payments\", json=body, headers=headers)\n r2 = client.post(\"/v1/payments\", json=body, headers=headers)\n assert r1.status_code == 200 and r2.status_code == 200\n assert r1.json() == r2.json()\n\ndef test_payload_conflict():\n headers = {\"Idempotency-Key\": \"abc\"}\n b1 = {\"tenant_id\":\"t1\",\"amount_cents\":100,\"currency\":\"USD\"}\n b2 = {\"tenant_id\":\"t1\",\"amount_cents\":200,\"currency\":\"USD\"}\n assert client.post(\"/v1/payments\", json=b1, headers=headers).status_code == 200\n assert client.post(\"/v1/payments\", json=b2, headers=headers).status_code == 409\n```\n\nNotes:\n- Replace in-memory store with a DB table and transaction.\n- Store response + request hash to detect key reuse with different payload.\n\n\nChecks: input validation, tests, and safe defaults included.", "source": "WithinUsAI/GOD_Coder_100k"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: System domain: model serving gateway\nStack: Spring Boot, PostgreSQL, JUnit, Gradle, Docker, GitHub Actions\nCross-layer incident: transaction boundary bug\nTask type: cache_consistency_patch\nDifficulty: hard\n\nSolve this as a complete-project engineer.\nOutput must include:\n- root cause across layers\n- final implementation patch\n- tests touching at least two layers\n- deployment or observability note\n- verification commands\n\nRepository sketch:\nrepo/\n migrations/\n 001_init.sql\n 002_add_index.sql\n queries/\n report.sql\n tests/\n report_cases.md\n\nFocus: Focus on multi-layer debugging across frontend, backend, database, CI, caching, and deployment.\n\nassistant: Diagnosis:\n- Root cause: transaction boundary bug crosses service boundaries, so the fix must align code, contracts, tests, and deployment behavior.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```sql\nWITH ranked AS (\n SELECT\n user_id,\n created_at,\n amount,\n ROW_NUMBER() OVER (PARTITION BY user_id ORDER BY created_at DESC, id DESC) AS rn\n FROM orders\n)\nSELECT user_id, created_at, amount\nFROM ranked\nWHERE rn = 1;\n```\n\nTests:\n```sql\n-- Correctness checks:\n-- 1) multiple rows per user\n-- 2) identical timestamps require deterministic tie-breaker\n-- 3) null values handled by business rules\n```\n\nVerification:\n- `run migration checks`\n- `run query correctness cases`\n\nEngineering notes:\n- Language: SQL\n- Framework/tooling: MySQL\n- Stack context: Spring Boot, PostgreSQL, JUnit, Gradle, Docker, GitHub Actions\n- Domain: model serving gateway\n- Task type: cache_consistency_patch\n- Difficulty: hard\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: Project stack: Airflow, dbt, DuckDB, MinIO, pytest\nLanguage: Bash\nDependency challenge: log redaction failure\nTask type: build_reproducibility_fix\nDifficulty: hard\n\nFix this as a senior engineer.\nRequired:\n- identify the version or compatibility failure mode\n- produce the corrected config/code/build patch\n- explain rollback-safe migration notes\n- add regression tests or reproducibility checks\n- include concrete verification commands\n\nRepository sketch:\nrepo/\n scripts/\n run.sh\n deploy.sh\n tests/\n smoke.sh\n\nFocus: Focus on versioning, migrations, lockfiles, runtime compatibility, and secure dependency handling.\n\nassistant: Diagnosis:\n- Root cause: the issue around log redaction failure is a dependency, migration, or runtime-compatibility mismatch that needs a rollback-safe patch.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```bash\n#!/usr/bin/env bash\nset -euo pipefail\n\ninput=\"${1:-}\"\nif [[ -z \"$input\" ]]; then\n echo \"missing input\" >&2\n exit 1\nfi\n\nprintf '%s\n' \"$input\" | tr -d '\r'\n```\n\nTests:\n```bash\noutput=\"$(bash scripts/run.sh \"abc\")\"\ntest \"$output\" = \"abc\"\n```\n\nVerification:\n- `bash tests/smoke.sh`\n- `shellcheck scripts/*.sh`\n\nEngineering notes:\n- Language: Bash\n- Framework/tooling: curl\n- Stack context: Airflow, dbt, DuckDB, MinIO, pytest\n- Domain: benchmark harness\n- Task type: build_reproducibility_fix\n- Difficulty: hard\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: System domain: feature flag service\nStack: Next.js, Node.js, Prisma, PostgreSQL, Playwright, Docker\nCross-layer incident: timezone bug in reporting\nTask type: cache_consistency_patch\nDifficulty: hard\n\nSolve this as a complete-project engineer.\nOutput must include:\n- root cause across layers\n- final implementation patch\n- tests touching at least two layers\n- deployment or observability note\n- verification commands\n\nRepository sketch:\nrepo/\n src/main.rs\n src/lib.rs\n src/service.rs\n src/store.rs\n tests/integration.rs\n Cargo.toml\n\nFocus: Focus on multi-layer debugging across frontend, backend, database, CI, caching, and deployment.\n\nassistant: Diagnosis:\n- Root cause: timezone bug in reporting crosses service boundaries, so the fix must align code, contracts, tests, and deployment behavior.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```rust\nuse std::collections::HashMap;\n\npub fn normalize_payload(payload: HashMap) -> HashMap {\n payload\n .into_iter()\n .filter(|(_, v)| !v.trim().is_empty())\n .collect()\n}\n```\n\nTests:\n```rust\n#[test]\nfn normalize_payload_filters_empty_values() {\n use std::collections::HashMap;\n let mut payload = HashMap::new();\n payload.insert(\"id\".to_string(), \"7\".to_string());\n payload.insert(\"name\".to_string(), \"\".to_string());\n let out = normalize_payload(payload);\n assert!(out.contains_key(\"id\"));\n assert!(!out.contains_key(\"name\"));\n}\n```\n\nVerification:\n- `cargo test`\n- `cargo clippy -- -D warnings`\n\nEngineering notes:\n- Language: Rust\n- Framework/tooling: cargo test\n- Stack context: Next.js, Node.js, Prisma, PostgreSQL, Playwright, Docker\n- Domain: feature flag service\n- Task type: cache_consistency_patch\n- Difficulty: hard\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Optimize while preserving behavior.\n\nFile: z2813b9sx0.py\n```python\ndef poz6upe(xs):\n out = []\n for x in xs:\n if x not in out:\n out.append(x)\n return out\n```\n\nRequirements: preserve first-seen order; O(n) average; add types + docstring.\n\n# z2813b9sx0.py\nfrom __future__ import annotations\nfrom typing import Iterable, List, Set, TypeVar\n\nT = TypeVar(\"T\")\n\ndef poz6upe(xs: Iterable[T]) -> List[T]:\n \"\"\"Return unique items preserving first-seen order.\"\"\"\n seen: Set[T] = set()\n out: List[T] = []\n for x in xs:\n if x in seen:\n continue\n seen.add(x)\n out.append(x)\n return out", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Design and implement an algorithm for telemetry ingestion.\nRequirements: define inputs/outputs, implement solution with complexity analysis, and include tests.\nConstraints: must avoid global state, stdlib-only.\nDifficulty: easy. Support both Windows and POSIX paths correctly.\n\nDeliverable: implementation + tests.\nProblem: compute rolling sums over events (ts:int,value:int) with window W seconds. Events may be out-of-order.\n\nComplexity: sorting O(n log n); window maintenance O(n); memory O(k).\n\n```python\nfrom __future__ import annotations\nfrom collections import deque\nfrom dataclasses import dataclass\nfrom typing import Iterable, List, Tuple\n\n@dataclass(frozen=True, slots=True)\nclass Event:\n ts: int\n value: int\n\ndef rolling_sum(events: Iterable[Event], window_s: int) -> List[Tuple[int,int]]:\n if window_s < 0:\n raise ValueError(\"window_s must be >= 0\")\n evs = sorted(events, key=lambda e: e.ts)\n q: deque[Event] = deque()\n s = 0\n out: List[Tuple[int,int]] = []\n for e in evs:\n q.append(e)\n s += e.value\n cutoff = e.ts - window_s\n while q and q[0].ts < cutoff:\n old = q.popleft()\n s -= old.value\n out.append((e.ts, s))\n return out\n```\n\n```python\nimport pytest\nfrom module_under_test import Event, rolling_sum\n\ndef test_rolling_sum():\n ev = [Event(10,1), Event(11,2), Event(20,5)]\n assert rolling_sum(ev, 5) == [(10,1),(11,3),(20,5)]\n```", "source": "WithinUsAI/python_GOD_coder_100k"} {"text": "Fix the bug and add pytest tests.\n\n```python\ndef f09446(n: int) -> int:\n # sum 1..n inclusive\n if n < 0: raise ValueError\n total = 0\n for k in range(n): # BUG\n total += k\n return total\n```\nReturn unified diffs for `m72778.py` and `test_m72778.py`.\n\n*** Begin Patch\n*** Update File: m72778.py\n@@\n def f09446(n: int) -> int:\n@@\n- for k in range(n): # BUG\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_m72778.py\n+import pytest\n+from m72778 import f09446\n+\n+def test_small():\n+ assert f09446(7) == 28\n+\n+def test_zero():\n+ assert f09446(0) == 0\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ f09446(-1)\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Task type: runtime_gc\nScenario: document indexing pipeline\nDomain focus: high-frequency trading systems (safe engineering)\nPrimary language: go\nDifficulty: expert\nScale/SLO: p99 < 150ms\nComponent: component_cpbsxghf\nConstraints: include verification strategy, include backward compatibility and migration plan, assume adversarial inputs; validate everything, include security threat model (defensive only), avoid data races and undefined behavior\nAssume strict auditability and replayable history.\nDeliverable: Design a GC/runtime component (mark-sweep/arena/RC hybrid); include pause-time strategy and tests.\n\nOutput: rigorous design + invariants + verification plan + implementation sketch.\n**Contract**\n- Inputs validated at the boundary; explicit error taxonomy.\n- Idempotency for side effects via request_id; deterministic replay.\n- Backward compatibility: additive changes by default; versioned breaking changes.\n**Invariants**\n- Isolation: tenant boundary enforced; no cross-tenant reads/writes.\n- Liveness: under bounded faults and stable network, progress occurs.\n- Determinism: replay of the same event log yields identical outputs.\n**Failure modes & recovery**\n- Crash during commit: WAL replay completes or transaction aborts; no torn writes.\n- Network partition: minority cannot commit; clients receive retriable errors.\n- Duplicate requests: de-duplicate by (tenant, request_id) returning cached response.\n**Security posture (defensive)**\n- Threat model: auth/authz, injection, replay/abuse, supply chain.\n- Least privilege; secrets in managed store; audit logs for sensitive ops.\n- Input normalization, parameterized queries, path traversal protections.\n**Verification strategy**\n- Fuzzing of parsers/framers/validators with corpus seeds.\n- Canary + shadow traffic; invariants checked in production via assertions/metrics.\n- Property tests against a pure reference model (state machine).\n\n**Snippet**\n```text\nImplementation sketch: factor pure state-machine core; adapters for I/O; add deterministic replay log.\n```\nExpert checks: state-machine proof sketch + model checking; upgrade/rollback rehearsed.", "source": "WithinUsAI/Omega_Genesis_Coder_100k"} {"text": "Design and implement an algorithm for rate limiting.\nRequirements: define inputs/outputs, implement solution with complexity analysis, and include tests.\nConstraints: must include tests, must be streaming-friendly, must include docstrings.\nDifficulty: easy. Ensure the API is testable via dependency injection.\n\nDeliverable: production-ready reference solution.\nProblem: compute rolling sums over events (ts:int,value:int) with window W seconds. Events may be out-of-order.\n\nComplexity: sorting O(n log n); window maintenance O(n); memory O(k).\n\n```python\nfrom __future__ import annotations\nfrom collections import deque\nfrom dataclasses import dataclass\nfrom typing import Iterable, List, Tuple\n\n@dataclass(frozen=True, slots=True)\nclass Event:\n ts: int\n value: int\n\ndef rolling_sum(events: Iterable[Event], window_s: int) -> List[Tuple[int,int]]:\n if window_s < 0:\n raise ValueError(\"window_s must be >= 0\")\n evs = sorted(events, key=lambda e: e.ts)\n q: deque[Event] = deque()\n s = 0\n out: List[Tuple[int,int]] = []\n for e in evs:\n q.append(e)\n s += e.value\n cutoff = e.ts - window_s\n while q and q[0].ts < cutoff:\n old = q.popleft()\n s -= old.value\n out.append((e.ts, s))\n return out\n```\n\n```python\nimport pytest\nfrom module_under_test import Event, rolling_sum\n\ndef test_rolling_sum():\n ev = [Event(10,1), Event(11,2), Event(20,5)]\n assert rolling_sum(ev, 5) == [(10,1),(11,3),(20,5)]\n```", "source": "WithinUsAI/python_GOD_coder_100k"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: Project domain: repo automation\nImplementation stack: Rust, Axum, SQLx, Redis, Tokio, Docker\nSoftware delivery problem: S3-compatible upload inconsistency\nTask type: prd_to_patch\nDifficulty: medium\n\nReturn a complete delivery-grade response with:\n- diagnosis or design reasoning\n- implementation\n- test plan or tests\n- rollout plan\n- rollback or compatibility note\n- verification commands\n\nRepository sketch:\nrepo/\n cmd/server/main.go\n internal/service/service.go\n internal/store/store.go\n internal/api/api.go\n service_test.go\n go.mod\n\nFocus: Focus on shipping production software with rollout safety, acceptance criteria, telemetry, and maintenance quality.\n\nassistant: Diagnosis:\n- Root cause or delivery blocker: S3-compatible upload inconsistency needs both implementation work and a safe shipping plan.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```go\npackage service\n\nimport \"fmt\"\n\nfunc NormalizePayload(payload map[string]any) map[string]any {\n\tout := make(map[string]any)\n\tfor k, v := range payload {\n\t\tif v == nil {\n\t\t\tcontinue\n\t\t}\n\t\tout[k] = v\n\t}\n\treturn out\n}\n\nfunc Handle(payload map[string]any) (map[string]any, error) {\n\tclean := NormalizePayload(payload)\n\tif _, ok := clean[\"id\"]; !ok {\n\t\treturn nil, fmt.Errorf(\"missing id\")\n\t}\n\treturn map[string]any{\"ok\": true, \"data\": clean}, nil\n}\n```\n\nTests:\n```go\npackage service\n\nimport \"testing\"\n\nfunc TestHandle(t *testing.T) {\n\tgot, err := Handle(map[string]any{\"id\": 7, \"name\": \"ok\", \"unused\": nil})\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tif got[\"ok\"] != true {\n\t\tt.Fatalf(\"expected ok=true\")\n\t}\n\tif _, err := Handle(map[string]any{\"name\": \"x\"}); err == nil {\n\t\tt.Fatalf(\"expected missing id error\")\n\t}\n}\n```\n\nVerification:\n- `go test ./...`\n- `go vet ./...`\n\nEngineering notes:\n- Language: Go\n- Framework/tooling: Fiber\n- Stack context: Rust, Axum, SQLx, Redis, Tokio, Docker\n- Domain: repo automation\n- Task type: prd_to_patch\n- Difficulty: medium\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "Build an elite-grade solution in the domain of security engineering (defensive) for scenario: payment processing.\nPrimary language: python.\nDifficulty: hard.\nConstraints: make the interface contract explicit, provide rollout and rollback guidance, design for backward compatibility and migrations, include invariants and failure modes.\nComponent: component_yittxif.\nAssume strict auditability and replayable history.\nTask: Design an application-level protocol (framing, retries, timeouts, backpressure). Provide client/server skeleton and test vectors.\n\nOutput: elite-grade engineering answer with contracts, edge cases, and verification.\nOutput: protocol framing + retry policy + client/server skeleton.\n\n**Framing**\n- Length-prefixed: uint32_be length + payload\n- Payload: msgpack/json; include request_id, type, and optional checksum\n\n**Reliability**\n- Retries only for idempotent ops; exponential backoff + jitter.\n- Timeouts: connect, read, overall; enforce max in-flight to provide backpressure.\n\n**Test vectors**\n- Corrupted length / truncated frame rejected\n- Duplicate request_id returns cached response\n- Slowloris protection by read deadlines\n\n\nHard checks: failure injection tests and performance regressions gated.", "source": "WithinUsAI/Elite_GOD_Coder_100k"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: Project domain: feature flag service\nImplementation stack: Spring Boot, PostgreSQL, JUnit, Gradle, Docker, GitHub Actions\nSoftware delivery problem: path traversal on downloads\nTask type: release_engineering_fix\nDifficulty: medium\n\nReturn a complete delivery-grade response with:\n- diagnosis or design reasoning\n- implementation\n- test plan or tests\n- rollout plan\n- rollback or compatibility note\n- verification commands\n\nRepository sketch:\nrepo/\n src/\n api.ts\n service.ts\n schema.ts\n tests/\n api.test.ts\n package.json\n\nFocus: Focus on shipping production software with rollout safety, acceptance criteria, telemetry, and maintenance quality.\n\nassistant: Diagnosis:\n- Root cause or delivery blocker: path traversal on downloads needs both implementation work and a safe shipping plan.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```ts\ntype Payload = Record;\n\nexport function normalizePayload(payload: Payload): Payload {\n if (!payload || typeof payload !== \"object\" || Array.isArray(payload)) {\n throw new TypeError(\"payload must be a plain object\");\n }\n return Object.fromEntries(\n Object.entries(payload)\n .filter(([, value]) => value !== null && value !== undefined)\n .map(([key, value]) => [String(key).trim(), value])\n );\n}\n\nexport function handlePathTraversalOnDownloads(payload: Payload) {\n const clean = normalizePayload(payload);\n if (!(\"id\" in clean)) {\n return { ok: false, data: {}, error: \"missing id\" };\n }\n return { ok: true, data: clean, error: null };\n}\n```\n\nTests:\n```ts\nimport { describe, it, expect } from \"vitest\";\nimport { handlePathTraversalOnDownloads } from \"../src/service\";\n\ndescribe(\"handler\", () => {\n it(\"accepts valid input\", () => {\n expect(handlePathTraversalOnDownloads({ id: 7, name: \"ok\", unused: null })).toEqual({\n ok: true,\n data: { id: 7, name: \"ok\" },\n error: null\n });\n });\n\n it(\"rejects missing id\", () => {\n expect(handlePathTraversalOnDownloads({ name: \"x\" }).error).toMatch(/missing id/);\n });\n});\n```\n\nVerification:\n- `npm test`\n- `npm run typecheck`\n- `npm run lint`\n\nEngineering notes:\n- Language: TypeScript\n- Framework/tooling: NestJS\n- Stack context: Spring Boot, PostgreSQL, JUnit, Gradle, Docker, GitHub Actions\n- Domain: feature flag service\n- Task type: release_engineering_fix\n- Difficulty: medium\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: Repository domain: payments platform\nPrimary language: JavaScript\nFramework/tooling: Jest\nReported problem: build reproducibility failure\nTask type: api_endpoint_work\nDifficulty: hard\n\nProduce a complete professional engineering response:\n1. Diagnose the root cause.\n2. Provide the corrected implementation or patch.\n3. Add tests.\n4. Add verification commands.\n5. Note edge cases and any migration or rollback risk.\n\nRepository sketch:\nrepo/\n src/\n api.js\n service.js\n utils.js\n tests/\n api.test.js\n package.json\n\nQuality target:\n- Minimal diff unless redesign is clearly required\n- Production-ready code\n- No placeholders\n- Secure defaults\n- Clear acceptance of failure cases\n\nFocus: Focus on complete implementation quality, patch correctness, tests, and production readiness.\n\nassistant: Diagnosis:\n- Root cause: the failure around build reproducibility failure is caused by missing validation, weak edge-case handling, or unsafe lifecycle behavior in the current implementation.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```javascript\ntype Payload = Record;\n\nexport function normalizePayload(payload: Payload): Payload {\n if (!payload || typeof payload !== \"object\" || Array.isArray(payload)) {\n throw new TypeError(\"payload must be a plain object\");\n }\n return Object.fromEntries(\n Object.entries(payload)\n .filter(([, value]) => value !== null && value !== undefined)\n .map(([key, value]) => [String(key).trim(), value])\n );\n}\n\nexport function handleBuildReproducibilityFailure(payload: Payload) {\n const clean = normalizePayload(payload);\n if (!(\"id\" in clean)) {\n return { ok: false, data: {}, error: \"missing id\" };\n }\n return { ok: true, data: clean, error: null };\n}\n```\n\nTests:\n```javascript\nimport { describe, it, expect } from \"vitest\";\nimport { handleBuildReproducibilityFailure } from \"../src/service\";\n\ndescribe(\"handler\", () => {\n it(\"accepts valid input\", () => {\n expect(handleBuildReproducibilityFailure({ id: 7, name: \"ok\", unused: null })).toEqual({\n ok: true,\n data: { id: 7, name: \"ok\" },\n error: null\n });\n });\n\n it(\"rejects missing id\", () => {\n expect(handleBuildReproducibilityFailure({ name: \"x\" }).error).toMatch(/missing id/);\n });\n});\n```\n\nVerification:\n- `npm test`\n- `npm run lint`\n\nEngineering notes:\n- Language: JavaScript\n- Framework/tooling: Jest\n- Stack context: GitHub Actions, Docker Compose, Kubernetes, Terraform\n- Domain: payments platform\n- Task type: api_endpoint_work\n- Difficulty: hard\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "Implement an ML engineering workflow for healthtech focusing on A/B experimentation.\nTarget platform: ML (training + serving).\nRequirements: data contract, training loop, evaluation, model registry, serving API, monitoring.\nConstraints: must be easy to extend, must include documentation/comments, must be observable (logs/metrics/traces), must include tests.\nDifficulty: expert. Assume schema evolves frequently; design for migrations.\n\nOutput: engineering-grade answer with edge cases covered.\nDeliverable: ML engineering blueprint (training + serving + monitoring), safe and production-oriented.\n\n**Data contract**\n- Define feature schema + ranges; validate at training and serving.\n\n**Training**\n- Deterministic split; baseline model; track metrics (AUC/F1/latency).\n- Store artifacts: model, config, feature stats.\n\n**Registry**\n- Promote models via approval gates; record lineage.\n\n**Serving**\n- Separate inference service with `/predict`.\n- Input validation + default handling; timeouts.\n\n**Monitoring**\n- Data drift: feature distribution checks.\n- Performance: online metrics + periodic labels; alert on regression.\n\nMinimal serving skeleton (FastAPI-ish):\n```python\n# validate input -> vectorize -> model.predict_proba -> return\n```\n\n\nHard-mode checks: concurrency safety, idempotency, and rollback validated; add chaos tests where feasible.", "source": "WithinUsAI/GOD_Coder_100k"} {"text": "Add a clear docstring and type hints to this function:\n\n```python\ndef f50870(s):\n return ''.join(x for x in s if x.isalnum()).lower()\n```\n\n```python\nfrom __future__ import annotations\n\ndef f50870(s: str) -> str:\n \"\"\"Normalize a string: keep only alphanumerics and lowercase the result.\"\"\"\n return \"\".join(ch for ch in s if ch.isalnum()).lower()\n```", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Task type: storage_engine\nScenario: identity and access\nDomain focus: program synthesis (safe)\nPrimary language: bash\nDifficulty: expert+\nScale/SLO: 100k RPS peak\nComponent: component_mttceabg\nConstraints: explicit contracts and invariants, include performance model and limits, include verification strategy, include deterministic replay plan, include test vectors and fuzz strategy, include security threat model (defensive only)\nAssume hostile inputs and targeted abuse patterns.\nDeliverable: Design a storage engine subsystem (WAL, snapshots, compaction). Include crash recovery invariants and a benchmark plan.\n\nOutput: rigorous design + invariants + verification plan + implementation sketch.\n**Contract**\n- Inputs validated at the boundary; explicit error taxonomy.\n- Idempotency for side effects via request_id; deterministic replay.\n- Backward compatibility: additive changes by default; versioned breaking changes.\n**Invariants**\n- Liveness: under bounded faults and stable network, progress occurs.\n- Isolation: tenant boundary enforced; no cross-tenant reads/writes.\n- Determinism: replay of the same event log yields identical outputs.\n**Failure modes & recovery**\n- Network partition: minority cannot commit; clients receive retriable errors.\n- Duplicate requests: de-duplicate by (tenant, request_id) returning cached response.\n- Data corruption: checksums + scrubber; quarantine and rebuild from replicas/snapshots.\n**Security posture (defensive)**\n- Threat model: auth/authz, injection, replay/abuse, supply chain.\n- Least privilege; secrets in managed store; audit logs for sensitive ops.\n- Input normalization, parameterized queries, path traversal protections.\n**Verification strategy**\n- Deterministic simulation with fault injection (crash/partition/latency).\n- Fuzzing of parsers/framers/validators with corpus seeds.\n- Property tests against a pure reference model (state machine).\n\n**Snippet**\n```text\nImplementation sketch: factor pure state-machine core; adapters for I/O; add deterministic replay log.\n```\nExpert+ checks: mechanized invariants (or exhaustive model checking), adversarial fuzzing, and multi-region failure drills.", "source": "WithinUsAI/Omega_Genesis_Coder_100k"} {"text": "Build an elite-grade solution in the domain of networking for scenario: multi-tenant SaaS.\nPrimary language: go.\nDifficulty: medium.\nConstraints: assume untrusted inputs; validate and sanitize, document performance characteristics, provide rollout and rollback guidance.\nComponent: component_ndbyfgs.\nAssume strict auditability and replayable history.\nTask: Implement or outline a storage/indexing subsystem (LSM/B-Tree, WAL, snapshots). Include transaction/consistency considerations and benchmark plan.\n\nOutput: rigorous solution with invariants, failure modes, and performance notes.\nOutput: storage design + WAL + compaction + benchmarks.\n\n**Design**\n- WAL (append-only) for durability; fsync policy configurable.\n- Memtable (in-memory) → flush to immutable SSTables.\n- LSM compaction tiers; bloom filters per SSTable for point-lookups.\n- Manifest tracks SSTable set; atomic pointer swap on updates.\n\n**Correctness**\n- Crash recovery: replay WAL to rebuild memtable; manifest ensures last consistent set.\n- Reads: merge memtable + SSTables newest→oldest; tombstones override older values.\n\n**Bench plan**\n- Workloads: write-heavy, read-heavy, mixed; measure p50/p95 latency and write amplification.\n- Track compaction debt and space amplification.\n\n**Test plan**\n- Fuzz crash points: kill after WAL append / after manifest update; verify invariants on restart.\n\n\nChecks: boundary validation and deterministic behavior verified.", "source": "WithinUsAI/Elite_GOD_Coder_100k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Fix a bug and add tests.\n\nFile: ek9wt0md1or.py\n```python\ndef qox61_0(n: int) -> int:\n \"\"\"Sum 1..n inclusive.\"\"\"\n if n < 0:\n raise ValueError(\"n must be non-negative\")\n total = 0\n for k in range(n): # BUG: should include n\n total += k\n return total\n```\n\nReturn unified diffs for ek9wt0md1or.py and test_ek9wt0md1or.py (pytest).\n\n*** Begin Patch\n*** Update File: ek9wt0md1or.py\n@@\n def qox61_0(n: int) -> int:\n@@\n total = 0\n- for k in range(n): # BUG: should include n\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_ek9wt0md1or.py\n+import pytest\n+from ek9wt0md1or import qox61_0\n+\n+def test_zero():\n+ assert qox61_0(0) == 0\n+\n+def test_one():\n+ assert qox61_0(1) == 1\n+\n+def test_small():\n+ assert qox61_0(7) == 28\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ qox61_0(-1)\n+\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: Language: Python\nFramework/tooling: Pydantic\nDomain: search service\nLogic challenge: streaming timeout handling\nTask type: distributed_debug\nDifficulty: hard\n\nReturn a rigorous engineering answer:\n- identify the hidden root cause or logical failure\n- present the corrected implementation\n- add tests that prove the fix\n- list verification commands\n- explain why naive fixes are insufficient when relevant\n\nRepository sketch:\nrepo/\n app/\n api.py\n service.py\n models.py\n tests/\n test_api.py\n pyproject.toml\n\nFocus: Focus on ambiguity, misleading symptoms, hidden root causes, and high-stakes debugging.\n\nassistant: Diagnosis:\n- Hidden root cause: streaming timeout handling presents misleading symptoms, so the patch must target the actual logic boundary rather than the first visible failure.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```python\nfrom __future__ import annotations\n\nfrom dataclasses import dataclass\nfrom typing import Any\n\n@dataclass\nclass ServiceResult:\n ok: bool\n data: dict[str, Any]\n error: str | None = None\n\ndef normalize_payload(payload: dict[str, Any]) -> dict[str, Any]:\n if not isinstance(payload, dict):\n raise TypeError(\"payload must be a dict\")\n clean: dict[str, Any] = {}\n for key, value in payload.items():\n if value is None:\n continue\n clean[str(key).strip()] = value\n return clean\n\ndef handle_streaming_timeout_handling(payload: dict[str, Any]) -> ServiceResult:\n clean = normalize_payload(payload)\n if \"id\" not in clean:\n return ServiceResult(ok=False, data={}, error=\"missing id\")\n return ServiceResult(ok=True, data=clean)\n```\n\nTests:\n```python\nimport pytest\nfrom app.service import handle_jwt_refresh_token_rotation as handler\n\ndef test_handler_accepts_valid_payload():\n result = handler({\"id\": 7, \"name\": \"ok\", \"unused\": None})\n assert result.ok is True\n assert result.data == {\"id\": 7, \"name\": \"ok\"}\n\ndef test_handler_rejects_missing_id():\n result = handler({\"name\": \"x\"})\n assert result.ok is False\n assert result.error == \"missing id\"\n```\n\nVerification:\n- `pytest -q`\n- `ruff check .`\n- `python -m compileall .`\n\nEngineering notes:\n- Language: Python\n- Framework/tooling: Pydantic\n- Stack context: Go, Gin, PostgreSQL, gRPC, Prometheus, Docker\n- Domain: search service\n- Task type: distributed_debug\n- Difficulty: hard\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "Task type: secure_architecture\nScenario: real-time notification hub\nDomain focus: compiler toolchains\nPrimary language: rust\nDifficulty: expert+\nScale/SLO: p99 < 150ms\nComponent: component_qxvzdyxq\nConstraints: avoid data races and undefined behavior, explicit contracts and invariants, include verification strategy, assume adversarial inputs; validate everything, include performance model and limits\nAssume crash-only processes; recovery must be deterministic.\nDeliverable: Provide a defensive threat model and secure-by-default architecture; include monitoring/detection and tests (no offensive content).\n\nOutput: elite engineering answer optimized for correctness, performance, and operability.\n**Contract**\n- Inputs validated at the boundary; explicit error taxonomy.\n- Idempotency for side effects via request_id; deterministic replay.\n- Backward compatibility: additive changes by default; versioned breaking changes.\n**Invariants**\n- Isolation: tenant boundary enforced; no cross-tenant reads/writes.\n- Safety: state transitions preserve invariants; no partial commit leaks.\n- Liveness: under bounded faults and stable network, progress occurs.\n**Failure modes & recovery**\n- Data corruption: checksums + scrubber; quarantine and rebuild from replicas/snapshots.\n- Duplicate requests: de-duplicate by (tenant, request_id) returning cached response.\n- Crash during commit: WAL replay completes or transaction aborts; no torn writes.\n**Security posture (defensive)**\n- Threat model: auth/authz, injection, replay/abuse, supply chain.\n- Least privilege; secrets in managed store; audit logs for sensitive ops.\n- Input normalization, parameterized queries, path traversal protections.\n**Verification strategy**\n- Canary + shadow traffic; invariants checked in production via assertions/metrics.\n- Property tests against a pure reference model (state machine).\n- Deterministic simulation with fault injection (crash/partition/latency).\n\n**Snippet**\n```text\nImplementation sketch: factor pure state-machine core; adapters for I/O; add deterministic replay log.\n```\nExpert+ checks: mechanized invariants (or exhaustive model checking), adversarial fuzzing, and multi-region failure drills.", "source": "WithinUsAI/Omega_Genesis_Coder_100k"} {"text": "Design CI/CD for a calendar/scheduling service delivering rate limiting.\nTarget platform: mobile (Android Kotlin).\nRequirements: pipelines, checks, artifact strategy, deployments, and rollbacks.\nConstraints: must include clear error handling, must be secure-by-default, must be production-ready, must include tests, must be easy to extend.\nDifficulty: easy. Include rollback strategy.\n\nOutput: engineering-grade answer with edge cases covered.\nDeliverable: CI/CD pipeline (GitHub Actions) with quality gates.\n\n```yaml\nname: ci\non:\n pull_request:\n push:\n branches: [main]\n\njobs:\n test:\n runs-on: ubuntu-latest\n steps:\n - uses: actions/checkout@v4\n - uses: actions/setup-python@v5\n with:\n python-version: \"3.11\"\n - run: python -m pip install -U pip\n - run: pip install -r requirements.txt\n - run: pip install -r requirements-dev.txt\n - run: ruff check .\n - run: mypy .\n - run: pytest -q --maxfail=1 --disable-warnings\n\n docker:\n needs: test\n runs-on: ubuntu-latest\n steps:\n - uses: actions/checkout@v4\n - uses: docker/setup-buildx-action@v3\n - run: docker build -t app:${{ github.sha }} .\n```\n\nDeployment strategy:\n- main → build → deploy to staging → smoke tests → canary to prod.\n- Rollback: redeploy previous image + DB migration rollback plan.\n\n\nChecks: input validation, tests, and safe defaults included.", "source": "WithinUsAI/GOD_Coder_100k"} {"text": "Write a thorough test suite for a Python component used for time series.\nRequirements: cover edge cases, invalid inputs, and behavior invariants.\nConstraints: must avoid global state, must be streaming-friendly, must be easy to extend.\nDifficulty: hard. Guarantee deterministic output ordering.\n\nDeliverable: API + reference implementation + tests.\n```python\n# tests (pytest-style) for a module providing: normalize(), parse_lines(), compute_stats()\nimport math\nimport pytest\n\ndef test_normalize_idempotent(module_under_test):\n x = \" A\\tB \"\n assert module_under_test.normalize(module_under_test.normalize(x)) == module_under_test.normalize(x)\n\ndef test_parse_lines_rejects_invalid(module_under_test):\n with pytest.raises(ValueError):\n module_under_test.parse_lines([\"\", \"???\", None]) # type: ignore[arg-type]\n\ndef test_compute_stats_basic(module_under_test):\n data = [1, 2, 3, 4]\n s = module_under_test.compute_stats(data)\n assert s.count == 4\n assert s.total == 10\n assert math.isclose(s.mean, 2.5)\n```", "source": "WithinUsAI/python_GOD_coder_100k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Fix a bug and add tests.\n\nFile: fs_3nvw2tek.py\n```python\ndef flqr1u9mm(n: int) -> int:\n \"\"\"Sum 1..n inclusive.\"\"\"\n if n < 0:\n raise ValueError(\"n must be non-negative\")\n total = 0\n for k in range(n): # BUG: should include n\n total += k\n return total\n```\n\nReturn unified diffs for fs_3nvw2tek.py and test_fs_3nvw2tek.py (pytest).\n\n*** Begin Patch\n*** Update File: fs_3nvw2tek.py\n@@\n def flqr1u9mm(n: int) -> int:\n@@\n total = 0\n- for k in range(n): # BUG: should include n\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_fs_3nvw2tek.py\n+import pytest\n+from fs_3nvw2tek import flqr1u9mm\n+\n+def test_zero():\n+ assert flqr1u9mm(0) == 0\n+\n+def test_one():\n+ assert flqr1u9mm(1) == 1\n+\n+def test_small():\n+ assert flqr1u9mm(7) == 28\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ flqr1u9mm(-1)\n+\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Fix a bug and add tests.\n\nFile: fcftwaz1su.py\n```python\ndef yv0zxcj2p(n: int) -> int:\n \"\"\"Sum 1..n inclusive.\"\"\"\n if n < 0:\n raise ValueError(\"n must be non-negative\")\n total = 0\n for k in range(n): # BUG: should include n\n total += k\n return total\n```\n\nReturn unified diffs for fcftwaz1su.py and test_fcftwaz1su.py (pytest).\n\n*** Begin Patch\n*** Update File: fcftwaz1su.py\n@@\n def yv0zxcj2p(n: int) -> int:\n@@\n total = 0\n- for k in range(n): # BUG: should include n\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_fcftwaz1su.py\n+import pytest\n+from fcftwaz1su import yv0zxcj2p\n+\n+def test_zero():\n+ assert yv0zxcj2p(0) == 0\n+\n+def test_one():\n+ assert yv0zxcj2p(1) == 1\n+\n+def test_small():\n+ assert yv0zxcj2p(7) == 28\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ yv0zxcj2p(-1)\n+\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Produce an offline-first self-evolving code assistant architecture named `irz3tgp7v`.\nMust include: module layout, patch-safety policy, evaluation gates (tests/lint/types), versioned memory index.\n\nArchitecture: `irz3tgp7v` (offline-first, self-evolving)\n\nModules\n- core/loop.py: evolve → validate → accept/reject (bounded iterations)\n- patching/: diff builder, safe apply, atomic writes, rollback points\n- policy/: allowlist paths, deny globs (.git/, __pycache__/, binaries), patch size caps\n- signals/: parse pytest/ruff/mypy into normalized findings\n- memory/index.jsonl: append-only snapshots (hashes, metrics, rationale)\n\nSafety gates\n- refuse path traversal/symlink escapes; never edit binaries\n- accept only if tests/lint/types stay green or improve", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Refactor to typed, mostly-immutable Python and add minimal tests.\n\n```python\nclass C85452:\n def __init__(self, values): self.values=list(values)\n def mean(self): return sum(self.values)/len(self.values)\n```\nReturn `m75804.py` and `test_m75804.py`.\n\n```python\n# m75804.py\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom typing import Iterable, Tuple\n\n@dataclass(frozen=True)\nclass C85452:\n values: Tuple[float, ...]\n\n @staticmethod\n def create(values: Iterable[float]) -> \"C85452\":\n vals = tuple(float(v) for v in values)\n if not vals: raise ValueError(\"empty\")\n return C85452(vals)\n\n def mean(self) -> float:\n return sum(self.values)/len(self.values)\n```\n\n```python\n# test_m75804.py\nimport pytest\nfrom m75804 import C85452\n\ndef test_mean():\n assert C85452.create([1,2,3]).mean() == 2.0\ndef test_empty():\n with pytest.raises(ValueError):\n C85452.create([])\n```", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Write pytest tests for `f95504`.\n\n```python\ndef f95504(a: int, b: int) -> int:\n return a*a + b*b\n```\nInclude edge cases and a property-style check.\n\n```python\nimport random\nfrom m85072 import f95504\n\ndef test_known():\n assert f95504(3,4) == 25\n\ndef test_zero():\n assert f95504(0,0) == 0\n\ndef test_property_nonnegative():\n for _ in range(200):\n a=random.randint(-50,50)\n b=random.randint(-50,50)\n assert f95504(a,b) >= 0\n```", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Build an elite-grade solution in the domain of security engineering (defensive) for scenario: analytics pipeline.\nPrimary language: python.\nDifficulty: medium.\nConstraints: provide rollout and rollback guidance, include invariants and failure modes, design for backward compatibility and migrations, assume untrusted inputs; validate and sanitize.\nComponent: component_mzoshsj.\nAssume compliance requires data deletion with proofs.\nTask: Define a small DSL, implement tokenizer/parser, IR, and a codegen or interpreter. Include tests and complexity notes.\n\nOutput: production blueprint plus correctness arguments and test strategy.\nOutput: DSL + parser + IR + interpreter/codegen + tests.\n\n**DSL**\n- Expressions: integers, identifiers, `+ - * /`, let-binding: `let x = expr in expr`\n- Example: `let x = 2+3 in x*10`\n\n**Pipeline**\n1. Tokenize\n2. Parse into AST\n3. Lower into IR (stack ops) or interpret AST directly\n\n**Reference (Rust-style outline)**\n- `enum Expr { Int(i64), Var(String), Bin(Op, Box, Box), Let(String, Box, Box) }`\n- Parser: Pratt or recursive descent.\n\n**Tests**\n- Golden tests for parse trees.\n- Property: pretty-print(parse(x)) round-trips for a corpus.\n- Eval tests for precedence and scoping.\n\n\nChecks: boundary validation and deterministic behavior verified.", "source": "WithinUsAI/Elite_GOD_Coder_100k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Optimize while preserving behavior.\n\nFile: awmezi0sta.py\n```python\ndef outee0hqp(xs):\n out = []\n for x in xs:\n if x not in out:\n out.append(x)\n return out\n```\n\nRequirements: preserve first-seen order; O(n) average; add types + docstring.\n\n# awmezi0sta.py\nfrom __future__ import annotations\nfrom typing import Iterable, List, Set, TypeVar\n\nT = TypeVar(\"T\")\n\ndef outee0hqp(xs: Iterable[T]) -> List[T]:\n \"\"\"Return unique items preserving first-seen order.\"\"\"\n seen: Set[T] = set()\n out: List[T] = []\n for x in xs:\n if x in seen:\n continue\n seen.add(x)\n out.append(x)\n return out", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: Project stack: Airflow, dbt, DuckDB, MinIO, pytest\nLanguage: YAML\nDependency challenge: timezone bug in reporting\nTask type: cve_dependency_remediation\nDifficulty: medium\n\nFix this as a senior engineer.\nRequired:\n- identify the version or compatibility failure mode\n- produce the corrected config/code/build patch\n- explain rollback-safe migration notes\n- add regression tests or reproducibility checks\n- include concrete verification commands\n\nRepository sketch:\nrepo/\n .github/workflows/ci.yml\n docker-compose.yml\n deploy/\n app.yaml\n\nFocus: Focus on versioning, migrations, lockfiles, runtime compatibility, and secure dependency handling.\n\nassistant: Diagnosis:\n- Root cause: the issue around timezone bug in reporting is a dependency, migration, or runtime-compatibility mismatch that needs a rollback-safe patch.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```yaml\nname: ci\non: [push, pull_request]\njobs:\n test:\n runs-on: ubuntu-latest\n steps:\n - uses: actions/checkout@v4\n - name: Validate\n run: echo \"validated\"\n```\n\nTests:\n```yaml\n# Verification:\n# - validate syntax\n# - run smoke workflow\n# - fail fast on broken config\n```\n\nVerification:\n- `validate workflow syntax`\n- `run CI smoke job`\n\nEngineering notes:\n- Language: YAML\n- Framework/tooling: Terraform\n- Stack context: Airflow, dbt, DuckDB, MinIO, pytest\n- Domain: observability collector\n- Task type: cve_dependency_remediation\n- Difficulty: medium\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "Refactor to typed, mostly-immutable Python and add minimal tests.\n\n```python\nclass C60609:\n def __init__(self, values): self.values=list(values)\n def mean(self): return sum(self.values)/len(self.values)\n```\nReturn `m73893.py` and `test_m73893.py`.\n\n```python\n# m73893.py\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom typing import Iterable, Tuple\n\n@dataclass(frozen=True)\nclass C60609:\n values: Tuple[float, ...]\n\n @staticmethod\n def create(values: Iterable[float]) -> \"C60609\":\n vals = tuple(float(v) for v in values)\n if not vals: raise ValueError(\"empty\")\n return C60609(vals)\n\n def mean(self) -> float:\n return sum(self.values)/len(self.values)\n```\n\n```python\n# test_m73893.py\nimport pytest\nfrom m73893 import C60609\n\ndef test_mean():\n assert C60609.create([1,2,3]).mean() == 2.0\ndef test_empty():\n with pytest.raises(ValueError):\n C60609.create([])\n```", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Build an elite-grade solution in the domain of networking for scenario: document indexing.\nPrimary language: python.\nDifficulty: expert.\nConstraints: provide rollout and rollback guidance, assume untrusted inputs; validate and sanitize, document performance characteristics, include tests or verification strategy.\nComponent: component_eputrah.\nAssume 50k RPS and p99 < 250ms.\nTask: Define an API and evolving schema strategy (versioning, migrations, compatibility rules). Provide example schemas and validation tests.\n\nOutput: elite-grade engineering answer with contracts, edge cases, and verification.\nOutput: GPU pipeline design for throughput and tail-latency.\n\n**Pipeline**\n- Request batching with max batch size + max wait (e.g., 5ms) to control p99.\n- Separate CPU pre/post-processing threads; pin memory for transfers if available.\n- Model warmup; cache weights in VRAM; use concurrency limits.\n\n**Monitoring**\n- GPU utilization, queue wait time, batch size distribution, OOM events.\n\n**Fallback**\n- Graceful degradation to smaller batch size; circuit breaker on repeated OOM.\n\n\nExpert checks: state-machine reasoning, concurrency stress, and upgrade/rollback validated.", "source": "WithinUsAI/Elite_GOD_Coder_100k"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: Language: Python\nFramework/tooling: FastAPI\nDomain: job scheduler\nLogic challenge: path traversal on downloads\nTask type: performance_bottleneck_patch\nDifficulty: hard\n\nReturn a rigorous engineering answer:\n- identify the hidden root cause or logical failure\n- present the corrected implementation\n- add tests that prove the fix\n- list verification commands\n- explain why naive fixes are insufficient when relevant\n\nRepository sketch:\nrepo/\n app/\n api.py\n service.py\n models.py\n tests/\n test_api.py\n pyproject.toml\n\nFocus: Focus on ambiguity, misleading symptoms, hidden root causes, and high-stakes debugging.\n\nassistant: Diagnosis:\n- Hidden root cause: path traversal on downloads presents misleading symptoms, so the patch must target the actual logic boundary rather than the first visible failure.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```python\nfrom __future__ import annotations\n\nfrom dataclasses import dataclass\nfrom typing import Any\n\n@dataclass\nclass ServiceResult:\n ok: bool\n data: dict[str, Any]\n error: str | None = None\n\ndef normalize_payload(payload: dict[str, Any]) -> dict[str, Any]:\n if not isinstance(payload, dict):\n raise TypeError(\"payload must be a dict\")\n clean: dict[str, Any] = {}\n for key, value in payload.items():\n if value is None:\n continue\n clean[str(key).strip()] = value\n return clean\n\ndef handle_path_traversal_on_downloads(payload: dict[str, Any]) -> ServiceResult:\n clean = normalize_payload(payload)\n if \"id\" not in clean:\n return ServiceResult(ok=False, data={}, error=\"missing id\")\n return ServiceResult(ok=True, data=clean)\n```\n\nTests:\n```python\nimport pytest\nfrom app.service import handle_jwt_refresh_token_rotation as handler\n\ndef test_handler_accepts_valid_payload():\n result = handler({\"id\": 7, \"name\": \"ok\", \"unused\": None})\n assert result.ok is True\n assert result.data == {\"id\": 7, \"name\": \"ok\"}\n\ndef test_handler_rejects_missing_id():\n result = handler({\"name\": \"x\"})\n assert result.ok is False\n assert result.error == \"missing id\"\n```\n\nVerification:\n- `pytest -q`\n- `ruff check .`\n- `python -m compileall .`\n\nEngineering notes:\n- Language: Python\n- Framework/tooling: FastAPI\n- Stack context: Airflow, dbt, DuckDB, MinIO, pytest\n- Domain: job scheduler\n- Task type: performance_bottleneck_patch\n- Difficulty: hard\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "Write pytest tests for `f14409`.\n\n```python\ndef f14409(a: int, b: int) -> int:\n return a*a + b*b\n```\nInclude edge cases and a property-style check.\n\n```python\nimport random\nfrom m73487 import f14409\n\ndef test_known():\n assert f14409(3,4) == 25\n\ndef test_zero():\n assert f14409(0,0) == 0\n\ndef test_property_nonnegative():\n for _ in range(200):\n a=random.randint(-50,50)\n b=random.randint(-50,50)\n assert f14409(a,b) >= 0\n```", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Fix a bug and add tests.\n\nFile: tl4r4mm.py\n```python\ndef xtds0smuc(n: int) -> int:\n \"\"\"Sum 1..n inclusive.\"\"\"\n if n < 0:\n raise ValueError(\"n must be non-negative\")\n total = 0\n for k in range(n): # BUG: should include n\n total += k\n return total\n```\n\nReturn unified diffs for tl4r4mm.py and test_tl4r4mm.py (pytest).\n\n*** Begin Patch\n*** Update File: tl4r4mm.py\n@@\n def xtds0smuc(n: int) -> int:\n@@\n total = 0\n- for k in range(n): # BUG: should include n\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_tl4r4mm.py\n+import pytest\n+from tl4r4mm import xtds0smuc\n+\n+def test_zero():\n+ assert xtds0smuc(0) == 0\n+\n+def test_one():\n+ assert xtds0smuc(1) == 1\n+\n+def test_small():\n+ assert xtds0smuc(7) == 28\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ xtds0smuc(-1)\n+\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Fix a bug and add tests.\n\nFile: h7npqph.py\n```python\ndef txkhwsu(n: int) -> int:\n \"\"\"Sum 1..n inclusive.\"\"\"\n if n < 0:\n raise ValueError(\"n must be non-negative\")\n total = 0\n for k in range(n): # BUG: should include n\n total += k\n return total\n```\n\nReturn unified diffs for h7npqph.py and test_h7npqph.py (pytest).\n\n*** Begin Patch\n*** Update File: h7npqph.py\n@@\n def txkhwsu(n: int) -> int:\n@@\n total = 0\n- for k in range(n): # BUG: should include n\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_h7npqph.py\n+import pytest\n+from h7npqph import txkhwsu\n+\n+def test_zero():\n+ assert txkhwsu(0) == 0\n+\n+def test_one():\n+ assert txkhwsu(1) == 1\n+\n+def test_small():\n+ assert txkhwsu(7) == 28\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ txkhwsu(-1)\n+\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Build an elite-grade solution in the domain of security engineering (defensive) for scenario: multi-tenant SaaS.\nPrimary language: go.\nDifficulty: medium.\nConstraints: make the interface contract explicit, provide rollout and rollback guidance, include invariants and failure modes.\nComponent: component_wtofuut.\nAssume compliance requires data deletion with proofs.\nTask: Define a small DSL, implement tokenizer/parser, IR, and a codegen or interpreter. Include tests and complexity notes.\n\nOutput: production blueprint plus correctness arguments and test strategy.\nOutput: DSL + parser + IR + interpreter/codegen + tests.\n\n**DSL**\n- Expressions: integers, identifiers, `+ - * /`, let-binding: `let x = expr in expr`\n- Example: `let x = 2+3 in x*10`\n\n**Pipeline**\n1. Tokenize\n2. Parse into AST\n3. Lower into IR (stack ops) or interpret AST directly\n\n**Reference (Rust-style outline)**\n- `enum Expr { Int(i64), Var(String), Bin(Op, Box, Box), Let(String, Box, Box) }`\n- Parser: Pratt or recursive descent.\n\n**Tests**\n- Golden tests for parse trees.\n- Property: pretty-print(parse(x)) round-trips for a corpus.\n- Eval tests for precedence and scoping.\n\n\nChecks: boundary validation and deterministic behavior verified.", "source": "WithinUsAI/Elite_GOD_Coder_100k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Fix a bug and add tests.\n\nFile: xlxh3udyu.py\n```python\ndef yenl5ly3(n: int) -> int:\n \"\"\"Sum 1..n inclusive.\"\"\"\n if n < 0:\n raise ValueError(\"n must be non-negative\")\n total = 0\n for k in range(n): # BUG: should include n\n total += k\n return total\n```\n\nReturn unified diffs for xlxh3udyu.py and test_xlxh3udyu.py (pytest).\n\n*** Begin Patch\n*** Update File: xlxh3udyu.py\n@@\n def yenl5ly3(n: int) -> int:\n@@\n total = 0\n- for k in range(n): # BUG: should include n\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_xlxh3udyu.py\n+import pytest\n+from xlxh3udyu import yenl5ly3\n+\n+def test_zero():\n+ assert yenl5ly3(0) == 0\n+\n+def test_one():\n+ assert yenl5ly3(1) == 1\n+\n+def test_small():\n+ assert yenl5ly3(7) == 28\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ yenl5ly3(-1)\n+\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Optimize while preserving behavior.\n\nFile: aoin9m0s.py\n```python\ndef u5v161gv0m(xs):\n out = []\n for x in xs:\n if x not in out:\n out.append(x)\n return out\n```\n\nRequirements: preserve first-seen order; O(n) average; add types + docstring.\n\n# aoin9m0s.py\nfrom __future__ import annotations\nfrom typing import Iterable, List, Set, TypeVar\n\nT = TypeVar(\"T\")\n\ndef u5v161gv0m(xs: Iterable[T]) -> List[T]:\n \"\"\"Return unique items preserving first-seen order.\"\"\"\n seen: Set[T] = set()\n out: List[T] = []\n for x in xs:\n if x in seen:\n continue\n seen.add(x)\n out.append(x)\n return out", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Add a clear docstring and type hints to this function:\n\n```python\ndef f57718(s):\n return ''.join(x for x in s if x.isalnum()).lower()\n```\n\n```python\nfrom __future__ import annotations\n\ndef f57718(s: str) -> str:\n \"\"\"Normalize a string: keep only alphanumerics and lowercase the result.\"\"\"\n return \"\".join(ch for ch in s if ch.isalnum()).lower()\n```", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Refactor to modern typed Python with immutability and tests.\n\nFile: rxhi_u0.py\n```python\nclass Tdu6Xsdqkyi:\n def __init__(self, name, values):\n self.name = name\n self.values = list(values)\n def add(self, v):\n self.values.append(v)\n def mean(self):\n s = 0\n for x in self.values:\n s += x\n return s / len(self.values)\n```\n\nReturn full new rxhi_u0.py and test_rxhi_u0.py.\n\n# rxhi_u0.py\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom typing import Iterable, Tuple\n\n@dataclass(frozen=True)\nclass Tdu6Xsdqkyi:\n name: str\n values: Tuple[float, ...]\n\n @staticmethod\n def create(name: str, values: Iterable[float]) -> \"Tdu6Xsdqkyi\":\n vals = tuple(float(v) for v in values)\n if not vals:\n raise ValueError(\"values must be non-empty\")\n return Tdu6Xsdqkyi(name=name, values=vals)\n\n def add(self, v: float) -> \"Tdu6Xsdqkyi\":\n return Tdu6Xsdqkyi(name=self.name, values=self.values + (float(v),))\n\n def mean(self) -> float:\n return sum(self.values) / len(self.values)\n\n# test_rxhi_u0.py\nimport pytest\nfrom rxhi_u0 import Tdu6Xsdqkyi\n\ndef test_mean_and_add():\n c = Tdu6Xsdqkyi.create(\"a\", [1, 2, 3])\n assert c.mean() == 2.0\n assert c.add(5).mean() == (1 + 2 + 3 + 5) / 4\n\ndef test_empty_raises():\n with pytest.raises(ValueError):\n Tdu6Xsdqkyi.create(\"x\", [])", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: Language: Java\nFramework/tooling: Hibernate\nDomain: model serving gateway\nLogic challenge: mismatched API contract\nTask type: edge_case_hardening\nDifficulty: medium\n\nReturn a rigorous engineering answer:\n- identify the hidden root cause or logical failure\n- present the corrected implementation\n- add tests that prove the fix\n- list verification commands\n- explain why naive fixes are insufficient when relevant\n\nRepository sketch:\nrepo/\n src/main/java/com/acme/App.java\n src/main/java/com/acme/Service.java\n src/test/java/com/acme/AppTest.java\n pom.xml\n\nFocus: Focus on strong structured logic with edge cases, data validation, and concurrency safety.\n\nassistant: Diagnosis:\n- Root cause: the failure around mismatched API contract is caused by missing validation, weak edge-case handling, or unsafe lifecycle behavior in the current implementation.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```java\nimport java.util.HashMap;\nimport java.util.Map;\n\npublic final class RequestHandler {\n public static Map handleRequest(Map payload) {\n Map clean = new HashMap<>();\n for (Map.Entry entry : payload.entrySet()) {\n if (entry.getValue() != null) clean.put(entry.getKey().trim(), entry.getValue());\n }\n if (!clean.containsKey(\"id\")) throw new IllegalArgumentException(\"missing id\");\n return Map.of(\"ok\", true, \"data\", clean);\n }\n}\n```\n\nTests:\n```java\nimport static org.junit.jupiter.api.Assertions.*;\nimport java.util.Map;\nimport org.junit.jupiter.api.Test;\n\nclass RequestHandlerTest {\n @Test\n void requiresId() {\n assertThrows(IllegalArgumentException.class, () -> RequestHandler.handleRequest(Map.of(\"name\", \"x\")));\n }\n}\n```\n\nVerification:\n- `./gradlew test`\n- `mvn test`\n\nEngineering notes:\n- Language: Java\n- Framework/tooling: Hibernate\n- Stack context: Airflow, dbt, DuckDB, MinIO, pytest\n- Domain: model serving gateway\n- Task type: edge_case_hardening\n- Difficulty: medium\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "Task type: mechanized_spec\nScenario: streaming ETL\nDomain focus: observability platforms\nPrimary language: lean\nDifficulty: expert\nScale/SLO: 99.99% availability\nComponent: component_ravpcxsp\nConstraints: include test vectors and fuzz strategy, assume adversarial inputs; validate everything, include security threat model (defensive only), include performance model and limits, avoid data races and undefined behavior, explicit contracts and invariants\nAssume hostile inputs and targeted abuse patterns.\nDeliverable: Provide a mechanized-style spec outline (Lean-like), key definitions, and a proof plan. Include executable reference code skeleton and tests.\n\nOutput: rigorous design + invariants + verification plan + implementation sketch.\n**Contract**\n- Inputs validated at the boundary; explicit error taxonomy.\n- Idempotency for side effects via request_id; deterministic replay.\n- Backward compatibility: additive changes by default; versioned breaking changes.\n**Invariants**\n- Determinism: replay of the same event log yields identical outputs.\n- Liveness: under bounded faults and stable network, progress occurs.\n- Isolation: tenant boundary enforced; no cross-tenant reads/writes.\n**Failure modes & recovery**\n- Data corruption: checksums + scrubber; quarantine and rebuild from replicas/snapshots.\n- Duplicate requests: de-duplicate by (tenant, request_id) returning cached response.\n- Crash during commit: WAL replay completes or transaction aborts; no torn writes.\n**Security posture (defensive)**\n- Threat model: auth/authz, injection, replay/abuse, supply chain.\n- Least privilege; secrets in managed store; audit logs for sensitive ops.\n- Input normalization, parameterized queries, path traversal protections.\n**Verification strategy**\n- Deterministic simulation with fault injection (crash/partition/latency).\n- Canary + shadow traffic; invariants checked in production via assertions/metrics.\n- Property tests against a pure reference model (state machine).\n\n**Snippet**\n```lean\n-- Pseudo-Lean outline\nstructure State where\n ver : Nat\n val : Option ByteArray\n\ndef invariant (s : State) : Prop := True\n\ntheorem step_preserves_invariant :\n ∀ s, invariant s → ∀ s', Step s s' → invariant s' := by\n intro s hs s' hstep\n -- proof plan: case analysis on transition; trivial here\n trivial\n```\n\nExpert checks: state-machine proof sketch + model checking; upgrade/rollback rehearsed.", "source": "WithinUsAI/Omega_Genesis_Coder_100k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Produce an offline-first self-evolving code assistant architecture named `qxzymro`.\nMust include: module layout, patch-safety policy, evaluation gates (tests/lint/types), versioned memory index.\n\nArchitecture: `qxzymro` (offline-first, self-evolving)\n\nModules\n- core/loop.py: evolve → validate → accept/reject (bounded iterations)\n- patching/: diff builder, safe apply, atomic writes, rollback points\n- policy/: allowlist paths, deny globs (.git/, __pycache__/, binaries), patch size caps\n- signals/: parse pytest/ruff/mypy into normalized findings\n- memory/index.jsonl: append-only snapshots (hashes, metrics, rationale)\n\nSafety gates\n- refuse path traversal/symlink escapes; never edit binaries\n- accept only if tests/lint/types stay green or improve", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Create a comprehensive test plan and automated tests for real-time notifications in a enterprise SaaS product.\nTarget platform: web (React + TypeScript).\nRequirements: unit/integration tests, edge cases, load tests strategy, and CI gates.\nConstraints: must be secure-by-default, must be easy to extend, must include documentation/comments, must be observable (logs/metrics/traces).\nDifficulty: expert. Assume strict latency budget (p95 < 200ms).\n\nOutput: engineering-grade answer with edge cases covered.\nDeliverable: test plan + automation guidance.\n\n**Unit tests**\n- Validation: malformed payloads rejected with correct codes.\n- AuthZ: tenant boundary enforced.\n- Idempotency: replay returns same response; conflicting reuse yields 409.\n\n**Integration tests**\n- DB transaction behavior; unique constraints.\n- Cache behavior: correctness under concurrent requests.\n\n**Load tests**\n- 10k RPS target: measure p95 latency, error rate, saturation.\n\n**CI gates**\n- Lint + typecheck + unit tests required.\n- Coverage threshold for critical modules.\n- Block merge on flaky test detection.\n\n\nHard-mode checks: concurrency safety, idempotency, and rollback validated; add chaos tests where feasible.", "source": "WithinUsAI/GOD_Coder_100k"} {"text": "Build an elite-grade solution in the domain of databases for scenario: chat messaging.\nPrimary language: rust.\nDifficulty: medium.\nConstraints: include invariants and failure modes, provide rollout and rollback guidance, document performance characteristics, avoid undefined behavior and data races, design for backward compatibility and migrations.\nComponent: component_lcuqfwv.\nAssume schema changes every sprint; must be backward compatible.\nTask: Write a precise interface contract, list invariants, and provide a lightweight formal/spec-style description (pseudo-TLA+/state machine) plus reference implementation skeleton and tests.\n\nOutput: rigorous solution with invariants, failure modes, and performance notes.\nOutput: contract + invariants + spec + reference skeleton.\n\n**Interface contract**\n- Commands: `Put(key, value, expected_version?)`, `Get(key)`, `Delete(key, expected_version?)`\n- Responses: `Ok(version, value?)`, `NotFound`, `Conflict(current_version)`, `InvalidInput`\n- Idempotency: client supplies `request_id`; server must de-duplicate per (tenant_id, request_id).\n\n**Invariants**\n1. Monotonic version per key (strictly increases on successful writes).\n2. Reads return latest committed value for a given consistency level.\n3. Exactly-once effect for a given `request_id` (at-most-once execution + replay response).\n4. Tenant isolation: keys are scoped by tenant_id.\n\n**State machine (pseudo)**\nState:\n- store: map[(tenant,key)] -> (version:int, value:bytes|tombstone)\n- seen: map[(tenant,request_id)] -> response\nTransition Put:\n- if request_id in seen: return seen[...]\n- validate input; if expected_version set and != current version -> Conflict\n- version' = version + 1; store[...] := (version', value); seen[...] := Ok(version', value)\n\n**Reference skeleton (Python)**\n```python\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom typing import Dict, Optional, Tuple\n\nclass Conflict(Exception): pass\nclass InvalidInput(ValueError): pass\n\n@dataclass(frozen=True, slots=True)\nclass Value:\n version: int\n data: Optional[bytes] # None == tombstone\n\n@dataclass(frozen=True, slots=True)\nclass Reply:\n kind: str\n version: Optional[int] = None\n data: Optional[bytes] = None\n\nclass KV:\n def __init__(self) -> None:\n self._store: Dict[Tuple[str,str], Value] = {}\n self._seen: Dict[Tuple[str,str], Reply] = {}\n\n def put(self, tenant: str, request_id: str, key: str, data: bytes, expected_version: Optional[int]=None) -> Reply:\n if not tenant or not request_id or not key:\n raise InvalidInput(\"tenant/request_id/key required\")\n de = self._seen.get((tenant, request_id))\n if de: \n return de\n cur = self._store.get((tenant, key), Value(0, None))\n if expected_version is not None and expected_version != cur.version:\n r = Reply(\"conflict\", version=cur.version)\n self._seen[(tenant, request_id)] = r\n return r\n nxt = Value(cur.version + 1, data)\n self._store[(tenant, key)] = nxt\n r = Reply(\"ok\", version=nxt.version)\n self._seen[(tenant, request_id)] = r\n return r\n```\n\n**Tests**\n- Determinism: same request_id → same reply.\n- Conflict detection and version monotonicity.\n\n\nChecks: boundary validation and deterministic behavior verified.", "source": "WithinUsAI/Elite_GOD_Coder_100k"} {"text": "Task type: perf_microarchitecture\nScenario: payment ledger\nDomain focus: kernel primitives\nPrimary language: python\nDifficulty: hard\nScale/SLO: p99 < 50ms\nComponent: component_dfxvuzru\nConstraints: include deterministic replay plan, include failure modes and recovery, include performance model and limits, include verification strategy, include backward compatibility and migration plan, assume adversarial inputs; validate everything, include security threat model (defensive only)\nAssume partial data corruption; include scrubbing strategy.\nDeliverable: Provide performance engineering plan: profiling, hot-path redesign, cache behavior assumptions, and microbench harness.\n\nOutput: elite engineering answer optimized for correctness, performance, and operability.\n**Contract**\n- Inputs validated at the boundary; explicit error taxonomy.\n- Idempotency for side effects via request_id; deterministic replay.\n- Backward compatibility: additive changes by default; versioned breaking changes.\n**Invariants**\n- Isolation: tenant boundary enforced; no cross-tenant reads/writes.\n- Safety: state transitions preserve invariants; no partial commit leaks.\n- Liveness: under bounded faults and stable network, progress occurs.\n**Failure modes & recovery**\n- Crash during commit: WAL replay completes or transaction aborts; no torn writes.\n- Duplicate requests: de-duplicate by (tenant, request_id) returning cached response.\n- Data corruption: checksums + scrubber; quarantine and rebuild from replicas/snapshots.\n**Security posture (defensive)**\n- Threat model: auth/authz, injection, replay/abuse, supply chain.\n- Least privilege; secrets in managed store; audit logs for sensitive ops.\n- Input normalization, parameterized queries, path traversal protections.\n**Verification strategy**\n- Property tests against a pure reference model (state machine).\n- Fuzzing of parsers/framers/validators with corpus seeds.\n- Deterministic simulation with fault injection (crash/partition/latency).\n\n**Snippet**\n```text\nImplementation sketch: factor pure state-machine core; adapters for I/O; add deterministic replay log.\n```\nHard checks: fault injection tests gate merges; perf thresholds enforced in CI.", "source": "WithinUsAI/Omega_Genesis_Coder_100k"} {"text": "Fix the bug and add pytest tests.\n\n```python\ndef f01001(n: int) -> int:\n # sum 1..n inclusive\n if n < 0: raise ValueError\n total = 0\n for k in range(n): # BUG\n total += k\n return total\n```\nReturn unified diffs for `m00143.py` and `test_m00143.py`.\n\n*** Begin Patch\n*** Update File: m00143.py\n@@\n def f01001(n: int) -> int:\n@@\n- for k in range(n): # BUG\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_m00143.py\n+import pytest\n+from m00143 import f01001\n+\n+def test_small():\n+ assert f01001(7) == 28\n+\n+def test_zero():\n+ assert f01001(0) == 0\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ f01001(-1)\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: Project domain: reporting engine\nImplementation stack: Go, Gin, PostgreSQL, gRPC, Prometheus, Docker\nSoftware delivery problem: multi-tenant access leak\nTask type: prd_to_patch\nDifficulty: medium\n\nReturn a complete delivery-grade response with:\n- diagnosis or design reasoning\n- implementation\n- test plan or tests\n- rollout plan\n- rollback or compatibility note\n- verification commands\n\nRepository sketch:\nrepo/\n app/\n api.py\n service.py\n models.py\n tests/\n test_api.py\n pyproject.toml\n\nFocus: Focus on shipping production software with rollout safety, acceptance criteria, telemetry, and maintenance quality.\n\nassistant: Diagnosis:\n- Root cause or delivery blocker: multi-tenant access leak needs both implementation work and a safe shipping plan.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```python\nfrom __future__ import annotations\n\nfrom dataclasses import dataclass\nfrom typing import Any\n\n@dataclass\nclass ServiceResult:\n ok: bool\n data: dict[str, Any]\n error: str | None = None\n\ndef normalize_payload(payload: dict[str, Any]) -> dict[str, Any]:\n if not isinstance(payload, dict):\n raise TypeError(\"payload must be a dict\")\n clean: dict[str, Any] = {}\n for key, value in payload.items():\n if value is None:\n continue\n clean[str(key).strip()] = value\n return clean\n\ndef handle_multi_tenant_access_leak(payload: dict[str, Any]) -> ServiceResult:\n clean = normalize_payload(payload)\n if \"id\" not in clean:\n return ServiceResult(ok=False, data={}, error=\"missing id\")\n return ServiceResult(ok=True, data=clean)\n```\n\nTests:\n```python\nimport pytest\nfrom app.service import handle_jwt_refresh_token_rotation as handler\n\ndef test_handler_accepts_valid_payload():\n result = handler({\"id\": 7, \"name\": \"ok\", \"unused\": None})\n assert result.ok is True\n assert result.data == {\"id\": 7, \"name\": \"ok\"}\n\ndef test_handler_rejects_missing_id():\n result = handler({\"name\": \"x\"})\n assert result.ok is False\n assert result.error == \"missing id\"\n```\n\nVerification:\n- `pytest -q`\n- `ruff check .`\n- `python -m compileall .`\n\nEngineering notes:\n- Language: Python\n- Framework/tooling: Django\n- Stack context: Go, Gin, PostgreSQL, gRPC, Prometheus, Docker\n- Domain: reporting engine\n- Task type: prd_to_patch\n- Difficulty: medium\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "Fix the bug and add pytest tests.\n\n```python\ndef f20388(n: int) -> int:\n # sum 1..n inclusive\n if n < 0: raise ValueError\n total = 0\n for k in range(n): # BUG\n total += k\n return total\n```\nReturn unified diffs for `m31484.py` and `test_m31484.py`.\n\n*** Begin Patch\n*** Update File: m31484.py\n@@\n def f20388(n: int) -> int:\n@@\n- for k in range(n): # BUG\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_m31484.py\n+import pytest\n+from m31484 import f20388\n+\n+def test_small():\n+ assert f20388(7) == 28\n+\n+def test_zero():\n+ assert f20388(0) == 0\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ f20388(-1)\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Create a comprehensive test plan and automated tests for caching in a fintech product.\nTarget platform: CI (GitHub Actions).\nRequirements: unit/integration tests, edge cases, load tests strategy, and CI gates.\nConstraints: must include tests, must include clear error handling, must be production-ready, must avoid global state, must be observable (logs/metrics/traces).\nDifficulty: hard. Include rollback strategy.\n\nOutput: actionable implementation and verification artifacts.\nDeliverable: test plan + automation guidance.\n\n**Unit tests**\n- Validation: malformed payloads rejected with correct codes.\n- AuthZ: tenant boundary enforced.\n- Idempotency: replay returns same response; conflicting reuse yields 409.\n\n**Integration tests**\n- DB transaction behavior; unique constraints.\n- Cache behavior: correctness under concurrent requests.\n\n**Load tests**\n- 10k RPS target: measure p95 latency, error rate, saturation.\n\n**CI gates**\n- Lint + typecheck + unit tests required.\n- Coverage threshold for critical modules.\n- Block merge on flaky test detection.\n\n\nHard-mode checks: concurrency safety, idempotency, and rollback validated; add chaos tests where feasible.", "source": "WithinUsAI/GOD_Coder_100k"} {"text": "Fix a subtle bug in a Python module used for ETL pipelines.\nRequirements: explain root cause briefly, provide corrected code, and add regression tests.\nConstraints: must handle Windows paths safely, must include tests, must provide clear error messages.\nDifficulty: easy. Ensure the API is testable via dependency injection.\n\nDeliverable: implementation + tests.\n```python\nfrom __future__ import annotations\n\nfrom dataclasses import dataclass\nfrom pathlib import Path\nfrom typing import Iterable\nimport json\n\n\nclass ValidationError(ValueError):\n \"\"\"Raised when input validation fails.\"\"\"\n\n\ndef safe_join(base: Path, *parts: str) -> Path:\n \"\"\"Join paths while preventing traversal outside base.\"\"\"\n b = base.resolve()\n p = (b / Path(*parts)).resolve()\n if p != b and b not in p.parents:\n raise ValidationError(f\"unsafe path: {p}\")\n return p\n\n\n@dataclass(frozen=True, slots=True)\nclass Record:\n key: str\n value: int\n\n\ndef parse_jsonl(lines: Iterable[str]) -> list[Record]:\n out: list[Record] = []\n for idx, line in enumerate(lines, 1):\n s = line.strip()\n if not s:\n continue\n try:\n obj = json.loads(s)\n except json.JSONDecodeError as e:\n raise ValidationError(f\"line {idx}: invalid json\") from e\n if not isinstance(obj, dict):\n raise ValidationError(f\"line {idx}: expected object\")\n key = obj.get(\"key\")\n val = obj.get(\"value\")\n if not isinstance(key, str) or not key:\n raise ValidationError(f\"line {idx}: key must be non-empty str\")\n if not isinstance(val, int):\n raise ValidationError(f\"line {idx}: value must be int\")\n out.append(Record(key, val))\n return out\n\n\ndef write_jsonl(base: Path, rel: str, records: Iterable[Record]) -> Path:\n base.mkdir(parents=True, exist_ok=True)\n dst = safe_join(base, rel)\n dst.parent.mkdir(parents=True, exist_ok=True)\n with dst.open(\"w\", encoding=\"utf-8\", newline=\"\\n\") as f:\n for r in records:\n f.write(json.dumps({\"key\": r.key, \"value\": r.value}, ensure_ascii=False) + \"\\n\")\n return dst\n```\n\n```python\n# tests (pytest-style)\nimport json\nfrom pathlib import Path\nimport pytest\nfrom module_under_test import ValidationError, Record, parse_jsonl, write_jsonl\n\ndef test_parse_ok():\n lines = [json.dumps({\"key\":\"a\",\"value\":1}), json.dumps({\"key\":\"b\",\"value\":2})]\n assert parse_jsonl(lines) == [Record(\"a\",1), Record(\"b\",2)]\n\ndef test_parse_rejects_bad_json():\n with pytest.raises(ValidationError):\n parse_jsonl([\"{not json}\"])\n\ndef test_safe_join_blocks_traversal(tmp_path: Path):\n with pytest.raises(ValidationError):\n write_jsonl(tmp_path, \"../x.jsonl\", [Record(\"a\",1)])\n```", "source": "WithinUsAI/python_GOD_coder_100k"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: Language: YAML\nFramework/tooling: Docker Compose\nDomain: repo automation\nLogic challenge: path traversal on downloads\nTask type: edge_case_hardening\nDifficulty: medium\n\nReturn a rigorous engineering answer:\n- identify the hidden root cause or logical failure\n- present the corrected implementation\n- add tests that prove the fix\n- list verification commands\n- explain why naive fixes are insufficient when relevant\n\nRepository sketch:\nrepo/\n .github/workflows/ci.yml\n docker-compose.yml\n deploy/\n app.yaml\n\nFocus: Focus on strong structured logic with edge cases, data validation, and concurrency safety.\n\nassistant: Diagnosis:\n- Root cause: the failure around path traversal on downloads is caused by missing validation, weak edge-case handling, or unsafe lifecycle behavior in the current implementation.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```yaml\nname: ci\non: [push, pull_request]\njobs:\n test:\n runs-on: ubuntu-latest\n steps:\n - uses: actions/checkout@v4\n - name: Validate\n run: echo \"validated\"\n```\n\nTests:\n```yaml\n# Verification:\n# - validate syntax\n# - run smoke workflow\n# - fail fast on broken config\n```\n\nVerification:\n- `validate workflow syntax`\n- `run CI smoke job`\n\nEngineering notes:\n- Language: YAML\n- Framework/tooling: Docker Compose\n- Stack context: GitHub Actions, Docker Compose, Kubernetes, Terraform\n- Domain: repo automation\n- Task type: edge_case_hardening\n- Difficulty: medium\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: Repository domain: benchmark harness\nPrimary language: YAML\nFramework/tooling: Terraform\nReported problem: CI failures after dependency upgrade\nTask type: code_review_fix\nDifficulty: medium\n\nProduce a complete professional engineering response:\n1. Diagnose the root cause.\n2. Provide the corrected implementation or patch.\n3. Add tests.\n4. Add verification commands.\n5. Note edge cases and any migration or rollback risk.\n\nRepository sketch:\nrepo/\n .github/workflows/ci.yml\n docker-compose.yml\n deploy/\n app.yaml\n\nQuality target:\n- Minimal diff unless redesign is clearly required\n- Production-ready code\n- No placeholders\n- Secure defaults\n- Clear acceptance of failure cases\n\nFocus: Focus on complete implementation quality, patch correctness, tests, and production readiness.\n\nassistant: Diagnosis:\n- Root cause: the failure around CI failures after dependency upgrade is caused by missing validation, weak edge-case handling, or unsafe lifecycle behavior in the current implementation.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```yaml\nname: ci\non: [push, pull_request]\njobs:\n test:\n runs-on: ubuntu-latest\n steps:\n - uses: actions/checkout@v4\n - name: Validate\n run: echo \"validated\"\n```\n\nTests:\n```yaml\n# Verification:\n# - validate syntax\n# - run smoke workflow\n# - fail fast on broken config\n```\n\nVerification:\n- `validate workflow syntax`\n- `run CI smoke job`\n\nEngineering notes:\n- Language: YAML\n- Framework/tooling: Terraform\n- Stack context: GitHub Actions, Docker Compose, Kubernetes, Terraform\n- Domain: benchmark harness\n- Task type: code_review_fix\n- Difficulty: medium\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: Language: TypeScript\nFramework/tooling: Vitest\nDomain: auth service\nLogic challenge: race condition on worker shutdown\nTask type: misleading_symptom_debug\nDifficulty: hard\n\nReturn a rigorous engineering answer:\n- identify the hidden root cause or logical failure\n- present the corrected implementation\n- add tests that prove the fix\n- list verification commands\n- explain why naive fixes are insufficient when relevant\n\nRepository sketch:\nrepo/\n src/\n api.ts\n service.ts\n schema.ts\n tests/\n api.test.ts\n package.json\n\nFocus: Focus on ambiguity, misleading symptoms, hidden root causes, and high-stakes debugging.\n\nassistant: Diagnosis:\n- Hidden root cause: race condition on worker shutdown presents misleading symptoms, so the patch must target the actual logic boundary rather than the first visible failure.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```ts\ntype Payload = Record;\n\nexport function normalizePayload(payload: Payload): Payload {\n if (!payload || typeof payload !== \"object\" || Array.isArray(payload)) {\n throw new TypeError(\"payload must be a plain object\");\n }\n return Object.fromEntries(\n Object.entries(payload)\n .filter(([, value]) => value !== null && value !== undefined)\n .map(([key, value]) => [String(key).trim(), value])\n );\n}\n\nexport function handleRaceConditionOnWorkerShutdown(payload: Payload) {\n const clean = normalizePayload(payload);\n if (!(\"id\" in clean)) {\n return { ok: false, data: {}, error: \"missing id\" };\n }\n return { ok: true, data: clean, error: null };\n}\n```\n\nTests:\n```ts\nimport { describe, it, expect } from \"vitest\";\nimport { handleRaceConditionOnWorkerShutdown } from \"../src/service\";\n\ndescribe(\"handler\", () => {\n it(\"accepts valid input\", () => {\n expect(handleRaceConditionOnWorkerShutdown({ id: 7, name: \"ok\", unused: null })).toEqual({\n ok: true,\n data: { id: 7, name: \"ok\" },\n error: null\n });\n });\n\n it(\"rejects missing id\", () => {\n expect(handleRaceConditionOnWorkerShutdown({ name: \"x\" }).error).toMatch(/missing id/);\n });\n});\n```\n\nVerification:\n- `npm test`\n- `npm run typecheck`\n- `npm run lint`\n\nEngineering notes:\n- Language: TypeScript\n- Framework/tooling: Vitest\n- Stack context: GitHub Actions, Docker Compose, Kubernetes, Terraform\n- Domain: auth service\n- Task type: misleading_symptom_debug\n- Difficulty: hard\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: Project stack: GitHub Actions, Docker Compose, Kubernetes, Terraform\nLanguage: YAML\nDependency challenge: streaming timeout handling\nTask type: cve_dependency_remediation\nDifficulty: medium\n\nFix this as a senior engineer.\nRequired:\n- identify the version or compatibility failure mode\n- produce the corrected config/code/build patch\n- explain rollback-safe migration notes\n- add regression tests or reproducibility checks\n- include concrete verification commands\n\nRepository sketch:\nrepo/\n .github/workflows/ci.yml\n docker-compose.yml\n deploy/\n app.yaml\n\nFocus: Focus on versioning, migrations, lockfiles, runtime compatibility, and secure dependency handling.\n\nassistant: Diagnosis:\n- Root cause: the issue around streaming timeout handling is a dependency, migration, or runtime-compatibility mismatch that needs a rollback-safe patch.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```yaml\nname: ci\non: [push, pull_request]\njobs:\n test:\n runs-on: ubuntu-latest\n steps:\n - uses: actions/checkout@v4\n - name: Validate\n run: echo \"validated\"\n```\n\nTests:\n```yaml\n# Verification:\n# - validate syntax\n# - run smoke workflow\n# - fail fast on broken config\n```\n\nVerification:\n- `validate workflow syntax`\n- `run CI smoke job`\n\nEngineering notes:\n- Language: YAML\n- Framework/tooling: Terraform\n- Stack context: GitHub Actions, Docker Compose, Kubernetes, Terraform\n- Domain: data pipeline\n- Task type: cve_dependency_remediation\n- Difficulty: medium\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "Design a production system for developer tooling supporting background jobs.\nTarget platform: CI (GitHub Actions).\nRequirements: APIs, data model, scaling strategy, failure modes, and security.\nConstraints: must include tests, must include clear error handling, must include documentation/comments.\nDifficulty: expert. Assume 10k RPS peak traffic.\n\nOutput: engineering-grade answer with edge cases covered.\nDeliverable: system design with APIs, data model, and operational plan.\n\n**High-level architecture**\n- Edge: API Gateway + WAF\n- Core service: stateless app pods behind L7 LB\n- Data: Postgres (primary), Redis (cache + rate limit tokens), Object storage (uploads if needed)\n- Async: message queue (e.g., SQS/Rabbit) + worker pool for background jobs\n- Observability: structured logs + metrics + tracing\n\n**APIs (example)**\n- `POST /v1/{resource}` create (idempotent via `Idempotency-Key`)\n- `GET /v1/{resource}/{id}` read\n- `POST /v1/{resource}/{id}:action` command endpoint when side effects exist\n\n**Data model (Postgres)**\n- `resources(id UUID PK, tenant_id UUID, status TEXT, payload JSONB, created_at, updated_at)`\n- Unique constraint for idempotency: `(tenant_id, idempotency_key)` in a separate table:\n - `idempotency(tenant_id, key TEXT, request_hash TEXT, response JSONB, created_at, PRIMARY KEY(tenant_id,key))`\n\n**Scaling**\n- App layer scales horizontally; keep sessions out of process.\n- Cache reads in Redis; write-through invalidation on mutations.\n- Use connection pooling; consider read replicas for heavy reads.\n\n**Failure modes**\n- Retries: only for safe/ idempotent operations; exponential backoff + jitter.\n- Partial failures: background jobs must be idempotent; use a de-dup key.\n\n**Security**\n- AuthN: JWT/OIDC; AuthZ: RBAC/ABAC with tenant isolation\n- Validate all inputs; enforce per-tenant quotas/rate limits.\n\n**Rollout**\n- Dark launch + feature flags; canary; rapid rollback by toggling flags.\n\n\nHard-mode checks: concurrency safety, idempotency, and rollback validated; add chaos tests where feasible.", "source": "WithinUsAI/GOD_Coder_100k"} {"text": "Build an elite-grade solution in the domain of gpu compute for scenario: event ingestion.\nPrimary language: go.\nDifficulty: hard.\nConstraints: include invariants and failure modes, design for backward compatibility and migrations, document performance characteristics.\nComponent: component_lvzxmxb.\nAssume strict auditability and replayable history.\nTask: Write a precise interface contract, list invariants, and provide a lightweight formal/spec-style description (pseudo-TLA+/state machine) plus reference implementation skeleton and tests.\n\nOutput: rigorous solution with invariants, failure modes, and performance notes.\nOutput: contract + invariants + spec + reference skeleton.\n\n**Interface contract**\n- Commands: `Put(key, value, expected_version?)`, `Get(key)`, `Delete(key, expected_version?)`\n- Responses: `Ok(version, value?)`, `NotFound`, `Conflict(current_version)`, `InvalidInput`\n- Idempotency: client supplies `request_id`; server must de-duplicate per (tenant_id, request_id).\n\n**Invariants**\n1. Monotonic version per key (strictly increases on successful writes).\n2. Reads return latest committed value for a given consistency level.\n3. Exactly-once effect for a given `request_id` (at-most-once execution + replay response).\n4. Tenant isolation: keys are scoped by tenant_id.\n\n**State machine (pseudo)**\nState:\n- store: map[(tenant,key)] -> (version:int, value:bytes|tombstone)\n- seen: map[(tenant,request_id)] -> response\nTransition Put:\n- if request_id in seen: return seen[...]\n- validate input; if expected_version set and != current version -> Conflict\n- version' = version + 1; store[...] := (version', value); seen[...] := Ok(version', value)\n\n**Reference skeleton (Python)**\n```python\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom typing import Dict, Optional, Tuple\n\nclass Conflict(Exception): pass\nclass InvalidInput(ValueError): pass\n\n@dataclass(frozen=True, slots=True)\nclass Value:\n version: int\n data: Optional[bytes] # None == tombstone\n\n@dataclass(frozen=True, slots=True)\nclass Reply:\n kind: str\n version: Optional[int] = None\n data: Optional[bytes] = None\n\nclass KV:\n def __init__(self) -> None:\n self._store: Dict[Tuple[str,str], Value] = {}\n self._seen: Dict[Tuple[str,str], Reply] = {}\n\n def put(self, tenant: str, request_id: str, key: str, data: bytes, expected_version: Optional[int]=None) -> Reply:\n if not tenant or not request_id or not key:\n raise InvalidInput(\"tenant/request_id/key required\")\n de = self._seen.get((tenant, request_id))\n if de: \n return de\n cur = self._store.get((tenant, key), Value(0, None))\n if expected_version is not None and expected_version != cur.version:\n r = Reply(\"conflict\", version=cur.version)\n self._seen[(tenant, request_id)] = r\n return r\n nxt = Value(cur.version + 1, data)\n self._store[(tenant, key)] = nxt\n r = Reply(\"ok\", version=nxt.version)\n self._seen[(tenant, request_id)] = r\n return r\n```\n\n**Tests**\n- Determinism: same request_id → same reply.\n- Conflict detection and version monotonicity.\n\n\nHard checks: failure injection tests and performance regressions gated.", "source": "WithinUsAI/Elite_GOD_Coder_100k"} {"text": "Provision infrastructure for a customer support workload providing role-based access control.\nTarget platform: ML (PyTorch + serving).\nRequirements: IaC (Terraform or Kubernetes YAML), networking, secrets, autoscaling.\nConstraints: must include documentation/comments, must include clear error handling, must be performant under load, must be observable (logs/metrics/traces).\nDifficulty: expert. Assume GDPR-style deletion requests must be supported.\n\nOutput: engineering-grade answer with edge cases covered.\nDeliverable: Kubernetes deployment + basic security posture.\n\n```yaml\napiVersion: apps/v1\nkind: Deployment\nmetadata:\n name: app\nspec:\n replicas: 3\n selector:\n matchLabels: { app: app }\n template:\n metadata:\n labels: { app: app }\n spec:\n containers:\n - name: app\n image: app:latest\n ports: [{ containerPort: 8080 }]\n readinessProbe:\n httpGet: { path: /healthz, port: 8080 }\n resources:\n requests: { cpu: \"200m\", memory: \"256Mi\" }\n limits: { cpu: \"1\", memory: \"1Gi\" }\n```\n\nAdditions:\n- NetworkPolicy to restrict egress/ingress.\n- Secrets via external secret store; rotate regularly.\n- HPA for autoscaling; PodDisruptionBudget for availability.\n\n\nHard-mode checks: concurrency safety, idempotency, and rollback validated; add chaos tests where feasible.", "source": "WithinUsAI/GOD_Coder_100k"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: System domain: feature flag service\nStack: Next.js, Node.js, Prisma, PostgreSQL, Playwright, Docker\nCross-layer incident: async cancellation bug\nTask type: cache_consistency_patch\nDifficulty: hard\n\nSolve this as a complete-project engineer.\nOutput must include:\n- root cause across layers\n- final implementation patch\n- tests touching at least two layers\n- deployment or observability note\n- verification commands\n\nRepository sketch:\nrepo/\n scripts/\n run.sh\n deploy.sh\n tests/\n smoke.sh\n\nFocus: Focus on multi-layer debugging across frontend, backend, database, CI, caching, and deployment.\n\nassistant: Diagnosis:\n- Root cause: async cancellation bug crosses service boundaries, so the fix must align code, contracts, tests, and deployment behavior.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```bash\n#!/usr/bin/env bash\nset -euo pipefail\n\ninput=\"${1:-}\"\nif [[ -z \"$input\" ]]; then\n echo \"missing input\" >&2\n exit 1\nfi\n\nprintf '%s\n' \"$input\" | tr -d '\r'\n```\n\nTests:\n```bash\noutput=\"$(bash scripts/run.sh \"abc\")\"\ntest \"$output\" = \"abc\"\n```\n\nVerification:\n- `bash tests/smoke.sh`\n- `shellcheck scripts/*.sh`\n\nEngineering notes:\n- Language: Bash\n- Framework/tooling: curl\n- Stack context: Next.js, Node.js, Prisma, PostgreSQL, Playwright, Docker\n- Domain: feature flag service\n- Task type: cache_consistency_patch\n- Difficulty: hard\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "Refactor an existing codebase in IoT telemetry to support file uploads cleanly.\nTarget platform: ML (scikit + batch).\nRequirements: propose new modules/layers, dependency boundaries, and migration plan.\nConstraints: must avoid global state, must be production-ready, must include tests.\nDifficulty: expert. Assume 10k RPS peak traffic.\n\nOutput: actionable implementation and verification artifacts.\nDeliverable: refactor plan + module boundaries.\n\n**Proposed modules**\n- `domain/` pure business logic (no I/O)\n- `adapters/` DB, cache, external APIs\n- `api/` request/response validation and routing\n- `observability/` logging/metrics/tracing\n- `tests/` unit + integration suites\n\n**Migration plan**\n1. Introduce new interfaces + adapters behind feature flags.\n2. Dual-write or read-compat layer if schema changes.\n3. Incremental cutover; deprecate legacy module.\n\nKey rule: dependencies flow inward; domain has no framework imports.\n\n\nHard-mode checks: concurrency safety, idempotency, and rollback validated; add chaos tests where feasible.", "source": "WithinUsAI/GOD_Coder_100k"} {"text": "Write pytest tests for `f09346`.\n\n```python\ndef f09346(a: int, b: int) -> int:\n return a*a + b*b\n```\nInclude edge cases and a property-style check.\n\n```python\nimport random\nfrom m58478 import f09346\n\ndef test_known():\n assert f09346(3,4) == 25\n\ndef test_zero():\n assert f09346(0,0) == 0\n\ndef test_property_nonnegative():\n for _ in range(200):\n a=random.randint(-50,50)\n b=random.randint(-50,50)\n assert f09346(a,b) >= 0\n```", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Task type: distributed_algorithm\nScenario: time-series metrics store\nDomain focus: cryptography engineering (defensive)\nPrimary language: rust\nDifficulty: expert+\nScale/SLO: p99 < 150ms\nComponent: component_xhxirzam\nConstraints: assume adversarial inputs; validate everything, avoid data races and undefined behavior, include verification strategy, include test vectors and fuzz strategy, include security threat model (defensive only), include failure modes and recovery\nAssume partial data corruption; include scrubbing strategy.\nDeliverable: Design an algorithm with message flows and correctness arguments (safety + liveness). Include failure handling and a minimal reference implementation skeleton.\n\nOutput: elite engineering answer optimized for correctness, performance, and operability.\n**Contract**\n- Inputs validated at the boundary; explicit error taxonomy.\n- Idempotency for side effects via request_id; deterministic replay.\n- Backward compatibility: additive changes by default; versioned breaking changes.\n**Invariants**\n- Liveness: under bounded faults and stable network, progress occurs.\n- Isolation: tenant boundary enforced; no cross-tenant reads/writes.\n- Determinism: replay of the same event log yields identical outputs.\n**Failure modes & recovery**\n- Data corruption: checksums + scrubber; quarantine and rebuild from replicas/snapshots.\n- Network partition: minority cannot commit; clients receive retriable errors.\n- Crash during commit: WAL replay completes or transaction aborts; no torn writes.\n**Security posture (defensive)**\n- Threat model: auth/authz, injection, replay/abuse, supply chain.\n- Least privilege; secrets in managed store; audit logs for sensitive ops.\n- Input normalization, parameterized queries, path traversal protections.\n**Verification strategy**\n- Canary + shadow traffic; invariants checked in production via assertions/metrics.\n- Fuzzing of parsers/framers/validators with corpus seeds.\n- Property tests against a pure reference model (state machine).\n\n**Snippet**\n```text\nImplementation sketch: factor pure state-machine core; adapters for I/O; add deterministic replay log.\n```\nExpert+ checks: mechanized invariants (or exhaustive model checking), adversarial fuzzing, and multi-region failure drills.", "source": "WithinUsAI/Omega_Genesis_Coder_100k"} {"text": "Task type: distributed_algorithm\nScenario: identity and access\nDomain focus: large-scale ML systems\nPrimary language: go\nDifficulty: hard\nScale/SLO: p99 < 150ms\nComponent: component_pvmpmccf\nConstraints: include test vectors and fuzz strategy, include security threat model (defensive only), include backward compatibility and migration plan, assume adversarial inputs; validate everything, include failure modes and recovery, include deterministic replay plan, include performance model and limits\nAssume strict auditability and replayable history.\nDeliverable: Design an algorithm with message flows and correctness arguments (safety + liveness). Include failure handling and a minimal reference implementation skeleton.\n\nOutput: rigorous design + invariants + verification plan + implementation sketch.\n**Contract**\n- Inputs validated at the boundary; explicit error taxonomy.\n- Idempotency for side effects via request_id; deterministic replay.\n- Backward compatibility: additive changes by default; versioned breaking changes.\n**Invariants**\n- Isolation: tenant boundary enforced; no cross-tenant reads/writes.\n- Determinism: replay of the same event log yields identical outputs.\n- Liveness: under bounded faults and stable network, progress occurs.\n**Failure modes & recovery**\n- Duplicate requests: de-duplicate by (tenant, request_id) returning cached response.\n- Network partition: minority cannot commit; clients receive retriable errors.\n- Data corruption: checksums + scrubber; quarantine and rebuild from replicas/snapshots.\n**Security posture (defensive)**\n- Threat model: auth/authz, injection, replay/abuse, supply chain.\n- Least privilege; secrets in managed store; audit logs for sensitive ops.\n- Input normalization, parameterized queries, path traversal protections.\n**Verification strategy**\n- Fuzzing of parsers/framers/validators with corpus seeds.\n- Canary + shadow traffic; invariants checked in production via assertions/metrics.\n- Deterministic simulation with fault injection (crash/partition/latency).\n\n**Snippet**\n```text\nImplementation sketch: factor pure state-machine core; adapters for I/O; add deterministic replay log.\n```\nHard checks: fault injection tests gate merges; perf thresholds enforced in CI.", "source": "WithinUsAI/Omega_Genesis_Coder_100k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Refactor to modern typed Python with immutability and tests.\n\nFile: b82_h3eqhc.py\n```python\nclass Osffxvma0Ox:\n def __init__(self, name, values):\n self.name = name\n self.values = list(values)\n def add(self, v):\n self.values.append(v)\n def mean(self):\n s = 0\n for x in self.values:\n s += x\n return s / len(self.values)\n```\n\nReturn full new b82_h3eqhc.py and test_b82_h3eqhc.py.\n\n# b82_h3eqhc.py\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom typing import Iterable, Tuple\n\n@dataclass(frozen=True)\nclass Osffxvma0Ox:\n name: str\n values: Tuple[float, ...]\n\n @staticmethod\n def create(name: str, values: Iterable[float]) -> \"Osffxvma0Ox\":\n vals = tuple(float(v) for v in values)\n if not vals:\n raise ValueError(\"values must be non-empty\")\n return Osffxvma0Ox(name=name, values=vals)\n\n def add(self, v: float) -> \"Osffxvma0Ox\":\n return Osffxvma0Ox(name=self.name, values=self.values + (float(v),))\n\n def mean(self) -> float:\n return sum(self.values) / len(self.values)\n\n# test_b82_h3eqhc.py\nimport pytest\nfrom b82_h3eqhc import Osffxvma0Ox\n\ndef test_mean_and_add():\n c = Osffxvma0Ox.create(\"a\", [1, 2, 3])\n assert c.mean() == 2.0\n assert c.add(5).mean() == (1 + 2 + 3 + 5) / 4\n\ndef test_empty_raises():\n with pytest.raises(ValueError):\n Osffxvma0Ox.create(\"x\", [])", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Fix a bug and add tests.\n\nFile: sgr1hlyp.py\n```python\ndef btjcph1md(n: int) -> int:\n \"\"\"Sum 1..n inclusive.\"\"\"\n if n < 0:\n raise ValueError(\"n must be non-negative\")\n total = 0\n for k in range(n): # BUG: should include n\n total += k\n return total\n```\n\nReturn unified diffs for sgr1hlyp.py and test_sgr1hlyp.py (pytest).\n\n*** Begin Patch\n*** Update File: sgr1hlyp.py\n@@\n def btjcph1md(n: int) -> int:\n@@\n total = 0\n- for k in range(n): # BUG: should include n\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_sgr1hlyp.py\n+import pytest\n+from sgr1hlyp import btjcph1md\n+\n+def test_zero():\n+ assert btjcph1md(0) == 0\n+\n+def test_one():\n+ assert btjcph1md(1) == 1\n+\n+def test_small():\n+ assert btjcph1md(7) == 28\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ btjcph1md(-1)\n+\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Optimize while preserving behavior.\n\nFile: nocnyis.py\n```python\ndef so6st41s(xs):\n out = []\n for x in xs:\n if x not in out:\n out.append(x)\n return out\n```\n\nRequirements: preserve first-seen order; O(n) average; add types + docstring.\n\n# nocnyis.py\nfrom __future__ import annotations\nfrom typing import Iterable, List, Set, TypeVar\n\nT = TypeVar(\"T\")\n\ndef so6st41s(xs: Iterable[T]) -> List[T]:\n \"\"\"Return unique items preserving first-seen order.\"\"\"\n seen: Set[T] = set()\n out: List[T] = []\n for x in xs:\n if x in seen:\n continue\n seen.add(x)\n out.append(x)\n return out", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Refactor to typed, mostly-immutable Python and add minimal tests.\n\n```python\nclass C65126:\n def __init__(self, values): self.values=list(values)\n def mean(self): return sum(self.values)/len(self.values)\n```\nReturn `m12702.py` and `test_m12702.py`.\n\n```python\n# m12702.py\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom typing import Iterable, Tuple\n\n@dataclass(frozen=True)\nclass C65126:\n values: Tuple[float, ...]\n\n @staticmethod\n def create(values: Iterable[float]) -> \"C65126\":\n vals = tuple(float(v) for v in values)\n if not vals: raise ValueError(\"empty\")\n return C65126(vals)\n\n def mean(self) -> float:\n return sum(self.values)/len(self.values)\n```\n\n```python\n# test_m12702.py\nimport pytest\nfrom m12702 import C65126\n\ndef test_mean():\n assert C65126.create([1,2,3]).mean() == 2.0\ndef test_empty():\n with pytest.raises(ValueError):\n C65126.create([])\n```", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: Language: SQL\nFramework/tooling: SQLite\nDomain: model serving gateway\nLogic challenge: schema drift during deployment\nTask type: multi_service_security_patch\nDifficulty: hard\n\nReturn a rigorous engineering answer:\n- identify the hidden root cause or logical failure\n- present the corrected implementation\n- add tests that prove the fix\n- list verification commands\n- explain why naive fixes are insufficient when relevant\n\nRepository sketch:\nrepo/\n migrations/\n 001_init.sql\n 002_add_index.sql\n queries/\n report.sql\n tests/\n report_cases.md\n\nFocus: Focus on staff-level problem solving with multi-file patches, rollout implications, performance and security tradeoffs.\n\nassistant: Diagnosis:\n- Staff-level diagnosis: schema drift during deployment impacts correctness, operability, and future maintenance, so the fix must be minimal where possible but complete where necessary.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```sql\nWITH ranked AS (\n SELECT\n user_id,\n created_at,\n amount,\n ROW_NUMBER() OVER (PARTITION BY user_id ORDER BY created_at DESC, id DESC) AS rn\n FROM orders\n)\nSELECT user_id, created_at, amount\nFROM ranked\nWHERE rn = 1;\n```\n\nTests:\n```sql\n-- Correctness checks:\n-- 1) multiple rows per user\n-- 2) identical timestamps require deterministic tie-breaker\n-- 3) null values handled by business rules\n```\n\nVerification:\n- `run migration checks`\n- `run query correctness cases`\n\nEngineering notes:\n- Language: SQL\n- Framework/tooling: SQLite\n- Stack context: Spring Boot, PostgreSQL, JUnit, Gradle, Docker, GitHub Actions\n- Domain: model serving gateway\n- Task type: multi_service_security_patch\n- Difficulty: hard\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: Project domain: payments platform\nImplementation stack: Rust, Axum, SQLx, Redis, Tokio, Docker\nSoftware delivery problem: N+1 query explosion\nTask type: incident_to_remediation\nDifficulty: medium\n\nReturn a complete delivery-grade response with:\n- diagnosis or design reasoning\n- implementation\n- test plan or tests\n- rollout plan\n- rollback or compatibility note\n- verification commands\n\nRepository sketch:\nrepo/\n .github/workflows/ci.yml\n docker-compose.yml\n deploy/\n app.yaml\n\nFocus: Focus on shipping production software with rollout safety, acceptance criteria, telemetry, and maintenance quality.\n\nassistant: Diagnosis:\n- Root cause or delivery blocker: N+1 query explosion needs both implementation work and a safe shipping plan.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```yaml\nname: ci\non: [push, pull_request]\njobs:\n test:\n runs-on: ubuntu-latest\n steps:\n - uses: actions/checkout@v4\n - name: Validate\n run: echo \"validated\"\n```\n\nTests:\n```yaml\n# Verification:\n# - validate syntax\n# - run smoke workflow\n# - fail fast on broken config\n```\n\nVerification:\n- `validate workflow syntax`\n- `run CI smoke job`\n\nEngineering notes:\n- Language: YAML\n- Framework/tooling: Docker Compose\n- Stack context: Rust, Axum, SQLx, Redis, Tokio, Docker\n- Domain: payments platform\n- Task type: incident_to_remediation\n- Difficulty: medium\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Refactor to modern typed Python with immutability and tests.\n\nFile: hlvdiawim.py\n```python\nclass Ixof3Vw5P0:\n def __init__(self, name, values):\n self.name = name\n self.values = list(values)\n def add(self, v):\n self.values.append(v)\n def mean(self):\n s = 0\n for x in self.values:\n s += x\n return s / len(self.values)\n```\n\nReturn full new hlvdiawim.py and test_hlvdiawim.py.\n\n# hlvdiawim.py\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom typing import Iterable, Tuple\n\n@dataclass(frozen=True)\nclass Ixof3Vw5P0:\n name: str\n values: Tuple[float, ...]\n\n @staticmethod\n def create(name: str, values: Iterable[float]) -> \"Ixof3Vw5P0\":\n vals = tuple(float(v) for v in values)\n if not vals:\n raise ValueError(\"values must be non-empty\")\n return Ixof3Vw5P0(name=name, values=vals)\n\n def add(self, v: float) -> \"Ixof3Vw5P0\":\n return Ixof3Vw5P0(name=self.name, values=self.values + (float(v),))\n\n def mean(self) -> float:\n return sum(self.values) / len(self.values)\n\n# test_hlvdiawim.py\nimport pytest\nfrom hlvdiawim import Ixof3Vw5P0\n\ndef test_mean_and_add():\n c = Ixof3Vw5P0.create(\"a\", [1, 2, 3])\n assert c.mean() == 2.0\n assert c.add(5).mean() == (1 + 2 + 3 + 5) / 4\n\ndef test_empty_raises():\n with pytest.raises(ValueError):\n Ixof3Vw5P0.create(\"x\", [])", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Write a thorough test suite for a Python component used for CLI tooling.\nRequirements: cover edge cases, invalid inputs, and behavior invariants.\nConstraints: must be streaming-friendly, must be easy to extend.\nDifficulty: expert. Handle empty inputs and malformed records gracefully.\n\nDeliverable: implementation + tests.\n```python\n# tests (pytest-style) for a module providing: normalize(), parse_lines(), compute_stats()\nimport math\nimport pytest\n\ndef test_normalize_idempotent(module_under_test):\n x = \" A\\tB \"\n assert module_under_test.normalize(module_under_test.normalize(x)) == module_under_test.normalize(x)\n\ndef test_parse_lines_rejects_invalid(module_under_test):\n with pytest.raises(ValueError):\n module_under_test.parse_lines([\"\", \"???\", None]) # type: ignore[arg-type]\n\ndef test_compute_stats_basic(module_under_test):\n data = [1, 2, 3, 4]\n s = module_under_test.compute_stats(data)\n assert s.count == 4\n assert s.total == 10\n assert math.isclose(s.mean, 2.5)\n```", "source": "WithinUsAI/python_GOD_coder_100k"} {"text": "Task type: storage_engine\nScenario: real-time notification hub\nDomain focus: secure enclaves (defensive)\nPrimary language: typescript\nDifficulty: expert+\nScale/SLO: 100k RPS peak\nComponent: component_ugibanjh\nConstraints: include test vectors and fuzz strategy, include backward compatibility and migration plan, include security threat model (defensive only), avoid data races and undefined behavior, include deterministic replay plan, include performance model and limits, explicit contracts and invariants\nAssume weekly network partitions.\nDeliverable: Design a storage engine subsystem (WAL, snapshots, compaction). Include crash recovery invariants and a benchmark plan.\n\nOutput: rigorous design + invariants + verification plan + implementation sketch.\n**Contract**\n- Inputs validated at the boundary; explicit error taxonomy.\n- Idempotency for side effects via request_id; deterministic replay.\n- Backward compatibility: additive changes by default; versioned breaking changes.\n**Invariants**\n- Liveness: under bounded faults and stable network, progress occurs.\n- Determinism: replay of the same event log yields identical outputs.\n- Isolation: tenant boundary enforced; no cross-tenant reads/writes.\n**Failure modes & recovery**\n- Crash during commit: WAL replay completes or transaction aborts; no torn writes.\n- Data corruption: checksums + scrubber; quarantine and rebuild from replicas/snapshots.\n- Duplicate requests: de-duplicate by (tenant, request_id) returning cached response.\n**Security posture (defensive)**\n- Threat model: auth/authz, injection, replay/abuse, supply chain.\n- Least privilege; secrets in managed store; audit logs for sensitive ops.\n- Input normalization, parameterized queries, path traversal protections.\n**Verification strategy**\n- Fuzzing of parsers/framers/validators with corpus seeds.\n- Canary + shadow traffic; invariants checked in production via assertions/metrics.\n- Property tests against a pure reference model (state machine).\n\n**Snippet**\n```text\nImplementation sketch: factor pure state-machine core; adapters for I/O; add deterministic replay log.\n```\nExpert+ checks: mechanized invariants (or exhaustive model checking), adversarial fuzzing, and multi-region failure drills.", "source": "WithinUsAI/Omega_Genesis_Coder_100k"} {"text": "Fix the bug and add pytest tests.\n\n```python\ndef f41433(n: int) -> int:\n # sum 1..n inclusive\n if n < 0: raise ValueError\n total = 0\n for k in range(n): # BUG\n total += k\n return total\n```\nReturn unified diffs for `m05919.py` and `test_m05919.py`.\n\n*** Begin Patch\n*** Update File: m05919.py\n@@\n def f41433(n: int) -> int:\n@@\n- for k in range(n): # BUG\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_m05919.py\n+import pytest\n+from m05919 import f41433\n+\n+def test_small():\n+ assert f41433(7) == 28\n+\n+def test_zero():\n+ assert f41433(0) == 0\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ f41433(-1)\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Fix a bug and add tests.\n\nFile: t01pxtqnt09.py\n```python\ndef w7v7kzyq03(n: int) -> int:\n \"\"\"Sum 1..n inclusive.\"\"\"\n if n < 0:\n raise ValueError(\"n must be non-negative\")\n total = 0\n for k in range(n): # BUG: should include n\n total += k\n return total\n```\n\nReturn unified diffs for t01pxtqnt09.py and test_t01pxtqnt09.py (pytest).\n\n*** Begin Patch\n*** Update File: t01pxtqnt09.py\n@@\n def w7v7kzyq03(n: int) -> int:\n@@\n total = 0\n- for k in range(n): # BUG: should include n\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_t01pxtqnt09.py\n+import pytest\n+from t01pxtqnt09 import w7v7kzyq03\n+\n+def test_zero():\n+ assert w7v7kzyq03(0) == 0\n+\n+def test_one():\n+ assert w7v7kzyq03(1) == 1\n+\n+def test_small():\n+ assert w7v7kzyq03(7) == 28\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ w7v7kzyq03(-1)\n+\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Fix a bug and add tests.\n\nFile: bcxc5otwl.py\n```python\ndef q02rsl86(n: int) -> int:\n \"\"\"Sum 1..n inclusive.\"\"\"\n if n < 0:\n raise ValueError(\"n must be non-negative\")\n total = 0\n for k in range(n): # BUG: should include n\n total += k\n return total\n```\n\nReturn unified diffs for bcxc5otwl.py and test_bcxc5otwl.py (pytest).\n\n*** Begin Patch\n*** Update File: bcxc5otwl.py\n@@\n def q02rsl86(n: int) -> int:\n@@\n total = 0\n- for k in range(n): # BUG: should include n\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_bcxc5otwl.py\n+import pytest\n+from bcxc5otwl import q02rsl86\n+\n+def test_zero():\n+ assert q02rsl86(0) == 0\n+\n+def test_one():\n+ assert q02rsl86(1) == 1\n+\n+def test_small():\n+ assert q02rsl86(7) == 28\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ q02rsl86(-1)\n+\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Refactor to modern typed Python with immutability and tests.\n\nFile: m6v8xq5bb.py\n```python\nclass Jns7Ono94:\n def __init__(self, name, values):\n self.name = name\n self.values = list(values)\n def add(self, v):\n self.values.append(v)\n def mean(self):\n s = 0\n for x in self.values:\n s += x\n return s / len(self.values)\n```\n\nReturn full new m6v8xq5bb.py and test_m6v8xq5bb.py.\n\n# m6v8xq5bb.py\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom typing import Iterable, Tuple\n\n@dataclass(frozen=True)\nclass Jns7Ono94:\n name: str\n values: Tuple[float, ...]\n\n @staticmethod\n def create(name: str, values: Iterable[float]) -> \"Jns7Ono94\":\n vals = tuple(float(v) for v in values)\n if not vals:\n raise ValueError(\"values must be non-empty\")\n return Jns7Ono94(name=name, values=vals)\n\n def add(self, v: float) -> \"Jns7Ono94\":\n return Jns7Ono94(name=self.name, values=self.values + (float(v),))\n\n def mean(self) -> float:\n return sum(self.values) / len(self.values)\n\n# test_m6v8xq5bb.py\nimport pytest\nfrom m6v8xq5bb import Jns7Ono94\n\ndef test_mean_and_add():\n c = Jns7Ono94.create(\"a\", [1, 2, 3])\n assert c.mean() == 2.0\n assert c.add(5).mean() == (1 + 2 + 3 + 5) / 4\n\ndef test_empty_raises():\n with pytest.raises(ValueError):\n Jns7Ono94.create(\"x\", [])", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Implement a web feature for e-commerce: real-time notifications.\nTarget platform: web (React + TypeScript).\nRequirements: accessible UI, API integration, and tests.\nConstraints: must be production-ready, must include clear error handling, must include tests, must include type hints where applicable.\nDifficulty: hard. Assume schema evolves frequently; design for migrations.\n\nOutput: design + implementation guidance suitable for shipping.\nDeliverable: accessible React + TypeScript feature skeleton with tests.\n\n```tsx\n// Feature.tsx\nimport React, { useEffect, useMemo, useState } from \"react\";\n\ntype Item = { id: string; label: string };\n\nexport function Feature({ fetchItems }: { fetchItems: () => Promise }) {\n const [items, setItems] = useState([]);\n const [q, setQ] = useState(\"\");\n const filtered = useMemo(\n () => items.filter(i => i.label.toLowerCase().includes(q.toLowerCase())),\n [items, q]\n );\n\n useEffect(() => {\n let cancelled = false;\n fetchItems().then(xs => { if (!cancelled) setItems(xs); });\n return () => { cancelled = true; };\n }, [fetchItems]);\n\n return (\n
\n \n
    \n {filtered.map(i =>
  • {i.label}
  • )}\n
\n
\n );\n}\n```\n\n```tsx\n// Feature.test.tsx (vitest + testing-library)\nimport { render, screen } from \"@testing-library/react\";\nimport userEvent from \"@testing-library/user-event\";\nimport { Feature } from \"./Feature\";\n\ntest(\"filters items\", async () => {\n const fetchItems = async () => [{ id:\"1\", label:\"Alpha\" }, { id:\"2\", label:\"Beta\" }];\n render();\n expect(await screen.findByText(\"Alpha\")).toBeInTheDocument();\n await userEvent.type(screen.getByLabelText(\"Search\"), \"be\");\n expect(screen.queryByText(\"Alpha\")).toBeNull();\n expect(screen.getByText(\"Beta\")).toBeInTheDocument();\n});\n```\n\n\nHard-mode checks: concurrency safety, idempotency, and rollback validated; add chaos tests where feasible.", "source": "WithinUsAI/GOD_Coder_100k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Produce an offline-first self-evolving code assistant architecture named `flwbekn30pc`.\nMust include: module layout, patch-safety policy, evaluation gates (tests/lint/types), versioned memory index.\n\nArchitecture: `flwbekn30pc` (offline-first, self-evolving)\n\nModules\n- core/loop.py: evolve → validate → accept/reject (bounded iterations)\n- patching/: diff builder, safe apply, atomic writes, rollback points\n- policy/: allowlist paths, deny globs (.git/, __pycache__/, binaries), patch size caps\n- signals/: parse pytest/ruff/mypy into normalized findings\n- memory/index.jsonl: append-only snapshots (hashes, metrics, rationale)\n\nSafety gates\n- refuse path traversal/symlink escapes; never edit binaries\n- accept only if tests/lint/types stay green or improve", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Fix a subtle bug in a Python module used for CLI tooling.\nRequirements: explain root cause briefly, provide corrected code, and add regression tests.\nConstraints: must provide clear error messages, must be streaming-friendly, must be memory-efficient, must include tests.\nDifficulty: hard. Guarantee deterministic output ordering.\n\nDeliverable: production-ready reference solution.\n```python\nfrom __future__ import annotations\n\nfrom dataclasses import dataclass\nfrom pathlib import Path\nfrom typing import Iterable\nimport json\n\n\nclass ValidationError(ValueError):\n \"\"\"Raised when input validation fails.\"\"\"\n\n\ndef safe_join(base: Path, *parts: str) -> Path:\n \"\"\"Join paths while preventing traversal outside base.\"\"\"\n b = base.resolve()\n p = (b / Path(*parts)).resolve()\n if p != b and b not in p.parents:\n raise ValidationError(f\"unsafe path: {p}\")\n return p\n\n\n@dataclass(frozen=True, slots=True)\nclass Record:\n key: str\n value: int\n\n\ndef parse_jsonl(lines: Iterable[str]) -> list[Record]:\n out: list[Record] = []\n for idx, line in enumerate(lines, 1):\n s = line.strip()\n if not s:\n continue\n try:\n obj = json.loads(s)\n except json.JSONDecodeError as e:\n raise ValidationError(f\"line {idx}: invalid json\") from e\n if not isinstance(obj, dict):\n raise ValidationError(f\"line {idx}: expected object\")\n key = obj.get(\"key\")\n val = obj.get(\"value\")\n if not isinstance(key, str) or not key:\n raise ValidationError(f\"line {idx}: key must be non-empty str\")\n if not isinstance(val, int):\n raise ValidationError(f\"line {idx}: value must be int\")\n out.append(Record(key, val))\n return out\n\n\ndef write_jsonl(base: Path, rel: str, records: Iterable[Record]) -> Path:\n base.mkdir(parents=True, exist_ok=True)\n dst = safe_join(base, rel)\n dst.parent.mkdir(parents=True, exist_ok=True)\n with dst.open(\"w\", encoding=\"utf-8\", newline=\"\\n\") as f:\n for r in records:\n f.write(json.dumps({\"key\": r.key, \"value\": r.value}, ensure_ascii=False) + \"\\n\")\n return dst\n```\n\n```python\n# tests (pytest-style)\nimport json\nfrom pathlib import Path\nimport pytest\nfrom module_under_test import ValidationError, Record, parse_jsonl, write_jsonl\n\ndef test_parse_ok():\n lines = [json.dumps({\"key\":\"a\",\"value\":1}), json.dumps({\"key\":\"b\",\"value\":2})]\n assert parse_jsonl(lines) == [Record(\"a\",1), Record(\"b\",2)]\n\ndef test_parse_rejects_bad_json():\n with pytest.raises(ValidationError):\n parse_jsonl([\"{not json}\"])\n\ndef test_safe_join_blocks_traversal(tmp_path: Path):\n with pytest.raises(ValidationError):\n write_jsonl(tmp_path, \"../x.jsonl\", [Record(\"a\",1)])\n```", "source": "WithinUsAI/python_GOD_coder_100k"} {"text": "Task type: mechanized_spec\nScenario: multi-tenant event ingestion\nDomain focus: query planning\nPrimary language: lean\nDifficulty: expert\nScale/SLO: 10k RPS peak\nComponent: component_hnxzipzf\nConstraints: include failure modes and recovery, include security threat model (defensive only), explicit contracts and invariants, include performance model and limits, include test vectors and fuzz strategy\nAssume strict auditability and replayable history.\nDeliverable: Provide a mechanized-style spec outline (Lean-like), key definitions, and a proof plan. Include executable reference code skeleton and tests.\n\nOutput: elite engineering answer optimized for correctness, performance, and operability.\n**Contract**\n- Inputs validated at the boundary; explicit error taxonomy.\n- Idempotency for side effects via request_id; deterministic replay.\n- Backward compatibility: additive changes by default; versioned breaking changes.\n**Invariants**\n- Liveness: under bounded faults and stable network, progress occurs.\n- Safety: state transitions preserve invariants; no partial commit leaks.\n- Isolation: tenant boundary enforced; no cross-tenant reads/writes.\n**Failure modes & recovery**\n- Network partition: minority cannot commit; clients receive retriable errors.\n- Crash during commit: WAL replay completes or transaction aborts; no torn writes.\n- Data corruption: checksums + scrubber; quarantine and rebuild from replicas/snapshots.\n**Security posture (defensive)**\n- Threat model: auth/authz, injection, replay/abuse, supply chain.\n- Least privilege; secrets in managed store; audit logs for sensitive ops.\n- Input normalization, parameterized queries, path traversal protections.\n**Verification strategy**\n- Fuzzing of parsers/framers/validators with corpus seeds.\n- Canary + shadow traffic; invariants checked in production via assertions/metrics.\n- Property tests against a pure reference model (state machine).\n\n**Snippet**\n```lean\n-- Pseudo-Lean outline\nstructure State where\n ver : Nat\n val : Option ByteArray\n\ndef invariant (s : State) : Prop := True\n\ntheorem step_preserves_invariant :\n ∀ s, invariant s → ∀ s', Step s s' → invariant s' := by\n intro s hs s' hstep\n -- proof plan: case analysis on transition; trivial here\n trivial\n```\n\nExpert checks: state-machine proof sketch + model checking; upgrade/rollback rehearsed.", "source": "WithinUsAI/Omega_Genesis_Coder_100k"} {"text": "Fix a subtle bug in a Python module used for rate limiting.\nRequirements: explain root cause briefly, provide corrected code, and add regression tests.\nConstraints: must be streaming-friendly, must be easy to extend.\nDifficulty: medium. Handle empty inputs and malformed records gracefully.\n\nDeliverable: implementation + tests.\n```python\nfrom __future__ import annotations\n\nfrom dataclasses import dataclass\nfrom pathlib import Path\nfrom typing import Iterable\nimport json\n\n\nclass ValidationError(ValueError):\n \"\"\"Raised when input validation fails.\"\"\"\n\n\ndef safe_join(base: Path, *parts: str) -> Path:\n \"\"\"Join paths while preventing traversal outside base.\"\"\"\n b = base.resolve()\n p = (b / Path(*parts)).resolve()\n if p != b and b not in p.parents:\n raise ValidationError(f\"unsafe path: {p}\")\n return p\n\n\n@dataclass(frozen=True, slots=True)\nclass Record:\n key: str\n value: int\n\n\ndef parse_jsonl(lines: Iterable[str]) -> list[Record]:\n out: list[Record] = []\n for idx, line in enumerate(lines, 1):\n s = line.strip()\n if not s:\n continue\n try:\n obj = json.loads(s)\n except json.JSONDecodeError as e:\n raise ValidationError(f\"line {idx}: invalid json\") from e\n if not isinstance(obj, dict):\n raise ValidationError(f\"line {idx}: expected object\")\n key = obj.get(\"key\")\n val = obj.get(\"value\")\n if not isinstance(key, str) or not key:\n raise ValidationError(f\"line {idx}: key must be non-empty str\")\n if not isinstance(val, int):\n raise ValidationError(f\"line {idx}: value must be int\")\n out.append(Record(key, val))\n return out\n\n\ndef write_jsonl(base: Path, rel: str, records: Iterable[Record]) -> Path:\n base.mkdir(parents=True, exist_ok=True)\n dst = safe_join(base, rel)\n dst.parent.mkdir(parents=True, exist_ok=True)\n with dst.open(\"w\", encoding=\"utf-8\", newline=\"\\n\") as f:\n for r in records:\n f.write(json.dumps({\"key\": r.key, \"value\": r.value}, ensure_ascii=False) + \"\\n\")\n return dst\n```\n\n```python\n# tests (pytest-style)\nimport json\nfrom pathlib import Path\nimport pytest\nfrom module_under_test import ValidationError, Record, parse_jsonl, write_jsonl\n\ndef test_parse_ok():\n lines = [json.dumps({\"key\":\"a\",\"value\":1}), json.dumps({\"key\":\"b\",\"value\":2})]\n assert parse_jsonl(lines) == [Record(\"a\",1), Record(\"b\",2)]\n\ndef test_parse_rejects_bad_json():\n with pytest.raises(ValidationError):\n parse_jsonl([\"{not json}\"])\n\ndef test_safe_join_blocks_traversal(tmp_path: Path):\n with pytest.raises(ValidationError):\n write_jsonl(tmp_path, \"../x.jsonl\", [Record(\"a\",1)])\n```", "source": "WithinUsAI/python_GOD_coder_100k"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: Project domain: observability collector\nImplementation stack: Next.js, Node.js, Prisma, PostgreSQL, Playwright, Docker\nSoftware delivery problem: transaction boundary bug\nTask type: architecture_patch\nDifficulty: medium\n\nReturn a complete delivery-grade response with:\n- diagnosis or design reasoning\n- implementation\n- test plan or tests\n- rollout plan\n- rollback or compatibility note\n- verification commands\n\nRepository sketch:\nrepo/\n src/App/Program.cs\n src/App/Service.cs\n tests/App.Tests/ServiceTests.cs\n App.sln\n\nFocus: Focus on shipping production software with rollout safety, acceptance criteria, telemetry, and maintenance quality.\n\nassistant: Diagnosis:\n- Root cause or delivery blocker: transaction boundary bug needs both implementation work and a safe shipping plan.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```csharp\nusing System;\nusing System.Collections.Generic;\n\npublic static class RequestHandler\n{\n public static Dictionary HandleRequest(Dictionary payload)\n {\n var clean = new Dictionary();\n foreach (var entry in payload)\n {\n if (entry.Value != null)\n clean[entry.Key.Trim()] = entry.Value;\n }\n if (!clean.ContainsKey(\"id\"))\n throw new ArgumentException(\"missing id\");\n return new Dictionary\n {\n [\"ok\"] = true,\n [\"data\"] = clean\n };\n }\n}\n```\n\nTests:\n```csharp\nusing System;\nusing System.Collections.Generic;\nusing Xunit;\n\npublic class RequestHandlerTests\n{\n [Fact]\n public void RequiresId()\n {\n Assert.Throws(() => RequestHandler.HandleRequest(new Dictionary { [\"name\"] = \"x\" }));\n }\n}\n```\n\nVerification:\n- `dotnet test`\n- `dotnet build`\n\nEngineering notes:\n- Language: C#\n- Framework/tooling: EF Core\n- Stack context: Next.js, Node.js, Prisma, PostgreSQL, Playwright, Docker\n- Domain: observability collector\n- Task type: architecture_patch\n- Difficulty: medium\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Fix a bug and add tests.\n\nFile: ausbueu5.py\n```python\ndef humziy574nc(n: int) -> int:\n \"\"\"Sum 1..n inclusive.\"\"\"\n if n < 0:\n raise ValueError(\"n must be non-negative\")\n total = 0\n for k in range(n): # BUG: should include n\n total += k\n return total\n```\n\nReturn unified diffs for ausbueu5.py and test_ausbueu5.py (pytest).\n\n*** Begin Patch\n*** Update File: ausbueu5.py\n@@\n def humziy574nc(n: int) -> int:\n@@\n total = 0\n- for k in range(n): # BUG: should include n\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_ausbueu5.py\n+import pytest\n+from ausbueu5 import humziy574nc\n+\n+def test_zero():\n+ assert humziy574nc(0) == 0\n+\n+def test_one():\n+ assert humziy574nc(1) == 1\n+\n+def test_small():\n+ assert humziy574nc(7) == 28\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ humziy574nc(-1)\n+\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Perform a code review for a fintech PR implementing real-time notifications.\nTarget platform: backend (Go).\nRequirements: list critical issues, improvements, and provide an improved patch excerpt.\nConstraints: must be secure-by-default, must include tests, must avoid global state, must be production-ready, must be easy to extend.\nDifficulty: easy. Assume 10k RPS peak traffic.\n\nOutput: production-oriented blueprint with code where appropriate.\nDeliverable: code review findings + improved patch excerpt.\n\n**Critical issues**\n1. Missing input validation at boundary; potential unexpected exceptions.\n2. No idempotency / retry safety for side-effecting endpoint.\n3. No tests for edge cases (empty input, duplicates, timeouts).\n4. Observability gaps: no request_id correlation, no metrics.\n\n**Improvements**\n- Add strict validation and explicit error responses.\n- Add idempotency key support for create endpoints.\n- Add unit + integration tests with CI gating.\n- Add structured logs and basic metrics.\n\nPatch excerpt (illustrative):\n```python\nif not idem_key:\n raise HTTPException(400, \"Missing Idempotency-Key\")\n```\n\n\nChecks: input validation, tests, and safe defaults included.", "source": "WithinUsAI/GOD_Coder_100k"} {"text": "Build an elite-grade solution in the domain of distributed systems for scenario: payment processing.\nPrimary language: go.\nDifficulty: expert.\nConstraints: make the interface contract explicit, design for backward compatibility and migrations, include invariants and failure modes, avoid undefined behavior and data races.\nComponent: component_wkrwxsu.\nAssume cold-start and memory limits are tight.\nTask: Define properties/invariants and implement property-based tests (or generative tests) with a reference model and edge-case generators.\n\nOutput: rigorous solution with invariants, failure modes, and performance notes.\nOutput: properties + reference model + generative tests.\n\n**Properties**\n- Idempotency: replayed command yields same result.\n- Monotonicity: versions only increase.\n- Conservation: for queues, produced items == consumed items (multiset) under no-loss assumption.\n\n**Approach**\n- Write a small reference model (pure function).\n- Generate random sequences of operations; compare implementation outputs to model.\n\n\nExpert checks: state-machine reasoning, concurrency stress, and upgrade/rollback validated.", "source": "WithinUsAI/Elite_GOD_Coder_100k"} {"text": "Fix a subtle bug in a Python module used for metrics aggregation.\nRequirements: explain root cause briefly, provide corrected code, and add regression tests.\nConstraints: stdlib-only, must include tests, must include docstrings.\nDifficulty: hard. Handle empty inputs and malformed records gracefully.\n\nDeliverable: implementation + tests.\n```python\nfrom __future__ import annotations\n\nfrom dataclasses import dataclass\nfrom pathlib import Path\nfrom typing import Iterable\nimport json\n\n\nclass ValidationError(ValueError):\n \"\"\"Raised when input validation fails.\"\"\"\n\n\ndef safe_join(base: Path, *parts: str) -> Path:\n \"\"\"Join paths while preventing traversal outside base.\"\"\"\n b = base.resolve()\n p = (b / Path(*parts)).resolve()\n if p != b and b not in p.parents:\n raise ValidationError(f\"unsafe path: {p}\")\n return p\n\n\n@dataclass(frozen=True, slots=True)\nclass Record:\n key: str\n value: int\n\n\ndef parse_jsonl(lines: Iterable[str]) -> list[Record]:\n out: list[Record] = []\n for idx, line in enumerate(lines, 1):\n s = line.strip()\n if not s:\n continue\n try:\n obj = json.loads(s)\n except json.JSONDecodeError as e:\n raise ValidationError(f\"line {idx}: invalid json\") from e\n if not isinstance(obj, dict):\n raise ValidationError(f\"line {idx}: expected object\")\n key = obj.get(\"key\")\n val = obj.get(\"value\")\n if not isinstance(key, str) or not key:\n raise ValidationError(f\"line {idx}: key must be non-empty str\")\n if not isinstance(val, int):\n raise ValidationError(f\"line {idx}: value must be int\")\n out.append(Record(key, val))\n return out\n\n\ndef write_jsonl(base: Path, rel: str, records: Iterable[Record]) -> Path:\n base.mkdir(parents=True, exist_ok=True)\n dst = safe_join(base, rel)\n dst.parent.mkdir(parents=True, exist_ok=True)\n with dst.open(\"w\", encoding=\"utf-8\", newline=\"\\n\") as f:\n for r in records:\n f.write(json.dumps({\"key\": r.key, \"value\": r.value}, ensure_ascii=False) + \"\\n\")\n return dst\n```\n\n```python\n# tests (pytest-style)\nimport json\nfrom pathlib import Path\nimport pytest\nfrom module_under_test import ValidationError, Record, parse_jsonl, write_jsonl\n\ndef test_parse_ok():\n lines = [json.dumps({\"key\":\"a\",\"value\":1}), json.dumps({\"key\":\"b\",\"value\":2})]\n assert parse_jsonl(lines) == [Record(\"a\",1), Record(\"b\",2)]\n\ndef test_parse_rejects_bad_json():\n with pytest.raises(ValidationError):\n parse_jsonl([\"{not json}\"])\n\ndef test_safe_join_blocks_traversal(tmp_path: Path):\n with pytest.raises(ValidationError):\n write_jsonl(tmp_path, \"../x.jsonl\", [Record(\"a\",1)])\n```", "source": "WithinUsAI/python_GOD_coder_100k"} {"text": "Build an elite-grade solution in the domain of edge/IoT for scenario: job scheduler.\nPrimary language: python.\nDifficulty: medium.\nConstraints: include invariants and failure modes, design for backward compatibility and migrations, avoid undefined behavior and data races, assume untrusted inputs; validate and sanitize.\nComponent: component_vlbfdyj.\nAssume partial network partitions occur weekly.\nTask: Provide SLOs, alerting, dashboards, runbooks, and incident playbook. Include chaos testing and safe rollout strategy.\n\nOutput: production blueprint plus correctness arguments and test strategy.\nOutput: SLOs + alerts + runbooks + chaos strategy.\n\n**SLOs**\n- Availability: 99.9% monthly\n- Latency: p95 < 200ms, p99 < 400ms\n- Error rate: < 0.1%\n\n**Alerts**\n- Burn-rate alerts for SLOs (fast/slow windows)\n- Saturation: CPU, memory, queue depth, DB connections\n- Dependency health: cache hit rate drop, downstream timeouts\n\n**Runbooks**\n- Triage: identify blast radius, feature-flag rollback, capacity mitigation\n- Post-incident: timeline, contributing factors, action items\n\n**Chaos**\n- Inject latency, partial outages, and restarts in staging; verify steady-state SLOs.\n\n\nChecks: boundary validation and deterministic behavior verified.", "source": "WithinUsAI/Elite_GOD_Coder_100k"} {"text": "Build an elite-grade solution in the domain of compilers for scenario: edge sync.\nPrimary language: go.\nDifficulty: expert.\nConstraints: avoid undefined behavior and data races, include invariants and failure modes, provide rollout and rollback guidance.\nComponent: component_tkfgjck.\nAssume cold-start and memory limits are tight.\nTask: Write a precise interface contract, list invariants, and provide a lightweight formal/spec-style description (pseudo-TLA+/state machine) plus reference implementation skeleton and tests.\n\nOutput: elite-grade engineering answer with contracts, edge cases, and verification.\nOutput: contract + invariants + spec + reference skeleton.\n\n**Interface contract**\n- Commands: `Put(key, value, expected_version?)`, `Get(key)`, `Delete(key, expected_version?)`\n- Responses: `Ok(version, value?)`, `NotFound`, `Conflict(current_version)`, `InvalidInput`\n- Idempotency: client supplies `request_id`; server must de-duplicate per (tenant_id, request_id).\n\n**Invariants**\n1. Monotonic version per key (strictly increases on successful writes).\n2. Reads return latest committed value for a given consistency level.\n3. Exactly-once effect for a given `request_id` (at-most-once execution + replay response).\n4. Tenant isolation: keys are scoped by tenant_id.\n\n**State machine (pseudo)**\nState:\n- store: map[(tenant,key)] -> (version:int, value:bytes|tombstone)\n- seen: map[(tenant,request_id)] -> response\nTransition Put:\n- if request_id in seen: return seen[...]\n- validate input; if expected_version set and != current version -> Conflict\n- version' = version + 1; store[...] := (version', value); seen[...] := Ok(version', value)\n\n**Reference skeleton (Python)**\n```python\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom typing import Dict, Optional, Tuple\n\nclass Conflict(Exception): pass\nclass InvalidInput(ValueError): pass\n\n@dataclass(frozen=True, slots=True)\nclass Value:\n version: int\n data: Optional[bytes] # None == tombstone\n\n@dataclass(frozen=True, slots=True)\nclass Reply:\n kind: str\n version: Optional[int] = None\n data: Optional[bytes] = None\n\nclass KV:\n def __init__(self) -> None:\n self._store: Dict[Tuple[str,str], Value] = {}\n self._seen: Dict[Tuple[str,str], Reply] = {}\n\n def put(self, tenant: str, request_id: str, key: str, data: bytes, expected_version: Optional[int]=None) -> Reply:\n if not tenant or not request_id or not key:\n raise InvalidInput(\"tenant/request_id/key required\")\n de = self._seen.get((tenant, request_id))\n if de: \n return de\n cur = self._store.get((tenant, key), Value(0, None))\n if expected_version is not None and expected_version != cur.version:\n r = Reply(\"conflict\", version=cur.version)\n self._seen[(tenant, request_id)] = r\n return r\n nxt = Value(cur.version + 1, data)\n self._store[(tenant, key)] = nxt\n r = Reply(\"ok\", version=nxt.version)\n self._seen[(tenant, request_id)] = r\n return r\n```\n\n**Tests**\n- Determinism: same request_id → same reply.\n- Conflict detection and version monotonicity.\n\n\nExpert checks: state-machine reasoning, concurrency stress, and upgrade/rollback validated.", "source": "WithinUsAI/Elite_GOD_Coder_100k"} {"text": "Build an elite-grade solution in the domain of databases for scenario: feature flagging.\nPrimary language: rust.\nDifficulty: expert.\nConstraints: avoid undefined behavior and data races, assume untrusted inputs; validate and sanitize, document performance characteristics, include invariants and failure modes.\nComponent: component_doryzmg.\nAssume schema changes every sprint; must be backward compatible.\nTask: Implement a concurrency primitive or subsystem (lock-free queue, thread pool, async runtime component). Explain memory ordering and correctness arguments; include stress tests.\n\nOutput: rigorous solution with invariants, failure modes, and performance notes.\nOutput: correctness-focused concurrency primitive + stress tests.\n\n**Primitive**\n- Bounded MPMC queue with backpressure (blocking push/pop) OR lock-free SPSC ring buffer.\n\n**Correctness notes**\n- For lock-free: use acquire/release semantics on head/tail indices.\n- Avoid ABA by monotonic counters; ring index = counter % capacity.\n\n**Stress tests**\n- Multi-thread producers/consumers; assert item multiset preserved.\n- Use time-bounded randomized schedules; detect deadlocks.\n\n\nExpert checks: state-machine reasoning, concurrency stress, and upgrade/rollback validated.", "source": "WithinUsAI/Elite_GOD_Coder_100k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Fix a bug and add tests.\n\nFile: d5gqfotz3.py\n```python\ndef xvbl5yyvz3a(n: int) -> int:\n \"\"\"Sum 1..n inclusive.\"\"\"\n if n < 0:\n raise ValueError(\"n must be non-negative\")\n total = 0\n for k in range(n): # BUG: should include n\n total += k\n return total\n```\n\nReturn unified diffs for d5gqfotz3.py and test_d5gqfotz3.py (pytest).\n\n*** Begin Patch\n*** Update File: d5gqfotz3.py\n@@\n def xvbl5yyvz3a(n: int) -> int:\n@@\n total = 0\n- for k in range(n): # BUG: should include n\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_d5gqfotz3.py\n+import pytest\n+from d5gqfotz3 import xvbl5yyvz3a\n+\n+def test_zero():\n+ assert xvbl5yyvz3a(0) == 0\n+\n+def test_one():\n+ assert xvbl5yyvz3a(1) == 1\n+\n+def test_small():\n+ assert xvbl5yyvz3a(7) == 28\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ xvbl5yyvz3a(-1)\n+\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Task type: lockfree_primitive\nScenario: multi-tenant event ingestion\nDomain focus: cryptography engineering (defensive)\nPrimary language: cpp\nDifficulty: expert+\nScale/SLO: p99 < 150ms\nComponent: component_pwmivvbu\nConstraints: include test vectors and fuzz strategy, assume adversarial inputs; validate everything, include failure modes and recovery, include backward compatibility and migration plan, include verification strategy, explicit contracts and invariants, include performance model and limits\nAssume tight memory budget and cold-start constraints.\nDeliverable: Design a lock-free primitive with memory ordering reasoning and stress tests (no UB).\n\nOutput: elite engineering answer optimized for correctness, performance, and operability.\n**Contract**\n- Inputs validated at the boundary; explicit error taxonomy.\n- Idempotency for side effects via request_id; deterministic replay.\n- Backward compatibility: additive changes by default; versioned breaking changes.\n**Invariants**\n- Safety: state transitions preserve invariants; no partial commit leaks.\n- Determinism: replay of the same event log yields identical outputs.\n- Liveness: under bounded faults and stable network, progress occurs.\n**Failure modes & recovery**\n- Duplicate requests: de-duplicate by (tenant, request_id) returning cached response.\n- Crash during commit: WAL replay completes or transaction aborts; no torn writes.\n- Data corruption: checksums + scrubber; quarantine and rebuild from replicas/snapshots.\n**Security posture (defensive)**\n- Threat model: auth/authz, injection, replay/abuse, supply chain.\n- Least privilege; secrets in managed store; audit logs for sensitive ops.\n- Input normalization, parameterized queries, path traversal protections.\n**Verification strategy**\n- Canary + shadow traffic; invariants checked in production via assertions/metrics.\n- Deterministic simulation with fault injection (crash/partition/latency).\n- Property tests against a pure reference model (state machine).\n\n**Snippet**\n```rust\n// Skeleton: SPSC ring buffer with acquire/release (outline)\nuse std::sync::atomic::{AtomicUsize, Ordering};\n\npub struct Ring {\n buf: Vec>,\n head: AtomicUsize,\n tail: AtomicUsize,\n cap: usize,\n}\n\n// Correctness sketch: producer uses Release on tail store, consumer uses Acquire on tail load.\n```\n\nExpert+ checks: mechanized invariants (or exhaustive model checking), adversarial fuzzing, and multi-region failure drills.", "source": "WithinUsAI/Omega_Genesis_Coder_100k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Optimize while preserving behavior.\n\nFile: uliap_.py\n```python\ndef cef8pn(xs):\n out = []\n for x in xs:\n if x not in out:\n out.append(x)\n return out\n```\n\nRequirements: preserve first-seen order; O(n) average; add types + docstring.\n\n# uliap_.py\nfrom __future__ import annotations\nfrom typing import Iterable, List, Set, TypeVar\n\nT = TypeVar(\"T\")\n\ndef cef8pn(xs: Iterable[T]) -> List[T]:\n \"\"\"Return unique items preserving first-seen order.\"\"\"\n seen: Set[T] = set()\n out: List[T] = []\n for x in xs:\n if x in seen:\n continue\n seen.add(x)\n out.append(x)\n return out", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Produce an offline-first self-evolving code assistant architecture named `q8txjmsqpx4`.\nMust include: module layout, patch-safety policy, evaluation gates (tests/lint/types), versioned memory index.\n\nArchitecture: `q8txjmsqpx4` (offline-first, self-evolving)\n\nModules\n- core/loop.py: evolve → validate → accept/reject (bounded iterations)\n- patching/: diff builder, safe apply, atomic writes, rollback points\n- policy/: allowlist paths, deny globs (.git/, __pycache__/, binaries), patch size caps\n- signals/: parse pytest/ruff/mypy into normalized findings\n- memory/index.jsonl: append-only snapshots (hashes, metrics, rationale)\n\nSafety gates\n- refuse path traversal/symlink escapes; never edit binaries\n- accept only if tests/lint/types stay green or improve", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Implement an ML engineering workflow for healthtech focusing on A/B experimentation.\nTarget platform: ML (training + serving).\nRequirements: data contract, training loop, evaluation, model registry, serving API, monitoring.\nConstraints: must avoid global state, must be easy to extend, must be production-ready, must include clear error handling.\nDifficulty: hard. Assume 10k RPS peak traffic.\n\nOutput: actionable implementation and verification artifacts.\nDeliverable: ML engineering blueprint (training + serving + monitoring), safe and production-oriented.\n\n**Data contract**\n- Define feature schema + ranges; validate at training and serving.\n\n**Training**\n- Deterministic split; baseline model; track metrics (AUC/F1/latency).\n- Store artifacts: model, config, feature stats.\n\n**Registry**\n- Promote models via approval gates; record lineage.\n\n**Serving**\n- Separate inference service with `/predict`.\n- Input validation + default handling; timeouts.\n\n**Monitoring**\n- Data drift: feature distribution checks.\n- Performance: online metrics + periodic labels; alert on regression.\n\nMinimal serving skeleton (FastAPI-ish):\n```python\n# validate input -> vectorize -> model.predict_proba -> return\n```\n\n\nHard-mode checks: concurrency safety, idempotency, and rollback validated; add chaos tests where feasible.", "source": "WithinUsAI/GOD_Coder_100k"} {"text": "Create a comprehensive test plan and automated tests for audit logs in a gaming product.\nTarget platform: data (SQL + Python).\nRequirements: unit/integration tests, edge cases, load tests strategy, and CI gates.\nConstraints: must be easy to extend, must be observable (logs/metrics/traces), must be secure-by-default, must include tests.\nDifficulty: hard. Assume schema evolves frequently; design for migrations.\n\nOutput: actionable implementation and verification artifacts.\nDeliverable: test plan + automation guidance.\n\n**Unit tests**\n- Validation: malformed payloads rejected with correct codes.\n- AuthZ: tenant boundary enforced.\n- Idempotency: replay returns same response; conflicting reuse yields 409.\n\n**Integration tests**\n- DB transaction behavior; unique constraints.\n- Cache behavior: correctness under concurrent requests.\n\n**Load tests**\n- 10k RPS target: measure p95 latency, error rate, saturation.\n\n**CI gates**\n- Lint + typecheck + unit tests required.\n- Coverage threshold for critical modules.\n- Block merge on flaky test detection.\n\n\nHard-mode checks: concurrency safety, idempotency, and rollback validated; add chaos tests where feasible.", "source": "WithinUsAI/GOD_Coder_100k"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: Language: C#\nFramework/tooling: EF Core\nDomain: auth service\nLogic challenge: unsafe deserialization\nTask type: security_logic_interaction\nDifficulty: hard\n\nReturn a rigorous engineering answer:\n- identify the hidden root cause or logical failure\n- present the corrected implementation\n- add tests that prove the fix\n- list verification commands\n- explain why naive fixes are insufficient when relevant\n\nRepository sketch:\nrepo/\n src/App/Program.cs\n src/App/Service.cs\n tests/App.Tests/ServiceTests.cs\n App.sln\n\nFocus: Focus on ambiguity, misleading symptoms, hidden root causes, and high-stakes debugging.\n\nassistant: Diagnosis:\n- Hidden root cause: unsafe deserialization presents misleading symptoms, so the patch must target the actual logic boundary rather than the first visible failure.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```csharp\nusing System;\nusing System.Collections.Generic;\n\npublic static class RequestHandler\n{\n public static Dictionary HandleRequest(Dictionary payload)\n {\n var clean = new Dictionary();\n foreach (var entry in payload)\n {\n if (entry.Value != null)\n clean[entry.Key.Trim()] = entry.Value;\n }\n if (!clean.ContainsKey(\"id\"))\n throw new ArgumentException(\"missing id\");\n return new Dictionary\n {\n [\"ok\"] = true,\n [\"data\"] = clean\n };\n }\n}\n```\n\nTests:\n```csharp\nusing System;\nusing System.Collections.Generic;\nusing Xunit;\n\npublic class RequestHandlerTests\n{\n [Fact]\n public void RequiresId()\n {\n Assert.Throws(() => RequestHandler.HandleRequest(new Dictionary { [\"name\"] = \"x\" }));\n }\n}\n```\n\nVerification:\n- `dotnet test`\n- `dotnet build`\n\nEngineering notes:\n- Language: C#\n- Framework/tooling: EF Core\n- Stack context: Rust, Axum, SQLx, Redis, Tokio, Docker\n- Domain: auth service\n- Task type: security_logic_interaction\n- Difficulty: hard\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "Refactor to typed, mostly-immutable Python and add minimal tests.\n\n```python\nclass C83971:\n def __init__(self, values): self.values=list(values)\n def mean(self): return sum(self.values)/len(self.values)\n```\nReturn `m98767.py` and `test_m98767.py`.\n\n```python\n# m98767.py\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom typing import Iterable, Tuple\n\n@dataclass(frozen=True)\nclass C83971:\n values: Tuple[float, ...]\n\n @staticmethod\n def create(values: Iterable[float]) -> \"C83971\":\n vals = tuple(float(v) for v in values)\n if not vals: raise ValueError(\"empty\")\n return C83971(vals)\n\n def mean(self) -> float:\n return sum(self.values)/len(self.values)\n```\n\n```python\n# test_m98767.py\nimport pytest\nfrom m98767 import C83971\n\ndef test_mean():\n assert C83971.create([1,2,3]).mean() == 2.0\ndef test_empty():\n with pytest.raises(ValueError):\n C83971.create([])\n```", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Build an elite-grade solution in the domain of ml systems for scenario: chat messaging.\nPrimary language: sql.\nDifficulty: expert.\nConstraints: include invariants and failure modes, document performance characteristics, make the interface contract explicit, include tests or verification strategy.\nComponent: component_igtjrnx.\nAssume crash-only design; recovery must be deterministic.\nTask: Write a precise interface contract, list invariants, and provide a lightweight formal/spec-style description (pseudo-TLA+/state machine) plus reference implementation skeleton and tests.\n\nOutput: elite-grade engineering answer with contracts, edge cases, and verification.\nOutput: contract + invariants + spec + reference skeleton.\n\n**Interface contract**\n- Commands: `Put(key, value, expected_version?)`, `Get(key)`, `Delete(key, expected_version?)`\n- Responses: `Ok(version, value?)`, `NotFound`, `Conflict(current_version)`, `InvalidInput`\n- Idempotency: client supplies `request_id`; server must de-duplicate per (tenant_id, request_id).\n\n**Invariants**\n1. Monotonic version per key (strictly increases on successful writes).\n2. Reads return latest committed value for a given consistency level.\n3. Exactly-once effect for a given `request_id` (at-most-once execution + replay response).\n4. Tenant isolation: keys are scoped by tenant_id.\n\n**State machine (pseudo)**\nState:\n- store: map[(tenant,key)] -> (version:int, value:bytes|tombstone)\n- seen: map[(tenant,request_id)] -> response\nTransition Put:\n- if request_id in seen: return seen[...]\n- validate input; if expected_version set and != current version -> Conflict\n- version' = version + 1; store[...] := (version', value); seen[...] := Ok(version', value)\n\n**Reference skeleton (Python)**\n```python\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom typing import Dict, Optional, Tuple\n\nclass Conflict(Exception): pass\nclass InvalidInput(ValueError): pass\n\n@dataclass(frozen=True, slots=True)\nclass Value:\n version: int\n data: Optional[bytes] # None == tombstone\n\n@dataclass(frozen=True, slots=True)\nclass Reply:\n kind: str\n version: Optional[int] = None\n data: Optional[bytes] = None\n\nclass KV:\n def __init__(self) -> None:\n self._store: Dict[Tuple[str,str], Value] = {}\n self._seen: Dict[Tuple[str,str], Reply] = {}\n\n def put(self, tenant: str, request_id: str, key: str, data: bytes, expected_version: Optional[int]=None) -> Reply:\n if not tenant or not request_id or not key:\n raise InvalidInput(\"tenant/request_id/key required\")\n de = self._seen.get((tenant, request_id))\n if de: \n return de\n cur = self._store.get((tenant, key), Value(0, None))\n if expected_version is not None and expected_version != cur.version:\n r = Reply(\"conflict\", version=cur.version)\n self._seen[(tenant, request_id)] = r\n return r\n nxt = Value(cur.version + 1, data)\n self._store[(tenant, key)] = nxt\n r = Reply(\"ok\", version=nxt.version)\n self._seen[(tenant, request_id)] = r\n return r\n```\n\n**Tests**\n- Determinism: same request_id → same reply.\n- Conflict detection and version monotonicity.\n\n\nExpert checks: state-machine reasoning, concurrency stress, and upgrade/rollback validated.", "source": "WithinUsAI/Elite_GOD_Coder_100k"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: Language: SQL\nFramework/tooling: DuckDB\nDomain: payments platform\nLogic challenge: CI failures after dependency upgrade\nTask type: security_logic_interaction\nDifficulty: hard\n\nReturn a rigorous engineering answer:\n- identify the hidden root cause or logical failure\n- present the corrected implementation\n- add tests that prove the fix\n- list verification commands\n- explain why naive fixes are insufficient when relevant\n\nRepository sketch:\nrepo/\n migrations/\n 001_init.sql\n 002_add_index.sql\n queries/\n report.sql\n tests/\n report_cases.md\n\nFocus: Focus on ambiguity, misleading symptoms, hidden root causes, and high-stakes debugging.\n\nassistant: Diagnosis:\n- Hidden root cause: CI failures after dependency upgrade presents misleading symptoms, so the patch must target the actual logic boundary rather than the first visible failure.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```sql\nWITH ranked AS (\n SELECT\n user_id,\n created_at,\n amount,\n ROW_NUMBER() OVER (PARTITION BY user_id ORDER BY created_at DESC, id DESC) AS rn\n FROM orders\n)\nSELECT user_id, created_at, amount\nFROM ranked\nWHERE rn = 1;\n```\n\nTests:\n```sql\n-- Correctness checks:\n-- 1) multiple rows per user\n-- 2) identical timestamps require deterministic tie-breaker\n-- 3) null values handled by business rules\n```\n\nVerification:\n- `run migration checks`\n- `run query correctness cases`\n\nEngineering notes:\n- Language: SQL\n- Framework/tooling: DuckDB\n- Stack context: FastAPI, PostgreSQL, Redis, Celery, pytest, Docker\n- Domain: payments platform\n- Task type: security_logic_interaction\n- Difficulty: hard\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "Refactor an existing codebase in calendar/scheduling to support real-time notifications cleanly.\nTarget platform: data (SQL + Python).\nRequirements: propose new modules/layers, dependency boundaries, and migration plan.\nConstraints: must be performant under load, must include type hints where applicable, must avoid global state.\nDifficulty: medium. Assume schema evolves frequently; design for migrations.\n\nOutput: actionable implementation and verification artifacts.\nDeliverable: refactor plan + module boundaries.\n\n**Proposed modules**\n- `domain/` pure business logic (no I/O)\n- `adapters/` DB, cache, external APIs\n- `api/` request/response validation and routing\n- `observability/` logging/metrics/tracing\n- `tests/` unit + integration suites\n\n**Migration plan**\n1. Introduce new interfaces + adapters behind feature flags.\n2. Dual-write or read-compat layer if schema changes.\n3. Incremental cutover; deprecate legacy module.\n\nKey rule: dependencies flow inward; domain has no framework imports.\n\n\nChecks: input validation, tests, and safe defaults included.", "source": "WithinUsAI/GOD_Coder_100k"} {"text": "Optimize while preserving behavior and order.\n\n```python\ndef f77242(xs):\n out=[]\n for x in xs:\n if x not in out: out.append(x)\n return out\n```\nReturn `m39606.py` with types and O(n) average.\n\n```python\n# m39606.py\nfrom __future__ import annotations\nfrom typing import Iterable, List, Set, TypeVar\nT=TypeVar(\"T\")\n\ndef f77242(xs: Iterable[T]) -> List[T]:\n \"\"\"Unique items preserving first-seen order.\"\"\"\n seen: Set[T]=set()\n out: List[T]=[]\n for x in xs:\n if x in seen: continue\n seen.add(x); out.append(x)\n return out\n```", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Perform a code review for a healthtech PR implementing caching.\nTarget platform: ML (PyTorch + serving).\nRequirements: list critical issues, improvements, and provide an improved patch excerpt.\nConstraints: must include clear error handling, must be production-ready, must avoid global state.\nDifficulty: expert. Assume strict latency budget (p95 < 200ms).\n\nOutput: design + implementation guidance suitable for shipping.\nDeliverable: code review findings + improved patch excerpt.\n\n**Critical issues**\n1. Missing input validation at boundary; potential unexpected exceptions.\n2. No idempotency / retry safety for side-effecting endpoint.\n3. No tests for edge cases (empty input, duplicates, timeouts).\n4. Observability gaps: no request_id correlation, no metrics.\n\n**Improvements**\n- Add strict validation and explicit error responses.\n- Add idempotency key support for create endpoints.\n- Add unit + integration tests with CI gating.\n- Add structured logs and basic metrics.\n\nPatch excerpt (illustrative):\n```python\nif not idem_key:\n raise HTTPException(400, \"Missing Idempotency-Key\")\n```\n\n\nHard-mode checks: concurrency safety, idempotency, and rollback validated; add chaos tests where feasible.", "source": "WithinUsAI/GOD_Coder_100k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Fix a bug and add tests.\n\nFile: kj_bix.py\n```python\ndef kl5fif(n: int) -> int:\n \"\"\"Sum 1..n inclusive.\"\"\"\n if n < 0:\n raise ValueError(\"n must be non-negative\")\n total = 0\n for k in range(n): # BUG: should include n\n total += k\n return total\n```\n\nReturn unified diffs for kj_bix.py and test_kj_bix.py (pytest).\n\n*** Begin Patch\n*** Update File: kj_bix.py\n@@\n def kl5fif(n: int) -> int:\n@@\n total = 0\n- for k in range(n): # BUG: should include n\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_kj_bix.py\n+import pytest\n+from kj_bix import kl5fif\n+\n+def test_zero():\n+ assert kl5fif(0) == 0\n+\n+def test_one():\n+ assert kl5fif(1) == 1\n+\n+def test_small():\n+ assert kl5fif(7) == 28\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ kl5fif(-1)\n+\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Refactor to modern typed Python with immutability and tests.\n\nFile: ldopiy1.py\n```python\nclass Df1Um7Swscow:\n def __init__(self, name, values):\n self.name = name\n self.values = list(values)\n def add(self, v):\n self.values.append(v)\n def mean(self):\n s = 0\n for x in self.values:\n s += x\n return s / len(self.values)\n```\n\nReturn full new ldopiy1.py and test_ldopiy1.py.\n\n# ldopiy1.py\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom typing import Iterable, Tuple\n\n@dataclass(frozen=True)\nclass Df1Um7Swscow:\n name: str\n values: Tuple[float, ...]\n\n @staticmethod\n def create(name: str, values: Iterable[float]) -> \"Df1Um7Swscow\":\n vals = tuple(float(v) for v in values)\n if not vals:\n raise ValueError(\"values must be non-empty\")\n return Df1Um7Swscow(name=name, values=vals)\n\n def add(self, v: float) -> \"Df1Um7Swscow\":\n return Df1Um7Swscow(name=self.name, values=self.values + (float(v),))\n\n def mean(self) -> float:\n return sum(self.values) / len(self.values)\n\n# test_ldopiy1.py\nimport pytest\nfrom ldopiy1 import Df1Um7Swscow\n\ndef test_mean_and_add():\n c = Df1Um7Swscow.create(\"a\", [1, 2, 3])\n assert c.mean() == 2.0\n assert c.add(5).mean() == (1 + 2 + 3 + 5) / 4\n\ndef test_empty_raises():\n with pytest.raises(ValueError):\n Df1Um7Swscow.create(\"x\", [])", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Build an elite-grade solution in the domain of gpu compute for scenario: time-series metrics.\nPrimary language: sql.\nDifficulty: expert.\nConstraints: provide rollout and rollback guidance, assume untrusted inputs; validate and sanitize, include tests or verification strategy.\nComponent: component_qxltybw.\nAssume strict auditability and replayable history.\nTask: Provide threat model, secure-by-default design, and defensive implementation patterns. No offensive/exploit content; focus on prevention and detection.\n\nOutput: production blueprint plus correctness arguments and test strategy.\nOutput: threat model + defensive design + detection.\n\n**Threat model**\n- Auth: token theft → short-lived tokens, rotation, audience checks\n- AuthZ: privilege escalation → centralized policy checks, tenant isolation tests\n- Input: injection → strict validation, parameterized queries, output encoding\n- Supply chain: dependencies → lockfiles, signature verification, SBOM\n\n**Defensive patterns**\n- Idempotency keys for side effects; replay-safe handlers\n- Secrets in managed store; never logs\n- Audit logging for sensitive ops; tamper-evident storage\n\n**Detection**\n- Alert on unusual auth failures, access pattern anomalies, and data exfil signals.\n\n\nExpert checks: state-machine reasoning, concurrency stress, and upgrade/rollback validated.", "source": "WithinUsAI/Elite_GOD_Coder_100k"} {"text": "Fix a subtle bug in a Python module used for task scheduling.\nRequirements: explain root cause briefly, provide corrected code, and add regression tests.\nConstraints: must be memory-efficient, must avoid global state, must include tests, must be streaming-friendly.\nDifficulty: expert. Provide helpful exceptions with actionable messages.\n\nDeliverable: implementation + tests.\n```python\nfrom __future__ import annotations\n\nfrom dataclasses import dataclass\nfrom pathlib import Path\nfrom typing import Iterable\nimport json\n\n\nclass ValidationError(ValueError):\n \"\"\"Raised when input validation fails.\"\"\"\n\n\ndef safe_join(base: Path, *parts: str) -> Path:\n \"\"\"Join paths while preventing traversal outside base.\"\"\"\n b = base.resolve()\n p = (b / Path(*parts)).resolve()\n if p != b and b not in p.parents:\n raise ValidationError(f\"unsafe path: {p}\")\n return p\n\n\n@dataclass(frozen=True, slots=True)\nclass Record:\n key: str\n value: int\n\n\ndef parse_jsonl(lines: Iterable[str]) -> list[Record]:\n out: list[Record] = []\n for idx, line in enumerate(lines, 1):\n s = line.strip()\n if not s:\n continue\n try:\n obj = json.loads(s)\n except json.JSONDecodeError as e:\n raise ValidationError(f\"line {idx}: invalid json\") from e\n if not isinstance(obj, dict):\n raise ValidationError(f\"line {idx}: expected object\")\n key = obj.get(\"key\")\n val = obj.get(\"value\")\n if not isinstance(key, str) or not key:\n raise ValidationError(f\"line {idx}: key must be non-empty str\")\n if not isinstance(val, int):\n raise ValidationError(f\"line {idx}: value must be int\")\n out.append(Record(key, val))\n return out\n\n\ndef write_jsonl(base: Path, rel: str, records: Iterable[Record]) -> Path:\n base.mkdir(parents=True, exist_ok=True)\n dst = safe_join(base, rel)\n dst.parent.mkdir(parents=True, exist_ok=True)\n with dst.open(\"w\", encoding=\"utf-8\", newline=\"\\n\") as f:\n for r in records:\n f.write(json.dumps({\"key\": r.key, \"value\": r.value}, ensure_ascii=False) + \"\\n\")\n return dst\n```\n\n```python\n# tests (pytest-style)\nimport json\nfrom pathlib import Path\nimport pytest\nfrom module_under_test import ValidationError, Record, parse_jsonl, write_jsonl\n\ndef test_parse_ok():\n lines = [json.dumps({\"key\":\"a\",\"value\":1}), json.dumps({\"key\":\"b\",\"value\":2})]\n assert parse_jsonl(lines) == [Record(\"a\",1), Record(\"b\",2)]\n\ndef test_parse_rejects_bad_json():\n with pytest.raises(ValidationError):\n parse_jsonl([\"{not json}\"])\n\ndef test_safe_join_blocks_traversal(tmp_path: Path):\n with pytest.raises(ValidationError):\n write_jsonl(tmp_path, \"../x.jsonl\", [Record(\"a\",1)])\n```", "source": "WithinUsAI/python_GOD_coder_100k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Produce an offline-first self-evolving code assistant architecture named `oj28882aau`.\nMust include: module layout, patch-safety policy, evaluation gates (tests/lint/types), versioned memory index.\n\nArchitecture: `oj28882aau` (offline-first, self-evolving)\n\nModules\n- core/loop.py: evolve → validate → accept/reject (bounded iterations)\n- patching/: diff builder, safe apply, atomic writes, rollback points\n- policy/: allowlist paths, deny globs (.git/, __pycache__/, binaries), patch size caps\n- signals/: parse pytest/ruff/mypy into normalized findings\n- memory/index.jsonl: append-only snapshots (hashes, metrics, rationale)\n\nSafety gates\n- refuse path traversal/symlink escapes; never edit binaries\n- accept only if tests/lint/types stay green or improve", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: Language: Go\nFramework/tooling: Gin\nDomain: document processing API\nLogic challenge: mismatched API contract\nTask type: multi_service_security_patch\nDifficulty: hard\n\nReturn a rigorous engineering answer:\n- identify the hidden root cause or logical failure\n- present the corrected implementation\n- add tests that prove the fix\n- list verification commands\n- explain why naive fixes are insufficient when relevant\n\nRepository sketch:\nrepo/\n cmd/server/main.go\n internal/service/service.go\n internal/store/store.go\n internal/api/api.go\n service_test.go\n go.mod\n\nFocus: Focus on staff-level problem solving with multi-file patches, rollout implications, performance and security tradeoffs.\n\nassistant: Diagnosis:\n- Staff-level diagnosis: mismatched API contract impacts correctness, operability, and future maintenance, so the fix must be minimal where possible but complete where necessary.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```go\npackage service\n\nimport \"fmt\"\n\nfunc NormalizePayload(payload map[string]any) map[string]any {\n\tout := make(map[string]any)\n\tfor k, v := range payload {\n\t\tif v == nil {\n\t\t\tcontinue\n\t\t}\n\t\tout[k] = v\n\t}\n\treturn out\n}\n\nfunc Handle(payload map[string]any) (map[string]any, error) {\n\tclean := NormalizePayload(payload)\n\tif _, ok := clean[\"id\"]; !ok {\n\t\treturn nil, fmt.Errorf(\"missing id\")\n\t}\n\treturn map[string]any{\"ok\": true, \"data\": clean}, nil\n}\n```\n\nTests:\n```go\npackage service\n\nimport \"testing\"\n\nfunc TestHandle(t *testing.T) {\n\tgot, err := Handle(map[string]any{\"id\": 7, \"name\": \"ok\", \"unused\": nil})\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tif got[\"ok\"] != true {\n\t\tt.Fatalf(\"expected ok=true\")\n\t}\n\tif _, err := Handle(map[string]any{\"name\": \"x\"}); err == nil {\n\t\tt.Fatalf(\"expected missing id error\")\n\t}\n}\n```\n\nVerification:\n- `go test ./...`\n- `go vet ./...`\n\nEngineering notes:\n- Language: Go\n- Framework/tooling: Gin\n- Stack context: Spring Boot, PostgreSQL, JUnit, Gradle, Docker, GitHub Actions\n- Domain: document processing API\n- Task type: multi_service_security_patch\n- Difficulty: hard\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "Design a production system for fintech supporting file uploads.\nTarget platform: mobile (Android Kotlin).\nRequirements: APIs, data model, scaling strategy, failure modes, and security.\nConstraints: must be observable (logs/metrics/traces), must be performant under load, must avoid global state, must include tests.\nDifficulty: hard. Assume mobile clients are occasionally offline.\n\nOutput: actionable implementation and verification artifacts.\nDeliverable: system design with APIs, data model, and operational plan.\n\n**High-level architecture**\n- Edge: API Gateway + WAF\n- Core service: stateless app pods behind L7 LB\n- Data: Postgres (primary), Redis (cache + rate limit tokens), Object storage (uploads if needed)\n- Async: message queue (e.g., SQS/Rabbit) + worker pool for background jobs\n- Observability: structured logs + metrics + tracing\n\n**APIs (example)**\n- `POST /v1/{resource}` create (idempotent via `Idempotency-Key`)\n- `GET /v1/{resource}/{id}` read\n- `POST /v1/{resource}/{id}:action` command endpoint when side effects exist\n\n**Data model (Postgres)**\n- `resources(id UUID PK, tenant_id UUID, status TEXT, payload JSONB, created_at, updated_at)`\n- Unique constraint for idempotency: `(tenant_id, idempotency_key)` in a separate table:\n - `idempotency(tenant_id, key TEXT, request_hash TEXT, response JSONB, created_at, PRIMARY KEY(tenant_id,key))`\n\n**Scaling**\n- App layer scales horizontally; keep sessions out of process.\n- Cache reads in Redis; write-through invalidation on mutations.\n- Use connection pooling; consider read replicas for heavy reads.\n\n**Failure modes**\n- Retries: only for safe/ idempotent operations; exponential backoff + jitter.\n- Partial failures: background jobs must be idempotent; use a de-dup key.\n\n**Security**\n- AuthN: JWT/OIDC; AuthZ: RBAC/ABAC with tenant isolation\n- Validate all inputs; enforce per-tenant quotas/rate limits.\n\n**Rollout**\n- Dark launch + feature flags; canary; rapid rollback by toggling flags.\n\n\nHard-mode checks: concurrency safety, idempotency, and rollback validated; add chaos tests where feasible.", "source": "WithinUsAI/GOD_Coder_100k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Refactor to modern typed Python with immutability and tests.\n\nFile: t77tgb5.py\n```python\nclass Qg6X1D2Zq3K:\n def __init__(self, name, values):\n self.name = name\n self.values = list(values)\n def add(self, v):\n self.values.append(v)\n def mean(self):\n s = 0\n for x in self.values:\n s += x\n return s / len(self.values)\n```\n\nReturn full new t77tgb5.py and test_t77tgb5.py.\n\n# t77tgb5.py\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom typing import Iterable, Tuple\n\n@dataclass(frozen=True)\nclass Qg6X1D2Zq3K:\n name: str\n values: Tuple[float, ...]\n\n @staticmethod\n def create(name: str, values: Iterable[float]) -> \"Qg6X1D2Zq3K\":\n vals = tuple(float(v) for v in values)\n if not vals:\n raise ValueError(\"values must be non-empty\")\n return Qg6X1D2Zq3K(name=name, values=vals)\n\n def add(self, v: float) -> \"Qg6X1D2Zq3K\":\n return Qg6X1D2Zq3K(name=self.name, values=self.values + (float(v),))\n\n def mean(self) -> float:\n return sum(self.values) / len(self.values)\n\n# test_t77tgb5.py\nimport pytest\nfrom t77tgb5 import Qg6X1D2Zq3K\n\ndef test_mean_and_add():\n c = Qg6X1D2Zq3K.create(\"a\", [1, 2, 3])\n assert c.mean() == 2.0\n assert c.add(5).mean() == (1 + 2 + 3 + 5) / 4\n\ndef test_empty_raises():\n with pytest.raises(ValueError):\n Qg6X1D2Zq3K.create(\"x\", [])", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Optimize while preserving behavior and order.\n\n```python\ndef f68532(xs):\n out=[]\n for x in xs:\n if x not in out: out.append(x)\n return out\n```\nReturn `m24076.py` with types and O(n) average.\n\n```python\n# m24076.py\nfrom __future__ import annotations\nfrom typing import Iterable, List, Set, TypeVar\nT=TypeVar(\"T\")\n\ndef f68532(xs: Iterable[T]) -> List[T]:\n \"\"\"Unique items preserving first-seen order.\"\"\"\n seen: Set[T]=set()\n out: List[T]=[]\n for x in xs:\n if x in seen: continue\n seen.add(x); out.append(x)\n return out\n```", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Design a production system for customer support supporting multi-tenant isolation.\nTarget platform: backend (Go).\nRequirements: APIs, data model, scaling strategy, failure modes, and security.\nConstraints: must include clear error handling, must include tests, must be observable (logs/metrics/traces), must be performant under load.\nDifficulty: medium. Assume strict latency budget (p95 < 200ms).\n\nOutput: engineering-grade answer with edge cases covered.\nDeliverable: system design with APIs, data model, and operational plan.\n\n**High-level architecture**\n- Edge: API Gateway + WAF\n- Core service: stateless app pods behind L7 LB\n- Data: Postgres (primary), Redis (cache + rate limit tokens), Object storage (uploads if needed)\n- Async: message queue (e.g., SQS/Rabbit) + worker pool for background jobs\n- Observability: structured logs + metrics + tracing\n\n**APIs (example)**\n- `POST /v1/{resource}` create (idempotent via `Idempotency-Key`)\n- `GET /v1/{resource}/{id}` read\n- `POST /v1/{resource}/{id}:action` command endpoint when side effects exist\n\n**Data model (Postgres)**\n- `resources(id UUID PK, tenant_id UUID, status TEXT, payload JSONB, created_at, updated_at)`\n- Unique constraint for idempotency: `(tenant_id, idempotency_key)` in a separate table:\n - `idempotency(tenant_id, key TEXT, request_hash TEXT, response JSONB, created_at, PRIMARY KEY(tenant_id,key))`\n\n**Scaling**\n- App layer scales horizontally; keep sessions out of process.\n- Cache reads in Redis; write-through invalidation on mutations.\n- Use connection pooling; consider read replicas for heavy reads.\n\n**Failure modes**\n- Retries: only for safe/ idempotent operations; exponential backoff + jitter.\n- Partial failures: background jobs must be idempotent; use a de-dup key.\n\n**Security**\n- AuthN: JWT/OIDC; AuthZ: RBAC/ABAC with tenant isolation\n- Validate all inputs; enforce per-tenant quotas/rate limits.\n\n**Rollout**\n- Dark launch + feature flags; canary; rapid rollback by toggling flags.\n\n\nChecks: input validation, tests, and safe defaults included.", "source": "WithinUsAI/GOD_Coder_100k"} {"text": "Refactor to typed, mostly-immutable Python and add minimal tests.\n\n```python\nclass C34390:\n def __init__(self, values): self.values=list(values)\n def mean(self): return sum(self.values)/len(self.values)\n```\nReturn `m18030.py` and `test_m18030.py`.\n\n```python\n# m18030.py\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom typing import Iterable, Tuple\n\n@dataclass(frozen=True)\nclass C34390:\n values: Tuple[float, ...]\n\n @staticmethod\n def create(values: Iterable[float]) -> \"C34390\":\n vals = tuple(float(v) for v in values)\n if not vals: raise ValueError(\"empty\")\n return C34390(vals)\n\n def mean(self) -> float:\n return sum(self.values)/len(self.values)\n```\n\n```python\n# test_m18030.py\nimport pytest\nfrom m18030 import C34390\n\ndef test_mean():\n assert C34390.create([1,2,3]).mean() == 2.0\ndef test_empty():\n with pytest.raises(ValueError):\n C34390.create([])\n```", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: Language: TypeScript\nFramework/tooling: Prisma\nDomain: benchmark harness\nLogic challenge: idempotent retry design\nTask type: distributed_debug\nDifficulty: hard\n\nReturn a rigorous engineering answer:\n- identify the hidden root cause or logical failure\n- present the corrected implementation\n- add tests that prove the fix\n- list verification commands\n- explain why naive fixes are insufficient when relevant\n\nRepository sketch:\nrepo/\n src/\n api.ts\n service.ts\n schema.ts\n tests/\n api.test.ts\n package.json\n\nFocus: Focus on ambiguity, misleading symptoms, hidden root causes, and high-stakes debugging.\n\nassistant: Diagnosis:\n- Hidden root cause: idempotent retry design presents misleading symptoms, so the patch must target the actual logic boundary rather than the first visible failure.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```ts\ntype Payload = Record;\n\nexport function normalizePayload(payload: Payload): Payload {\n if (!payload || typeof payload !== \"object\" || Array.isArray(payload)) {\n throw new TypeError(\"payload must be a plain object\");\n }\n return Object.fromEntries(\n Object.entries(payload)\n .filter(([, value]) => value !== null && value !== undefined)\n .map(([key, value]) => [String(key).trim(), value])\n );\n}\n\nexport function handleIdempotentRetryDesign(payload: Payload) {\n const clean = normalizePayload(payload);\n if (!(\"id\" in clean)) {\n return { ok: false, data: {}, error: \"missing id\" };\n }\n return { ok: true, data: clean, error: null };\n}\n```\n\nTests:\n```ts\nimport { describe, it, expect } from \"vitest\";\nimport { handleIdempotentRetryDesign } from \"../src/service\";\n\ndescribe(\"handler\", () => {\n it(\"accepts valid input\", () => {\n expect(handleIdempotentRetryDesign({ id: 7, name: \"ok\", unused: null })).toEqual({\n ok: true,\n data: { id: 7, name: \"ok\" },\n error: null\n });\n });\n\n it(\"rejects missing id\", () => {\n expect(handleIdempotentRetryDesign({ name: \"x\" }).error).toMatch(/missing id/);\n });\n});\n```\n\nVerification:\n- `npm test`\n- `npm run typecheck`\n- `npm run lint`\n\nEngineering notes:\n- Language: TypeScript\n- Framework/tooling: Prisma\n- Stack context: Go, Gin, PostgreSQL, gRPC, Prometheus, Docker\n- Domain: benchmark harness\n- Task type: distributed_debug\n- Difficulty: hard\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Fix a bug and add tests.\n\nFile: scfp58.py\n```python\ndef o8vrcdiud(n: int) -> int:\n \"\"\"Sum 1..n inclusive.\"\"\"\n if n < 0:\n raise ValueError(\"n must be non-negative\")\n total = 0\n for k in range(n): # BUG: should include n\n total += k\n return total\n```\n\nReturn unified diffs for scfp58.py and test_scfp58.py (pytest).\n\n*** Begin Patch\n*** Update File: scfp58.py\n@@\n def o8vrcdiud(n: int) -> int:\n@@\n total = 0\n- for k in range(n): # BUG: should include n\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_scfp58.py\n+import pytest\n+from scfp58 import o8vrcdiud\n+\n+def test_zero():\n+ assert o8vrcdiud(0) == 0\n+\n+def test_one():\n+ assert o8vrcdiud(1) == 1\n+\n+def test_small():\n+ assert o8vrcdiud(7) == 28\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ o8vrcdiud(-1)\n+\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: Repository domain: model serving gateway\nPrimary language: SQL\nFramework/tooling: DuckDB\nReported problem: schema drift during deployment\nTask type: security_patch\nDifficulty: medium\n\nProduce a complete professional engineering response:\n1. Diagnose the root cause.\n2. Provide the corrected implementation or patch.\n3. Add tests.\n4. Add verification commands.\n5. Note edge cases and any migration or rollback risk.\n\nRepository sketch:\nrepo/\n migrations/\n 001_init.sql\n 002_add_index.sql\n queries/\n report.sql\n tests/\n report_cases.md\n\nQuality target:\n- Minimal diff unless redesign is clearly required\n- Production-ready code\n- No placeholders\n- Secure defaults\n- Clear acceptance of failure cases\n\nFocus: Focus on complete implementation quality, patch correctness, tests, and production readiness.\n\nassistant: Diagnosis:\n- Root cause: the failure around schema drift during deployment is caused by missing validation, weak edge-case handling, or unsafe lifecycle behavior in the current implementation.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```sql\nWITH ranked AS (\n SELECT\n user_id,\n created_at,\n amount,\n ROW_NUMBER() OVER (PARTITION BY user_id ORDER BY created_at DESC, id DESC) AS rn\n FROM orders\n)\nSELECT user_id, created_at, amount\nFROM ranked\nWHERE rn = 1;\n```\n\nTests:\n```sql\n-- Correctness checks:\n-- 1) multiple rows per user\n-- 2) identical timestamps require deterministic tie-breaker\n-- 3) null values handled by business rules\n```\n\nVerification:\n- `run migration checks`\n- `run query correctness cases`\n\nEngineering notes:\n- Language: SQL\n- Framework/tooling: DuckDB\n- Stack context: ASP.NET Core, SQL Server, EF Core, xUnit, Docker\n- Domain: model serving gateway\n- Task type: security_patch\n- Difficulty: medium\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "Refactor a Python module used for CLI tooling into a clean, extensible design.\nRequirements: outline the new architecture briefly, then provide the refactored code and tests.\nConstraints: must be memory-efficient, must avoid global state.\nDifficulty: medium. Avoid quadratic behavior on large inputs.\n\nDeliverable: implementation + tests.\nArchitecture:\n- Public facade class coordinating concerns (parsing, validation, persistence)\n- Small pure functions for testability\n- No global state; dependency injection for filesystem I/O\n\n```python\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom pathlib import Path\nfrom typing import Protocol, Iterable\nimport json\n\nclass Store(Protocol):\n def write_text(self, path: Path, data: str) -> None: ...\n\nclass FSStore:\n def write_text(self, path: Path, data: str) -> None:\n path.parent.mkdir(parents=True, exist_ok=True)\n path.write_text(data, encoding=\"utf-8\")\n\n@dataclass(frozen=True, slots=True)\nclass Item:\n name: str\n qty: int\n\ndef parse_items(lines: Iterable[str]) -> list[Item]:\n out: list[Item] = []\n for i, line in enumerate(lines, 1):\n s = line.strip()\n if not s:\n continue\n obj = json.loads(s)\n if not isinstance(obj, dict):\n raise ValueError(f\"line {i}: expected object\")\n name = obj.get(\"name\")\n qty = obj.get(\"qty\")\n if not isinstance(name, str) or not name:\n raise ValueError(f\"line {i}: name must be str\")\n if not isinstance(qty, int) or qty < 0:\n raise ValueError(f\"line {i}: qty must be non-negative int\")\n out.append(Item(name, qty))\n return out\n\nclass InventoryWriter:\n def __init__(self, base_dir: Path, store: Store | None = None) -> None:\n self._base = base_dir\n self._store: Store = store or FSStore()\n\n def write(self, rel_path: str, items: list[Item]) -> Path:\n dst = (self._base / rel_path).resolve()\n base = self._base.resolve()\n if dst != base and base not in dst.parents:\n raise ValueError(\"unsafe path traversal\")\n payload = json.dumps([item.__dict__ for item in items], ensure_ascii=False)\n self._store.write_text(dst, payload)\n return dst\n```\n\n```python\nimport json\nfrom pathlib import Path\nimport pytest\nfrom module_under_test import InventoryWriter, parse_items\n\ndef test_parse_items_valid():\n lines = [json.dumps({\"name\":\"x\",\"qty\":1})]\n assert parse_items(lines)[0].name == \"x\"\n\ndef test_writer_blocks_traversal(tmp_path: Path):\n w = InventoryWriter(tmp_path)\n with pytest.raises(ValueError):\n w.write(\"../evil.json\", [])\n```", "source": "WithinUsAI/python_GOD_coder_100k"} {"text": "Build an elite-grade solution in the domain of databases for scenario: time-series metrics.\nPrimary language: typescript.\nDifficulty: medium.\nConstraints: make the interface contract explicit, avoid undefined behavior and data races, include tests or verification strategy, design for backward compatibility and migrations.\nComponent: component_muxschw.\nAssume crash-only design; recovery must be deterministic.\nTask: Provide SLOs, alerting, dashboards, runbooks, and incident playbook. Include chaos testing and safe rollout strategy.\n\nOutput: rigorous solution with invariants, failure modes, and performance notes.\nOutput: SLOs + alerts + runbooks + chaos strategy.\n\n**SLOs**\n- Availability: 99.9% monthly\n- Latency: p95 < 200ms, p99 < 400ms\n- Error rate: < 0.1%\n\n**Alerts**\n- Burn-rate alerts for SLOs (fast/slow windows)\n- Saturation: CPU, memory, queue depth, DB connections\n- Dependency health: cache hit rate drop, downstream timeouts\n\n**Runbooks**\n- Triage: identify blast radius, feature-flag rollback, capacity mitigation\n- Post-incident: timeline, contributing factors, action items\n\n**Chaos**\n- Inject latency, partial outages, and restarts in staging; verify steady-state SLOs.\n\n\nChecks: boundary validation and deterministic behavior verified.", "source": "WithinUsAI/Elite_GOD_Coder_100k"} {"text": "Refactor a Python module used for file synchronization into a clean, extensible design.\nRequirements: outline the new architecture briefly, then provide the refactored code and tests.\nConstraints: must provide clear error messages, must handle Windows paths safely, must include type hints, must be streaming-friendly.\nDifficulty: hard. Avoid quadratic behavior on large inputs.\n\nDeliverable: corrected code and verification tests.\nArchitecture:\n- Public facade class coordinating concerns (parsing, validation, persistence)\n- Small pure functions for testability\n- No global state; dependency injection for filesystem I/O\n\n```python\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom pathlib import Path\nfrom typing import Protocol, Iterable\nimport json\n\nclass Store(Protocol):\n def write_text(self, path: Path, data: str) -> None: ...\n\nclass FSStore:\n def write_text(self, path: Path, data: str) -> None:\n path.parent.mkdir(parents=True, exist_ok=True)\n path.write_text(data, encoding=\"utf-8\")\n\n@dataclass(frozen=True, slots=True)\nclass Item:\n name: str\n qty: int\n\ndef parse_items(lines: Iterable[str]) -> list[Item]:\n out: list[Item] = []\n for i, line in enumerate(lines, 1):\n s = line.strip()\n if not s:\n continue\n obj = json.loads(s)\n if not isinstance(obj, dict):\n raise ValueError(f\"line {i}: expected object\")\n name = obj.get(\"name\")\n qty = obj.get(\"qty\")\n if not isinstance(name, str) or not name:\n raise ValueError(f\"line {i}: name must be str\")\n if not isinstance(qty, int) or qty < 0:\n raise ValueError(f\"line {i}: qty must be non-negative int\")\n out.append(Item(name, qty))\n return out\n\nclass InventoryWriter:\n def __init__(self, base_dir: Path, store: Store | None = None) -> None:\n self._base = base_dir\n self._store: Store = store or FSStore()\n\n def write(self, rel_path: str, items: list[Item]) -> Path:\n dst = (self._base / rel_path).resolve()\n base = self._base.resolve()\n if dst != base and base not in dst.parents:\n raise ValueError(\"unsafe path traversal\")\n payload = json.dumps([item.__dict__ for item in items], ensure_ascii=False)\n self._store.write_text(dst, payload)\n return dst\n```\n\n```python\nimport json\nfrom pathlib import Path\nimport pytest\nfrom module_under_test import InventoryWriter, parse_items\n\ndef test_parse_items_valid():\n lines = [json.dumps({\"name\":\"x\",\"qty\":1})]\n assert parse_items(lines)[0].name == \"x\"\n\ndef test_writer_blocks_traversal(tmp_path: Path):\n w = InventoryWriter(tmp_path)\n with pytest.raises(ValueError):\n w.write(\"../evil.json\", [])\n```", "source": "WithinUsAI/python_GOD_coder_100k"} {"text": "Fix the bug and add pytest tests.\n\n```python\ndef f66649(n: int) -> int:\n # sum 1..n inclusive\n if n < 0: raise ValueError\n total = 0\n for k in range(n): # BUG\n total += k\n return total\n```\nReturn unified diffs for `m23807.py` and `test_m23807.py`.\n\n*** Begin Patch\n*** Update File: m23807.py\n@@\n def f66649(n: int) -> int:\n@@\n- for k in range(n): # BUG\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_m23807.py\n+import pytest\n+from m23807 import f66649\n+\n+def test_small():\n+ assert f66649(7) == 28\n+\n+def test_zero():\n+ assert f66649(0) == 0\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ f66649(-1)\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Optimize while preserving behavior.\n\nFile: uu3a2h7srbfz.py\n```python\ndef cspqets7_(xs):\n out = []\n for x in xs:\n if x not in out:\n out.append(x)\n return out\n```\n\nRequirements: preserve first-seen order; O(n) average; add types + docstring.\n\n# uu3a2h7srbfz.py\nfrom __future__ import annotations\nfrom typing import Iterable, List, Set, TypeVar\n\nT = TypeVar(\"T\")\n\ndef cspqets7_(xs: Iterable[T]) -> List[T]:\n \"\"\"Return unique items preserving first-seen order.\"\"\"\n seen: Set[T] = set()\n out: List[T] = []\n for x in xs:\n if x in seen:\n continue\n seen.add(x)\n out.append(x)\n return out", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: Language: C#\nFramework/tooling: NUnit\nDomain: search service\nLogic challenge: timezone bug in reporting\nTask type: security_logic_interaction\nDifficulty: hard\n\nReturn a rigorous engineering answer:\n- identify the hidden root cause or logical failure\n- present the corrected implementation\n- add tests that prove the fix\n- list verification commands\n- explain why naive fixes are insufficient when relevant\n\nRepository sketch:\nrepo/\n src/App/Program.cs\n src/App/Service.cs\n tests/App.Tests/ServiceTests.cs\n App.sln\n\nFocus: Focus on ambiguity, misleading symptoms, hidden root causes, and high-stakes debugging.\n\nassistant: Diagnosis:\n- Hidden root cause: timezone bug in reporting presents misleading symptoms, so the patch must target the actual logic boundary rather than the first visible failure.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```csharp\nusing System;\nusing System.Collections.Generic;\n\npublic static class RequestHandler\n{\n public static Dictionary HandleRequest(Dictionary payload)\n {\n var clean = new Dictionary();\n foreach (var entry in payload)\n {\n if (entry.Value != null)\n clean[entry.Key.Trim()] = entry.Value;\n }\n if (!clean.ContainsKey(\"id\"))\n throw new ArgumentException(\"missing id\");\n return new Dictionary\n {\n [\"ok\"] = true,\n [\"data\"] = clean\n };\n }\n}\n```\n\nTests:\n```csharp\nusing System;\nusing System.Collections.Generic;\nusing Xunit;\n\npublic class RequestHandlerTests\n{\n [Fact]\n public void RequiresId()\n {\n Assert.Throws(() => RequestHandler.HandleRequest(new Dictionary { [\"name\"] = \"x\" }));\n }\n}\n```\n\nVerification:\n- `dotnet test`\n- `dotnet build`\n\nEngineering notes:\n- Language: C#\n- Framework/tooling: NUnit\n- Stack context: Next.js, Node.js, Prisma, PostgreSQL, Playwright, Docker\n- Domain: search service\n- Task type: security_logic_interaction\n- Difficulty: hard\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Fix a bug and add tests.\n\nFile: ku2dwvns.py\n```python\ndef wrsjwp2(n: int) -> int:\n \"\"\"Sum 1..n inclusive.\"\"\"\n if n < 0:\n raise ValueError(\"n must be non-negative\")\n total = 0\n for k in range(n): # BUG: should include n\n total += k\n return total\n```\n\nReturn unified diffs for ku2dwvns.py and test_ku2dwvns.py (pytest).\n\n*** Begin Patch\n*** Update File: ku2dwvns.py\n@@\n def wrsjwp2(n: int) -> int:\n@@\n total = 0\n- for k in range(n): # BUG: should include n\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_ku2dwvns.py\n+import pytest\n+from ku2dwvns import wrsjwp2\n+\n+def test_zero():\n+ assert wrsjwp2(0) == 0\n+\n+def test_one():\n+ assert wrsjwp2(1) == 1\n+\n+def test_small():\n+ assert wrsjwp2(7) == 28\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ wrsjwp2(-1)\n+\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: Language: Python\nFramework/tooling: Celery\nDomain: search service\nLogic challenge: async cancellation bug\nTask type: multi_service_security_patch\nDifficulty: expert\n\nReturn a rigorous engineering answer:\n- identify the hidden root cause or logical failure\n- present the corrected implementation\n- add tests that prove the fix\n- list verification commands\n- explain why naive fixes are insufficient when relevant\n\nRepository sketch:\nrepo/\n app/\n api.py\n service.py\n models.py\n tests/\n test_api.py\n pyproject.toml\n\nFocus: Focus on staff-level problem solving with multi-file patches, rollout implications, performance and security tradeoffs.\n\nassistant: Diagnosis:\n- Staff-level diagnosis: async cancellation bug impacts correctness, operability, and future maintenance, so the fix must be minimal where possible but complete where necessary.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```python\nfrom __future__ import annotations\n\nfrom dataclasses import dataclass\nfrom typing import Any\n\n@dataclass\nclass ServiceResult:\n ok: bool\n data: dict[str, Any]\n error: str | None = None\n\ndef normalize_payload(payload: dict[str, Any]) -> dict[str, Any]:\n if not isinstance(payload, dict):\n raise TypeError(\"payload must be a dict\")\n clean: dict[str, Any] = {}\n for key, value in payload.items():\n if value is None:\n continue\n clean[str(key).strip()] = value\n return clean\n\ndef handle_async_cancellation_bug(payload: dict[str, Any]) -> ServiceResult:\n clean = normalize_payload(payload)\n if \"id\" not in clean:\n return ServiceResult(ok=False, data={}, error=\"missing id\")\n return ServiceResult(ok=True, data=clean)\n```\n\nTests:\n```python\nimport pytest\nfrom app.service import handle_jwt_refresh_token_rotation as handler\n\ndef test_handler_accepts_valid_payload():\n result = handler({\"id\": 7, \"name\": \"ok\", \"unused\": None})\n assert result.ok is True\n assert result.data == {\"id\": 7, \"name\": \"ok\"}\n\ndef test_handler_rejects_missing_id():\n result = handler({\"name\": \"x\"})\n assert result.ok is False\n assert result.error == \"missing id\"\n```\n\nVerification:\n- `pytest -q`\n- `ruff check .`\n- `python -m compileall .`\n\nEngineering notes:\n- Language: Python\n- Framework/tooling: Celery\n- Stack context: GitHub Actions, Docker Compose, Kubernetes, Terraform\n- Domain: search service\n- Task type: multi_service_security_patch\n- Difficulty: expert\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "Task type: secure_architecture\nScenario: streaming ETL\nDomain focus: consensus & replication\nPrimary language: rust\nDifficulty: hard\nScale/SLO: 1M msgs/min\nComponent: component_ohhaqlji\nConstraints: explicit contracts and invariants, include failure modes and recovery, assume adversarial inputs; validate everything, avoid data races and undefined behavior, include security threat model (defensive only)\nAssume partial data corruption; include scrubbing strategy.\nDeliverable: Provide a defensive threat model and secure-by-default architecture; include monitoring/detection and tests (no offensive content).\n\nOutput: rigorous design + invariants + verification plan + implementation sketch.\n**Contract**\n- Inputs validated at the boundary; explicit error taxonomy.\n- Idempotency for side effects via request_id; deterministic replay.\n- Backward compatibility: additive changes by default; versioned breaking changes.\n**Invariants**\n- Liveness: under bounded faults and stable network, progress occurs.\n- Isolation: tenant boundary enforced; no cross-tenant reads/writes.\n- Determinism: replay of the same event log yields identical outputs.\n**Failure modes & recovery**\n- Duplicate requests: de-duplicate by (tenant, request_id) returning cached response.\n- Network partition: minority cannot commit; clients receive retriable errors.\n- Crash during commit: WAL replay completes or transaction aborts; no torn writes.\n**Security posture (defensive)**\n- Threat model: auth/authz, injection, replay/abuse, supply chain.\n- Least privilege; secrets in managed store; audit logs for sensitive ops.\n- Input normalization, parameterized queries, path traversal protections.\n**Verification strategy**\n- Fuzzing of parsers/framers/validators with corpus seeds.\n- Canary + shadow traffic; invariants checked in production via assertions/metrics.\n- Property tests against a pure reference model (state machine).\n\n**Snippet**\n```text\nImplementation sketch: factor pure state-machine core; adapters for I/O; add deterministic replay log.\n```\nHard checks: fault injection tests gate merges; perf thresholds enforced in CI.", "source": "WithinUsAI/Omega_Genesis_Coder_100k"} {"text": "Refactor a Python module used for configuration loading into a clean, extensible design.\nRequirements: outline the new architecture briefly, then provide the refactored code and tests.\nConstraints: must be streaming-friendly, stdlib-only, must include type hints, must include tests.\nDifficulty: expert. Support both Windows and POSIX paths correctly.\n\nDeliverable: API + reference implementation + tests.\nArchitecture:\n- Public facade class coordinating concerns (parsing, validation, persistence)\n- Small pure functions for testability\n- No global state; dependency injection for filesystem I/O\n\n```python\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom pathlib import Path\nfrom typing import Protocol, Iterable\nimport json\n\nclass Store(Protocol):\n def write_text(self, path: Path, data: str) -> None: ...\n\nclass FSStore:\n def write_text(self, path: Path, data: str) -> None:\n path.parent.mkdir(parents=True, exist_ok=True)\n path.write_text(data, encoding=\"utf-8\")\n\n@dataclass(frozen=True, slots=True)\nclass Item:\n name: str\n qty: int\n\ndef parse_items(lines: Iterable[str]) -> list[Item]:\n out: list[Item] = []\n for i, line in enumerate(lines, 1):\n s = line.strip()\n if not s:\n continue\n obj = json.loads(s)\n if not isinstance(obj, dict):\n raise ValueError(f\"line {i}: expected object\")\n name = obj.get(\"name\")\n qty = obj.get(\"qty\")\n if not isinstance(name, str) or not name:\n raise ValueError(f\"line {i}: name must be str\")\n if not isinstance(qty, int) or qty < 0:\n raise ValueError(f\"line {i}: qty must be non-negative int\")\n out.append(Item(name, qty))\n return out\n\nclass InventoryWriter:\n def __init__(self, base_dir: Path, store: Store | None = None) -> None:\n self._base = base_dir\n self._store: Store = store or FSStore()\n\n def write(self, rel_path: str, items: list[Item]) -> Path:\n dst = (self._base / rel_path).resolve()\n base = self._base.resolve()\n if dst != base and base not in dst.parents:\n raise ValueError(\"unsafe path traversal\")\n payload = json.dumps([item.__dict__ for item in items], ensure_ascii=False)\n self._store.write_text(dst, payload)\n return dst\n```\n\n```python\nimport json\nfrom pathlib import Path\nimport pytest\nfrom module_under_test import InventoryWriter, parse_items\n\ndef test_parse_items_valid():\n lines = [json.dumps({\"name\":\"x\",\"qty\":1})]\n assert parse_items(lines)[0].name == \"x\"\n\ndef test_writer_blocks_traversal(tmp_path: Path):\n w = InventoryWriter(tmp_path)\n with pytest.raises(ValueError):\n w.write(\"../evil.json\", [])\n```", "source": "WithinUsAI/python_GOD_coder_100k"} {"text": "Design and implement an algorithm for CLI tooling.\nRequirements: define inputs/outputs, implement solution with complexity analysis, and include tests.\nConstraints: must be memory-efficient, must provide clear error messages, must include docstrings.\nDifficulty: expert. Ensure the API is testable via dependency injection.\n\nDeliverable: API + reference implementation + tests.\nProblem: compute rolling sums over events (ts:int,value:int) with window W seconds. Events may be out-of-order.\n\nComplexity: sorting O(n log n); window maintenance O(n); memory O(k).\n\n```python\nfrom __future__ import annotations\nfrom collections import deque\nfrom dataclasses import dataclass\nfrom typing import Iterable, List, Tuple\n\n@dataclass(frozen=True, slots=True)\nclass Event:\n ts: int\n value: int\n\ndef rolling_sum(events: Iterable[Event], window_s: int) -> List[Tuple[int,int]]:\n if window_s < 0:\n raise ValueError(\"window_s must be >= 0\")\n evs = sorted(events, key=lambda e: e.ts)\n q: deque[Event] = deque()\n s = 0\n out: List[Tuple[int,int]] = []\n for e in evs:\n q.append(e)\n s += e.value\n cutoff = e.ts - window_s\n while q and q[0].ts < cutoff:\n old = q.popleft()\n s -= old.value\n out.append((e.ts, s))\n return out\n```\n\n```python\nimport pytest\nfrom module_under_test import Event, rolling_sum\n\ndef test_rolling_sum():\n ev = [Event(10,1), Event(11,2), Event(20,5)]\n assert rolling_sum(ev, 5) == [(10,1),(11,3),(20,5)]\n```", "source": "WithinUsAI/python_GOD_coder_100k"} {"text": "Build an elite-grade solution in the domain of security engineering (defensive) for scenario: job scheduler.\nPrimary language: python.\nDifficulty: hard.\nConstraints: make the interface contract explicit, include invariants and failure modes, provide rollout and rollback guidance.\nComponent: component_ealtaag.\nAssume cold-start and memory limits are tight.\nTask: Provide a cross-language reference (API contract + implementation in two languages) and compatibility tests.\n\nOutput: production blueprint plus correctness arguments and test strategy.\nOutput: API contract + two implementations + compat tests.\n\n**Contract**\n- JSON schema for request/response; strict field validation; explicit version.\n\n**Example**\n- Implement validator + handler in Python and TypeScript.\n- Compatibility tests: same inputs produce equivalent outputs; reject unknown fields when in strict mode.\n\n\nHard checks: failure injection tests and performance regressions gated.", "source": "WithinUsAI/Elite_GOD_Coder_100k"} {"text": "Build an elite-grade solution in the domain of sre/observability for scenario: rate limiting gateway.\nPrimary language: rust.\nDifficulty: hard.\nConstraints: document performance characteristics, include invariants and failure modes, assume untrusted inputs; validate and sanitize.\nComponent: component_rkusmts.\nAssume cold-start and memory limits are tight.\nTask: Design a replication/consistency approach (e.g., leader-based, quorum reads/writes). Provide message flows, failure handling, and a minimal reference implementation skeleton.\n\nOutput: elite-grade engineering answer with contracts, edge cases, and verification.\nOutput: replication design + failure handling + minimal skeleton.\n\n**Model**\n- Leader-based replication with term + log index.\n- Quorum acks for durability: write committed when majority acks.\n- Read options: leader-read (linearizable) or quorum-read (monotonic if using read-index).\n\n**Message flow (write)**\n1. Client → Leader: Put(request_id, payload)\n2. Leader appends to log, sends AppendEntries to followers\n3. Followers append + ack\n4. On majority ack: commit index advances; apply to state machine; respond to client\n\n**Failure modes**\n- Leader crash: new election; uncommitted entries may be rolled back.\n- Partition: minority side cannot commit.\n- Duplicate requests: deduplicate by request_id stored in state.\n\n**Skeleton (Go pseudo)**\n```go\ntype Entry struct { Term uint64; Index uint64; Cmd []byte }\ntype Node struct {\n id int\n term uint64\n log []Entry\n commit uint64\n seen map[string][]byte // request_id -> response\n}\n```\n\n**Verification**\n- Invariant: committed index never decreases.\n- Property: if a write is committed, all future leaders contain it.\n- Test with simulated partitions and crash/restart.\n\n\nHard checks: failure injection tests and performance regressions gated.", "source": "WithinUsAI/Elite_GOD_Coder_100k"} {"text": "Add a clear docstring and type hints to this function:\n\n```python\ndef f77234(s):\n return ''.join(x for x in s if x.isalnum()).lower()\n```\n\n```python\nfrom __future__ import annotations\n\ndef f77234(s: str) -> str:\n \"\"\"Normalize a string: keep only alphanumerics and lowercase the result.\"\"\"\n return \"\".join(ch for ch in s if ch.isalnum()).lower()\n```", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Build an elite-grade solution in the domain of gpu compute for scenario: rate limiting gateway.\nPrimary language: rust.\nDifficulty: expert.\nConstraints: document performance characteristics, avoid undefined behavior and data races, provide rollout and rollback guidance.\nComponent: component_bvqylbm.\nAssume compliance requires data deletion with proofs.\nTask: Implement a concurrency primitive or subsystem (lock-free queue, thread pool, async runtime component). Explain memory ordering and correctness arguments; include stress tests.\n\nOutput: production blueprint plus correctness arguments and test strategy.\nOutput: correctness-focused concurrency primitive + stress tests.\n\n**Primitive**\n- Bounded MPMC queue with backpressure (blocking push/pop) OR lock-free SPSC ring buffer.\n\n**Correctness notes**\n- For lock-free: use acquire/release semantics on head/tail indices.\n- Avoid ABA by monotonic counters; ring index = counter % capacity.\n\n**Stress tests**\n- Multi-thread producers/consumers; assert item multiset preserved.\n- Use time-bounded randomized schedules; detect deadlocks.\n\n\nExpert checks: state-machine reasoning, concurrency stress, and upgrade/rollback validated.", "source": "WithinUsAI/Elite_GOD_Coder_100k"} {"text": "Fix the bug and add pytest tests.\n\n```python\ndef f70817(n: int) -> int:\n # sum 1..n inclusive\n if n < 0: raise ValueError\n total = 0\n for k in range(n): # BUG\n total += k\n return total\n```\nReturn unified diffs for `m95831.py` and `test_m95831.py`.\n\n*** Begin Patch\n*** Update File: m95831.py\n@@\n def f70817(n: int) -> int:\n@@\n- for k in range(n): # BUG\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_m95831.py\n+import pytest\n+from m95831 import f70817\n+\n+def test_small():\n+ assert f70817(7) == 28\n+\n+def test_zero():\n+ assert f70817(0) == 0\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ f70817(-1)\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Design and implement an algorithm for telemetry ingestion.\nRequirements: define inputs/outputs, implement solution with complexity analysis, and include tests.\nConstraints: must be streaming-friendly, must include docstrings, must handle Windows paths safely.\nDifficulty: hard. Avoid quadratic behavior on large inputs.\n\nDeliverable: corrected code and verification tests.\nProblem: compute rolling sums over events (ts:int,value:int) with window W seconds. Events may be out-of-order.\n\nComplexity: sorting O(n log n); window maintenance O(n); memory O(k).\n\n```python\nfrom __future__ import annotations\nfrom collections import deque\nfrom dataclasses import dataclass\nfrom typing import Iterable, List, Tuple\n\n@dataclass(frozen=True, slots=True)\nclass Event:\n ts: int\n value: int\n\ndef rolling_sum(events: Iterable[Event], window_s: int) -> List[Tuple[int,int]]:\n if window_s < 0:\n raise ValueError(\"window_s must be >= 0\")\n evs = sorted(events, key=lambda e: e.ts)\n q: deque[Event] = deque()\n s = 0\n out: List[Tuple[int,int]] = []\n for e in evs:\n q.append(e)\n s += e.value\n cutoff = e.ts - window_s\n while q and q[0].ts < cutoff:\n old = q.popleft()\n s -= old.value\n out.append((e.ts, s))\n return out\n```\n\n```python\nimport pytest\nfrom module_under_test import Event, rolling_sum\n\ndef test_rolling_sum():\n ev = [Event(10,1), Event(11,2), Event(20,5)]\n assert rolling_sum(ev, 5) == [(10,1),(11,3),(20,5)]\n```", "source": "WithinUsAI/python_GOD_coder_100k"} {"text": "Refactor a Python module used for task scheduling into a clean, extensible design.\nRequirements: outline the new architecture briefly, then provide the refactored code and tests.\nConstraints: must avoid global state, must handle Windows paths safely, must provide clear error messages.\nDifficulty: easy. Support both Windows and POSIX paths correctly.\n\nDeliverable: API + reference implementation + tests.\nArchitecture:\n- Public facade class coordinating concerns (parsing, validation, persistence)\n- Small pure functions for testability\n- No global state; dependency injection for filesystem I/O\n\n```python\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom pathlib import Path\nfrom typing import Protocol, Iterable\nimport json\n\nclass Store(Protocol):\n def write_text(self, path: Path, data: str) -> None: ...\n\nclass FSStore:\n def write_text(self, path: Path, data: str) -> None:\n path.parent.mkdir(parents=True, exist_ok=True)\n path.write_text(data, encoding=\"utf-8\")\n\n@dataclass(frozen=True, slots=True)\nclass Item:\n name: str\n qty: int\n\ndef parse_items(lines: Iterable[str]) -> list[Item]:\n out: list[Item] = []\n for i, line in enumerate(lines, 1):\n s = line.strip()\n if not s:\n continue\n obj = json.loads(s)\n if not isinstance(obj, dict):\n raise ValueError(f\"line {i}: expected object\")\n name = obj.get(\"name\")\n qty = obj.get(\"qty\")\n if not isinstance(name, str) or not name:\n raise ValueError(f\"line {i}: name must be str\")\n if not isinstance(qty, int) or qty < 0:\n raise ValueError(f\"line {i}: qty must be non-negative int\")\n out.append(Item(name, qty))\n return out\n\nclass InventoryWriter:\n def __init__(self, base_dir: Path, store: Store | None = None) -> None:\n self._base = base_dir\n self._store: Store = store or FSStore()\n\n def write(self, rel_path: str, items: list[Item]) -> Path:\n dst = (self._base / rel_path).resolve()\n base = self._base.resolve()\n if dst != base and base not in dst.parents:\n raise ValueError(\"unsafe path traversal\")\n payload = json.dumps([item.__dict__ for item in items], ensure_ascii=False)\n self._store.write_text(dst, payload)\n return dst\n```\n\n```python\nimport json\nfrom pathlib import Path\nimport pytest\nfrom module_under_test import InventoryWriter, parse_items\n\ndef test_parse_items_valid():\n lines = [json.dumps({\"name\":\"x\",\"qty\":1})]\n assert parse_items(lines)[0].name == \"x\"\n\ndef test_writer_blocks_traversal(tmp_path: Path):\n w = InventoryWriter(tmp_path)\n with pytest.raises(ValueError):\n w.write(\"../evil.json\", [])\n```", "source": "WithinUsAI/python_GOD_coder_100k"} {"text": "Fix the bug and add pytest tests.\n\n```python\ndef f06537(n: int) -> int:\n # sum 1..n inclusive\n if n < 0: raise ValueError\n total = 0\n for k in range(n): # BUG\n total += k\n return total\n```\nReturn unified diffs for `m43791.py` and `test_m43791.py`.\n\n*** Begin Patch\n*** Update File: m43791.py\n@@\n def f06537(n: int) -> int:\n@@\n- for k in range(n): # BUG\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_m43791.py\n+import pytest\n+from m43791 import f06537\n+\n+def test_small():\n+ assert f06537(7) == 28\n+\n+def test_zero():\n+ assert f06537(0) == 0\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ f06537(-1)\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Task type: gpu_serving_pipeline\nScenario: edge sync\nDomain focus: formal verification\nPrimary language: typescript\nDifficulty: expert\nScale/SLO: p99 < 50ms\nComponent: component_ajpstiwn\nConstraints: explicit contracts and invariants, include backward compatibility and migration plan, include security threat model (defensive only), include deterministic replay plan, include test vectors and fuzz strategy, avoid data races and undefined behavior, include verification strategy\nAssume weekly network partitions.\nDeliverable: Design a GPU inference serving pipeline: batching, scheduling, memory management, tail-latency control, and monitoring.\n\nOutput: elite engineering answer optimized for correctness, performance, and operability.\n**Contract**\n- Inputs validated at the boundary; explicit error taxonomy.\n- Idempotency for side effects via request_id; deterministic replay.\n- Backward compatibility: additive changes by default; versioned breaking changes.\n**Invariants**\n- Isolation: tenant boundary enforced; no cross-tenant reads/writes.\n- Safety: state transitions preserve invariants; no partial commit leaks.\n- Liveness: under bounded faults and stable network, progress occurs.\n**Failure modes & recovery**\n- Network partition: minority cannot commit; clients receive retriable errors.\n- Data corruption: checksums + scrubber; quarantine and rebuild from replicas/snapshots.\n- Duplicate requests: de-duplicate by (tenant, request_id) returning cached response.\n**Security posture (defensive)**\n- Threat model: auth/authz, injection, replay/abuse, supply chain.\n- Least privilege; secrets in managed store; audit logs for sensitive ops.\n- Input normalization, parameterized queries, path traversal protections.\n**Verification strategy**\n- Deterministic simulation with fault injection (crash/partition/latency).\n- Canary + shadow traffic; invariants checked in production via assertions/metrics.\n- Fuzzing of parsers/framers/validators with corpus seeds.\n\n**Snippet**\n```text\nImplementation sketch: factor pure state-machine core; adapters for I/O; add deterministic replay log.\n```\nExpert checks: state-machine proof sketch + model checking; upgrade/rollback rehearsed.", "source": "WithinUsAI/Omega_Genesis_Coder_100k"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: Language: YAML\nFramework/tooling: Terraform\nDomain: artifact registry\nLogic challenge: streaming timeout handling\nTask type: backwards_compatible_redesign\nDifficulty: hard\n\nReturn a rigorous engineering answer:\n- identify the hidden root cause or logical failure\n- present the corrected implementation\n- add tests that prove the fix\n- list verification commands\n- explain why naive fixes are insufficient when relevant\n\nRepository sketch:\nrepo/\n .github/workflows/ci.yml\n docker-compose.yml\n deploy/\n app.yaml\n\nFocus: Focus on staff-level problem solving with multi-file patches, rollout implications, performance and security tradeoffs.\n\nassistant: Diagnosis:\n- Staff-level diagnosis: streaming timeout handling impacts correctness, operability, and future maintenance, so the fix must be minimal where possible but complete where necessary.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```yaml\nname: ci\non: [push, pull_request]\njobs:\n test:\n runs-on: ubuntu-latest\n steps:\n - uses: actions/checkout@v4\n - name: Validate\n run: echo \"validated\"\n```\n\nTests:\n```yaml\n# Verification:\n# - validate syntax\n# - run smoke workflow\n# - fail fast on broken config\n```\n\nVerification:\n- `validate workflow syntax`\n- `run CI smoke job`\n\nEngineering notes:\n- Language: YAML\n- Framework/tooling: Terraform\n- Stack context: FastAPI, PostgreSQL, Redis, Celery, pytest, Docker\n- Domain: artifact registry\n- Task type: backwards_compatible_redesign\n- Difficulty: hard\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "Task type: distributed_algorithm\nScenario: payment ledger\nDomain focus: real-time scheduling\nPrimary language: python\nDifficulty: expert+\nScale/SLO: 1M msgs/min\nComponent: component_ojhefjtu\nConstraints: explicit contracts and invariants, include test vectors and fuzz strategy, include deterministic replay plan, include backward compatibility and migration plan, include failure modes and recovery\nAssume crash-only processes; recovery must be deterministic.\nDeliverable: Design an algorithm with message flows and correctness arguments (safety + liveness). Include failure handling and a minimal reference implementation skeleton.\n\nOutput: elite engineering answer optimized for correctness, performance, and operability.\n**Contract**\n- Inputs validated at the boundary; explicit error taxonomy.\n- Idempotency for side effects via request_id; deterministic replay.\n- Backward compatibility: additive changes by default; versioned breaking changes.\n**Invariants**\n- Isolation: tenant boundary enforced; no cross-tenant reads/writes.\n- Safety: state transitions preserve invariants; no partial commit leaks.\n- Determinism: replay of the same event log yields identical outputs.\n**Failure modes & recovery**\n- Network partition: minority cannot commit; clients receive retriable errors.\n- Crash during commit: WAL replay completes or transaction aborts; no torn writes.\n- Data corruption: checksums + scrubber; quarantine and rebuild from replicas/snapshots.\n**Security posture (defensive)**\n- Threat model: auth/authz, injection, replay/abuse, supply chain.\n- Least privilege; secrets in managed store; audit logs for sensitive ops.\n- Input normalization, parameterized queries, path traversal protections.\n**Verification strategy**\n- Deterministic simulation with fault injection (crash/partition/latency).\n- Fuzzing of parsers/framers/validators with corpus seeds.\n- Canary + shadow traffic; invariants checked in production via assertions/metrics.\n\n**Snippet**\n```text\nImplementation sketch: factor pure state-machine core; adapters for I/O; add deterministic replay log.\n```\nExpert+ checks: mechanized invariants (or exhaustive model checking), adversarial fuzzing, and multi-region failure drills.", "source": "WithinUsAI/Omega_Genesis_Coder_100k"} {"text": "Optimize while preserving behavior and order.\n\n```python\ndef f87378(xs):\n out=[]\n for x in xs:\n if x not in out: out.append(x)\n return out\n```\nReturn `m41054.py` with types and O(n) average.\n\n```python\n# m41054.py\nfrom __future__ import annotations\nfrom typing import Iterable, List, Set, TypeVar\nT=TypeVar(\"T\")\n\ndef f87378(xs: Iterable[T]) -> List[T]:\n \"\"\"Unique items preserving first-seen order.\"\"\"\n seen: Set[T]=set()\n out: List[T]=[]\n for x in xs:\n if x in seen: continue\n seen.add(x); out.append(x)\n return out\n```", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Optimize while preserving behavior and order.\n\n```python\ndef f38340(xs):\n out=[]\n for x in xs:\n if x not in out: out.append(x)\n return out\n```\nReturn `m62620.py` with types and O(n) average.\n\n```python\n# m62620.py\nfrom __future__ import annotations\nfrom typing import Iterable, List, Set, TypeVar\nT=TypeVar(\"T\")\n\ndef f38340(xs: Iterable[T]) -> List[T]:\n \"\"\"Unique items preserving first-seen order.\"\"\"\n seen: Set[T]=set()\n out: List[T]=[]\n for x in xs:\n if x in seen: continue\n seen.add(x); out.append(x)\n return out\n```", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Perform a code review for a developer tooling PR implementing multi-tenant isolation.\nTarget platform: ML (scikit + batch).\nRequirements: list critical issues, improvements, and provide an improved patch excerpt.\nConstraints: must be secure-by-default, must include documentation/comments, must include type hints where applicable, must avoid global state.\nDifficulty: expert. Assume untrusted input; validate everything.\n\nOutput: production-oriented blueprint with code where appropriate.\nDeliverable: code review findings + improved patch excerpt.\n\n**Critical issues**\n1. Missing input validation at boundary; potential unexpected exceptions.\n2. No idempotency / retry safety for side-effecting endpoint.\n3. No tests for edge cases (empty input, duplicates, timeouts).\n4. Observability gaps: no request_id correlation, no metrics.\n\n**Improvements**\n- Add strict validation and explicit error responses.\n- Add idempotency key support for create endpoints.\n- Add unit + integration tests with CI gating.\n- Add structured logs and basic metrics.\n\nPatch excerpt (illustrative):\n```python\nif not idem_key:\n raise HTTPException(400, \"Missing Idempotency-Key\")\n```\n\n\nHard-mode checks: concurrency safety, idempotency, and rollback validated; add chaos tests where feasible.", "source": "WithinUsAI/GOD_Coder_100k"} {"text": "Task type: secure_architecture\nScenario: streaming ETL\nDomain focus: kernel primitives\nPrimary language: go\nDifficulty: expert+\nScale/SLO: p99 < 50ms\nComponent: component_fvxneesz\nConstraints: assume adversarial inputs; validate everything, include test vectors and fuzz strategy, include verification strategy, include deterministic replay plan, explicit contracts and invariants\nAssume crash-only processes; recovery must be deterministic.\nDeliverable: Provide a defensive threat model and secure-by-default architecture; include monitoring/detection and tests (no offensive content).\n\nOutput: contract-first solution with failure modes, security posture, and test/verification strategy.\n**Contract**\n- Inputs validated at the boundary; explicit error taxonomy.\n- Idempotency for side effects via request_id; deterministic replay.\n- Backward compatibility: additive changes by default; versioned breaking changes.\n**Invariants**\n- Safety: state transitions preserve invariants; no partial commit leaks.\n- Determinism: replay of the same event log yields identical outputs.\n- Isolation: tenant boundary enforced; no cross-tenant reads/writes.\n**Failure modes & recovery**\n- Network partition: minority cannot commit; clients receive retriable errors.\n- Data corruption: checksums + scrubber; quarantine and rebuild from replicas/snapshots.\n- Crash during commit: WAL replay completes or transaction aborts; no torn writes.\n**Security posture (defensive)**\n- Threat model: auth/authz, injection, replay/abuse, supply chain.\n- Least privilege; secrets in managed store; audit logs for sensitive ops.\n- Input normalization, parameterized queries, path traversal protections.\n**Verification strategy**\n- Canary + shadow traffic; invariants checked in production via assertions/metrics.\n- Property tests against a pure reference model (state machine).\n- Fuzzing of parsers/framers/validators with corpus seeds.\n\n**Snippet**\n```text\nImplementation sketch: factor pure state-machine core; adapters for I/O; add deterministic replay log.\n```\nExpert+ checks: mechanized invariants (or exhaustive model checking), adversarial fuzzing, and multi-region failure drills.", "source": "WithinUsAI/Omega_Genesis_Coder_100k"} {"text": "Task type: network_protocol\nScenario: job scheduler\nDomain focus: GPU serving\nPrimary language: typescript\nDifficulty: expert+\nScale/SLO: multi-region active-active\nComponent: component_ezkgyyau\nConstraints: include deterministic replay plan, include security threat model (defensive only), include failure modes and recovery, include performance model and limits, include test vectors and fuzz strategy\nAssume weekly network partitions.\nDeliverable: Design an application protocol: framing, retries, backpressure, timeouts; include client/server skeleton and test vectors.\n\nOutput: contract-first solution with failure modes, security posture, and test/verification strategy.\n**Contract**\n- Inputs validated at the boundary; explicit error taxonomy.\n- Idempotency for side effects via request_id; deterministic replay.\n- Backward compatibility: additive changes by default; versioned breaking changes.\n**Invariants**\n- Isolation: tenant boundary enforced; no cross-tenant reads/writes.\n- Liveness: under bounded faults and stable network, progress occurs.\n- Determinism: replay of the same event log yields identical outputs.\n**Failure modes & recovery**\n- Duplicate requests: de-duplicate by (tenant, request_id) returning cached response.\n- Data corruption: checksums + scrubber; quarantine and rebuild from replicas/snapshots.\n- Network partition: minority cannot commit; clients receive retriable errors.\n**Security posture (defensive)**\n- Threat model: auth/authz, injection, replay/abuse, supply chain.\n- Least privilege; secrets in managed store; audit logs for sensitive ops.\n- Input normalization, parameterized queries, path traversal protections.\n**Verification strategy**\n- Canary + shadow traffic; invariants checked in production via assertions/metrics.\n- Property tests against a pure reference model (state machine).\n- Fuzzing of parsers/framers/validators with corpus seeds.\n\n**Snippet**\n```text\nImplementation sketch: factor pure state-machine core; adapters for I/O; add deterministic replay log.\n```\nExpert+ checks: mechanized invariants (or exhaustive model checking), adversarial fuzzing, and multi-region failure drills.", "source": "WithinUsAI/Omega_Genesis_Coder_100k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Optimize while preserving behavior.\n\nFile: ccg4xy.py\n```python\ndef ojmo5o(xs):\n out = []\n for x in xs:\n if x not in out:\n out.append(x)\n return out\n```\n\nRequirements: preserve first-seen order; O(n) average; add types + docstring.\n\n# ccg4xy.py\nfrom __future__ import annotations\nfrom typing import Iterable, List, Set, TypeVar\n\nT = TypeVar(\"T\")\n\ndef ojmo5o(xs: Iterable[T]) -> List[T]:\n \"\"\"Return unique items preserving first-seen order.\"\"\"\n seen: Set[T] = set()\n out: List[T] = []\n for x in xs:\n if x in seen:\n continue\n seen.add(x)\n out.append(x)\n return out", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Refactor to typed, mostly-immutable Python and add minimal tests.\n\n```python\nclass C28620:\n def __init__(self, values): self.values=list(values)\n def mean(self): return sum(self.values)/len(self.values)\n```\nReturn `m63740.py` and `test_m63740.py`.\n\n```python\n# m63740.py\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom typing import Iterable, Tuple\n\n@dataclass(frozen=True)\nclass C28620:\n values: Tuple[float, ...]\n\n @staticmethod\n def create(values: Iterable[float]) -> \"C28620\":\n vals = tuple(float(v) for v in values)\n if not vals: raise ValueError(\"empty\")\n return C28620(vals)\n\n def mean(self) -> float:\n return sum(self.values)/len(self.values)\n```\n\n```python\n# test_m63740.py\nimport pytest\nfrom m63740 import C28620\n\ndef test_mean():\n assert C28620.create([1,2,3]).mean() == 2.0\ndef test_empty():\n with pytest.raises(ValueError):\n C28620.create([])\n```", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Write pytest tests for `f84712`.\n\n```python\ndef f84712(a: int, b: int) -> int:\n return a*a + b*b\n```\nInclude edge cases and a property-style check.\n\n```python\nimport random\nfrom m97816 import f84712\n\ndef test_known():\n assert f84712(3,4) == 25\n\ndef test_zero():\n assert f84712(0,0) == 0\n\ndef test_property_nonnegative():\n for _ in range(200):\n a=random.randint(-50,50)\n b=random.randint(-50,50)\n assert f84712(a,b) >= 0\n```", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Implement a concurrent Python solution for file synchronization.\nRequirements: choose appropriate concurrency model, handle cancellation/timeouts, include tests.\nConstraints: must be streaming-friendly, must be easy to extend, must include docstrings.\nDifficulty: hard. Guarantee deterministic output ordering.\n\nDeliverable: corrected code and verification tests.\n```python\nfrom __future__ import annotations\nimport asyncio\nfrom dataclasses import dataclass\nfrom typing import Awaitable, Callable, Iterable, Optional\n\n@dataclass(frozen=True, slots=True)\nclass JobResult:\n ok: bool\n value: Optional[int]\n error: Optional[str]\n\nasync def run_bounded(\n factories: Iterable[Callable[[], Awaitable[int]]],\n *,\n limit: int = 10,\n timeout_s: float = 5.0,\n) -> list[JobResult]:\n if limit <= 0:\n raise ValueError(\"limit must be > 0\")\n sem = asyncio.Semaphore(limit)\n results: list[JobResult] = []\n\n async def one(factory: Callable[[], Awaitable[int]]) -> None:\n async with sem:\n try:\n v = await asyncio.wait_for(factory(), timeout=timeout_s)\n results.append(JobResult(True, v, None))\n except Exception as e:\n results.append(JobResult(False, None, str(e)))\n\n tasks = [asyncio.create_task(one(f)) for f in factories]\n try:\n await asyncio.gather(*tasks)\n finally:\n for t in tasks:\n if not t.done():\n t.cancel()\n return results\n```\n\n```python\nimport asyncio\nimport pytest\nfrom module_under_test import run_bounded\n\n@pytest.mark.asyncio\nasync def test_run_bounded_collects():\n async def work(x: int) -> int:\n await asyncio.sleep(0.01)\n return x\n fs = [(lambda i=i: work(i)) for i in range(30)]\n out = await run_bounded(fs, limit=5, timeout_s=1.0)\n assert len(out) == 30\n assert all(r.ok for r in out)\n```", "source": "WithinUsAI/python_GOD_coder_100k"} {"text": "Perform a code review for a enterprise SaaS PR implementing multi-tenant isolation.\nTarget platform: backend (Node.js).\nRequirements: list critical issues, improvements, and provide an improved patch excerpt.\nConstraints: must be secure-by-default, must be production-ready, must be observable (logs/metrics/traces), must include type hints where applicable, must be easy to extend.\nDifficulty: expert. Assume 10k RPS peak traffic.\n\nOutput: engineering-grade answer with edge cases covered.\nDeliverable: code review findings + improved patch excerpt.\n\n**Critical issues**\n1. Missing input validation at boundary; potential unexpected exceptions.\n2. No idempotency / retry safety for side-effecting endpoint.\n3. No tests for edge cases (empty input, duplicates, timeouts).\n4. Observability gaps: no request_id correlation, no metrics.\n\n**Improvements**\n- Add strict validation and explicit error responses.\n- Add idempotency key support for create endpoints.\n- Add unit + integration tests with CI gating.\n- Add structured logs and basic metrics.\n\nPatch excerpt (illustrative):\n```python\nif not idem_key:\n raise HTTPException(400, \"Missing Idempotency-Key\")\n```\n\n\nHard-mode checks: concurrency safety, idempotency, and rollback validated; add chaos tests where feasible.", "source": "WithinUsAI/GOD_Coder_100k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Fix a bug and add tests.\n\nFile: sj33pw.py\n```python\ndef vyzfcpg(n: int) -> int:\n \"\"\"Sum 1..n inclusive.\"\"\"\n if n < 0:\n raise ValueError(\"n must be non-negative\")\n total = 0\n for k in range(n): # BUG: should include n\n total += k\n return total\n```\n\nReturn unified diffs for sj33pw.py and test_sj33pw.py (pytest).\n\n*** Begin Patch\n*** Update File: sj33pw.py\n@@\n def vyzfcpg(n: int) -> int:\n@@\n total = 0\n- for k in range(n): # BUG: should include n\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_sj33pw.py\n+import pytest\n+from sj33pw import vyzfcpg\n+\n+def test_zero():\n+ assert vyzfcpg(0) == 0\n+\n+def test_one():\n+ assert vyzfcpg(1) == 1\n+\n+def test_small():\n+ assert vyzfcpg(7) == 28\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ vyzfcpg(-1)\n+\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Design a production system for fraud detection supporting multi-tenant isolation.\nTarget platform: infra (Docker + Kubernetes).\nRequirements: APIs, data model, scaling strategy, failure modes, and security.\nConstraints: must be performant under load, must include clear error handling, must include type hints where applicable.\nDifficulty: hard. Assume mobile clients are occasionally offline.\n\nOutput: actionable implementation and verification artifacts.\nDeliverable: system design with APIs, data model, and operational plan.\n\n**High-level architecture**\n- Edge: API Gateway + WAF\n- Core service: stateless app pods behind L7 LB\n- Data: Postgres (primary), Redis (cache + rate limit tokens), Object storage (uploads if needed)\n- Async: message queue (e.g., SQS/Rabbit) + worker pool for background jobs\n- Observability: structured logs + metrics + tracing\n\n**APIs (example)**\n- `POST /v1/{resource}` create (idempotent via `Idempotency-Key`)\n- `GET /v1/{resource}/{id}` read\n- `POST /v1/{resource}/{id}:action` command endpoint when side effects exist\n\n**Data model (Postgres)**\n- `resources(id UUID PK, tenant_id UUID, status TEXT, payload JSONB, created_at, updated_at)`\n- Unique constraint for idempotency: `(tenant_id, idempotency_key)` in a separate table:\n - `idempotency(tenant_id, key TEXT, request_hash TEXT, response JSONB, created_at, PRIMARY KEY(tenant_id,key))`\n\n**Scaling**\n- App layer scales horizontally; keep sessions out of process.\n- Cache reads in Redis; write-through invalidation on mutations.\n- Use connection pooling; consider read replicas for heavy reads.\n\n**Failure modes**\n- Retries: only for safe/ idempotent operations; exponential backoff + jitter.\n- Partial failures: background jobs must be idempotent; use a de-dup key.\n\n**Security**\n- AuthN: JWT/OIDC; AuthZ: RBAC/ABAC with tenant isolation\n- Validate all inputs; enforce per-tenant quotas/rate limits.\n\n**Rollout**\n- Dark launch + feature flags; canary; rapid rollback by toggling flags.\n\n\nHard-mode checks: concurrency safety, idempotency, and rollback validated; add chaos tests where feasible.", "source": "WithinUsAI/GOD_Coder_100k"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: Language: Bash\nFramework/tooling: jq\nDomain: observability collector\nLogic challenge: websocket reconnect storm\nTask type: algorithmic_correctness\nDifficulty: hard\n\nReturn a rigorous engineering answer:\n- identify the hidden root cause or logical failure\n- present the corrected implementation\n- add tests that prove the fix\n- list verification commands\n- explain why naive fixes are insufficient when relevant\n\nRepository sketch:\nrepo/\n scripts/\n run.sh\n deploy.sh\n tests/\n smoke.sh\n\nFocus: Focus on strong structured logic with edge cases, data validation, and concurrency safety.\n\nassistant: Diagnosis:\n- Root cause: the failure around websocket reconnect storm is caused by missing validation, weak edge-case handling, or unsafe lifecycle behavior in the current implementation.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```bash\n#!/usr/bin/env bash\nset -euo pipefail\n\ninput=\"${1:-}\"\nif [[ -z \"$input\" ]]; then\n echo \"missing input\" >&2\n exit 1\nfi\n\nprintf '%s\n' \"$input\" | tr -d '\r'\n```\n\nTests:\n```bash\noutput=\"$(bash scripts/run.sh \"abc\")\"\ntest \"$output\" = \"abc\"\n```\n\nVerification:\n- `bash tests/smoke.sh`\n- `shellcheck scripts/*.sh`\n\nEngineering notes:\n- Language: Bash\n- Framework/tooling: jq\n- Stack context: ASP.NET Core, SQL Server, EF Core, xUnit, Docker\n- Domain: observability collector\n- Task type: algorithmic_correctness\n- Difficulty: hard\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "Task type: kernel_syscall_design\nScenario: multi-tenant event ingestion\nDomain focus: fault injection & chaos engineering\nPrimary language: c\nDifficulty: expert+\nScale/SLO: p99 < 50ms\nComponent: component_ltgrcall\nConstraints: explicit contracts and invariants, include security threat model (defensive only), include performance model and limits, include deterministic replay plan, include failure modes and recovery, include backward compatibility and migration plan, include verification strategy\nAssume crash-only processes; recovery must be deterministic.\nDeliverable: Design a safe syscall/API boundary: ABI, validation, error codes, and compatibility; include tests and fuzz plan.\n\nOutput: rigorous design + invariants + verification plan + implementation sketch.\n**Contract**\n- Inputs validated at the boundary; explicit error taxonomy.\n- Idempotency for side effects via request_id; deterministic replay.\n- Backward compatibility: additive changes by default; versioned breaking changes.\n**Invariants**\n- Isolation: tenant boundary enforced; no cross-tenant reads/writes.\n- Determinism: replay of the same event log yields identical outputs.\n- Liveness: under bounded faults and stable network, progress occurs.\n**Failure modes & recovery**\n- Crash during commit: WAL replay completes or transaction aborts; no torn writes.\n- Duplicate requests: de-duplicate by (tenant, request_id) returning cached response.\n- Network partition: minority cannot commit; clients receive retriable errors.\n**Security posture (defensive)**\n- Threat model: auth/authz, injection, replay/abuse, supply chain.\n- Least privilege; secrets in managed store; audit logs for sensitive ops.\n- Input normalization, parameterized queries, path traversal protections.\n**Verification strategy**\n- Canary + shadow traffic; invariants checked in production via assertions/metrics.\n- Property tests against a pure reference model (state machine).\n- Fuzzing of parsers/framers/validators with corpus seeds.\n\n**Snippet**\n```text\nImplementation sketch: factor pure state-machine core; adapters for I/O; add deterministic replay log.\n```\nExpert+ checks: mechanized invariants (or exhaustive model checking), adversarial fuzzing, and multi-region failure drills.", "source": "WithinUsAI/Omega_Genesis_Coder_100k"} {"text": "Design CI/CD for a e-commerce service delivering audit logs.\nTarget platform: backend (Python FastAPI).\nRequirements: pipelines, checks, artifact strategy, deployments, and rollbacks.\nConstraints: must avoid global state, must be performant under load, must include type hints where applicable.\nDifficulty: medium. Assume 10k RPS peak traffic.\n\nOutput: engineering-grade answer with edge cases covered.\nDeliverable: CI/CD pipeline (GitHub Actions) with quality gates.\n\n```yaml\nname: ci\non:\n pull_request:\n push:\n branches: [main]\n\njobs:\n test:\n runs-on: ubuntu-latest\n steps:\n - uses: actions/checkout@v4\n - uses: actions/setup-python@v5\n with:\n python-version: \"3.11\"\n - run: python -m pip install -U pip\n - run: pip install -r requirements.txt\n - run: pip install -r requirements-dev.txt\n - run: ruff check .\n - run: mypy .\n - run: pytest -q --maxfail=1 --disable-warnings\n\n docker:\n needs: test\n runs-on: ubuntu-latest\n steps:\n - uses: actions/checkout@v4\n - uses: docker/setup-buildx-action@v3\n - run: docker build -t app:${{ github.sha }} .\n```\n\nDeployment strategy:\n- main → build → deploy to staging → smoke tests → canary to prod.\n- Rollback: redeploy previous image + DB migration rollback plan.\n\n\nChecks: input validation, tests, and safe defaults included.", "source": "WithinUsAI/GOD_Coder_100k"} {"text": "Build an elite-grade solution in the domain of compilers for scenario: event ingestion.\nPrimary language: go.\nDifficulty: expert.\nConstraints: assume untrusted inputs; validate and sanitize, avoid undefined behavior and data races, include tests or verification strategy, document performance characteristics.\nComponent: component_kotmyjy.\nAssume 50k RPS and p99 < 250ms.\nTask: Design a replication/consistency approach (e.g., leader-based, quorum reads/writes). Provide message flows, failure handling, and a minimal reference implementation skeleton.\n\nOutput: production blueprint plus correctness arguments and test strategy.\nOutput: replication design + failure handling + minimal skeleton.\n\n**Model**\n- Leader-based replication with term + log index.\n- Quorum acks for durability: write committed when majority acks.\n- Read options: leader-read (linearizable) or quorum-read (monotonic if using read-index).\n\n**Message flow (write)**\n1. Client → Leader: Put(request_id, payload)\n2. Leader appends to log, sends AppendEntries to followers\n3. Followers append + ack\n4. On majority ack: commit index advances; apply to state machine; respond to client\n\n**Failure modes**\n- Leader crash: new election; uncommitted entries may be rolled back.\n- Partition: minority side cannot commit.\n- Duplicate requests: deduplicate by request_id stored in state.\n\n**Skeleton (Go pseudo)**\n```go\ntype Entry struct { Term uint64; Index uint64; Cmd []byte }\ntype Node struct {\n id int\n term uint64\n log []Entry\n commit uint64\n seen map[string][]byte // request_id -> response\n}\n```\n\n**Verification**\n- Invariant: committed index never decreases.\n- Property: if a write is committed, all future leaders contain it.\n- Test with simulated partitions and crash/restart.\n\n\nExpert checks: state-machine reasoning, concurrency stress, and upgrade/rollback validated.", "source": "WithinUsAI/Elite_GOD_Coder_100k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Refactor to modern typed Python with immutability and tests.\n\nFile: gibdtu3t0.py\n```python\nclass Rhi3Vs8:\n def __init__(self, name, values):\n self.name = name\n self.values = list(values)\n def add(self, v):\n self.values.append(v)\n def mean(self):\n s = 0\n for x in self.values:\n s += x\n return s / len(self.values)\n```\n\nReturn full new gibdtu3t0.py and test_gibdtu3t0.py.\n\n# gibdtu3t0.py\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom typing import Iterable, Tuple\n\n@dataclass(frozen=True)\nclass Rhi3Vs8:\n name: str\n values: Tuple[float, ...]\n\n @staticmethod\n def create(name: str, values: Iterable[float]) -> \"Rhi3Vs8\":\n vals = tuple(float(v) for v in values)\n if not vals:\n raise ValueError(\"values must be non-empty\")\n return Rhi3Vs8(name=name, values=vals)\n\n def add(self, v: float) -> \"Rhi3Vs8\":\n return Rhi3Vs8(name=self.name, values=self.values + (float(v),))\n\n def mean(self) -> float:\n return sum(self.values) / len(self.values)\n\n# test_gibdtu3t0.py\nimport pytest\nfrom gibdtu3t0 import Rhi3Vs8\n\ndef test_mean_and_add():\n c = Rhi3Vs8.create(\"a\", [1, 2, 3])\n assert c.mean() == 2.0\n assert c.add(5).mean() == (1 + 2 + 3 + 5) / 4\n\ndef test_empty_raises():\n with pytest.raises(ValueError):\n Rhi3Vs8.create(\"x\", [])", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Refactor to typed, mostly-immutable Python and add minimal tests.\n\n```python\nclass C85010:\n def __init__(self, values): self.values=list(values)\n def mean(self): return sum(self.values)/len(self.values)\n```\nReturn `m75770.py` and `test_m75770.py`.\n\n```python\n# m75770.py\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom typing import Iterable, Tuple\n\n@dataclass(frozen=True)\nclass C85010:\n values: Tuple[float, ...]\n\n @staticmethod\n def create(values: Iterable[float]) -> \"C85010\":\n vals = tuple(float(v) for v in values)\n if not vals: raise ValueError(\"empty\")\n return C85010(vals)\n\n def mean(self) -> float:\n return sum(self.values)/len(self.values)\n```\n\n```python\n# test_m75770.py\nimport pytest\nfrom m75770 import C85010\n\ndef test_mean():\n assert C85010.create([1,2,3]).mean() == 2.0\ndef test_empty():\n with pytest.raises(ValueError):\n C85010.create([])\n```", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Refactor to modern typed Python with immutability and tests.\n\nFile: vlstkv02hnu.py\n```python\nclass Pjcvr67Ca2Qa:\n def __init__(self, name, values):\n self.name = name\n self.values = list(values)\n def add(self, v):\n self.values.append(v)\n def mean(self):\n s = 0\n for x in self.values:\n s += x\n return s / len(self.values)\n```\n\nReturn full new vlstkv02hnu.py and test_vlstkv02hnu.py.\n\n# vlstkv02hnu.py\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom typing import Iterable, Tuple\n\n@dataclass(frozen=True)\nclass Pjcvr67Ca2Qa:\n name: str\n values: Tuple[float, ...]\n\n @staticmethod\n def create(name: str, values: Iterable[float]) -> \"Pjcvr67Ca2Qa\":\n vals = tuple(float(v) for v in values)\n if not vals:\n raise ValueError(\"values must be non-empty\")\n return Pjcvr67Ca2Qa(name=name, values=vals)\n\n def add(self, v: float) -> \"Pjcvr67Ca2Qa\":\n return Pjcvr67Ca2Qa(name=self.name, values=self.values + (float(v),))\n\n def mean(self) -> float:\n return sum(self.values) / len(self.values)\n\n# test_vlstkv02hnu.py\nimport pytest\nfrom vlstkv02hnu import Pjcvr67Ca2Qa\n\ndef test_mean_and_add():\n c = Pjcvr67Ca2Qa.create(\"a\", [1, 2, 3])\n assert c.mean() == 2.0\n assert c.add(5).mean() == (1 + 2 + 3 + 5) / 4\n\ndef test_empty_raises():\n with pytest.raises(ValueError):\n Pjcvr67Ca2Qa.create(\"x\", [])", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Task type: compiler_frontend\nScenario: edge sync\nDomain focus: secure enclaves (defensive)\nPrimary language: sql\nDifficulty: expert+\nScale/SLO: p99 < 150ms\nComponent: component_xwikmhyx\nConstraints: include backward compatibility and migration plan, assume adversarial inputs; validate everything, include verification strategy, include performance model and limits, explicit contracts and invariants, include deterministic replay plan\nAssume tight memory budget and cold-start constraints.\nDeliverable: Design a DSL language frontend: lexer/parser, AST, type checking, error reporting, and tests.\n\nOutput: contract-first solution with failure modes, security posture, and test/verification strategy.\n**Contract**\n- Inputs validated at the boundary; explicit error taxonomy.\n- Idempotency for side effects via request_id; deterministic replay.\n- Backward compatibility: additive changes by default; versioned breaking changes.\n**Invariants**\n- Isolation: tenant boundary enforced; no cross-tenant reads/writes.\n- Safety: state transitions preserve invariants; no partial commit leaks.\n- Determinism: replay of the same event log yields identical outputs.\n**Failure modes & recovery**\n- Crash during commit: WAL replay completes or transaction aborts; no torn writes.\n- Data corruption: checksums + scrubber; quarantine and rebuild from replicas/snapshots.\n- Network partition: minority cannot commit; clients receive retriable errors.\n**Security posture (defensive)**\n- Threat model: auth/authz, injection, replay/abuse, supply chain.\n- Least privilege; secrets in managed store; audit logs for sensitive ops.\n- Input normalization, parameterized queries, path traversal protections.\n**Verification strategy**\n- Property tests against a pure reference model (state machine).\n- Fuzzing of parsers/framers/validators with corpus seeds.\n- Deterministic simulation with fault injection (crash/partition/latency).\n\n**Snippet**\n```text\nImplementation sketch: factor pure state-machine core; adapters for I/O; add deterministic replay log.\n```\nExpert+ checks: mechanized invariants (or exhaustive model checking), adversarial fuzzing, and multi-region failure drills.", "source": "WithinUsAI/Omega_Genesis_Coder_100k"} {"text": "Build a data pipeline for a enterprise SaaS product around role-based access control.\nTarget platform: data (SQL + Python).\nRequirements: schema, ingestion, validation, backfills, and tests.\nConstraints: must be secure-by-default, must include tests, must include documentation/comments, must be performant under load, must include type hints where applicable.\nDifficulty: expert. Assume schema evolves frequently; design for migrations.\n\nOutput: production-oriented blueprint with code where appropriate.\nDeliverable: schema + ingestion + validation + backfill strategy.\n\n**Schema (example)**\n- events(event_id TEXT PK, tenant_id TEXT, ts TIMESTAMP, type TEXT, payload JSONB)\n\n**Ingestion**\n- Write to raw table first; validate; then materialize to curated tables.\n- Idempotency by event_id; enforce uniqueness.\n\n**Validation**\n- Reject missing tenant_id/type/ts.\n- Quarantine bad records with reason.\n\n**Backfills**\n- Re-run deterministic transforms from raw → curated.\n- Version transformations; store transform_version with outputs.\n\n**Tests**\n- Unit tests for validators and transforms.\n- Integration test: sample raw batch produces expected curated rows.\n\n\nHard-mode checks: concurrency safety, idempotency, and rollback validated; add chaos tests where feasible.", "source": "WithinUsAI/GOD_Coder_100k"} {"text": "Add a clear docstring and type hints to this function:\n\n```python\ndef f45674(s):\n return ''.join(x for x in s if x.isalnum()).lower()\n```\n\n```python\nfrom __future__ import annotations\n\ndef f45674(s: str) -> str:\n \"\"\"Normalize a string: keep only alphanumerics and lowercase the result.\"\"\"\n return \"\".join(ch for ch in s if ch.isalnum()).lower()\n```", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Fix a subtle bug in a Python module used for file synchronization.\nRequirements: explain root cause briefly, provide corrected code, and add regression tests.\nConstraints: must include docstrings, must include type hints.\nDifficulty: hard. Guarantee deterministic output ordering.\n\nDeliverable: implementation + tests.\n```python\nfrom __future__ import annotations\n\nfrom dataclasses import dataclass\nfrom pathlib import Path\nfrom typing import Iterable\nimport json\n\n\nclass ValidationError(ValueError):\n \"\"\"Raised when input validation fails.\"\"\"\n\n\ndef safe_join(base: Path, *parts: str) -> Path:\n \"\"\"Join paths while preventing traversal outside base.\"\"\"\n b = base.resolve()\n p = (b / Path(*parts)).resolve()\n if p != b and b not in p.parents:\n raise ValidationError(f\"unsafe path: {p}\")\n return p\n\n\n@dataclass(frozen=True, slots=True)\nclass Record:\n key: str\n value: int\n\n\ndef parse_jsonl(lines: Iterable[str]) -> list[Record]:\n out: list[Record] = []\n for idx, line in enumerate(lines, 1):\n s = line.strip()\n if not s:\n continue\n try:\n obj = json.loads(s)\n except json.JSONDecodeError as e:\n raise ValidationError(f\"line {idx}: invalid json\") from e\n if not isinstance(obj, dict):\n raise ValidationError(f\"line {idx}: expected object\")\n key = obj.get(\"key\")\n val = obj.get(\"value\")\n if not isinstance(key, str) or not key:\n raise ValidationError(f\"line {idx}: key must be non-empty str\")\n if not isinstance(val, int):\n raise ValidationError(f\"line {idx}: value must be int\")\n out.append(Record(key, val))\n return out\n\n\ndef write_jsonl(base: Path, rel: str, records: Iterable[Record]) -> Path:\n base.mkdir(parents=True, exist_ok=True)\n dst = safe_join(base, rel)\n dst.parent.mkdir(parents=True, exist_ok=True)\n with dst.open(\"w\", encoding=\"utf-8\", newline=\"\\n\") as f:\n for r in records:\n f.write(json.dumps({\"key\": r.key, \"value\": r.value}, ensure_ascii=False) + \"\\n\")\n return dst\n```\n\n```python\n# tests (pytest-style)\nimport json\nfrom pathlib import Path\nimport pytest\nfrom module_under_test import ValidationError, Record, parse_jsonl, write_jsonl\n\ndef test_parse_ok():\n lines = [json.dumps({\"key\":\"a\",\"value\":1}), json.dumps({\"key\":\"b\",\"value\":2})]\n assert parse_jsonl(lines) == [Record(\"a\",1), Record(\"b\",2)]\n\ndef test_parse_rejects_bad_json():\n with pytest.raises(ValidationError):\n parse_jsonl([\"{not json}\"])\n\ndef test_safe_join_blocks_traversal(tmp_path: Path):\n with pytest.raises(ValidationError):\n write_jsonl(tmp_path, \"../x.jsonl\", [Record(\"a\",1)])\n```", "source": "WithinUsAI/python_GOD_coder_100k"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: Language: JavaScript\nFramework/tooling: React\nDomain: payments platform\nLogic challenge: N+1 query explosion\nTask type: performance_bottleneck_patch\nDifficulty: hard\n\nReturn a rigorous engineering answer:\n- identify the hidden root cause or logical failure\n- present the corrected implementation\n- add tests that prove the fix\n- list verification commands\n- explain why naive fixes are insufficient when relevant\n\nRepository sketch:\nrepo/\n src/\n api.js\n service.js\n utils.js\n tests/\n api.test.js\n package.json\n\nFocus: Focus on ambiguity, misleading symptoms, hidden root causes, and high-stakes debugging.\n\nassistant: Diagnosis:\n- Hidden root cause: N+1 query explosion presents misleading symptoms, so the patch must target the actual logic boundary rather than the first visible failure.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```javascript\ntype Payload = Record;\n\nexport function normalizePayload(payload: Payload): Payload {\n if (!payload || typeof payload !== \"object\" || Array.isArray(payload)) {\n throw new TypeError(\"payload must be a plain object\");\n }\n return Object.fromEntries(\n Object.entries(payload)\n .filter(([, value]) => value !== null && value !== undefined)\n .map(([key, value]) => [String(key).trim(), value])\n );\n}\n\nexport function handleN+1QueryExplosion(payload: Payload) {\n const clean = normalizePayload(payload);\n if (!(\"id\" in clean)) {\n return { ok: false, data: {}, error: \"missing id\" };\n }\n return { ok: true, data: clean, error: null };\n}\n```\n\nTests:\n```javascript\nimport { describe, it, expect } from \"vitest\";\nimport { handleN+1QueryExplosion } from \"../src/service\";\n\ndescribe(\"handler\", () => {\n it(\"accepts valid input\", () => {\n expect(handleN+1QueryExplosion({ id: 7, name: \"ok\", unused: null })).toEqual({\n ok: true,\n data: { id: 7, name: \"ok\" },\n error: null\n });\n });\n\n it(\"rejects missing id\", () => {\n expect(handleN+1QueryExplosion({ name: \"x\" }).error).toMatch(/missing id/);\n });\n});\n```\n\nVerification:\n- `npm test`\n- `npm run lint`\n\nEngineering notes:\n- Language: JavaScript\n- Framework/tooling: React\n- Stack context: Rust, Axum, SQLx, Redis, Tokio, Docker\n- Domain: payments platform\n- Task type: performance_bottleneck_patch\n- Difficulty: hard\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "Task type: kernel_syscall_design\nScenario: time-series metrics store\nDomain focus: consensus & replication\nPrimary language: cpp\nDifficulty: expert\nScale/SLO: 99.99% availability\nComponent: component_egpnjkgz\nConstraints: explicit contracts and invariants, include backward compatibility and migration plan, include security threat model (defensive only), include performance model and limits, include verification strategy, avoid data races and undefined behavior\nAssume schema changes every sprint; must be backward compatible.\nDeliverable: Design a safe syscall/API boundary: ABI, validation, error codes, and compatibility; include tests and fuzz plan.\n\nOutput: rigorous design + invariants + verification plan + implementation sketch.\n**Contract**\n- Inputs validated at the boundary; explicit error taxonomy.\n- Idempotency for side effects via request_id; deterministic replay.\n- Backward compatibility: additive changes by default; versioned breaking changes.\n**Invariants**\n- Determinism: replay of the same event log yields identical outputs.\n- Safety: state transitions preserve invariants; no partial commit leaks.\n- Isolation: tenant boundary enforced; no cross-tenant reads/writes.\n**Failure modes & recovery**\n- Data corruption: checksums + scrubber; quarantine and rebuild from replicas/snapshots.\n- Duplicate requests: de-duplicate by (tenant, request_id) returning cached response.\n- Network partition: minority cannot commit; clients receive retriable errors.\n**Security posture (defensive)**\n- Threat model: auth/authz, injection, replay/abuse, supply chain.\n- Least privilege; secrets in managed store; audit logs for sensitive ops.\n- Input normalization, parameterized queries, path traversal protections.\n**Verification strategy**\n- Property tests against a pure reference model (state machine).\n- Deterministic simulation with fault injection (crash/partition/latency).\n- Fuzzing of parsers/framers/validators with corpus seeds.\n\n**Snippet**\n```text\nImplementation sketch: factor pure state-machine core; adapters for I/O; add deterministic replay log.\n```\nExpert checks: state-machine proof sketch + model checking; upgrade/rollback rehearsed.", "source": "WithinUsAI/Omega_Genesis_Coder_100k"} {"text": "Implement a web feature for fraud detection: caching.\nTarget platform: web (React + TypeScript).\nRequirements: accessible UI, API integration, and tests.\nConstraints: must be easy to extend, must be performant under load, must include tests.\nDifficulty: easy. Assume strict latency budget (p95 < 200ms).\n\nOutput: design + implementation guidance suitable for shipping.\nDeliverable: accessible React + TypeScript feature skeleton with tests.\n\n```tsx\n// Feature.tsx\nimport React, { useEffect, useMemo, useState } from \"react\";\n\ntype Item = { id: string; label: string };\n\nexport function Feature({ fetchItems }: { fetchItems: () => Promise }) {\n const [items, setItems] = useState([]);\n const [q, setQ] = useState(\"\");\n const filtered = useMemo(\n () => items.filter(i => i.label.toLowerCase().includes(q.toLowerCase())),\n [items, q]\n );\n\n useEffect(() => {\n let cancelled = false;\n fetchItems().then(xs => { if (!cancelled) setItems(xs); });\n return () => { cancelled = true; };\n }, [fetchItems]);\n\n return (\n
\n \n
    \n {filtered.map(i =>
  • {i.label}
  • )}\n
\n
\n );\n}\n```\n\n```tsx\n// Feature.test.tsx (vitest + testing-library)\nimport { render, screen } from \"@testing-library/react\";\nimport userEvent from \"@testing-library/user-event\";\nimport { Feature } from \"./Feature\";\n\ntest(\"filters items\", async () => {\n const fetchItems = async () => [{ id:\"1\", label:\"Alpha\" }, { id:\"2\", label:\"Beta\" }];\n render();\n expect(await screen.findByText(\"Alpha\")).toBeInTheDocument();\n await userEvent.type(screen.getByLabelText(\"Search\"), \"be\");\n expect(screen.queryByText(\"Alpha\")).toBeNull();\n expect(screen.getByText(\"Beta\")).toBeInTheDocument();\n});\n```\n\n\nChecks: input validation, tests, and safe defaults included.", "source": "WithinUsAI/GOD_Coder_100k"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: System domain: auth service\nStack: Airflow, dbt, DuckDB, MinIO, pytest\nCross-layer incident: transaction boundary bug\nTask type: auth_session_repair\nDifficulty: hard\n\nSolve this as a complete-project engineer.\nOutput must include:\n- root cause across layers\n- final implementation patch\n- tests touching at least two layers\n- deployment or observability note\n- verification commands\n\nRepository sketch:\nrepo/\n src/\n api.ts\n service.ts\n schema.ts\n tests/\n api.test.ts\n package.json\n\nFocus: Focus on multi-layer debugging across frontend, backend, database, CI, caching, and deployment.\n\nassistant: Diagnosis:\n- Root cause: transaction boundary bug crosses service boundaries, so the fix must align code, contracts, tests, and deployment behavior.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```ts\ntype Payload = Record;\n\nexport function normalizePayload(payload: Payload): Payload {\n if (!payload || typeof payload !== \"object\" || Array.isArray(payload)) {\n throw new TypeError(\"payload must be a plain object\");\n }\n return Object.fromEntries(\n Object.entries(payload)\n .filter(([, value]) => value !== null && value !== undefined)\n .map(([key, value]) => [String(key).trim(), value])\n );\n}\n\nexport function handleTransactionBoundaryBug(payload: Payload) {\n const clean = normalizePayload(payload);\n if (!(\"id\" in clean)) {\n return { ok: false, data: {}, error: \"missing id\" };\n }\n return { ok: true, data: clean, error: null };\n}\n```\n\nTests:\n```ts\nimport { describe, it, expect } from \"vitest\";\nimport { handleTransactionBoundaryBug } from \"../src/service\";\n\ndescribe(\"handler\", () => {\n it(\"accepts valid input\", () => {\n expect(handleTransactionBoundaryBug({ id: 7, name: \"ok\", unused: null })).toEqual({\n ok: true,\n data: { id: 7, name: \"ok\" },\n error: null\n });\n });\n\n it(\"rejects missing id\", () => {\n expect(handleTransactionBoundaryBug({ name: \"x\" }).error).toMatch(/missing id/);\n });\n});\n```\n\nVerification:\n- `npm test`\n- `npm run typecheck`\n- `npm run lint`\n\nEngineering notes:\n- Language: TypeScript\n- Framework/tooling: Express\n- Stack context: Airflow, dbt, DuckDB, MinIO, pytest\n- Domain: auth service\n- Task type: auth_session_repair\n- Difficulty: hard\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "Task type: tla_state_machine\nScenario: multi-tenant event ingestion\nDomain focus: network protocols\nPrimary language: tla+\nDifficulty: hard\nScale/SLO: p99 < 150ms\nComponent: component_wctqfmva\nConstraints: include failure modes and recovery, include security threat model (defensive only), include deterministic replay plan, avoid data races and undefined behavior, explicit contracts and invariants, include test vectors and fuzz strategy, include backward compatibility and migration plan\nAssume tight memory budget and cold-start constraints.\nDeliverable: Provide a TLA+-style state machine (pseudo), safety/liveness properties, and a model-checking strategy. Include an implementation sketch and test vectors.\n\nOutput: contract-first solution with failure modes, security posture, and test/verification strategy.\n**Contract**\n- Inputs validated at the boundary; explicit error taxonomy.\n- Idempotency for side effects via request_id; deterministic replay.\n- Backward compatibility: additive changes by default; versioned breaking changes.\n**Invariants**\n- Liveness: under bounded faults and stable network, progress occurs.\n- Determinism: replay of the same event log yields identical outputs.\n- Safety: state transitions preserve invariants; no partial commit leaks.\n**Failure modes & recovery**\n- Data corruption: checksums + scrubber; quarantine and rebuild from replicas/snapshots.\n- Crash during commit: WAL replay completes or transaction aborts; no torn writes.\n- Duplicate requests: de-duplicate by (tenant, request_id) returning cached response.\n**Security posture (defensive)**\n- Threat model: auth/authz, injection, replay/abuse, supply chain.\n- Least privilege; secrets in managed store; audit logs for sensitive ops.\n- Input normalization, parameterized queries, path traversal protections.\n**Verification strategy**\n- Fuzzing of parsers/framers/validators with corpus seeds.\n- Deterministic simulation with fault injection (crash/partition/latency).\n- Canary + shadow traffic; invariants checked in production via assertions/metrics.\n\n**Snippet**\n```tla\nVARIABLES state, log, seen\n\nInit == state = [k \\in Keys |-> <<0, NULL>>] /\\ log = << >> /\\ seen = [r \\in ReqIds |-> NULL]\n\nPut(req, k, v) ==\n IF seen[req] # NULL THEN UNCHANGED <>\n ELSE\n LET ver == state[k][1] + 1 IN\n /\\ state' = [state EXCEPT ![k] = <>]\n /\\ log' = Append(log, <>)\n /\\ seen' = [seen EXCEPT ![req] = <<\"ok\", ver>>]\n\nSafety == \\A k \\in Keys: state[k][1] >= 0\n```\n\nHard checks: fault injection tests gate merges; perf thresholds enforced in CI.", "source": "WithinUsAI/Omega_Genesis_Coder_100k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Fix a bug and add tests.\n\nFile: xgx00xv.py\n```python\ndef cv0fgtcpedei(n: int) -> int:\n \"\"\"Sum 1..n inclusive.\"\"\"\n if n < 0:\n raise ValueError(\"n must be non-negative\")\n total = 0\n for k in range(n): # BUG: should include n\n total += k\n return total\n```\n\nReturn unified diffs for xgx00xv.py and test_xgx00xv.py (pytest).\n\n*** Begin Patch\n*** Update File: xgx00xv.py\n@@\n def cv0fgtcpedei(n: int) -> int:\n@@\n total = 0\n- for k in range(n): # BUG: should include n\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_xgx00xv.py\n+import pytest\n+from xgx00xv import cv0fgtcpedei\n+\n+def test_zero():\n+ assert cv0fgtcpedei(0) == 0\n+\n+def test_one():\n+ assert cv0fgtcpedei(1) == 1\n+\n+def test_small():\n+ assert cv0fgtcpedei(7) == 28\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ cv0fgtcpedei(-1)\n+\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: System domain: notification service\nStack: FastAPI, PostgreSQL, Redis, Celery, pytest, Docker\nCross-layer incident: transaction boundary bug\nTask type: cache_consistency_patch\nDifficulty: hard\n\nSolve this as a complete-project engineer.\nOutput must include:\n- root cause across layers\n- final implementation patch\n- tests touching at least two layers\n- deployment or observability note\n- verification commands\n\nRepository sketch:\nrepo/\n scripts/\n run.sh\n deploy.sh\n tests/\n smoke.sh\n\nFocus: Focus on multi-layer debugging across frontend, backend, database, CI, caching, and deployment.\n\nassistant: Diagnosis:\n- Root cause: transaction boundary bug crosses service boundaries, so the fix must align code, contracts, tests, and deployment behavior.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```bash\n#!/usr/bin/env bash\nset -euo pipefail\n\ninput=\"${1:-}\"\nif [[ -z \"$input\" ]]; then\n echo \"missing input\" >&2\n exit 1\nfi\n\nprintf '%s\n' \"$input\" | tr -d '\r'\n```\n\nTests:\n```bash\noutput=\"$(bash scripts/run.sh \"abc\")\"\ntest \"$output\" = \"abc\"\n```\n\nVerification:\n- `bash tests/smoke.sh`\n- `shellcheck scripts/*.sh`\n\nEngineering notes:\n- Language: Bash\n- Framework/tooling: awk\n- Stack context: FastAPI, PostgreSQL, Redis, Celery, pytest, Docker\n- Domain: notification service\n- Task type: cache_consistency_patch\n- Difficulty: hard\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "Write pytest tests for `f70160`.\n\n```python\ndef f70160(a: int, b: int) -> int:\n return a*a + b*b\n```\nInclude edge cases and a property-style check.\n\n```python\nimport random\nfrom m52880 import f70160\n\ndef test_known():\n assert f70160(3,4) == 25\n\ndef test_zero():\n assert f70160(0,0) == 0\n\ndef test_property_nonnegative():\n for _ in range(200):\n a=random.randint(-50,50)\n b=random.randint(-50,50)\n assert f70160(a,b) >= 0\n```", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Task type: distributed_algorithm\nScenario: identity and access\nDomain focus: compiler toolchains\nPrimary language: python\nDifficulty: hard\nScale/SLO: multi-region active-active\nComponent: component_nugxcywb\nConstraints: include verification strategy, include security threat model (defensive only), include performance model and limits, avoid data races and undefined behavior, explicit contracts and invariants\nAssume tight memory budget and cold-start constraints.\nDeliverable: Design an algorithm with message flows and correctness arguments (safety + liveness). Include failure handling and a minimal reference implementation skeleton.\n\nOutput: contract-first solution with failure modes, security posture, and test/verification strategy.\n**Contract**\n- Inputs validated at the boundary; explicit error taxonomy.\n- Idempotency for side effects via request_id; deterministic replay.\n- Backward compatibility: additive changes by default; versioned breaking changes.\n**Invariants**\n- Determinism: replay of the same event log yields identical outputs.\n- Safety: state transitions preserve invariants; no partial commit leaks.\n- Liveness: under bounded faults and stable network, progress occurs.\n**Failure modes & recovery**\n- Data corruption: checksums + scrubber; quarantine and rebuild from replicas/snapshots.\n- Network partition: minority cannot commit; clients receive retriable errors.\n- Duplicate requests: de-duplicate by (tenant, request_id) returning cached response.\n**Security posture (defensive)**\n- Threat model: auth/authz, injection, replay/abuse, supply chain.\n- Least privilege; secrets in managed store; audit logs for sensitive ops.\n- Input normalization, parameterized queries, path traversal protections.\n**Verification strategy**\n- Deterministic simulation with fault injection (crash/partition/latency).\n- Property tests against a pure reference model (state machine).\n- Fuzzing of parsers/framers/validators with corpus seeds.\n\n**Snippet**\n```text\nImplementation sketch: factor pure state-machine core; adapters for I/O; add deterministic replay log.\n```\nHard checks: fault injection tests gate merges; perf thresholds enforced in CI.", "source": "WithinUsAI/Omega_Genesis_Coder_100k"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: System domain: feature flag service\nStack: Rust, Axum, SQLx, Redis, Tokio, Docker\nCross-layer incident: race condition on worker shutdown\nTask type: auth_session_repair\nDifficulty: hard\n\nSolve this as a complete-project engineer.\nOutput must include:\n- root cause across layers\n- final implementation patch\n- tests touching at least two layers\n- deployment or observability note\n- verification commands\n\nRepository sketch:\nrepo/\n migrations/\n 001_init.sql\n 002_add_index.sql\n queries/\n report.sql\n tests/\n report_cases.md\n\nFocus: Focus on multi-layer debugging across frontend, backend, database, CI, caching, and deployment.\n\nassistant: Diagnosis:\n- Root cause: race condition on worker shutdown crosses service boundaries, so the fix must align code, contracts, tests, and deployment behavior.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```sql\nWITH ranked AS (\n SELECT\n user_id,\n created_at,\n amount,\n ROW_NUMBER() OVER (PARTITION BY user_id ORDER BY created_at DESC, id DESC) AS rn\n FROM orders\n)\nSELECT user_id, created_at, amount\nFROM ranked\nWHERE rn = 1;\n```\n\nTests:\n```sql\n-- Correctness checks:\n-- 1) multiple rows per user\n-- 2) identical timestamps require deterministic tie-breaker\n-- 3) null values handled by business rules\n```\n\nVerification:\n- `run migration checks`\n- `run query correctness cases`\n\nEngineering notes:\n- Language: SQL\n- Framework/tooling: SQLite\n- Stack context: Rust, Axum, SQLx, Redis, Tokio, Docker\n- Domain: feature flag service\n- Task type: auth_session_repair\n- Difficulty: hard\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Produce an offline-first self-evolving code assistant architecture named `t2h_c9qg209k`.\nMust include: module layout, patch-safety policy, evaluation gates (tests/lint/types), versioned memory index.\n\nArchitecture: `t2h_c9qg209k` (offline-first, self-evolving)\n\nModules\n- core/loop.py: evolve → validate → accept/reject (bounded iterations)\n- patching/: diff builder, safe apply, atomic writes, rollback points\n- policy/: allowlist paths, deny globs (.git/, __pycache__/, binaries), patch size caps\n- signals/: parse pytest/ruff/mypy into normalized findings\n- memory/index.jsonl: append-only snapshots (hashes, metrics, rationale)\n\nSafety gates\n- refuse path traversal/symlink escapes; never edit binaries\n- accept only if tests/lint/types stay green or improve", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Build an elite-grade solution in the domain of edge/IoT for scenario: event ingestion.\nPrimary language: python.\nDifficulty: hard.\nConstraints: document performance characteristics, provide rollout and rollback guidance, make the interface contract explicit, include invariants and failure modes, include tests or verification strategy.\nComponent: component_dkcltub.\nAssume partial network partitions occur weekly.\nTask: Provide threat model, secure-by-default design, and defensive implementation patterns. No offensive/exploit content; focus on prevention and detection.\n\nOutput: elite-grade engineering answer with contracts, edge cases, and verification.\nOutput: threat model + defensive design + detection.\n\n**Threat model**\n- Auth: token theft → short-lived tokens, rotation, audience checks\n- AuthZ: privilege escalation → centralized policy checks, tenant isolation tests\n- Input: injection → strict validation, parameterized queries, output encoding\n- Supply chain: dependencies → lockfiles, signature verification, SBOM\n\n**Defensive patterns**\n- Idempotency keys for side effects; replay-safe handlers\n- Secrets in managed store; never logs\n- Audit logging for sensitive ops; tamper-evident storage\n\n**Detection**\n- Alert on unusual auth failures, access pattern anomalies, and data exfil signals.\n\n\nHard checks: failure injection tests and performance regressions gated.", "source": "WithinUsAI/Elite_GOD_Coder_100k"} {"text": "Build an elite-grade solution in the domain of ml systems for scenario: time-series metrics.\nPrimary language: python.\nDifficulty: expert.\nConstraints: include invariants and failure modes, assume untrusted inputs; validate and sanitize, make the interface contract explicit, provide rollout and rollback guidance, document performance characteristics.\nComponent: component_btniypc.\nAssume strict auditability and replayable history.\nTask: Design a replication/consistency approach (e.g., leader-based, quorum reads/writes). Provide message flows, failure handling, and a minimal reference implementation skeleton.\n\nOutput: elite-grade engineering answer with contracts, edge cases, and verification.\nOutput: replication design + failure handling + minimal skeleton.\n\n**Model**\n- Leader-based replication with term + log index.\n- Quorum acks for durability: write committed when majority acks.\n- Read options: leader-read (linearizable) or quorum-read (monotonic if using read-index).\n\n**Message flow (write)**\n1. Client → Leader: Put(request_id, payload)\n2. Leader appends to log, sends AppendEntries to followers\n3. Followers append + ack\n4. On majority ack: commit index advances; apply to state machine; respond to client\n\n**Failure modes**\n- Leader crash: new election; uncommitted entries may be rolled back.\n- Partition: minority side cannot commit.\n- Duplicate requests: deduplicate by request_id stored in state.\n\n**Skeleton (Go pseudo)**\n```go\ntype Entry struct { Term uint64; Index uint64; Cmd []byte }\ntype Node struct {\n id int\n term uint64\n log []Entry\n commit uint64\n seen map[string][]byte // request_id -> response\n}\n```\n\n**Verification**\n- Invariant: committed index never decreases.\n- Property: if a write is committed, all future leaders contain it.\n- Test with simulated partitions and crash/restart.\n\n\nExpert checks: state-machine reasoning, concurrency stress, and upgrade/rollback validated.", "source": "WithinUsAI/Elite_GOD_Coder_100k"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: Language: Java\nFramework/tooling: Gradle\nDomain: developer platform\nLogic challenge: schema drift during deployment\nTask type: multi_file_migration_repair\nDifficulty: hard\n\nReturn a rigorous engineering answer:\n- identify the hidden root cause or logical failure\n- present the corrected implementation\n- add tests that prove the fix\n- list verification commands\n- explain why naive fixes are insufficient when relevant\n\nRepository sketch:\nrepo/\n src/main/java/com/acme/App.java\n src/main/java/com/acme/Service.java\n src/test/java/com/acme/AppTest.java\n pom.xml\n\nFocus: Focus on staff-level problem solving with multi-file patches, rollout implications, performance and security tradeoffs.\n\nassistant: Diagnosis:\n- Staff-level diagnosis: schema drift during deployment impacts correctness, operability, and future maintenance, so the fix must be minimal where possible but complete where necessary.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```java\nimport java.util.HashMap;\nimport java.util.Map;\n\npublic final class RequestHandler {\n public static Map handleRequest(Map payload) {\n Map clean = new HashMap<>();\n for (Map.Entry entry : payload.entrySet()) {\n if (entry.getValue() != null) clean.put(entry.getKey().trim(), entry.getValue());\n }\n if (!clean.containsKey(\"id\")) throw new IllegalArgumentException(\"missing id\");\n return Map.of(\"ok\", true, \"data\", clean);\n }\n}\n```\n\nTests:\n```java\nimport static org.junit.jupiter.api.Assertions.*;\nimport java.util.Map;\nimport org.junit.jupiter.api.Test;\n\nclass RequestHandlerTest {\n @Test\n void requiresId() {\n assertThrows(IllegalArgumentException.class, () -> RequestHandler.handleRequest(Map.of(\"name\", \"x\")));\n }\n}\n```\n\nVerification:\n- `./gradlew test`\n- `mvn test`\n\nEngineering notes:\n- Language: Java\n- Framework/tooling: Gradle\n- Stack context: Rust, Axum, SQLx, Redis, Tokio, Docker\n- Domain: developer platform\n- Task type: multi_file_migration_repair\n- Difficulty: hard\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Produce an offline-first self-evolving code assistant architecture named `rf5u52urs2hi`.\nMust include: module layout, patch-safety policy, evaluation gates (tests/lint/types), versioned memory index.\n\nArchitecture: `rf5u52urs2hi` (offline-first, self-evolving)\n\nModules\n- core/loop.py: evolve → validate → accept/reject (bounded iterations)\n- patching/: diff builder, safe apply, atomic writes, rollback points\n- policy/: allowlist paths, deny globs (.git/, __pycache__/, binaries), patch size caps\n- signals/: parse pytest/ruff/mypy into normalized findings\n- memory/index.jsonl: append-only snapshots (hashes, metrics, rationale)\n\nSafety gates\n- refuse path traversal/symlink escapes; never edit binaries\n- accept only if tests/lint/types stay green or improve", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Fix a bug and add tests.\n\nFile: mn91kn5tlu.py\n```python\ndef ex7poi(n: int) -> int:\n \"\"\"Sum 1..n inclusive.\"\"\"\n if n < 0:\n raise ValueError(\"n must be non-negative\")\n total = 0\n for k in range(n): # BUG: should include n\n total += k\n return total\n```\n\nReturn unified diffs for mn91kn5tlu.py and test_mn91kn5tlu.py (pytest).\n\n*** Begin Patch\n*** Update File: mn91kn5tlu.py\n@@\n def ex7poi(n: int) -> int:\n@@\n total = 0\n- for k in range(n): # BUG: should include n\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_mn91kn5tlu.py\n+import pytest\n+from mn91kn5tlu import ex7poi\n+\n+def test_zero():\n+ assert ex7poi(0) == 0\n+\n+def test_one():\n+ assert ex7poi(1) == 1\n+\n+def test_small():\n+ assert ex7poi(7) == 28\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ ex7poi(-1)\n+\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Design a small, production-grade Python API for CLI tooling.\nRequirements: define data models and interfaces, implement reference version, include tests.\nConstraints: stdlib-only, must handle Windows paths safely, must avoid global state, must include docstrings.\nDifficulty: hard. Avoid quadratic behavior on large inputs.\n\nDeliverable: API + reference implementation + tests.\nArchitecture:\n- Public facade class coordinating concerns (parsing, validation, persistence)\n- Small pure functions for testability\n- No global state; dependency injection for filesystem I/O\n\n```python\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom pathlib import Path\nfrom typing import Protocol, Iterable\nimport json\n\nclass Store(Protocol):\n def write_text(self, path: Path, data: str) -> None: ...\n\nclass FSStore:\n def write_text(self, path: Path, data: str) -> None:\n path.parent.mkdir(parents=True, exist_ok=True)\n path.write_text(data, encoding=\"utf-8\")\n\n@dataclass(frozen=True, slots=True)\nclass Item:\n name: str\n qty: int\n\ndef parse_items(lines: Iterable[str]) -> list[Item]:\n out: list[Item] = []\n for i, line in enumerate(lines, 1):\n s = line.strip()\n if not s:\n continue\n obj = json.loads(s)\n if not isinstance(obj, dict):\n raise ValueError(f\"line {i}: expected object\")\n name = obj.get(\"name\")\n qty = obj.get(\"qty\")\n if not isinstance(name, str) or not name:\n raise ValueError(f\"line {i}: name must be str\")\n if not isinstance(qty, int) or qty < 0:\n raise ValueError(f\"line {i}: qty must be non-negative int\")\n out.append(Item(name, qty))\n return out\n\nclass InventoryWriter:\n def __init__(self, base_dir: Path, store: Store | None = None) -> None:\n self._base = base_dir\n self._store: Store = store or FSStore()\n\n def write(self, rel_path: str, items: list[Item]) -> Path:\n dst = (self._base / rel_path).resolve()\n base = self._base.resolve()\n if dst != base and base not in dst.parents:\n raise ValueError(\"unsafe path traversal\")\n payload = json.dumps([item.__dict__ for item in items], ensure_ascii=False)\n self._store.write_text(dst, payload)\n return dst\n```\n\n```python\nimport json\nfrom pathlib import Path\nimport pytest\nfrom module_under_test import InventoryWriter, parse_items\n\ndef test_parse_items_valid():\n lines = [json.dumps({\"name\":\"x\",\"qty\":1})]\n assert parse_items(lines)[0].name == \"x\"\n\ndef test_writer_blocks_traversal(tmp_path: Path):\n w = InventoryWriter(tmp_path)\n with pytest.raises(ValueError):\n w.write(\"../evil.json\", [])\n```", "source": "WithinUsAI/python_GOD_coder_100k"} {"text": "Refactor to typed, mostly-immutable Python and add minimal tests.\n\n```python\nclass C99873:\n def __init__(self, values): self.values=list(values)\n def mean(self): return sum(self.values)/len(self.values)\n```\nReturn `m69221.py` and `test_m69221.py`.\n\n```python\n# m69221.py\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom typing import Iterable, Tuple\n\n@dataclass(frozen=True)\nclass C99873:\n values: Tuple[float, ...]\n\n @staticmethod\n def create(values: Iterable[float]) -> \"C99873\":\n vals = tuple(float(v) for v in values)\n if not vals: raise ValueError(\"empty\")\n return C99873(vals)\n\n def mean(self) -> float:\n return sum(self.values)/len(self.values)\n```\n\n```python\n# test_m69221.py\nimport pytest\nfrom m69221 import C99873\n\ndef test_mean():\n assert C99873.create([1,2,3]).mean() == 2.0\ndef test_empty():\n with pytest.raises(ValueError):\n C99873.create([])\n```", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Write pytest tests for `f05550`.\n\n```python\ndef f05550(a: int, b: int) -> int:\n return a*a + b*b\n```\nInclude edge cases and a property-style check.\n\n```python\nimport random\nfrom m43650 import f05550\n\ndef test_known():\n assert f05550(3,4) == 25\n\ndef test_zero():\n assert f05550(0,0) == 0\n\ndef test_property_nonnegative():\n for _ in range(200):\n a=random.randint(-50,50)\n b=random.randint(-50,50)\n assert f05550(a,b) >= 0\n```", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Implement a mobile feature for logistics: offline-first sync.\nTarget platform: mobile.\nRequirements: offline-safe behavior, UI state handling, and tests.\nConstraints: must be easy to extend, must include type hints where applicable, must be production-ready.\nDifficulty: medium. Assume untrusted input; validate everything.\n\nOutput: production-oriented blueprint with code where appropriate.\nDeliverable: offline-safe mobile approach (Kotlin) + key snippets.\n\n```kotlin\n// Repository.kt\ninterface Api {\n suspend fun fetch(): List\n suspend fun post(item: Item): Item\n}\n\ninterface LocalStore {\n suspend fun getAll(): List\n suspend fun upsert(items: List)\n suspend fun enqueuePending(item: Item)\n suspend fun pending(): List\n suspend fun markSent(id: String)\n}\n\nclass Repo(private val api: Api, private val db: LocalStore) {\n suspend fun sync(): List {\n val local = db.getAll()\n // optimistic: show local first, then refresh\n return try {\n val remote = api.fetch()\n db.upsert(remote)\n flushPending()\n remote\n } catch (e: Exception) {\n local\n }\n }\n\n suspend fun createOfflineFirst(item: Item): Item {\n db.enqueuePending(item)\n return item\n }\n\n private suspend fun flushPending() {\n for (p in db.pending()) {\n try {\n api.post(p)\n db.markSent(p.id)\n } catch (_: Exception) {\n // keep pending; retry later with backoff in a WorkManager job\n }\n }\n }\n}\n```\n\nTesting guidance:\n- Unit test Repo with fake Api/LocalStore.\n- Integration test offline queue + retry policy (WorkManager).\n\n\nChecks: input validation, tests, and safe defaults included.", "source": "WithinUsAI/GOD_Coder_100k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Refactor to modern typed Python with immutability and tests.\n\nFile: pwikn0ij.py\n```python\nclass H5Ks9Jw3K:\n def __init__(self, name, values):\n self.name = name\n self.values = list(values)\n def add(self, v):\n self.values.append(v)\n def mean(self):\n s = 0\n for x in self.values:\n s += x\n return s / len(self.values)\n```\n\nReturn full new pwikn0ij.py and test_pwikn0ij.py.\n\n# pwikn0ij.py\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom typing import Iterable, Tuple\n\n@dataclass(frozen=True)\nclass H5Ks9Jw3K:\n name: str\n values: Tuple[float, ...]\n\n @staticmethod\n def create(name: str, values: Iterable[float]) -> \"H5Ks9Jw3K\":\n vals = tuple(float(v) for v in values)\n if not vals:\n raise ValueError(\"values must be non-empty\")\n return H5Ks9Jw3K(name=name, values=vals)\n\n def add(self, v: float) -> \"H5Ks9Jw3K\":\n return H5Ks9Jw3K(name=self.name, values=self.values + (float(v),))\n\n def mean(self) -> float:\n return sum(self.values) / len(self.values)\n\n# test_pwikn0ij.py\nimport pytest\nfrom pwikn0ij import H5Ks9Jw3K\n\ndef test_mean_and_add():\n c = H5Ks9Jw3K.create(\"a\", [1, 2, 3])\n assert c.mean() == 2.0\n assert c.add(5).mean() == (1 + 2 + 3 + 5) / 4\n\ndef test_empty_raises():\n with pytest.raises(ValueError):\n H5Ks9Jw3K.create(\"x\", [])", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Optimize while preserving behavior and order.\n\n```python\ndef f83191(xs):\n out=[]\n for x in xs:\n if x not in out: out.append(x)\n return out\n```\nReturn `m83313.py` with types and O(n) average.\n\n```python\n# m83313.py\nfrom __future__ import annotations\nfrom typing import Iterable, List, Set, TypeVar\nT=TypeVar(\"T\")\n\ndef f83191(xs: Iterable[T]) -> List[T]:\n \"\"\"Unique items preserving first-seen order.\"\"\"\n seen: Set[T]=set()\n out: List[T]=[]\n for x in xs:\n if x in seen: continue\n seen.add(x); out.append(x)\n return out\n```", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Build an elite-grade solution in the domain of sre/observability for scenario: time-series metrics.\nPrimary language: bash.\nDifficulty: hard.\nConstraints: document performance characteristics, avoid undefined behavior and data races, design for backward compatibility and migrations.\nComponent: component_lehqmfv.\nAssume cold-start and memory limits are tight.\nTask: Provide SLOs, alerting, dashboards, runbooks, and incident playbook. Include chaos testing and safe rollout strategy.\n\nOutput: production blueprint plus correctness arguments and test strategy.\nOutput: SLOs + alerts + runbooks + chaos strategy.\n\n**SLOs**\n- Availability: 99.9% monthly\n- Latency: p95 < 200ms, p99 < 400ms\n- Error rate: < 0.1%\n\n**Alerts**\n- Burn-rate alerts for SLOs (fast/slow windows)\n- Saturation: CPU, memory, queue depth, DB connections\n- Dependency health: cache hit rate drop, downstream timeouts\n\n**Runbooks**\n- Triage: identify blast radius, feature-flag rollback, capacity mitigation\n- Post-incident: timeline, contributing factors, action items\n\n**Chaos**\n- Inject latency, partial outages, and restarts in staging; verify steady-state SLOs.\n\n\nHard checks: failure injection tests and performance regressions gated.", "source": "WithinUsAI/Elite_GOD_Coder_100k"} {"text": "Refactor a Python module used for caching layer into a clean, extensible design.\nRequirements: outline the new architecture briefly, then provide the refactored code and tests.\nConstraints: must be easy to extend, must be memory-efficient, must include tests.\nDifficulty: expert. Include a small CLI example if relevant.\n\nDeliverable: implementation + tests.\nArchitecture:\n- Public facade class coordinating concerns (parsing, validation, persistence)\n- Small pure functions for testability\n- No global state; dependency injection for filesystem I/O\n\n```python\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom pathlib import Path\nfrom typing import Protocol, Iterable\nimport json\n\nclass Store(Protocol):\n def write_text(self, path: Path, data: str) -> None: ...\n\nclass FSStore:\n def write_text(self, path: Path, data: str) -> None:\n path.parent.mkdir(parents=True, exist_ok=True)\n path.write_text(data, encoding=\"utf-8\")\n\n@dataclass(frozen=True, slots=True)\nclass Item:\n name: str\n qty: int\n\ndef parse_items(lines: Iterable[str]) -> list[Item]:\n out: list[Item] = []\n for i, line in enumerate(lines, 1):\n s = line.strip()\n if not s:\n continue\n obj = json.loads(s)\n if not isinstance(obj, dict):\n raise ValueError(f\"line {i}: expected object\")\n name = obj.get(\"name\")\n qty = obj.get(\"qty\")\n if not isinstance(name, str) or not name:\n raise ValueError(f\"line {i}: name must be str\")\n if not isinstance(qty, int) or qty < 0:\n raise ValueError(f\"line {i}: qty must be non-negative int\")\n out.append(Item(name, qty))\n return out\n\nclass InventoryWriter:\n def __init__(self, base_dir: Path, store: Store | None = None) -> None:\n self._base = base_dir\n self._store: Store = store or FSStore()\n\n def write(self, rel_path: str, items: list[Item]) -> Path:\n dst = (self._base / rel_path).resolve()\n base = self._base.resolve()\n if dst != base and base not in dst.parents:\n raise ValueError(\"unsafe path traversal\")\n payload = json.dumps([item.__dict__ for item in items], ensure_ascii=False)\n self._store.write_text(dst, payload)\n return dst\n```\n\n```python\nimport json\nfrom pathlib import Path\nimport pytest\nfrom module_under_test import InventoryWriter, parse_items\n\ndef test_parse_items_valid():\n lines = [json.dumps({\"name\":\"x\",\"qty\":1})]\n assert parse_items(lines)[0].name == \"x\"\n\ndef test_writer_blocks_traversal(tmp_path: Path):\n w = InventoryWriter(tmp_path)\n with pytest.raises(ValueError):\n w.write(\"../evil.json\", [])\n```", "source": "WithinUsAI/python_GOD_coder_100k"} {"text": "Task type: secure_architecture\nScenario: job scheduler\nDomain focus: program synthesis (safe)\nPrimary language: rust\nDifficulty: expert+\nScale/SLO: 99.99% availability\nComponent: component_eicgqzvc\nConstraints: avoid data races and undefined behavior, include failure modes and recovery, assume adversarial inputs; validate everything, include verification strategy, include performance model and limits, include test vectors and fuzz strategy, include security threat model (defensive only)\nAssume hostile inputs and targeted abuse patterns.\nDeliverable: Provide a defensive threat model and secure-by-default architecture; include monitoring/detection and tests (no offensive content).\n\nOutput: rigorous design + invariants + verification plan + implementation sketch.\n**Contract**\n- Inputs validated at the boundary; explicit error taxonomy.\n- Idempotency for side effects via request_id; deterministic replay.\n- Backward compatibility: additive changes by default; versioned breaking changes.\n**Invariants**\n- Determinism: replay of the same event log yields identical outputs.\n- Safety: state transitions preserve invariants; no partial commit leaks.\n- Isolation: tenant boundary enforced; no cross-tenant reads/writes.\n**Failure modes & recovery**\n- Duplicate requests: de-duplicate by (tenant, request_id) returning cached response.\n- Crash during commit: WAL replay completes or transaction aborts; no torn writes.\n- Data corruption: checksums + scrubber; quarantine and rebuild from replicas/snapshots.\n**Security posture (defensive)**\n- Threat model: auth/authz, injection, replay/abuse, supply chain.\n- Least privilege; secrets in managed store; audit logs for sensitive ops.\n- Input normalization, parameterized queries, path traversal protections.\n**Verification strategy**\n- Canary + shadow traffic; invariants checked in production via assertions/metrics.\n- Property tests against a pure reference model (state machine).\n- Fuzzing of parsers/framers/validators with corpus seeds.\n\n**Snippet**\n```text\nImplementation sketch: factor pure state-machine core; adapters for I/O; add deterministic replay log.\n```\nExpert+ checks: mechanized invariants (or exhaustive model checking), adversarial fuzzing, and multi-region failure drills.", "source": "WithinUsAI/Omega_Genesis_Coder_100k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Produce an offline-first self-evolving code assistant architecture named `kn5ddy`.\nMust include: module layout, patch-safety policy, evaluation gates (tests/lint/types), versioned memory index.\n\nArchitecture: `kn5ddy` (offline-first, self-evolving)\n\nModules\n- core/loop.py: evolve → validate → accept/reject (bounded iterations)\n- patching/: diff builder, safe apply, atomic writes, rollback points\n- policy/: allowlist paths, deny globs (.git/, __pycache__/, binaries), patch size caps\n- signals/: parse pytest/ruff/mypy into normalized findings\n- memory/index.jsonl: append-only snapshots (hashes, metrics, rationale)\n\nSafety gates\n- refuse path traversal/symlink escapes; never edit binaries\n- accept only if tests/lint/types stay green or improve", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Fix a bug and add tests.\n\nFile: wdeg4lwfiauk.py\n```python\ndef jckzjw(n: int) -> int:\n \"\"\"Sum 1..n inclusive.\"\"\"\n if n < 0:\n raise ValueError(\"n must be non-negative\")\n total = 0\n for k in range(n): # BUG: should include n\n total += k\n return total\n```\n\nReturn unified diffs for wdeg4lwfiauk.py and test_wdeg4lwfiauk.py (pytest).\n\n*** Begin Patch\n*** Update File: wdeg4lwfiauk.py\n@@\n def jckzjw(n: int) -> int:\n@@\n total = 0\n- for k in range(n): # BUG: should include n\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_wdeg4lwfiauk.py\n+import pytest\n+from wdeg4lwfiauk import jckzjw\n+\n+def test_zero():\n+ assert jckzjw(0) == 0\n+\n+def test_one():\n+ assert jckzjw(1) == 1\n+\n+def test_small():\n+ assert jckzjw(7) == 28\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ jckzjw(-1)\n+\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: Language: YAML\nFramework/tooling: Docker Compose\nDomain: observability collector\nLogic challenge: gRPC retry storm\nTask type: performance_bottleneck_patch\nDifficulty: hard\n\nReturn a rigorous engineering answer:\n- identify the hidden root cause or logical failure\n- present the corrected implementation\n- add tests that prove the fix\n- list verification commands\n- explain why naive fixes are insufficient when relevant\n\nRepository sketch:\nrepo/\n .github/workflows/ci.yml\n docker-compose.yml\n deploy/\n app.yaml\n\nFocus: Focus on ambiguity, misleading symptoms, hidden root causes, and high-stakes debugging.\n\nassistant: Diagnosis:\n- Hidden root cause: gRPC retry storm presents misleading symptoms, so the patch must target the actual logic boundary rather than the first visible failure.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```yaml\nname: ci\non: [push, pull_request]\njobs:\n test:\n runs-on: ubuntu-latest\n steps:\n - uses: actions/checkout@v4\n - name: Validate\n run: echo \"validated\"\n```\n\nTests:\n```yaml\n# Verification:\n# - validate syntax\n# - run smoke workflow\n# - fail fast on broken config\n```\n\nVerification:\n- `validate workflow syntax`\n- `run CI smoke job`\n\nEngineering notes:\n- Language: YAML\n- Framework/tooling: Docker Compose\n- Stack context: ASP.NET Core, SQL Server, EF Core, xUnit, Docker\n- Domain: observability collector\n- Task type: performance_bottleneck_patch\n- Difficulty: hard\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "Task type: distributed_algorithm\nScenario: identity and access\nDomain focus: zero-downtime migrations\nPrimary language: typescript\nDifficulty: hard\nScale/SLO: 50 TB/day ingestion\nComponent: component_dgwcojvz\nConstraints: avoid data races and undefined behavior, assume adversarial inputs; validate everything, include verification strategy, include security threat model (defensive only), include performance model and limits, include deterministic replay plan, include failure modes and recovery\nAssume weekly network partitions.\nDeliverable: Design an algorithm with message flows and correctness arguments (safety + liveness). Include failure handling and a minimal reference implementation skeleton.\n\nOutput: elite engineering answer optimized for correctness, performance, and operability.\n**Contract**\n- Inputs validated at the boundary; explicit error taxonomy.\n- Idempotency for side effects via request_id; deterministic replay.\n- Backward compatibility: additive changes by default; versioned breaking changes.\n**Invariants**\n- Isolation: tenant boundary enforced; no cross-tenant reads/writes.\n- Safety: state transitions preserve invariants; no partial commit leaks.\n- Determinism: replay of the same event log yields identical outputs.\n**Failure modes & recovery**\n- Crash during commit: WAL replay completes or transaction aborts; no torn writes.\n- Data corruption: checksums + scrubber; quarantine and rebuild from replicas/snapshots.\n- Network partition: minority cannot commit; clients receive retriable errors.\n**Security posture (defensive)**\n- Threat model: auth/authz, injection, replay/abuse, supply chain.\n- Least privilege; secrets in managed store; audit logs for sensitive ops.\n- Input normalization, parameterized queries, path traversal protections.\n**Verification strategy**\n- Canary + shadow traffic; invariants checked in production via assertions/metrics.\n- Property tests against a pure reference model (state machine).\n- Fuzzing of parsers/framers/validators with corpus seeds.\n\n**Snippet**\n```text\nImplementation sketch: factor pure state-machine core; adapters for I/O; add deterministic replay log.\n```\nHard checks: fault injection tests gate merges; perf thresholds enforced in CI.", "source": "WithinUsAI/Omega_Genesis_Coder_100k"} {"text": "Task type: static_analyzer\nScenario: multi-tenant event ingestion\nDomain focus: large-scale ML systems\nPrimary language: python\nDifficulty: hard\nScale/SLO: multi-region active-active\nComponent: component_lycgqiqr\nConstraints: avoid data races and undefined behavior, include deterministic replay plan, include security threat model (defensive only), include verification strategy, explicit contracts and invariants\nAssume crash-only processes; recovery must be deterministic.\nDeliverable: Design a static analyzer for a safety property (e.g., taint/SQLi prevention); include rule set, false-positive strategy, and tests.\n\nOutput: elite engineering answer optimized for correctness, performance, and operability.\n**Contract**\n- Inputs validated at the boundary; explicit error taxonomy.\n- Idempotency for side effects via request_id; deterministic replay.\n- Backward compatibility: additive changes by default; versioned breaking changes.\n**Invariants**\n- Isolation: tenant boundary enforced; no cross-tenant reads/writes.\n- Determinism: replay of the same event log yields identical outputs.\n- Safety: state transitions preserve invariants; no partial commit leaks.\n**Failure modes & recovery**\n- Duplicate requests: de-duplicate by (tenant, request_id) returning cached response.\n- Crash during commit: WAL replay completes or transaction aborts; no torn writes.\n- Data corruption: checksums + scrubber; quarantine and rebuild from replicas/snapshots.\n**Security posture (defensive)**\n- Threat model: auth/authz, injection, replay/abuse, supply chain.\n- Least privilege; secrets in managed store; audit logs for sensitive ops.\n- Input normalization, parameterized queries, path traversal protections.\n**Verification strategy**\n- Fuzzing of parsers/framers/validators with corpus seeds.\n- Property tests against a pure reference model (state machine).\n- Deterministic simulation with fault injection (crash/partition/latency).\n\n**Snippet**\n```text\nImplementation sketch: factor pure state-machine core; adapters for I/O; add deterministic replay log.\n```\nHard checks: fault injection tests gate merges; perf thresholds enforced in CI.", "source": "WithinUsAI/Omega_Genesis_Coder_100k"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: Language: YAML\nFramework/tooling: Terraform\nDomain: artifact registry\nLogic challenge: monorepo toolchain skew\nTask type: security_logic_interaction\nDifficulty: hard\n\nReturn a rigorous engineering answer:\n- identify the hidden root cause or logical failure\n- present the corrected implementation\n- add tests that prove the fix\n- list verification commands\n- explain why naive fixes are insufficient when relevant\n\nRepository sketch:\nrepo/\n .github/workflows/ci.yml\n docker-compose.yml\n deploy/\n app.yaml\n\nFocus: Focus on ambiguity, misleading symptoms, hidden root causes, and high-stakes debugging.\n\nassistant: Diagnosis:\n- Hidden root cause: monorepo toolchain skew presents misleading symptoms, so the patch must target the actual logic boundary rather than the first visible failure.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```yaml\nname: ci\non: [push, pull_request]\njobs:\n test:\n runs-on: ubuntu-latest\n steps:\n - uses: actions/checkout@v4\n - name: Validate\n run: echo \"validated\"\n```\n\nTests:\n```yaml\n# Verification:\n# - validate syntax\n# - run smoke workflow\n# - fail fast on broken config\n```\n\nVerification:\n- `validate workflow syntax`\n- `run CI smoke job`\n\nEngineering notes:\n- Language: YAML\n- Framework/tooling: Terraform\n- Stack context: Go, Gin, PostgreSQL, gRPC, Prometheus, Docker\n- Domain: artifact registry\n- Task type: security_logic_interaction\n- Difficulty: hard\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "Implement real-time notifications for a fraud detection product.\nTarget platform: ML (PyTorch + serving).\nRequirements: provide production-ready code, configuration, and tests.\nConstraints: must include type hints where applicable, must be production-ready, must be secure-by-default, must avoid global state, must include tests.\nDifficulty: expert. Assume mobile clients are occasionally offline.\n\nOutput: design + implementation guidance suitable for shipping.\nDeliverable: production-grade reference implementation (FastAPI) + tests.\n\n```python\n# app.py\nfrom __future__ import annotations\n\nimport hashlib\nimport json\nfrom dataclasses import dataclass\nfrom datetime import datetime, timezone\nfrom typing import Any, Optional\n\nfrom fastapi import FastAPI, Header, HTTPException\nfrom pydantic import BaseModel, Field\n\napp = FastAPI(title=\"Idempotent API\")\n\nclass CreateReq(BaseModel):\n tenant_id: str = Field(min_length=1)\n amount_cents: int = Field(ge=0)\n currency: str = Field(min_length=3, max_length=3)\n\nclass CreateResp(BaseModel):\n id: str\n created_at: str\n echo: CreateReq\n\n@dataclass\nclass _IdempoEntry:\n request_hash: str\n response_json: str\n\n# In production: Postgres table with UNIQUE(tenant_id, key)\n_IDEMPO: dict[tuple[str, str], _IdempoEntry] = {}\n\ndef _hash_req(req: CreateReq) -> str:\n raw = req.model_dump_json()\n return hashlib.sha256(raw.encode(\"utf-8\")).hexdigest()\n\n@app.post(\"/v1/payments\", response_model=CreateResp)\ndef create_payment(\n req: CreateReq,\n idempotency_key: Optional[str] = Header(default=None, alias=\"Idempotency-Key\"),\n) -> Any:\n if not idempotency_key:\n raise HTTPException(status_code=400, detail=\"Missing Idempotency-Key\")\n if len(idempotency_key) > 128:\n raise HTTPException(status_code=400, detail=\"Idempotency-Key too long\")\n\n key = (req.tenant_id, idempotency_key)\n rh = _hash_req(req)\n\n existing = _IDEMPO.get(key)\n if existing:\n if existing.request_hash != rh:\n raise HTTPException(status_code=409, detail=\"Idempotency-Key reuse with different payload\")\n return json.loads(existing.response_json)\n\n # Create new payment (stubbed)\n pid = hashlib.md5(f\"{req.tenant_id}:{idempotency_key}\".encode()).hexdigest()\n resp = CreateResp(\n id=pid,\n created_at=datetime.now(timezone.utc).isoformat(),\n echo=req,\n )\n _IDEMPO[key] = _IdempoEntry(request_hash=rh, response_json=resp.model_dump_json())\n return resp\n```\n\n```python\n# test_app.py (pytest)\nfrom fastapi.testclient import TestClient\nfrom app import app\n\nclient = TestClient(app)\n\ndef test_idempotent_replay():\n headers = {\"Idempotency-Key\": \"abc\"}\n body = {\"tenant_id\":\"t1\",\"amount_cents\":100,\"currency\":\"USD\"}\n r1 = client.post(\"/v1/payments\", json=body, headers=headers)\n r2 = client.post(\"/v1/payments\", json=body, headers=headers)\n assert r1.status_code == 200 and r2.status_code == 200\n assert r1.json() == r2.json()\n\ndef test_payload_conflict():\n headers = {\"Idempotency-Key\": \"abc\"}\n b1 = {\"tenant_id\":\"t1\",\"amount_cents\":100,\"currency\":\"USD\"}\n b2 = {\"tenant_id\":\"t1\",\"amount_cents\":200,\"currency\":\"USD\"}\n assert client.post(\"/v1/payments\", json=b1, headers=headers).status_code == 200\n assert client.post(\"/v1/payments\", json=b2, headers=headers).status_code == 409\n```\n\nNotes:\n- Replace in-memory store with a DB table and transaction.\n- Store response + request hash to detect key reuse with different payload.\n\n\nHard-mode checks: concurrency safety, idempotency, and rollback validated; add chaos tests where feasible.", "source": "WithinUsAI/GOD_Coder_100k"} {"text": "Build an elite-grade solution in the domain of high-performance services for scenario: inventory & ordering.\nPrimary language: typescript.\nDifficulty: expert.\nConstraints: provide rollout and rollback guidance, avoid undefined behavior and data races, document performance characteristics, design for backward compatibility and migrations.\nComponent: component_lunemms.\nAssume compliance requires data deletion with proofs.\nTask: Provide threat model, secure-by-default design, and defensive implementation patterns. No offensive/exploit content; focus on prevention and detection.\n\nOutput: production blueprint plus correctness arguments and test strategy.\nOutput: threat model + defensive design + detection.\n\n**Threat model**\n- Auth: token theft → short-lived tokens, rotation, audience checks\n- AuthZ: privilege escalation → centralized policy checks, tenant isolation tests\n- Input: injection → strict validation, parameterized queries, output encoding\n- Supply chain: dependencies → lockfiles, signature verification, SBOM\n\n**Defensive patterns**\n- Idempotency keys for side effects; replay-safe handlers\n- Secrets in managed store; never logs\n- Audit logging for sensitive ops; tamper-evident storage\n\n**Detection**\n- Alert on unusual auth failures, access pattern anomalies, and data exfil signals.\n\n\nExpert checks: state-machine reasoning, concurrency stress, and upgrade/rollback validated.", "source": "WithinUsAI/Elite_GOD_Coder_100k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Optimize while preserving behavior.\n\nFile: ifejo18vsabr.py\n```python\ndef yxx7yk(xs):\n out = []\n for x in xs:\n if x not in out:\n out.append(x)\n return out\n```\n\nRequirements: preserve first-seen order; O(n) average; add types + docstring.\n\n# ifejo18vsabr.py\nfrom __future__ import annotations\nfrom typing import Iterable, List, Set, TypeVar\n\nT = TypeVar(\"T\")\n\ndef yxx7yk(xs: Iterable[T]) -> List[T]:\n \"\"\"Return unique items preserving first-seen order.\"\"\"\n seen: Set[T] = set()\n out: List[T] = []\n for x in xs:\n if x in seen:\n continue\n seen.add(x)\n out.append(x)\n return out", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Refactor to typed, mostly-immutable Python and add minimal tests.\n\n```python\nclass C35258:\n def __init__(self, values): self.values=list(values)\n def mean(self): return sum(self.values)/len(self.values)\n```\nReturn `m48866.py` and `test_m48866.py`.\n\n```python\n# m48866.py\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom typing import Iterable, Tuple\n\n@dataclass(frozen=True)\nclass C35258:\n values: Tuple[float, ...]\n\n @staticmethod\n def create(values: Iterable[float]) -> \"C35258\":\n vals = tuple(float(v) for v in values)\n if not vals: raise ValueError(\"empty\")\n return C35258(vals)\n\n def mean(self) -> float:\n return sum(self.values)/len(self.values)\n```\n\n```python\n# test_m48866.py\nimport pytest\nfrom m48866 import C35258\n\ndef test_mean():\n assert C35258.create([1,2,3]).mean() == 2.0\ndef test_empty():\n with pytest.raises(ValueError):\n C35258.create([])\n```", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Fix a bug and add tests.\n\nFile: uvfl1ju.py\n```python\ndef s75lkoj_(n: int) -> int:\n \"\"\"Sum 1..n inclusive.\"\"\"\n if n < 0:\n raise ValueError(\"n must be non-negative\")\n total = 0\n for k in range(n): # BUG: should include n\n total += k\n return total\n```\n\nReturn unified diffs for uvfl1ju.py and test_uvfl1ju.py (pytest).\n\n*** Begin Patch\n*** Update File: uvfl1ju.py\n@@\n def s75lkoj_(n: int) -> int:\n@@\n total = 0\n- for k in range(n): # BUG: should include n\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_uvfl1ju.py\n+import pytest\n+from uvfl1ju import s75lkoj_\n+\n+def test_zero():\n+ assert s75lkoj_(0) == 0\n+\n+def test_one():\n+ assert s75lkoj_(1) == 1\n+\n+def test_small():\n+ assert s75lkoj_(7) == 28\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ s75lkoj_(-1)\n+\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Optimize while preserving behavior.\n\nFile: nowxyv0.py\n```python\ndef jt0gdo(xs):\n out = []\n for x in xs:\n if x not in out:\n out.append(x)\n return out\n```\n\nRequirements: preserve first-seen order; O(n) average; add types + docstring.\n\n# nowxyv0.py\nfrom __future__ import annotations\nfrom typing import Iterable, List, Set, TypeVar\n\nT = TypeVar(\"T\")\n\ndef jt0gdo(xs: Iterable[T]) -> List[T]:\n \"\"\"Return unique items preserving first-seen order.\"\"\"\n seen: Set[T] = set()\n out: List[T] = []\n for x in xs:\n if x in seen:\n continue\n seen.add(x)\n out.append(x)\n return out", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Refactor to typed, mostly-immutable Python and add minimal tests.\n\n```python\nclass C44166:\n def __init__(self, values): self.values=list(values)\n def mean(self): return sum(self.values)/len(self.values)\n```\nReturn `m18782.py` and `test_m18782.py`.\n\n```python\n# m18782.py\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom typing import Iterable, Tuple\n\n@dataclass(frozen=True)\nclass C44166:\n values: Tuple[float, ...]\n\n @staticmethod\n def create(values: Iterable[float]) -> \"C44166\":\n vals = tuple(float(v) for v in values)\n if not vals: raise ValueError(\"empty\")\n return C44166(vals)\n\n def mean(self) -> float:\n return sum(self.values)/len(self.values)\n```\n\n```python\n# test_m18782.py\nimport pytest\nfrom m18782 import C44166\n\ndef test_mean():\n assert C44166.create([1,2,3]).mean() == 2.0\ndef test_empty():\n with pytest.raises(ValueError):\n C44166.create([])\n```", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Fix a bug and add tests.\n\nFile: xlb3d9hdq.py\n```python\ndef blzbup(n: int) -> int:\n \"\"\"Sum 1..n inclusive.\"\"\"\n if n < 0:\n raise ValueError(\"n must be non-negative\")\n total = 0\n for k in range(n): # BUG: should include n\n total += k\n return total\n```\n\nReturn unified diffs for xlb3d9hdq.py and test_xlb3d9hdq.py (pytest).\n\n*** Begin Patch\n*** Update File: xlb3d9hdq.py\n@@\n def blzbup(n: int) -> int:\n@@\n total = 0\n- for k in range(n): # BUG: should include n\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_xlb3d9hdq.py\n+import pytest\n+from xlb3d9hdq import blzbup\n+\n+def test_zero():\n+ assert blzbup(0) == 0\n+\n+def test_one():\n+ assert blzbup(1) == 1\n+\n+def test_small():\n+ assert blzbup(7) == 28\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ blzbup(-1)\n+\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: Language: YAML\nFramework/tooling: Terraform\nDomain: job scheduler\nLogic challenge: stale cache invalidation\nTask type: concurrency_fix\nDifficulty: hard\n\nReturn a rigorous engineering answer:\n- identify the hidden root cause or logical failure\n- present the corrected implementation\n- add tests that prove the fix\n- list verification commands\n- explain why naive fixes are insufficient when relevant\n\nRepository sketch:\nrepo/\n .github/workflows/ci.yml\n docker-compose.yml\n deploy/\n app.yaml\n\nFocus: Focus on strong structured logic with edge cases, data validation, and concurrency safety.\n\nassistant: Diagnosis:\n- Root cause: the failure around stale cache invalidation is caused by missing validation, weak edge-case handling, or unsafe lifecycle behavior in the current implementation.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```yaml\nname: ci\non: [push, pull_request]\njobs:\n test:\n runs-on: ubuntu-latest\n steps:\n - uses: actions/checkout@v4\n - name: Validate\n run: echo \"validated\"\n```\n\nTests:\n```yaml\n# Verification:\n# - validate syntax\n# - run smoke workflow\n# - fail fast on broken config\n```\n\nVerification:\n- `validate workflow syntax`\n- `run CI smoke job`\n\nEngineering notes:\n- Language: YAML\n- Framework/tooling: Terraform\n- Stack context: Next.js, Node.js, Prisma, PostgreSQL, Playwright, Docker\n- Domain: job scheduler\n- Task type: concurrency_fix\n- Difficulty: hard\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "Create a comprehensive test plan and automated tests for A/B experimentation in a document processing product.\nTarget platform: backend (Go).\nRequirements: unit/integration tests, edge cases, load tests strategy, and CI gates.\nConstraints: must include documentation/comments, must be easy to extend, must be secure-by-default, must be production-ready.\nDifficulty: easy. Assume strict latency budget (p95 < 200ms).\n\nOutput: engineering-grade answer with edge cases covered.\nDeliverable: test plan + automation guidance.\n\n**Unit tests**\n- Validation: malformed payloads rejected with correct codes.\n- AuthZ: tenant boundary enforced.\n- Idempotency: replay returns same response; conflicting reuse yields 409.\n\n**Integration tests**\n- DB transaction behavior; unique constraints.\n- Cache behavior: correctness under concurrent requests.\n\n**Load tests**\n- 10k RPS target: measure p95 latency, error rate, saturation.\n\n**CI gates**\n- Lint + typecheck + unit tests required.\n- Coverage threshold for critical modules.\n- Block merge on flaky test detection.\n\n\nChecks: input validation, tests, and safe defaults included.", "source": "WithinUsAI/GOD_Coder_100k"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: Project stack: FastAPI, PostgreSQL, Redis, Celery, pytest, Docker\nLanguage: Java\nDependency challenge: stale cache invalidation\nTask type: lockfile_repair\nDifficulty: medium\n\nFix this as a senior engineer.\nRequired:\n- identify the version or compatibility failure mode\n- produce the corrected config/code/build patch\n- explain rollback-safe migration notes\n- add regression tests or reproducibility checks\n- include concrete verification commands\n\nRepository sketch:\nrepo/\n src/main/java/com/acme/App.java\n src/main/java/com/acme/Service.java\n src/test/java/com/acme/AppTest.java\n pom.xml\n\nFocus: Focus on versioning, migrations, lockfiles, runtime compatibility, and secure dependency handling.\n\nassistant: Diagnosis:\n- Root cause: the issue around stale cache invalidation is a dependency, migration, or runtime-compatibility mismatch that needs a rollback-safe patch.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```java\nimport java.util.HashMap;\nimport java.util.Map;\n\npublic final class RequestHandler {\n public static Map handleRequest(Map payload) {\n Map clean = new HashMap<>();\n for (Map.Entry entry : payload.entrySet()) {\n if (entry.getValue() != null) clean.put(entry.getKey().trim(), entry.getValue());\n }\n if (!clean.containsKey(\"id\")) throw new IllegalArgumentException(\"missing id\");\n return Map.of(\"ok\", true, \"data\", clean);\n }\n}\n```\n\nTests:\n```java\nimport static org.junit.jupiter.api.Assertions.*;\nimport java.util.Map;\nimport org.junit.jupiter.api.Test;\n\nclass RequestHandlerTest {\n @Test\n void requiresId() {\n assertThrows(IllegalArgumentException.class, () -> RequestHandler.handleRequest(Map.of(\"name\", \"x\")));\n }\n}\n```\n\nVerification:\n- `./gradlew test`\n- `mvn test`\n\nEngineering notes:\n- Language: Java\n- Framework/tooling: Hibernate\n- Stack context: FastAPI, PostgreSQL, Redis, Celery, pytest, Docker\n- Domain: document processing API\n- Task type: lockfile_repair\n- Difficulty: medium\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "Task type: query_optimizer\nScenario: streaming ETL\nDomain focus: fault injection & chaos engineering\nPrimary language: typescript\nDifficulty: expert+\nScale/SLO: 10k RPS peak\nComponent: component_hvcclltc\nConstraints: explicit contracts and invariants, include performance model and limits, avoid data races and undefined behavior, assume adversarial inputs; validate everything, include deterministic replay plan\nAssume partial data corruption; include scrubbing strategy.\nDeliverable: Design a cost-based optimizer slice: logical rules, physical operators, and cost model. Include regression tests and query-plan explain examples.\n\nOutput: elite engineering answer optimized for correctness, performance, and operability.\n**Contract**\n- Inputs validated at the boundary; explicit error taxonomy.\n- Idempotency for side effects via request_id; deterministic replay.\n- Backward compatibility: additive changes by default; versioned breaking changes.\n**Invariants**\n- Liveness: under bounded faults and stable network, progress occurs.\n- Safety: state transitions preserve invariants; no partial commit leaks.\n- Isolation: tenant boundary enforced; no cross-tenant reads/writes.\n**Failure modes & recovery**\n- Data corruption: checksums + scrubber; quarantine and rebuild from replicas/snapshots.\n- Network partition: minority cannot commit; clients receive retriable errors.\n- Crash during commit: WAL replay completes or transaction aborts; no torn writes.\n**Security posture (defensive)**\n- Threat model: auth/authz, injection, replay/abuse, supply chain.\n- Least privilege; secrets in managed store; audit logs for sensitive ops.\n- Input normalization, parameterized queries, path traversal protections.\n**Verification strategy**\n- Property tests against a pure reference model (state machine).\n- Canary + shadow traffic; invariants checked in production via assertions/metrics.\n- Deterministic simulation with fault injection (crash/partition/latency).\n\n**Snippet**\n```python\n# Minimal cost model skeleton\nfrom dataclasses import dataclass\n\n@dataclass(frozen=True)\nclass Plan:\n op: str\n cost: float\n children: tuple[\"Plan\", ...] = ()\n\ndef choose_best(plans: list[Plan]) -> Plan:\n return min(plans, key=lambda p: p.cost)\n```\n\nExpert+ checks: mechanized invariants (or exhaustive model checking), adversarial fuzzing, and multi-region failure drills.", "source": "WithinUsAI/Omega_Genesis_Coder_100k"} {"text": "Refactor an existing codebase in document processing to support offline-first sync cleanly.\nTarget platform: ML (PyTorch + serving).\nRequirements: propose new modules/layers, dependency boundaries, and migration plan.\nConstraints: must be easy to extend, must include tests, must include type hints where applicable.\nDifficulty: hard. Assume untrusted input; validate everything.\n\nOutput: engineering-grade answer with edge cases covered.\nDeliverable: refactor plan + module boundaries.\n\n**Proposed modules**\n- `domain/` pure business logic (no I/O)\n- `adapters/` DB, cache, external APIs\n- `api/` request/response validation and routing\n- `observability/` logging/metrics/tracing\n- `tests/` unit + integration suites\n\n**Migration plan**\n1. Introduce new interfaces + adapters behind feature flags.\n2. Dual-write or read-compat layer if schema changes.\n3. Incremental cutover; deprecate legacy module.\n\nKey rule: dependencies flow inward; domain has no framework imports.\n\n\nHard-mode checks: concurrency safety, idempotency, and rollback validated; add chaos tests where feasible.", "source": "WithinUsAI/GOD_Coder_100k"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: Repository domain: job scheduler\nPrimary language: YAML\nFramework/tooling: Helm\nReported problem: rate-limit bypass\nTask type: api_endpoint_work\nDifficulty: medium\n\nProduce a complete professional engineering response:\n1. Diagnose the root cause.\n2. Provide the corrected implementation or patch.\n3. Add tests.\n4. Add verification commands.\n5. Note edge cases and any migration or rollback risk.\n\nRepository sketch:\nrepo/\n .github/workflows/ci.yml\n docker-compose.yml\n deploy/\n app.yaml\n\nQuality target:\n- Minimal diff unless redesign is clearly required\n- Production-ready code\n- No placeholders\n- Secure defaults\n- Clear acceptance of failure cases\n\nFocus: Focus on complete implementation quality, patch correctness, tests, and production readiness.\n\nassistant: Diagnosis:\n- Root cause: the failure around rate-limit bypass is caused by missing validation, weak edge-case handling, or unsafe lifecycle behavior in the current implementation.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```yaml\nname: ci\non: [push, pull_request]\njobs:\n test:\n runs-on: ubuntu-latest\n steps:\n - uses: actions/checkout@v4\n - name: Validate\n run: echo \"validated\"\n```\n\nTests:\n```yaml\n# Verification:\n# - validate syntax\n# - run smoke workflow\n# - fail fast on broken config\n```\n\nVerification:\n- `validate workflow syntax`\n- `run CI smoke job`\n\nEngineering notes:\n- Language: YAML\n- Framework/tooling: Helm\n- Stack context: Spring Boot, PostgreSQL, JUnit, Gradle, Docker, GitHub Actions\n- Domain: job scheduler\n- Task type: api_endpoint_work\n- Difficulty: medium\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "Build an elite-grade solution in the domain of gpu compute for scenario: inventory & ordering.\nPrimary language: rust.\nDifficulty: expert.\nConstraints: make the interface contract explicit, avoid undefined behavior and data races, include invariants and failure modes.\nComponent: component_jdjehvo.\nAssume 50k RPS and p99 < 250ms.\nTask: Design an application-level protocol (framing, retries, timeouts, backpressure). Provide client/server skeleton and test vectors.\n\nOutput: production blueprint plus correctness arguments and test strategy.\nOutput: protocol framing + retry policy + client/server skeleton.\n\n**Framing**\n- Length-prefixed: uint32_be length + payload\n- Payload: msgpack/json; include request_id, type, and optional checksum\n\n**Reliability**\n- Retries only for idempotent ops; exponential backoff + jitter.\n- Timeouts: connect, read, overall; enforce max in-flight to provide backpressure.\n\n**Test vectors**\n- Corrupted length / truncated frame rejected\n- Duplicate request_id returns cached response\n- Slowloris protection by read deadlines\n\n\nExpert checks: state-machine reasoning, concurrency stress, and upgrade/rollback validated.", "source": "WithinUsAI/Elite_GOD_Coder_100k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Produce an offline-first self-evolving code assistant architecture named `d9vwj_`.\nMust include: module layout, patch-safety policy, evaluation gates (tests/lint/types), versioned memory index.\n\nArchitecture: `d9vwj_` (offline-first, self-evolving)\n\nModules\n- core/loop.py: evolve → validate → accept/reject (bounded iterations)\n- patching/: diff builder, safe apply, atomic writes, rollback points\n- policy/: allowlist paths, deny globs (.git/, __pycache__/, binaries), patch size caps\n- signals/: parse pytest/ruff/mypy into normalized findings\n- memory/index.jsonl: append-only snapshots (hashes, metrics, rationale)\n\nSafety gates\n- refuse path traversal/symlink escapes; never edit binaries\n- accept only if tests/lint/types stay green or improve", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Refactor to typed, mostly-immutable Python and add minimal tests.\n\n```python\nclass C90214:\n def __init__(self, values): self.values=list(values)\n def mean(self): return sum(self.values)/len(self.values)\n```\nReturn `m68478.py` and `test_m68478.py`.\n\n```python\n# m68478.py\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom typing import Iterable, Tuple\n\n@dataclass(frozen=True)\nclass C90214:\n values: Tuple[float, ...]\n\n @staticmethod\n def create(values: Iterable[float]) -> \"C90214\":\n vals = tuple(float(v) for v in values)\n if not vals: raise ValueError(\"empty\")\n return C90214(vals)\n\n def mean(self) -> float:\n return sum(self.values)/len(self.values)\n```\n\n```python\n# test_m68478.py\nimport pytest\nfrom m68478 import C90214\n\ndef test_mean():\n assert C90214.create([1,2,3]).mean() == 2.0\ndef test_empty():\n with pytest.raises(ValueError):\n C90214.create([])\n```", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Fix a bug and add tests.\n\nFile: ovmuoj4t.py\n```python\ndef bt_v22xh9(n: int) -> int:\n \"\"\"Sum 1..n inclusive.\"\"\"\n if n < 0:\n raise ValueError(\"n must be non-negative\")\n total = 0\n for k in range(n): # BUG: should include n\n total += k\n return total\n```\n\nReturn unified diffs for ovmuoj4t.py and test_ovmuoj4t.py (pytest).\n\n*** Begin Patch\n*** Update File: ovmuoj4t.py\n@@\n def bt_v22xh9(n: int) -> int:\n@@\n total = 0\n- for k in range(n): # BUG: should include n\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_ovmuoj4t.py\n+import pytest\n+from ovmuoj4t import bt_v22xh9\n+\n+def test_zero():\n+ assert bt_v22xh9(0) == 0\n+\n+def test_one():\n+ assert bt_v22xh9(1) == 1\n+\n+def test_small():\n+ assert bt_v22xh9(7) == 28\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ bt_v22xh9(-1)\n+\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: Project domain: artifact registry\nImplementation stack: Spring Boot, PostgreSQL, JUnit, Gradle, Docker, GitHub Actions\nSoftware delivery problem: multi-tenant access leak\nTask type: release_engineering_fix\nDifficulty: hard\n\nReturn a complete delivery-grade response with:\n- diagnosis or design reasoning\n- implementation\n- test plan or tests\n- rollout plan\n- rollback or compatibility note\n- verification commands\n\nRepository sketch:\nrepo/\n src/\n api.ts\n service.ts\n schema.ts\n tests/\n api.test.ts\n package.json\n\nFocus: Focus on shipping production software with rollout safety, acceptance criteria, telemetry, and maintenance quality.\n\nassistant: Diagnosis:\n- Root cause or delivery blocker: multi-tenant access leak needs both implementation work and a safe shipping plan.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```ts\ntype Payload = Record;\n\nexport function normalizePayload(payload: Payload): Payload {\n if (!payload || typeof payload !== \"object\" || Array.isArray(payload)) {\n throw new TypeError(\"payload must be a plain object\");\n }\n return Object.fromEntries(\n Object.entries(payload)\n .filter(([, value]) => value !== null && value !== undefined)\n .map(([key, value]) => [String(key).trim(), value])\n );\n}\n\nexport function handleMultiTenantAccessLeak(payload: Payload) {\n const clean = normalizePayload(payload);\n if (!(\"id\" in clean)) {\n return { ok: false, data: {}, error: \"missing id\" };\n }\n return { ok: true, data: clean, error: null };\n}\n```\n\nTests:\n```ts\nimport { describe, it, expect } from \"vitest\";\nimport { handleMultiTenantAccessLeak } from \"../src/service\";\n\ndescribe(\"handler\", () => {\n it(\"accepts valid input\", () => {\n expect(handleMultiTenantAccessLeak({ id: 7, name: \"ok\", unused: null })).toEqual({\n ok: true,\n data: { id: 7, name: \"ok\" },\n error: null\n });\n });\n\n it(\"rejects missing id\", () => {\n expect(handleMultiTenantAccessLeak({ name: \"x\" }).error).toMatch(/missing id/);\n });\n});\n```\n\nVerification:\n- `npm test`\n- `npm run typecheck`\n- `npm run lint`\n\nEngineering notes:\n- Language: TypeScript\n- Framework/tooling: Prisma\n- Stack context: Spring Boot, PostgreSQL, JUnit, Gradle, Docker, GitHub Actions\n- Domain: artifact registry\n- Task type: release_engineering_fix\n- Difficulty: hard\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "Refactor an existing codebase in customer support to support analytics pipeline cleanly.\nTarget platform: web (React + TypeScript).\nRequirements: propose new modules/layers, dependency boundaries, and migration plan.\nConstraints: must be production-ready, must be easy to extend, must include clear error handling, must include documentation/comments, must be observable (logs/metrics/traces).\nDifficulty: hard. Assume strict latency budget (p95 < 200ms).\n\nOutput: production-oriented blueprint with code where appropriate.\nDeliverable: refactor plan + module boundaries.\n\n**Proposed modules**\n- `domain/` pure business logic (no I/O)\n- `adapters/` DB, cache, external APIs\n- `api/` request/response validation and routing\n- `observability/` logging/metrics/tracing\n- `tests/` unit + integration suites\n\n**Migration plan**\n1. Introduce new interfaces + adapters behind feature flags.\n2. Dual-write or read-compat layer if schema changes.\n3. Incremental cutover; deprecate legacy module.\n\nKey rule: dependencies flow inward; domain has no framework imports.\n\n\nHard-mode checks: concurrency safety, idempotency, and rollback validated; add chaos tests where feasible.", "source": "WithinUsAI/GOD_Coder_100k"} {"text": "Refactor to typed, mostly-immutable Python and add minimal tests.\n\n```python\nclass C04410:\n def __init__(self, values): self.values=list(values)\n def mean(self): return sum(self.values)/len(self.values)\n```\nReturn `m69570.py` and `test_m69570.py`.\n\n```python\n# m69570.py\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom typing import Iterable, Tuple\n\n@dataclass(frozen=True)\nclass C04410:\n values: Tuple[float, ...]\n\n @staticmethod\n def create(values: Iterable[float]) -> \"C04410\":\n vals = tuple(float(v) for v in values)\n if not vals: raise ValueError(\"empty\")\n return C04410(vals)\n\n def mean(self) -> float:\n return sum(self.values)/len(self.values)\n```\n\n```python\n# test_m69570.py\nimport pytest\nfrom m69570 import C04410\n\ndef test_mean():\n assert C04410.create([1,2,3]).mean() == 2.0\ndef test_empty():\n with pytest.raises(ValueError):\n C04410.create([])\n```", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Refactor to typed, mostly-immutable Python and add minimal tests.\n\n```python\nclass C98165:\n def __init__(self, values): self.values=list(values)\n def mean(self): return sum(self.values)/len(self.values)\n```\nReturn `m53705.py` and `test_m53705.py`.\n\n```python\n# m53705.py\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom typing import Iterable, Tuple\n\n@dataclass(frozen=True)\nclass C98165:\n values: Tuple[float, ...]\n\n @staticmethod\n def create(values: Iterable[float]) -> \"C98165\":\n vals = tuple(float(v) for v in values)\n if not vals: raise ValueError(\"empty\")\n return C98165(vals)\n\n def mean(self) -> float:\n return sum(self.values)/len(self.values)\n```\n\n```python\n# test_m53705.py\nimport pytest\nfrom m53705 import C98165\n\ndef test_mean():\n assert C98165.create([1,2,3]).mean() == 2.0\ndef test_empty():\n with pytest.raises(ValueError):\n C98165.create([])\n```", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: Language: Bash\nFramework/tooling: jq\nDomain: search service\nLogic challenge: S3-compatible upload inconsistency\nTask type: multi_service_security_patch\nDifficulty: expert\n\nReturn a rigorous engineering answer:\n- identify the hidden root cause or logical failure\n- present the corrected implementation\n- add tests that prove the fix\n- list verification commands\n- explain why naive fixes are insufficient when relevant\n\nRepository sketch:\nrepo/\n scripts/\n run.sh\n deploy.sh\n tests/\n smoke.sh\n\nFocus: Focus on staff-level problem solving with multi-file patches, rollout implications, performance and security tradeoffs.\n\nassistant: Diagnosis:\n- Staff-level diagnosis: S3-compatible upload inconsistency impacts correctness, operability, and future maintenance, so the fix must be minimal where possible but complete where necessary.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```bash\n#!/usr/bin/env bash\nset -euo pipefail\n\ninput=\"${1:-}\"\nif [[ -z \"$input\" ]]; then\n echo \"missing input\" >&2\n exit 1\nfi\n\nprintf '%s\n' \"$input\" | tr -d '\r'\n```\n\nTests:\n```bash\noutput=\"$(bash scripts/run.sh \"abc\")\"\ntest \"$output\" = \"abc\"\n```\n\nVerification:\n- `bash tests/smoke.sh`\n- `shellcheck scripts/*.sh`\n\nEngineering notes:\n- Language: Bash\n- Framework/tooling: jq\n- Stack context: Airflow, dbt, DuckDB, MinIO, pytest\n- Domain: search service\n- Task type: multi_service_security_patch\n- Difficulty: expert\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "Build a data pipeline for a customer support product around rate limiting.\nTarget platform: data (SQL + Python).\nRequirements: schema, ingestion, validation, backfills, and tests.\nConstraints: must be observable (logs/metrics/traces), must be performant under load, must be secure-by-default, must be easy to extend, must be production-ready.\nDifficulty: medium. Assume untrusted input; validate everything.\n\nOutput: design + implementation guidance suitable for shipping.\nDeliverable: schema + ingestion + validation + backfill strategy.\n\n**Schema (example)**\n- events(event_id TEXT PK, tenant_id TEXT, ts TIMESTAMP, type TEXT, payload JSONB)\n\n**Ingestion**\n- Write to raw table first; validate; then materialize to curated tables.\n- Idempotency by event_id; enforce uniqueness.\n\n**Validation**\n- Reject missing tenant_id/type/ts.\n- Quarantine bad records with reason.\n\n**Backfills**\n- Re-run deterministic transforms from raw → curated.\n- Version transformations; store transform_version with outputs.\n\n**Tests**\n- Unit tests for validators and transforms.\n- Integration test: sample raw batch produces expected curated rows.\n\n\nChecks: input validation, tests, and safe defaults included.", "source": "WithinUsAI/GOD_Coder_100k"} {"text": "Fix a subtle bug in a Python module used for ETL pipelines.\nRequirements: explain root cause briefly, provide corrected code, and add regression tests.\nConstraints: must avoid global state, must handle Windows paths safely, must be streaming-friendly.\nDifficulty: easy. Include a small CLI example if relevant.\n\nDeliverable: corrected code and verification tests.\n```python\nfrom __future__ import annotations\n\nfrom dataclasses import dataclass\nfrom pathlib import Path\nfrom typing import Iterable\nimport json\n\n\nclass ValidationError(ValueError):\n \"\"\"Raised when input validation fails.\"\"\"\n\n\ndef safe_join(base: Path, *parts: str) -> Path:\n \"\"\"Join paths while preventing traversal outside base.\"\"\"\n b = base.resolve()\n p = (b / Path(*parts)).resolve()\n if p != b and b not in p.parents:\n raise ValidationError(f\"unsafe path: {p}\")\n return p\n\n\n@dataclass(frozen=True, slots=True)\nclass Record:\n key: str\n value: int\n\n\ndef parse_jsonl(lines: Iterable[str]) -> list[Record]:\n out: list[Record] = []\n for idx, line in enumerate(lines, 1):\n s = line.strip()\n if not s:\n continue\n try:\n obj = json.loads(s)\n except json.JSONDecodeError as e:\n raise ValidationError(f\"line {idx}: invalid json\") from e\n if not isinstance(obj, dict):\n raise ValidationError(f\"line {idx}: expected object\")\n key = obj.get(\"key\")\n val = obj.get(\"value\")\n if not isinstance(key, str) or not key:\n raise ValidationError(f\"line {idx}: key must be non-empty str\")\n if not isinstance(val, int):\n raise ValidationError(f\"line {idx}: value must be int\")\n out.append(Record(key, val))\n return out\n\n\ndef write_jsonl(base: Path, rel: str, records: Iterable[Record]) -> Path:\n base.mkdir(parents=True, exist_ok=True)\n dst = safe_join(base, rel)\n dst.parent.mkdir(parents=True, exist_ok=True)\n with dst.open(\"w\", encoding=\"utf-8\", newline=\"\\n\") as f:\n for r in records:\n f.write(json.dumps({\"key\": r.key, \"value\": r.value}, ensure_ascii=False) + \"\\n\")\n return dst\n```\n\n```python\n# tests (pytest-style)\nimport json\nfrom pathlib import Path\nimport pytest\nfrom module_under_test import ValidationError, Record, parse_jsonl, write_jsonl\n\ndef test_parse_ok():\n lines = [json.dumps({\"key\":\"a\",\"value\":1}), json.dumps({\"key\":\"b\",\"value\":2})]\n assert parse_jsonl(lines) == [Record(\"a\",1), Record(\"b\",2)]\n\ndef test_parse_rejects_bad_json():\n with pytest.raises(ValidationError):\n parse_jsonl([\"{not json}\"])\n\ndef test_safe_join_blocks_traversal(tmp_path: Path):\n with pytest.raises(ValidationError):\n write_jsonl(tmp_path, \"../x.jsonl\", [Record(\"a\",1)])\n```", "source": "WithinUsAI/python_GOD_coder_100k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Fix a bug and add tests.\n\nFile: v2_i3j4.py\n```python\ndef n5wf3_gw(n: int) -> int:\n \"\"\"Sum 1..n inclusive.\"\"\"\n if n < 0:\n raise ValueError(\"n must be non-negative\")\n total = 0\n for k in range(n): # BUG: should include n\n total += k\n return total\n```\n\nReturn unified diffs for v2_i3j4.py and test_v2_i3j4.py (pytest).\n\n*** Begin Patch\n*** Update File: v2_i3j4.py\n@@\n def n5wf3_gw(n: int) -> int:\n@@\n total = 0\n- for k in range(n): # BUG: should include n\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_v2_i3j4.py\n+import pytest\n+from v2_i3j4 import n5wf3_gw\n+\n+def test_zero():\n+ assert n5wf3_gw(0) == 0\n+\n+def test_one():\n+ assert n5wf3_gw(1) == 1\n+\n+def test_small():\n+ assert n5wf3_gw(7) == 28\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ n5wf3_gw(-1)\n+\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Refactor a Python module used for caching layer into a clean, extensible design.\nRequirements: outline the new architecture briefly, then provide the refactored code and tests.\nConstraints: must be easy to extend, must include tests.\nDifficulty: hard. Support both Windows and POSIX paths correctly.\n\nDeliverable: API + reference implementation + tests.\nArchitecture:\n- Public facade class coordinating concerns (parsing, validation, persistence)\n- Small pure functions for testability\n- No global state; dependency injection for filesystem I/O\n\n```python\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom pathlib import Path\nfrom typing import Protocol, Iterable\nimport json\n\nclass Store(Protocol):\n def write_text(self, path: Path, data: str) -> None: ...\n\nclass FSStore:\n def write_text(self, path: Path, data: str) -> None:\n path.parent.mkdir(parents=True, exist_ok=True)\n path.write_text(data, encoding=\"utf-8\")\n\n@dataclass(frozen=True, slots=True)\nclass Item:\n name: str\n qty: int\n\ndef parse_items(lines: Iterable[str]) -> list[Item]:\n out: list[Item] = []\n for i, line in enumerate(lines, 1):\n s = line.strip()\n if not s:\n continue\n obj = json.loads(s)\n if not isinstance(obj, dict):\n raise ValueError(f\"line {i}: expected object\")\n name = obj.get(\"name\")\n qty = obj.get(\"qty\")\n if not isinstance(name, str) or not name:\n raise ValueError(f\"line {i}: name must be str\")\n if not isinstance(qty, int) or qty < 0:\n raise ValueError(f\"line {i}: qty must be non-negative int\")\n out.append(Item(name, qty))\n return out\n\nclass InventoryWriter:\n def __init__(self, base_dir: Path, store: Store | None = None) -> None:\n self._base = base_dir\n self._store: Store = store or FSStore()\n\n def write(self, rel_path: str, items: list[Item]) -> Path:\n dst = (self._base / rel_path).resolve()\n base = self._base.resolve()\n if dst != base and base not in dst.parents:\n raise ValueError(\"unsafe path traversal\")\n payload = json.dumps([item.__dict__ for item in items], ensure_ascii=False)\n self._store.write_text(dst, payload)\n return dst\n```\n\n```python\nimport json\nfrom pathlib import Path\nimport pytest\nfrom module_under_test import InventoryWriter, parse_items\n\ndef test_parse_items_valid():\n lines = [json.dumps({\"name\":\"x\",\"qty\":1})]\n assert parse_items(lines)[0].name == \"x\"\n\ndef test_writer_blocks_traversal(tmp_path: Path):\n w = InventoryWriter(tmp_path)\n with pytest.raises(ValueError):\n w.write(\"../evil.json\", [])\n```", "source": "WithinUsAI/python_GOD_coder_100k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Refactor to modern typed Python with immutability and tests.\n\nFile: oybtlu61.py\n```python\nclass Mmm5G9Xs019L:\n def __init__(self, name, values):\n self.name = name\n self.values = list(values)\n def add(self, v):\n self.values.append(v)\n def mean(self):\n s = 0\n for x in self.values:\n s += x\n return s / len(self.values)\n```\n\nReturn full new oybtlu61.py and test_oybtlu61.py.\n\n# oybtlu61.py\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom typing import Iterable, Tuple\n\n@dataclass(frozen=True)\nclass Mmm5G9Xs019L:\n name: str\n values: Tuple[float, ...]\n\n @staticmethod\n def create(name: str, values: Iterable[float]) -> \"Mmm5G9Xs019L\":\n vals = tuple(float(v) for v in values)\n if not vals:\n raise ValueError(\"values must be non-empty\")\n return Mmm5G9Xs019L(name=name, values=vals)\n\n def add(self, v: float) -> \"Mmm5G9Xs019L\":\n return Mmm5G9Xs019L(name=self.name, values=self.values + (float(v),))\n\n def mean(self) -> float:\n return sum(self.values) / len(self.values)\n\n# test_oybtlu61.py\nimport pytest\nfrom oybtlu61 import Mmm5G9Xs019L\n\ndef test_mean_and_add():\n c = Mmm5G9Xs019L.create(\"a\", [1, 2, 3])\n assert c.mean() == 2.0\n assert c.add(5).mean() == (1 + 2 + 3 + 5) / 4\n\ndef test_empty_raises():\n with pytest.raises(ValueError):\n Mmm5G9Xs019L.create(\"x\", [])", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Refactor to modern typed Python with immutability and tests.\n\nFile: q2ncwn6v5.py\n```python\nclass B2H568:\n def __init__(self, name, values):\n self.name = name\n self.values = list(values)\n def add(self, v):\n self.values.append(v)\n def mean(self):\n s = 0\n for x in self.values:\n s += x\n return s / len(self.values)\n```\n\nReturn full new q2ncwn6v5.py and test_q2ncwn6v5.py.\n\n# q2ncwn6v5.py\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom typing import Iterable, Tuple\n\n@dataclass(frozen=True)\nclass B2H568:\n name: str\n values: Tuple[float, ...]\n\n @staticmethod\n def create(name: str, values: Iterable[float]) -> \"B2H568\":\n vals = tuple(float(v) for v in values)\n if not vals:\n raise ValueError(\"values must be non-empty\")\n return B2H568(name=name, values=vals)\n\n def add(self, v: float) -> \"B2H568\":\n return B2H568(name=self.name, values=self.values + (float(v),))\n\n def mean(self) -> float:\n return sum(self.values) / len(self.values)\n\n# test_q2ncwn6v5.py\nimport pytest\nfrom q2ncwn6v5 import B2H568\n\ndef test_mean_and_add():\n c = B2H568.create(\"a\", [1, 2, 3])\n assert c.mean() == 2.0\n assert c.add(5).mean() == (1 + 2 + 3 + 5) / 4\n\ndef test_empty_raises():\n with pytest.raises(ValueError):\n B2H568.create(\"x\", [])", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: System domain: auth service\nStack: Next.js, Node.js, Prisma, PostgreSQL, Playwright, Docker\nCross-layer incident: async cancellation bug\nTask type: cache_consistency_patch\nDifficulty: hard\n\nSolve this as a complete-project engineer.\nOutput must include:\n- root cause across layers\n- final implementation patch\n- tests touching at least two layers\n- deployment or observability note\n- verification commands\n\nRepository sketch:\nrepo/\n .github/workflows/ci.yml\n docker-compose.yml\n deploy/\n app.yaml\n\nFocus: Focus on multi-layer debugging across frontend, backend, database, CI, caching, and deployment.\n\nassistant: Diagnosis:\n- Root cause: async cancellation bug crosses service boundaries, so the fix must align code, contracts, tests, and deployment behavior.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```yaml\nname: ci\non: [push, pull_request]\njobs:\n test:\n runs-on: ubuntu-latest\n steps:\n - uses: actions/checkout@v4\n - name: Validate\n run: echo \"validated\"\n```\n\nTests:\n```yaml\n# Verification:\n# - validate syntax\n# - run smoke workflow\n# - fail fast on broken config\n```\n\nVerification:\n- `validate workflow syntax`\n- `run CI smoke job`\n\nEngineering notes:\n- Language: YAML\n- Framework/tooling: Helm\n- Stack context: Next.js, Node.js, Prisma, PostgreSQL, Playwright, Docker\n- Domain: auth service\n- Task type: cache_consistency_patch\n- Difficulty: hard\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: System domain: reporting engine\nStack: FastAPI, PostgreSQL, Redis, Celery, pytest, Docker\nCross-layer incident: transaction boundary bug\nTask type: deploy_runtime_patch\nDifficulty: hard\n\nSolve this as a complete-project engineer.\nOutput must include:\n- root cause across layers\n- final implementation patch\n- tests touching at least two layers\n- deployment or observability note\n- verification commands\n\nRepository sketch:\nrepo/\n src/main.cpp\n src/service.cpp\n include/service.h\n tests/test_service.cpp\n CMakeLists.txt\n\nFocus: Focus on multi-layer debugging across frontend, backend, database, CI, caching, and deployment.\n\nassistant: Diagnosis:\n- Root cause: transaction boundary bug crosses service boundaries, so the fix must align code, contracts, tests, and deployment behavior.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```cpp\n#include \n#include \n\nusing Payload = std::unordered_map;\n\nPayload normalize_payload(const Payload& in) {\n Payload out;\n for (const auto& [k, v] : in) {\n if (!v.empty()) out[k] = v;\n }\n return out;\n}\n```\n\nTests:\n```cpp\nTEST_CASE(\"normalize_payload filters empty values\") {\n Payload in{{\"id\",\"7\"},{\"name\",\"\"}};\n auto out = normalize_payload(in);\n REQUIRE(out.count(\"id\") == 1);\n REQUIRE(out.count(\"name\") == 0);\n}\n```\n\nVerification:\n- `cmake --build build`\n- `ctest --test-dir build`\n\nEngineering notes:\n- Language: C++\n- Framework/tooling: CMake\n- Stack context: FastAPI, PostgreSQL, Redis, Celery, pytest, Docker\n- Domain: reporting engine\n- Task type: deploy_runtime_patch\n- Difficulty: hard\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Optimize while preserving behavior.\n\nFile: vh2qt1_.py\n```python\ndef l08togvj(xs):\n out = []\n for x in xs:\n if x not in out:\n out.append(x)\n return out\n```\n\nRequirements: preserve first-seen order; O(n) average; add types + docstring.\n\n# vh2qt1_.py\nfrom __future__ import annotations\nfrom typing import Iterable, List, Set, TypeVar\n\nT = TypeVar(\"T\")\n\ndef l08togvj(xs: Iterable[T]) -> List[T]:\n \"\"\"Return unique items preserving first-seen order.\"\"\"\n seen: Set[T] = set()\n out: List[T] = []\n for x in xs:\n if x in seen:\n continue\n seen.add(x)\n out.append(x)\n return out", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Optimize while preserving behavior and order.\n\n```python\ndef f23367(xs):\n out=[]\n for x in xs:\n if x not in out: out.append(x)\n return out\n```\nReturn `m60481.py` with types and O(n) average.\n\n```python\n# m60481.py\nfrom __future__ import annotations\nfrom typing import Iterable, List, Set, TypeVar\nT=TypeVar(\"T\")\n\ndef f23367(xs: Iterable[T]) -> List[T]:\n \"\"\"Unique items preserving first-seen order.\"\"\"\n seen: Set[T]=set()\n out: List[T]=[]\n for x in xs:\n if x in seen: continue\n seen.add(x); out.append(x)\n return out\n```", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: Language: TypeScript\nFramework/tooling: React\nDomain: feature flag service\nLogic challenge: N+1 query explosion\nTask type: multi_file_migration_repair\nDifficulty: expert\n\nReturn a rigorous engineering answer:\n- identify the hidden root cause or logical failure\n- present the corrected implementation\n- add tests that prove the fix\n- list verification commands\n- explain why naive fixes are insufficient when relevant\n\nRepository sketch:\nrepo/\n src/\n api.ts\n service.ts\n schema.ts\n tests/\n api.test.ts\n package.json\n\nFocus: Focus on staff-level problem solving with multi-file patches, rollout implications, performance and security tradeoffs.\n\nassistant: Diagnosis:\n- Staff-level diagnosis: N+1 query explosion impacts correctness, operability, and future maintenance, so the fix must be minimal where possible but complete where necessary.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```ts\ntype Payload = Record;\n\nexport function normalizePayload(payload: Payload): Payload {\n if (!payload || typeof payload !== \"object\" || Array.isArray(payload)) {\n throw new TypeError(\"payload must be a plain object\");\n }\n return Object.fromEntries(\n Object.entries(payload)\n .filter(([, value]) => value !== null && value !== undefined)\n .map(([key, value]) => [String(key).trim(), value])\n );\n}\n\nexport function handleN+1QueryExplosion(payload: Payload) {\n const clean = normalizePayload(payload);\n if (!(\"id\" in clean)) {\n return { ok: false, data: {}, error: \"missing id\" };\n }\n return { ok: true, data: clean, error: null };\n}\n```\n\nTests:\n```ts\nimport { describe, it, expect } from \"vitest\";\nimport { handleN+1QueryExplosion } from \"../src/service\";\n\ndescribe(\"handler\", () => {\n it(\"accepts valid input\", () => {\n expect(handleN+1QueryExplosion({ id: 7, name: \"ok\", unused: null })).toEqual({\n ok: true,\n data: { id: 7, name: \"ok\" },\n error: null\n });\n });\n\n it(\"rejects missing id\", () => {\n expect(handleN+1QueryExplosion({ name: \"x\" }).error).toMatch(/missing id/);\n });\n});\n```\n\nVerification:\n- `npm test`\n- `npm run typecheck`\n- `npm run lint`\n\nEngineering notes:\n- Language: TypeScript\n- Framework/tooling: React\n- Stack context: Spring Boot, PostgreSQL, JUnit, Gradle, Docker, GitHub Actions\n- Domain: feature flag service\n- Task type: multi_file_migration_repair\n- Difficulty: expert\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Fix a bug and add tests.\n\nFile: sg9bekku26rp.py\n```python\ndef qb9v_jasgzpc(n: int) -> int:\n \"\"\"Sum 1..n inclusive.\"\"\"\n if n < 0:\n raise ValueError(\"n must be non-negative\")\n total = 0\n for k in range(n): # BUG: should include n\n total += k\n return total\n```\n\nReturn unified diffs for sg9bekku26rp.py and test_sg9bekku26rp.py (pytest).\n\n*** Begin Patch\n*** Update File: sg9bekku26rp.py\n@@\n def qb9v_jasgzpc(n: int) -> int:\n@@\n total = 0\n- for k in range(n): # BUG: should include n\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_sg9bekku26rp.py\n+import pytest\n+from sg9bekku26rp import qb9v_jasgzpc\n+\n+def test_zero():\n+ assert qb9v_jasgzpc(0) == 0\n+\n+def test_one():\n+ assert qb9v_jasgzpc(1) == 1\n+\n+def test_small():\n+ assert qb9v_jasgzpc(7) == 28\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ qb9v_jasgzpc(-1)\n+\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Refactor a Python module used for validation into a clean, extensible design.\nRequirements: outline the new architecture briefly, then provide the refactored code and tests.\nConstraints: must include docstrings, must avoid global state.\nDifficulty: expert. Provide helpful exceptions with actionable messages.\n\nDeliverable: production-ready reference solution.\nArchitecture:\n- Public facade class coordinating concerns (parsing, validation, persistence)\n- Small pure functions for testability\n- No global state; dependency injection for filesystem I/O\n\n```python\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom pathlib import Path\nfrom typing import Protocol, Iterable\nimport json\n\nclass Store(Protocol):\n def write_text(self, path: Path, data: str) -> None: ...\n\nclass FSStore:\n def write_text(self, path: Path, data: str) -> None:\n path.parent.mkdir(parents=True, exist_ok=True)\n path.write_text(data, encoding=\"utf-8\")\n\n@dataclass(frozen=True, slots=True)\nclass Item:\n name: str\n qty: int\n\ndef parse_items(lines: Iterable[str]) -> list[Item]:\n out: list[Item] = []\n for i, line in enumerate(lines, 1):\n s = line.strip()\n if not s:\n continue\n obj = json.loads(s)\n if not isinstance(obj, dict):\n raise ValueError(f\"line {i}: expected object\")\n name = obj.get(\"name\")\n qty = obj.get(\"qty\")\n if not isinstance(name, str) or not name:\n raise ValueError(f\"line {i}: name must be str\")\n if not isinstance(qty, int) or qty < 0:\n raise ValueError(f\"line {i}: qty must be non-negative int\")\n out.append(Item(name, qty))\n return out\n\nclass InventoryWriter:\n def __init__(self, base_dir: Path, store: Store | None = None) -> None:\n self._base = base_dir\n self._store: Store = store or FSStore()\n\n def write(self, rel_path: str, items: list[Item]) -> Path:\n dst = (self._base / rel_path).resolve()\n base = self._base.resolve()\n if dst != base and base not in dst.parents:\n raise ValueError(\"unsafe path traversal\")\n payload = json.dumps([item.__dict__ for item in items], ensure_ascii=False)\n self._store.write_text(dst, payload)\n return dst\n```\n\n```python\nimport json\nfrom pathlib import Path\nimport pytest\nfrom module_under_test import InventoryWriter, parse_items\n\ndef test_parse_items_valid():\n lines = [json.dumps({\"name\":\"x\",\"qty\":1})]\n assert parse_items(lines)[0].name == \"x\"\n\ndef test_writer_blocks_traversal(tmp_path: Path):\n w = InventoryWriter(tmp_path)\n with pytest.raises(ValueError):\n w.write(\"../evil.json\", [])\n```", "source": "WithinUsAI/python_GOD_coder_100k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Optimize while preserving behavior.\n\nFile: vcv6r6395v6.py\n```python\ndef zs544y115d(xs):\n out = []\n for x in xs:\n if x not in out:\n out.append(x)\n return out\n```\n\nRequirements: preserve first-seen order; O(n) average; add types + docstring.\n\n# vcv6r6395v6.py\nfrom __future__ import annotations\nfrom typing import Iterable, List, Set, TypeVar\n\nT = TypeVar(\"T\")\n\ndef zs544y115d(xs: Iterable[T]) -> List[T]:\n \"\"\"Return unique items preserving first-seen order.\"\"\"\n seen: Set[T] = set()\n out: List[T] = []\n for x in xs:\n if x in seen:\n continue\n seen.add(x)\n out.append(x)\n return out", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Fix a subtle bug in a Python module used for validation.\nRequirements: explain root cause briefly, provide corrected code, and add regression tests.\nConstraints: must handle Windows paths safely, must be memory-efficient, must include tests.\nDifficulty: easy. Avoid quadratic behavior on large inputs.\n\nDeliverable: API + reference implementation + tests.\n```python\nfrom __future__ import annotations\n\nfrom dataclasses import dataclass\nfrom pathlib import Path\nfrom typing import Iterable\nimport json\n\n\nclass ValidationError(ValueError):\n \"\"\"Raised when input validation fails.\"\"\"\n\n\ndef safe_join(base: Path, *parts: str) -> Path:\n \"\"\"Join paths while preventing traversal outside base.\"\"\"\n b = base.resolve()\n p = (b / Path(*parts)).resolve()\n if p != b and b not in p.parents:\n raise ValidationError(f\"unsafe path: {p}\")\n return p\n\n\n@dataclass(frozen=True, slots=True)\nclass Record:\n key: str\n value: int\n\n\ndef parse_jsonl(lines: Iterable[str]) -> list[Record]:\n out: list[Record] = []\n for idx, line in enumerate(lines, 1):\n s = line.strip()\n if not s:\n continue\n try:\n obj = json.loads(s)\n except json.JSONDecodeError as e:\n raise ValidationError(f\"line {idx}: invalid json\") from e\n if not isinstance(obj, dict):\n raise ValidationError(f\"line {idx}: expected object\")\n key = obj.get(\"key\")\n val = obj.get(\"value\")\n if not isinstance(key, str) or not key:\n raise ValidationError(f\"line {idx}: key must be non-empty str\")\n if not isinstance(val, int):\n raise ValidationError(f\"line {idx}: value must be int\")\n out.append(Record(key, val))\n return out\n\n\ndef write_jsonl(base: Path, rel: str, records: Iterable[Record]) -> Path:\n base.mkdir(parents=True, exist_ok=True)\n dst = safe_join(base, rel)\n dst.parent.mkdir(parents=True, exist_ok=True)\n with dst.open(\"w\", encoding=\"utf-8\", newline=\"\\n\") as f:\n for r in records:\n f.write(json.dumps({\"key\": r.key, \"value\": r.value}, ensure_ascii=False) + \"\\n\")\n return dst\n```\n\n```python\n# tests (pytest-style)\nimport json\nfrom pathlib import Path\nimport pytest\nfrom module_under_test import ValidationError, Record, parse_jsonl, write_jsonl\n\ndef test_parse_ok():\n lines = [json.dumps({\"key\":\"a\",\"value\":1}), json.dumps({\"key\":\"b\",\"value\":2})]\n assert parse_jsonl(lines) == [Record(\"a\",1), Record(\"b\",2)]\n\ndef test_parse_rejects_bad_json():\n with pytest.raises(ValidationError):\n parse_jsonl([\"{not json}\"])\n\ndef test_safe_join_blocks_traversal(tmp_path: Path):\n with pytest.raises(ValidationError):\n write_jsonl(tmp_path, \"../x.jsonl\", [Record(\"a\",1)])\n```", "source": "WithinUsAI/python_GOD_coder_100k"} {"text": "Add a clear docstring and type hints to this function:\n\n```python\ndef f69796(s):\n return ''.join(x for x in s if x.isalnum()).lower()\n```\n\n```python\nfrom __future__ import annotations\n\ndef f69796(s: str) -> str:\n \"\"\"Normalize a string: keep only alphanumerics and lowercase the result.\"\"\"\n return \"\".join(ch for ch in s if ch.isalnum()).lower()\n```", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Fix the bug and add pytest tests.\n\n```python\ndef f20049(n: int) -> int:\n # sum 1..n inclusive\n if n < 0: raise ValueError\n total = 0\n for k in range(n): # BUG\n total += k\n return total\n```\nReturn unified diffs for `m60007.py` and `test_m60007.py`.\n\n*** Begin Patch\n*** Update File: m60007.py\n@@\n def f20049(n: int) -> int:\n@@\n- for k in range(n): # BUG\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_m60007.py\n+import pytest\n+from m60007 import f20049\n+\n+def test_small():\n+ assert f20049(7) == 28\n+\n+def test_zero():\n+ assert f20049(0) == 0\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ f20049(-1)\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Build an elite-grade solution in the domain of gpu compute for scenario: rate limiting gateway.\nPrimary language: rust.\nDifficulty: hard.\nConstraints: design for backward compatibility and migrations, include tests or verification strategy, document performance characteristics, include invariants and failure modes.\nComponent: component_duetnsx.\nAssume strict auditability and replayable history.\nTask: Define a small DSL, implement tokenizer/parser, IR, and a codegen or interpreter. Include tests and complexity notes.\n\nOutput: rigorous solution with invariants, failure modes, and performance notes.\nOutput: DSL + parser + IR + interpreter/codegen + tests.\n\n**DSL**\n- Expressions: integers, identifiers, `+ - * /`, let-binding: `let x = expr in expr`\n- Example: `let x = 2+3 in x*10`\n\n**Pipeline**\n1. Tokenize\n2. Parse into AST\n3. Lower into IR (stack ops) or interpret AST directly\n\n**Reference (Rust-style outline)**\n- `enum Expr { Int(i64), Var(String), Bin(Op, Box, Box), Let(String, Box, Box) }`\n- Parser: Pratt or recursive descent.\n\n**Tests**\n- Golden tests for parse trees.\n- Property: pretty-print(parse(x)) round-trips for a corpus.\n- Eval tests for precedence and scoping.\n\n\nHard checks: failure injection tests and performance regressions gated.", "source": "WithinUsAI/Elite_GOD_Coder_100k"} {"text": "Build an elite-grade solution in the domain of high-performance services for scenario: multi-tenant SaaS.\nPrimary language: python.\nDifficulty: medium.\nConstraints: design for backward compatibility and migrations, avoid undefined behavior and data races, include tests or verification strategy, assume untrusted inputs; validate and sanitize, document performance characteristics.\nComponent: component_acipghd.\nAssume cold-start and memory limits are tight.\nTask: Implement or outline a storage/indexing subsystem (LSM/B-Tree, WAL, snapshots). Include transaction/consistency considerations and benchmark plan.\n\nOutput: production blueprint plus correctness arguments and test strategy.\nOutput: storage design + WAL + compaction + benchmarks.\n\n**Design**\n- WAL (append-only) for durability; fsync policy configurable.\n- Memtable (in-memory) → flush to immutable SSTables.\n- LSM compaction tiers; bloom filters per SSTable for point-lookups.\n- Manifest tracks SSTable set; atomic pointer swap on updates.\n\n**Correctness**\n- Crash recovery: replay WAL to rebuild memtable; manifest ensures last consistent set.\n- Reads: merge memtable + SSTables newest→oldest; tombstones override older values.\n\n**Bench plan**\n- Workloads: write-heavy, read-heavy, mixed; measure p50/p95 latency and write amplification.\n- Track compaction debt and space amplification.\n\n**Test plan**\n- Fuzz crash points: kill after WAL append / after manifest update; verify invariants on restart.\n\n\nChecks: boundary validation and deterministic behavior verified.", "source": "WithinUsAI/Elite_GOD_Coder_100k"} {"text": "Fix the bug and add pytest tests.\n\n```python\ndef f05028(n: int) -> int:\n # sum 1..n inclusive\n if n < 0: raise ValueError\n total = 0\n for k in range(n): # BUG\n total += k\n return total\n```\nReturn unified diffs for `m15004.py` and `test_m15004.py`.\n\n*** Begin Patch\n*** Update File: m15004.py\n@@\n def f05028(n: int) -> int:\n@@\n- for k in range(n): # BUG\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_m15004.py\n+import pytest\n+from m15004 import f05028\n+\n+def test_small():\n+ assert f05028(7) == 28\n+\n+def test_zero():\n+ assert f05028(0) == 0\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ f05028(-1)\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: Repository domain: repo automation\nPrimary language: SQL\nFramework/tooling: MySQL\nReported problem: partial checkpoint corruption\nTask type: code_review_fix\nDifficulty: hard\n\nProduce a complete professional engineering response:\n1. Diagnose the root cause.\n2. Provide the corrected implementation or patch.\n3. Add tests.\n4. Add verification commands.\n5. Note edge cases and any migration or rollback risk.\n\nRepository sketch:\nrepo/\n migrations/\n 001_init.sql\n 002_add_index.sql\n queries/\n report.sql\n tests/\n report_cases.md\n\nQuality target:\n- Minimal diff unless redesign is clearly required\n- Production-ready code\n- No placeholders\n- Secure defaults\n- Clear acceptance of failure cases\n\nFocus: Focus on complete implementation quality, patch correctness, tests, and production readiness.\n\nassistant: Diagnosis:\n- Root cause: the failure around partial checkpoint corruption is caused by missing validation, weak edge-case handling, or unsafe lifecycle behavior in the current implementation.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```sql\nWITH ranked AS (\n SELECT\n user_id,\n created_at,\n amount,\n ROW_NUMBER() OVER (PARTITION BY user_id ORDER BY created_at DESC, id DESC) AS rn\n FROM orders\n)\nSELECT user_id, created_at, amount\nFROM ranked\nWHERE rn = 1;\n```\n\nTests:\n```sql\n-- Correctness checks:\n-- 1) multiple rows per user\n-- 2) identical timestamps require deterministic tie-breaker\n-- 3) null values handled by business rules\n```\n\nVerification:\n- `run migration checks`\n- `run query correctness cases`\n\nEngineering notes:\n- Language: SQL\n- Framework/tooling: MySQL\n- Stack context: Go, Gin, PostgreSQL, gRPC, Prometheus, Docker\n- Domain: repo automation\n- Task type: code_review_fix\n- Difficulty: hard\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: System domain: job scheduler\nStack: GitHub Actions, Docker Compose, Kubernetes, Terraform\nCross-layer incident: N+1 query explosion\nTask type: auth_session_repair\nDifficulty: hard\n\nSolve this as a complete-project engineer.\nOutput must include:\n- root cause across layers\n- final implementation patch\n- tests touching at least two layers\n- deployment or observability note\n- verification commands\n\nRepository sketch:\nrepo/\n src/main.cpp\n src/service.cpp\n include/service.h\n tests/test_service.cpp\n CMakeLists.txt\n\nFocus: Focus on multi-layer debugging across frontend, backend, database, CI, caching, and deployment.\n\nassistant: Diagnosis:\n- Root cause: N+1 query explosion crosses service boundaries, so the fix must align code, contracts, tests, and deployment behavior.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```cpp\n#include \n#include \n\nusing Payload = std::unordered_map;\n\nPayload normalize_payload(const Payload& in) {\n Payload out;\n for (const auto& [k, v] : in) {\n if (!v.empty()) out[k] = v;\n }\n return out;\n}\n```\n\nTests:\n```cpp\nTEST_CASE(\"normalize_payload filters empty values\") {\n Payload in{{\"id\",\"7\"},{\"name\",\"\"}};\n auto out = normalize_payload(in);\n REQUIRE(out.count(\"id\") == 1);\n REQUIRE(out.count(\"name\") == 0);\n}\n```\n\nVerification:\n- `cmake --build build`\n- `ctest --test-dir build`\n\nEngineering notes:\n- Language: C++\n- Framework/tooling: STL\n- Stack context: GitHub Actions, Docker Compose, Kubernetes, Terraform\n- Domain: job scheduler\n- Task type: auth_session_repair\n- Difficulty: hard\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Refactor to modern typed Python with immutability and tests.\n\nFile: qkl9stio.py\n```python\nclass Kd1Xligrp:\n def __init__(self, name, values):\n self.name = name\n self.values = list(values)\n def add(self, v):\n self.values.append(v)\n def mean(self):\n s = 0\n for x in self.values:\n s += x\n return s / len(self.values)\n```\n\nReturn full new qkl9stio.py and test_qkl9stio.py.\n\n# qkl9stio.py\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom typing import Iterable, Tuple\n\n@dataclass(frozen=True)\nclass Kd1Xligrp:\n name: str\n values: Tuple[float, ...]\n\n @staticmethod\n def create(name: str, values: Iterable[float]) -> \"Kd1Xligrp\":\n vals = tuple(float(v) for v in values)\n if not vals:\n raise ValueError(\"values must be non-empty\")\n return Kd1Xligrp(name=name, values=vals)\n\n def add(self, v: float) -> \"Kd1Xligrp\":\n return Kd1Xligrp(name=self.name, values=self.values + (float(v),))\n\n def mean(self) -> float:\n return sum(self.values) / len(self.values)\n\n# test_qkl9stio.py\nimport pytest\nfrom qkl9stio import Kd1Xligrp\n\ndef test_mean_and_add():\n c = Kd1Xligrp.create(\"a\", [1, 2, 3])\n assert c.mean() == 2.0\n assert c.add(5).mean() == (1 + 2 + 3 + 5) / 4\n\ndef test_empty_raises():\n with pytest.raises(ValueError):\n Kd1Xligrp.create(\"x\", [])", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Fix a bug and add tests.\n\nFile: yegv06.py\n```python\ndef qgvc_0wq6_u(n: int) -> int:\n \"\"\"Sum 1..n inclusive.\"\"\"\n if n < 0:\n raise ValueError(\"n must be non-negative\")\n total = 0\n for k in range(n): # BUG: should include n\n total += k\n return total\n```\n\nReturn unified diffs for yegv06.py and test_yegv06.py (pytest).\n\n*** Begin Patch\n*** Update File: yegv06.py\n@@\n def qgvc_0wq6_u(n: int) -> int:\n@@\n total = 0\n- for k in range(n): # BUG: should include n\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_yegv06.py\n+import pytest\n+from yegv06 import qgvc_0wq6_u\n+\n+def test_zero():\n+ assert qgvc_0wq6_u(0) == 0\n+\n+def test_one():\n+ assert qgvc_0wq6_u(1) == 1\n+\n+def test_small():\n+ assert qgvc_0wq6_u(7) == 28\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ qgvc_0wq6_u(-1)\n+\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Produce an offline-first self-evolving code assistant architecture named `a64affbtnqcp`.\nMust include: module layout, patch-safety policy, evaluation gates (tests/lint/types), versioned memory index.\n\nArchitecture: `a64affbtnqcp` (offline-first, self-evolving)\n\nModules\n- core/loop.py: evolve → validate → accept/reject (bounded iterations)\n- patching/: diff builder, safe apply, atomic writes, rollback points\n- policy/: allowlist paths, deny globs (.git/, __pycache__/, binaries), patch size caps\n- signals/: parse pytest/ruff/mypy into normalized findings\n- memory/index.jsonl: append-only snapshots (hashes, metrics, rationale)\n\nSafety gates\n- refuse path traversal/symlink escapes; never edit binaries\n- accept only if tests/lint/types stay green or improve", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: Repository domain: payments platform\nPrimary language: Go\nFramework/tooling: testify\nReported problem: idempotent retry design\nTask type: feature_delivery\nDifficulty: medium\n\nProduce a complete professional engineering response:\n1. Diagnose the root cause.\n2. Provide the corrected implementation or patch.\n3. Add tests.\n4. Add verification commands.\n5. Note edge cases and any migration or rollback risk.\n\nRepository sketch:\nrepo/\n cmd/server/main.go\n internal/service/service.go\n internal/store/store.go\n internal/api/api.go\n service_test.go\n go.mod\n\nQuality target:\n- Minimal diff unless redesign is clearly required\n- Production-ready code\n- No placeholders\n- Secure defaults\n- Clear acceptance of failure cases\n\nFocus: Focus on complete implementation quality, patch correctness, tests, and production readiness.\n\nassistant: Diagnosis:\n- Root cause: the failure around idempotent retry design is caused by missing validation, weak edge-case handling, or unsafe lifecycle behavior in the current implementation.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```go\npackage service\n\nimport \"fmt\"\n\nfunc NormalizePayload(payload map[string]any) map[string]any {\n\tout := make(map[string]any)\n\tfor k, v := range payload {\n\t\tif v == nil {\n\t\t\tcontinue\n\t\t}\n\t\tout[k] = v\n\t}\n\treturn out\n}\n\nfunc Handle(payload map[string]any) (map[string]any, error) {\n\tclean := NormalizePayload(payload)\n\tif _, ok := clean[\"id\"]; !ok {\n\t\treturn nil, fmt.Errorf(\"missing id\")\n\t}\n\treturn map[string]any{\"ok\": true, \"data\": clean}, nil\n}\n```\n\nTests:\n```go\npackage service\n\nimport \"testing\"\n\nfunc TestHandle(t *testing.T) {\n\tgot, err := Handle(map[string]any{\"id\": 7, \"name\": \"ok\", \"unused\": nil})\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tif got[\"ok\"] != true {\n\t\tt.Fatalf(\"expected ok=true\")\n\t}\n\tif _, err := Handle(map[string]any{\"name\": \"x\"}); err == nil {\n\t\tt.Fatalf(\"expected missing id error\")\n\t}\n}\n```\n\nVerification:\n- `go test ./...`\n- `go vet ./...`\n\nEngineering notes:\n- Language: Go\n- Framework/tooling: testify\n- Stack context: Go, Gin, PostgreSQL, gRPC, Prometheus, Docker\n- Domain: payments platform\n- Task type: feature_delivery\n- Difficulty: medium\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Produce an offline-first self-evolving code assistant architecture named `qrnc_c64vt`.\nMust include: module layout, patch-safety policy, evaluation gates (tests/lint/types), versioned memory index.\n\nArchitecture: `qrnc_c64vt` (offline-first, self-evolving)\n\nModules\n- core/loop.py: evolve → validate → accept/reject (bounded iterations)\n- patching/: diff builder, safe apply, atomic writes, rollback points\n- policy/: allowlist paths, deny globs (.git/, __pycache__/, binaries), patch size caps\n- signals/: parse pytest/ruff/mypy into normalized findings\n- memory/index.jsonl: append-only snapshots (hashes, metrics, rationale)\n\nSafety gates\n- refuse path traversal/symlink escapes; never edit binaries\n- accept only if tests/lint/types stay green or improve", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Produce an offline-first self-evolving code assistant architecture named `e_nwcg7_trjw`.\nMust include: module layout, patch-safety policy, evaluation gates (tests/lint/types), versioned memory index.\n\nArchitecture: `e_nwcg7_trjw` (offline-first, self-evolving)\n\nModules\n- core/loop.py: evolve → validate → accept/reject (bounded iterations)\n- patching/: diff builder, safe apply, atomic writes, rollback points\n- policy/: allowlist paths, deny globs (.git/, __pycache__/, binaries), patch size caps\n- signals/: parse pytest/ruff/mypy into normalized findings\n- memory/index.jsonl: append-only snapshots (hashes, metrics, rationale)\n\nSafety gates\n- refuse path traversal/symlink escapes; never edit binaries\n- accept only if tests/lint/types stay green or improve", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Optimize while preserving behavior.\n\nFile: qtqw2561b28m.py\n```python\ndef ngi18ud_b(xs):\n out = []\n for x in xs:\n if x not in out:\n out.append(x)\n return out\n```\n\nRequirements: preserve first-seen order; O(n) average; add types + docstring.\n\n# qtqw2561b28m.py\nfrom __future__ import annotations\nfrom typing import Iterable, List, Set, TypeVar\n\nT = TypeVar(\"T\")\n\ndef ngi18ud_b(xs: Iterable[T]) -> List[T]:\n \"\"\"Return unique items preserving first-seen order.\"\"\"\n seen: Set[T] = set()\n out: List[T] = []\n for x in xs:\n if x in seen:\n continue\n seen.add(x)\n out.append(x)\n return out", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: Language: Go\nFramework/tooling: Fiber\nDomain: repo automation\nLogic challenge: stale cache invalidation\nTask type: concurrency_fix\nDifficulty: medium\n\nReturn a rigorous engineering answer:\n- identify the hidden root cause or logical failure\n- present the corrected implementation\n- add tests that prove the fix\n- list verification commands\n- explain why naive fixes are insufficient when relevant\n\nRepository sketch:\nrepo/\n cmd/server/main.go\n internal/service/service.go\n internal/store/store.go\n internal/api/api.go\n service_test.go\n go.mod\n\nFocus: Focus on strong structured logic with edge cases, data validation, and concurrency safety.\n\nassistant: Diagnosis:\n- Root cause: the failure around stale cache invalidation is caused by missing validation, weak edge-case handling, or unsafe lifecycle behavior in the current implementation.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```go\npackage service\n\nimport \"fmt\"\n\nfunc NormalizePayload(payload map[string]any) map[string]any {\n\tout := make(map[string]any)\n\tfor k, v := range payload {\n\t\tif v == nil {\n\t\t\tcontinue\n\t\t}\n\t\tout[k] = v\n\t}\n\treturn out\n}\n\nfunc Handle(payload map[string]any) (map[string]any, error) {\n\tclean := NormalizePayload(payload)\n\tif _, ok := clean[\"id\"]; !ok {\n\t\treturn nil, fmt.Errorf(\"missing id\")\n\t}\n\treturn map[string]any{\"ok\": true, \"data\": clean}, nil\n}\n```\n\nTests:\n```go\npackage service\n\nimport \"testing\"\n\nfunc TestHandle(t *testing.T) {\n\tgot, err := Handle(map[string]any{\"id\": 7, \"name\": \"ok\", \"unused\": nil})\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tif got[\"ok\"] != true {\n\t\tt.Fatalf(\"expected ok=true\")\n\t}\n\tif _, err := Handle(map[string]any{\"name\": \"x\"}); err == nil {\n\t\tt.Fatalf(\"expected missing id error\")\n\t}\n}\n```\n\nVerification:\n- `go test ./...`\n- `go vet ./...`\n\nEngineering notes:\n- Language: Go\n- Framework/tooling: Fiber\n- Stack context: Airflow, dbt, DuckDB, MinIO, pytest\n- Domain: repo automation\n- Task type: concurrency_fix\n- Difficulty: medium\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Refactor to modern typed Python with immutability and tests.\n\nFile: iyndq69c.py\n```python\nclass Wwujivca3:\n def __init__(self, name, values):\n self.name = name\n self.values = list(values)\n def add(self, v):\n self.values.append(v)\n def mean(self):\n s = 0\n for x in self.values:\n s += x\n return s / len(self.values)\n```\n\nReturn full new iyndq69c.py and test_iyndq69c.py.\n\n# iyndq69c.py\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom typing import Iterable, Tuple\n\n@dataclass(frozen=True)\nclass Wwujivca3:\n name: str\n values: Tuple[float, ...]\n\n @staticmethod\n def create(name: str, values: Iterable[float]) -> \"Wwujivca3\":\n vals = tuple(float(v) for v in values)\n if not vals:\n raise ValueError(\"values must be non-empty\")\n return Wwujivca3(name=name, values=vals)\n\n def add(self, v: float) -> \"Wwujivca3\":\n return Wwujivca3(name=self.name, values=self.values + (float(v),))\n\n def mean(self) -> float:\n return sum(self.values) / len(self.values)\n\n# test_iyndq69c.py\nimport pytest\nfrom iyndq69c import Wwujivca3\n\ndef test_mean_and_add():\n c = Wwujivca3.create(\"a\", [1, 2, 3])\n assert c.mean() == 2.0\n assert c.add(5).mean() == (1 + 2 + 3 + 5) / 4\n\ndef test_empty_raises():\n with pytest.raises(ValueError):\n Wwujivca3.create(\"x\", [])", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Fix a bug and add tests.\n\nFile: q_u0efwzb.py\n```python\ndef ilwq0pb5e(n: int) -> int:\n \"\"\"Sum 1..n inclusive.\"\"\"\n if n < 0:\n raise ValueError(\"n must be non-negative\")\n total = 0\n for k in range(n): # BUG: should include n\n total += k\n return total\n```\n\nReturn unified diffs for q_u0efwzb.py and test_q_u0efwzb.py (pytest).\n\n*** Begin Patch\n*** Update File: q_u0efwzb.py\n@@\n def ilwq0pb5e(n: int) -> int:\n@@\n total = 0\n- for k in range(n): # BUG: should include n\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_q_u0efwzb.py\n+import pytest\n+from q_u0efwzb import ilwq0pb5e\n+\n+def test_zero():\n+ assert ilwq0pb5e(0) == 0\n+\n+def test_one():\n+ assert ilwq0pb5e(1) == 1\n+\n+def test_small():\n+ assert ilwq0pb5e(7) == 28\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ ilwq0pb5e(-1)\n+\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Fix a bug and add tests.\n\nFile: ou218awh29v1.py\n```python\ndef umujtt0(n: int) -> int:\n \"\"\"Sum 1..n inclusive.\"\"\"\n if n < 0:\n raise ValueError(\"n must be non-negative\")\n total = 0\n for k in range(n): # BUG: should include n\n total += k\n return total\n```\n\nReturn unified diffs for ou218awh29v1.py and test_ou218awh29v1.py (pytest).\n\n*** Begin Patch\n*** Update File: ou218awh29v1.py\n@@\n def umujtt0(n: int) -> int:\n@@\n total = 0\n- for k in range(n): # BUG: should include n\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_ou218awh29v1.py\n+import pytest\n+from ou218awh29v1 import umujtt0\n+\n+def test_zero():\n+ assert umujtt0(0) == 0\n+\n+def test_one():\n+ assert umujtt0(1) == 1\n+\n+def test_small():\n+ assert umujtt0(7) == 28\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ umujtt0(-1)\n+\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Fix a bug and add tests.\n\nFile: nliax2bl.py\n```python\ndef c08sygk3(n: int) -> int:\n \"\"\"Sum 1..n inclusive.\"\"\"\n if n < 0:\n raise ValueError(\"n must be non-negative\")\n total = 0\n for k in range(n): # BUG: should include n\n total += k\n return total\n```\n\nReturn unified diffs for nliax2bl.py and test_nliax2bl.py (pytest).\n\n*** Begin Patch\n*** Update File: nliax2bl.py\n@@\n def c08sygk3(n: int) -> int:\n@@\n total = 0\n- for k in range(n): # BUG: should include n\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_nliax2bl.py\n+import pytest\n+from nliax2bl import c08sygk3\n+\n+def test_zero():\n+ assert c08sygk3(0) == 0\n+\n+def test_one():\n+ assert c08sygk3(1) == 1\n+\n+def test_small():\n+ assert c08sygk3(7) == 28\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ c08sygk3(-1)\n+\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Build an elite-grade solution in the domain of compilers for scenario: time-series metrics.\nPrimary language: rust.\nDifficulty: medium.\nConstraints: provide rollout and rollback guidance, design for backward compatibility and migrations, assume untrusted inputs; validate and sanitize, make the interface contract explicit, avoid undefined behavior and data races.\nComponent: component_axtmwfr.\nAssume strict auditability and replayable history.\nTask: Implement a concurrency primitive or subsystem (lock-free queue, thread pool, async runtime component). Explain memory ordering and correctness arguments; include stress tests.\n\nOutput: production blueprint plus correctness arguments and test strategy.\nOutput: correctness-focused concurrency primitive + stress tests.\n\n**Primitive**\n- Bounded MPMC queue with backpressure (blocking push/pop) OR lock-free SPSC ring buffer.\n\n**Correctness notes**\n- For lock-free: use acquire/release semantics on head/tail indices.\n- Avoid ABA by monotonic counters; ring index = counter % capacity.\n\n**Stress tests**\n- Multi-thread producers/consumers; assert item multiset preserved.\n- Use time-bounded randomized schedules; detect deadlocks.\n\n\nChecks: boundary validation and deterministic behavior verified.", "source": "WithinUsAI/Elite_GOD_Coder_100k"} {"text": "Debug and fix a subtle production bug related to idempotent payments in a education service.\nTarget platform: backend (Node.js).\nRequirements: identify root cause, provide patch, and add regression tests.\nConstraints: must include tests, must be observable (logs/metrics/traces), must be performant under load.\nDifficulty: easy. Include rollback strategy.\n\nOutput: actionable implementation and verification artifacts.\nDeliverable: production-grade reference implementation (FastAPI) + tests.\n\n```python\n# app.py\nfrom __future__ import annotations\n\nimport hashlib\nimport json\nfrom dataclasses import dataclass\nfrom datetime import datetime, timezone\nfrom typing import Any, Optional\n\nfrom fastapi import FastAPI, Header, HTTPException\nfrom pydantic import BaseModel, Field\n\napp = FastAPI(title=\"Idempotent API\")\n\nclass CreateReq(BaseModel):\n tenant_id: str = Field(min_length=1)\n amount_cents: int = Field(ge=0)\n currency: str = Field(min_length=3, max_length=3)\n\nclass CreateResp(BaseModel):\n id: str\n created_at: str\n echo: CreateReq\n\n@dataclass\nclass _IdempoEntry:\n request_hash: str\n response_json: str\n\n# In production: Postgres table with UNIQUE(tenant_id, key)\n_IDEMPO: dict[tuple[str, str], _IdempoEntry] = {}\n\ndef _hash_req(req: CreateReq) -> str:\n raw = req.model_dump_json()\n return hashlib.sha256(raw.encode(\"utf-8\")).hexdigest()\n\n@app.post(\"/v1/payments\", response_model=CreateResp)\ndef create_payment(\n req: CreateReq,\n idempotency_key: Optional[str] = Header(default=None, alias=\"Idempotency-Key\"),\n) -> Any:\n if not idempotency_key:\n raise HTTPException(status_code=400, detail=\"Missing Idempotency-Key\")\n if len(idempotency_key) > 128:\n raise HTTPException(status_code=400, detail=\"Idempotency-Key too long\")\n\n key = (req.tenant_id, idempotency_key)\n rh = _hash_req(req)\n\n existing = _IDEMPO.get(key)\n if existing:\n if existing.request_hash != rh:\n raise HTTPException(status_code=409, detail=\"Idempotency-Key reuse with different payload\")\n return json.loads(existing.response_json)\n\n # Create new payment (stubbed)\n pid = hashlib.md5(f\"{req.tenant_id}:{idempotency_key}\".encode()).hexdigest()\n resp = CreateResp(\n id=pid,\n created_at=datetime.now(timezone.utc).isoformat(),\n echo=req,\n )\n _IDEMPO[key] = _IdempoEntry(request_hash=rh, response_json=resp.model_dump_json())\n return resp\n```\n\n```python\n# test_app.py (pytest)\nfrom fastapi.testclient import TestClient\nfrom app import app\n\nclient = TestClient(app)\n\ndef test_idempotent_replay():\n headers = {\"Idempotency-Key\": \"abc\"}\n body = {\"tenant_id\":\"t1\",\"amount_cents\":100,\"currency\":\"USD\"}\n r1 = client.post(\"/v1/payments\", json=body, headers=headers)\n r2 = client.post(\"/v1/payments\", json=body, headers=headers)\n assert r1.status_code == 200 and r2.status_code == 200\n assert r1.json() == r2.json()\n\ndef test_payload_conflict():\n headers = {\"Idempotency-Key\": \"abc\"}\n b1 = {\"tenant_id\":\"t1\",\"amount_cents\":100,\"currency\":\"USD\"}\n b2 = {\"tenant_id\":\"t1\",\"amount_cents\":200,\"currency\":\"USD\"}\n assert client.post(\"/v1/payments\", json=b1, headers=headers).status_code == 200\n assert client.post(\"/v1/payments\", json=b2, headers=headers).status_code == 409\n```\n\nNotes:\n- Replace in-memory store with a DB table and transaction.\n- Store response + request hash to detect key reuse with different payload.\n\n\nChecks: input validation, tests, and safe defaults included.", "source": "WithinUsAI/GOD_Coder_100k"} {"text": "Task type: compiler_backend_ir\nScenario: streaming ETL\nDomain focus: compiler toolchains\nPrimary language: cpp\nDifficulty: expert\nScale/SLO: 1M msgs/min\nComponent: component_yfrczcsl\nConstraints: include security threat model (defensive only), include verification strategy, include deterministic replay plan, avoid data races and undefined behavior, include performance model and limits\nAssume weekly network partitions.\nDeliverable: Design an IR and lowering pipeline; include an optimization pass and correctness checks. Provide minimal code skeleton and tests.\n\nOutput: elite engineering answer optimized for correctness, performance, and operability.\n**Contract**\n- Inputs validated at the boundary; explicit error taxonomy.\n- Idempotency for side effects via request_id; deterministic replay.\n- Backward compatibility: additive changes by default; versioned breaking changes.\n**Invariants**\n- Isolation: tenant boundary enforced; no cross-tenant reads/writes.\n- Safety: state transitions preserve invariants; no partial commit leaks.\n- Determinism: replay of the same event log yields identical outputs.\n**Failure modes & recovery**\n- Data corruption: checksums + scrubber; quarantine and rebuild from replicas/snapshots.\n- Network partition: minority cannot commit; clients receive retriable errors.\n- Duplicate requests: de-duplicate by (tenant, request_id) returning cached response.\n**Security posture (defensive)**\n- Threat model: auth/authz, injection, replay/abuse, supply chain.\n- Least privilege; secrets in managed store; audit logs for sensitive ops.\n- Input normalization, parameterized queries, path traversal protections.\n**Verification strategy**\n- Property tests against a pure reference model (state machine).\n- Fuzzing of parsers/framers/validators with corpus seeds.\n- Canary + shadow traffic; invariants checked in production via assertions/metrics.\n\n**Snippet**\n```text\nImplementation sketch: factor pure state-machine core; adapters for I/O; add deterministic replay log.\n```\nExpert checks: state-machine proof sketch + model checking; upgrade/rollback rehearsed.", "source": "WithinUsAI/Omega_Genesis_Coder_100k"} {"text": "Fix the bug and add pytest tests.\n\n```python\ndef f06989(n: int) -> int:\n # sum 1..n inclusive\n if n < 0: raise ValueError\n total = 0\n for k in range(n): # BUG\n total += k\n return total\n```\nReturn unified diffs for `m72427.py` and `test_m72427.py`.\n\n*** Begin Patch\n*** Update File: m72427.py\n@@\n def f06989(n: int) -> int:\n@@\n- for k in range(n): # BUG\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_m72427.py\n+import pytest\n+from m72427 import f06989\n+\n+def test_small():\n+ assert f06989(7) == 28\n+\n+def test_zero():\n+ assert f06989(0) == 0\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ f06989(-1)\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Task type: program_synthesis_safe\nScenario: time-series metrics store\nDomain focus: large-scale ML systems\nPrimary language: rust\nDifficulty: expert+\nScale/SLO: p99 < 50ms\nComponent: component_ufqansgy\nConstraints: include backward compatibility and migration plan, include performance model and limits, explicit contracts and invariants, include verification strategy, include security threat model (defensive only), avoid data races and undefined behavior, include failure modes and recovery\nAssume schema changes every sprint; must be backward compatible.\nDeliverable: Design a program-synthesis workflow that generates code from specs safely; include guardrails and verification.\n\nOutput: contract-first solution with failure modes, security posture, and test/verification strategy.\n**Contract**\n- Inputs validated at the boundary; explicit error taxonomy.\n- Idempotency for side effects via request_id; deterministic replay.\n- Backward compatibility: additive changes by default; versioned breaking changes.\n**Invariants**\n- Isolation: tenant boundary enforced; no cross-tenant reads/writes.\n- Safety: state transitions preserve invariants; no partial commit leaks.\n- Determinism: replay of the same event log yields identical outputs.\n**Failure modes & recovery**\n- Crash during commit: WAL replay completes or transaction aborts; no torn writes.\n- Data corruption: checksums + scrubber; quarantine and rebuild from replicas/snapshots.\n- Network partition: minority cannot commit; clients receive retriable errors.\n**Security posture (defensive)**\n- Threat model: auth/authz, injection, replay/abuse, supply chain.\n- Least privilege; secrets in managed store; audit logs for sensitive ops.\n- Input normalization, parameterized queries, path traversal protections.\n**Verification strategy**\n- Canary + shadow traffic; invariants checked in production via assertions/metrics.\n- Fuzzing of parsers/framers/validators with corpus seeds.\n- Deterministic simulation with fault injection (crash/partition/latency).\n\n**Snippet**\n```text\nImplementation sketch: factor pure state-machine core; adapters for I/O; add deterministic replay log.\n```\nExpert+ checks: mechanized invariants (or exhaustive model checking), adversarial fuzzing, and multi-region failure drills.", "source": "WithinUsAI/Omega_Genesis_Coder_100k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Produce an offline-first self-evolving code assistant architecture named `d94wg1ht`.\nMust include: module layout, patch-safety policy, evaluation gates (tests/lint/types), versioned memory index.\n\nArchitecture: `d94wg1ht` (offline-first, self-evolving)\n\nModules\n- core/loop.py: evolve → validate → accept/reject (bounded iterations)\n- patching/: diff builder, safe apply, atomic writes, rollback points\n- policy/: allowlist paths, deny globs (.git/, __pycache__/, binaries), patch size caps\n- signals/: parse pytest/ruff/mypy into normalized findings\n- memory/index.jsonl: append-only snapshots (hashes, metrics, rationale)\n\nSafety gates\n- refuse path traversal/symlink escapes; never edit binaries\n- accept only if tests/lint/types stay green or improve", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: Project domain: payments platform\nImplementation stack: Airflow, dbt, DuckDB, MinIO, pytest\nSoftware delivery problem: rate-limit bypass\nTask type: release_engineering_fix\nDifficulty: hard\n\nReturn a complete delivery-grade response with:\n- diagnosis or design reasoning\n- implementation\n- test plan or tests\n- rollout plan\n- rollback or compatibility note\n- verification commands\n\nRepository sketch:\nrepo/\n src/main/java/com/acme/App.java\n src/main/java/com/acme/Service.java\n src/test/java/com/acme/AppTest.java\n pom.xml\n\nFocus: Focus on shipping production software with rollout safety, acceptance criteria, telemetry, and maintenance quality.\n\nassistant: Diagnosis:\n- Root cause or delivery blocker: rate-limit bypass needs both implementation work and a safe shipping plan.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```java\nimport java.util.HashMap;\nimport java.util.Map;\n\npublic final class RequestHandler {\n public static Map handleRequest(Map payload) {\n Map clean = new HashMap<>();\n for (Map.Entry entry : payload.entrySet()) {\n if (entry.getValue() != null) clean.put(entry.getKey().trim(), entry.getValue());\n }\n if (!clean.containsKey(\"id\")) throw new IllegalArgumentException(\"missing id\");\n return Map.of(\"ok\", true, \"data\", clean);\n }\n}\n```\n\nTests:\n```java\nimport static org.junit.jupiter.api.Assertions.*;\nimport java.util.Map;\nimport org.junit.jupiter.api.Test;\n\nclass RequestHandlerTest {\n @Test\n void requiresId() {\n assertThrows(IllegalArgumentException.class, () -> RequestHandler.handleRequest(Map.of(\"name\", \"x\")));\n }\n}\n```\n\nVerification:\n- `./gradlew test`\n- `mvn test`\n\nEngineering notes:\n- Language: Java\n- Framework/tooling: Spring Boot\n- Stack context: Airflow, dbt, DuckDB, MinIO, pytest\n- Domain: payments platform\n- Task type: release_engineering_fix\n- Difficulty: hard\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: Language: TypeScript\nFramework/tooling: Node.js\nDomain: developer platform\nLogic challenge: memory leak in AST cache\nTask type: transaction_integrity_fix\nDifficulty: hard\n\nReturn a rigorous engineering answer:\n- identify the hidden root cause or logical failure\n- present the corrected implementation\n- add tests that prove the fix\n- list verification commands\n- explain why naive fixes are insufficient when relevant\n\nRepository sketch:\nrepo/\n src/\n api.ts\n service.ts\n schema.ts\n tests/\n api.test.ts\n package.json\n\nFocus: Focus on ambiguity, misleading symptoms, hidden root causes, and high-stakes debugging.\n\nassistant: Diagnosis:\n- Hidden root cause: memory leak in AST cache presents misleading symptoms, so the patch must target the actual logic boundary rather than the first visible failure.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```ts\ntype Payload = Record;\n\nexport function normalizePayload(payload: Payload): Payload {\n if (!payload || typeof payload !== \"object\" || Array.isArray(payload)) {\n throw new TypeError(\"payload must be a plain object\");\n }\n return Object.fromEntries(\n Object.entries(payload)\n .filter(([, value]) => value !== null && value !== undefined)\n .map(([key, value]) => [String(key).trim(), value])\n );\n}\n\nexport function handleMemoryLeakInAstCache(payload: Payload) {\n const clean = normalizePayload(payload);\n if (!(\"id\" in clean)) {\n return { ok: false, data: {}, error: \"missing id\" };\n }\n return { ok: true, data: clean, error: null };\n}\n```\n\nTests:\n```ts\nimport { describe, it, expect } from \"vitest\";\nimport { handleMemoryLeakInAstCache } from \"../src/service\";\n\ndescribe(\"handler\", () => {\n it(\"accepts valid input\", () => {\n expect(handleMemoryLeakInAstCache({ id: 7, name: \"ok\", unused: null })).toEqual({\n ok: true,\n data: { id: 7, name: \"ok\" },\n error: null\n });\n });\n\n it(\"rejects missing id\", () => {\n expect(handleMemoryLeakInAstCache({ name: \"x\" }).error).toMatch(/missing id/);\n });\n});\n```\n\nVerification:\n- `npm test`\n- `npm run typecheck`\n- `npm run lint`\n\nEngineering notes:\n- Language: TypeScript\n- Framework/tooling: Node.js\n- Stack context: ASP.NET Core, SQL Server, EF Core, xUnit, Docker\n- Domain: developer platform\n- Task type: transaction_integrity_fix\n- Difficulty: hard\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "Build a data pipeline for a logistics product around role-based access control.\nTarget platform: data (SQL + Python).\nRequirements: schema, ingestion, validation, backfills, and tests.\nConstraints: must avoid global state, must be secure-by-default, must include clear error handling, must be observable (logs/metrics/traces), must include type hints where applicable.\nDifficulty: easy. Assume untrusted input; validate everything.\n\nOutput: actionable implementation and verification artifacts.\nDeliverable: schema + ingestion + validation + backfill strategy.\n\n**Schema (example)**\n- events(event_id TEXT PK, tenant_id TEXT, ts TIMESTAMP, type TEXT, payload JSONB)\n\n**Ingestion**\n- Write to raw table first; validate; then materialize to curated tables.\n- Idempotency by event_id; enforce uniqueness.\n\n**Validation**\n- Reject missing tenant_id/type/ts.\n- Quarantine bad records with reason.\n\n**Backfills**\n- Re-run deterministic transforms from raw → curated.\n- Version transformations; store transform_version with outputs.\n\n**Tests**\n- Unit tests for validators and transforms.\n- Integration test: sample raw batch produces expected curated rows.\n\n\nChecks: input validation, tests, and safe defaults included.", "source": "WithinUsAI/GOD_Coder_100k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Produce an offline-first self-evolving code assistant architecture named `nhqj6qt`.\nMust include: module layout, patch-safety policy, evaluation gates (tests/lint/types), versioned memory index.\n\nArchitecture: `nhqj6qt` (offline-first, self-evolving)\n\nModules\n- core/loop.py: evolve → validate → accept/reject (bounded iterations)\n- patching/: diff builder, safe apply, atomic writes, rollback points\n- policy/: allowlist paths, deny globs (.git/, __pycache__/, binaries), patch size caps\n- signals/: parse pytest/ruff/mypy into normalized findings\n- memory/index.jsonl: append-only snapshots (hashes, metrics, rationale)\n\nSafety gates\n- refuse path traversal/symlink escapes; never edit binaries\n- accept only if tests/lint/types stay green or improve", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Fix a bug and add tests.\n\nFile: s68zb8sbhz.py\n```python\ndef zfyepynyf3(n: int) -> int:\n \"\"\"Sum 1..n inclusive.\"\"\"\n if n < 0:\n raise ValueError(\"n must be non-negative\")\n total = 0\n for k in range(n): # BUG: should include n\n total += k\n return total\n```\n\nReturn unified diffs for s68zb8sbhz.py and test_s68zb8sbhz.py (pytest).\n\n*** Begin Patch\n*** Update File: s68zb8sbhz.py\n@@\n def zfyepynyf3(n: int) -> int:\n@@\n total = 0\n- for k in range(n): # BUG: should include n\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_s68zb8sbhz.py\n+import pytest\n+from s68zb8sbhz import zfyepynyf3\n+\n+def test_zero():\n+ assert zfyepynyf3(0) == 0\n+\n+def test_one():\n+ assert zfyepynyf3(1) == 1\n+\n+def test_small():\n+ assert zfyepynyf3(7) == 28\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ zfyepynyf3(-1)\n+\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Task type: compiler_frontend\nScenario: time-series metrics store\nDomain focus: model checking\nPrimary language: python\nDifficulty: expert\nScale/SLO: 100k RPS peak\nComponent: component_lxzfeidk\nConstraints: include backward compatibility and migration plan, include verification strategy, assume adversarial inputs; validate everything, include failure modes and recovery, include performance model and limits, include test vectors and fuzz strategy\nAssume strict auditability and replayable history.\nDeliverable: Design a DSL language frontend: lexer/parser, AST, type checking, error reporting, and tests.\n\nOutput: elite engineering answer optimized for correctness, performance, and operability.\n**Contract**\n- Inputs validated at the boundary; explicit error taxonomy.\n- Idempotency for side effects via request_id; deterministic replay.\n- Backward compatibility: additive changes by default; versioned breaking changes.\n**Invariants**\n- Safety: state transitions preserve invariants; no partial commit leaks.\n- Liveness: under bounded faults and stable network, progress occurs.\n- Determinism: replay of the same event log yields identical outputs.\n**Failure modes & recovery**\n- Network partition: minority cannot commit; clients receive retriable errors.\n- Crash during commit: WAL replay completes or transaction aborts; no torn writes.\n- Duplicate requests: de-duplicate by (tenant, request_id) returning cached response.\n**Security posture (defensive)**\n- Threat model: auth/authz, injection, replay/abuse, supply chain.\n- Least privilege; secrets in managed store; audit logs for sensitive ops.\n- Input normalization, parameterized queries, path traversal protections.\n**Verification strategy**\n- Property tests against a pure reference model (state machine).\n- Canary + shadow traffic; invariants checked in production via assertions/metrics.\n- Fuzzing of parsers/framers/validators with corpus seeds.\n\n**Snippet**\n```text\nImplementation sketch: factor pure state-machine core; adapters for I/O; add deterministic replay log.\n```\nExpert checks: state-machine proof sketch + model checking; upgrade/rollback rehearsed.", "source": "WithinUsAI/Omega_Genesis_Coder_100k"} {"text": "Fix a subtle bug in a Python module used for CLI tooling.\nRequirements: explain root cause briefly, provide corrected code, and add regression tests.\nConstraints: must provide clear error messages, must be memory-efficient, must be streaming-friendly, must include type hints.\nDifficulty: hard. Guarantee deterministic output ordering.\n\nDeliverable: production-ready reference solution.\n```python\nfrom __future__ import annotations\n\nfrom dataclasses import dataclass\nfrom pathlib import Path\nfrom typing import Iterable\nimport json\n\n\nclass ValidationError(ValueError):\n \"\"\"Raised when input validation fails.\"\"\"\n\n\ndef safe_join(base: Path, *parts: str) -> Path:\n \"\"\"Join paths while preventing traversal outside base.\"\"\"\n b = base.resolve()\n p = (b / Path(*parts)).resolve()\n if p != b and b not in p.parents:\n raise ValidationError(f\"unsafe path: {p}\")\n return p\n\n\n@dataclass(frozen=True, slots=True)\nclass Record:\n key: str\n value: int\n\n\ndef parse_jsonl(lines: Iterable[str]) -> list[Record]:\n out: list[Record] = []\n for idx, line in enumerate(lines, 1):\n s = line.strip()\n if not s:\n continue\n try:\n obj = json.loads(s)\n except json.JSONDecodeError as e:\n raise ValidationError(f\"line {idx}: invalid json\") from e\n if not isinstance(obj, dict):\n raise ValidationError(f\"line {idx}: expected object\")\n key = obj.get(\"key\")\n val = obj.get(\"value\")\n if not isinstance(key, str) or not key:\n raise ValidationError(f\"line {idx}: key must be non-empty str\")\n if not isinstance(val, int):\n raise ValidationError(f\"line {idx}: value must be int\")\n out.append(Record(key, val))\n return out\n\n\ndef write_jsonl(base: Path, rel: str, records: Iterable[Record]) -> Path:\n base.mkdir(parents=True, exist_ok=True)\n dst = safe_join(base, rel)\n dst.parent.mkdir(parents=True, exist_ok=True)\n with dst.open(\"w\", encoding=\"utf-8\", newline=\"\\n\") as f:\n for r in records:\n f.write(json.dumps({\"key\": r.key, \"value\": r.value}, ensure_ascii=False) + \"\\n\")\n return dst\n```\n\n```python\n# tests (pytest-style)\nimport json\nfrom pathlib import Path\nimport pytest\nfrom module_under_test import ValidationError, Record, parse_jsonl, write_jsonl\n\ndef test_parse_ok():\n lines = [json.dumps({\"key\":\"a\",\"value\":1}), json.dumps({\"key\":\"b\",\"value\":2})]\n assert parse_jsonl(lines) == [Record(\"a\",1), Record(\"b\",2)]\n\ndef test_parse_rejects_bad_json():\n with pytest.raises(ValidationError):\n parse_jsonl([\"{not json}\"])\n\ndef test_safe_join_blocks_traversal(tmp_path: Path):\n with pytest.raises(ValidationError):\n write_jsonl(tmp_path, \"../x.jsonl\", [Record(\"a\",1)])\n```", "source": "WithinUsAI/python_GOD_coder_100k"} {"text": "Build an elite-grade solution in the domain of distributed systems for scenario: chat messaging.\nPrimary language: bash.\nDifficulty: medium.\nConstraints: include tests or verification strategy, assume untrusted inputs; validate and sanitize, provide rollout and rollback guidance.\nComponent: component_zazmgvg.\nAssume schema changes every sprint; must be backward compatible.\nTask: Write a precise interface contract, list invariants, and provide a lightweight formal/spec-style description (pseudo-TLA+/state machine) plus reference implementation skeleton and tests.\n\nOutput: production blueprint plus correctness arguments and test strategy.\nOutput: contract + invariants + spec + reference skeleton.\n\n**Interface contract**\n- Commands: `Put(key, value, expected_version?)`, `Get(key)`, `Delete(key, expected_version?)`\n- Responses: `Ok(version, value?)`, `NotFound`, `Conflict(current_version)`, `InvalidInput`\n- Idempotency: client supplies `request_id`; server must de-duplicate per (tenant_id, request_id).\n\n**Invariants**\n1. Monotonic version per key (strictly increases on successful writes).\n2. Reads return latest committed value for a given consistency level.\n3. Exactly-once effect for a given `request_id` (at-most-once execution + replay response).\n4. Tenant isolation: keys are scoped by tenant_id.\n\n**State machine (pseudo)**\nState:\n- store: map[(tenant,key)] -> (version:int, value:bytes|tombstone)\n- seen: map[(tenant,request_id)] -> response\nTransition Put:\n- if request_id in seen: return seen[...]\n- validate input; if expected_version set and != current version -> Conflict\n- version' = version + 1; store[...] := (version', value); seen[...] := Ok(version', value)\n\n**Reference skeleton (Python)**\n```python\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom typing import Dict, Optional, Tuple\n\nclass Conflict(Exception): pass\nclass InvalidInput(ValueError): pass\n\n@dataclass(frozen=True, slots=True)\nclass Value:\n version: int\n data: Optional[bytes] # None == tombstone\n\n@dataclass(frozen=True, slots=True)\nclass Reply:\n kind: str\n version: Optional[int] = None\n data: Optional[bytes] = None\n\nclass KV:\n def __init__(self) -> None:\n self._store: Dict[Tuple[str,str], Value] = {}\n self._seen: Dict[Tuple[str,str], Reply] = {}\n\n def put(self, tenant: str, request_id: str, key: str, data: bytes, expected_version: Optional[int]=None) -> Reply:\n if not tenant or not request_id or not key:\n raise InvalidInput(\"tenant/request_id/key required\")\n de = self._seen.get((tenant, request_id))\n if de: \n return de\n cur = self._store.get((tenant, key), Value(0, None))\n if expected_version is not None and expected_version != cur.version:\n r = Reply(\"conflict\", version=cur.version)\n self._seen[(tenant, request_id)] = r\n return r\n nxt = Value(cur.version + 1, data)\n self._store[(tenant, key)] = nxt\n r = Reply(\"ok\", version=nxt.version)\n self._seen[(tenant, request_id)] = r\n return r\n```\n\n**Tests**\n- Determinism: same request_id → same reply.\n- Conflict detection and version monotonicity.\n\n\nChecks: boundary validation and deterministic behavior verified.", "source": "WithinUsAI/Elite_GOD_Coder_100k"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: Project domain: reporting engine\nImplementation stack: Rust, Axum, SQLx, Redis, Tokio, Docker\nSoftware delivery problem: streaming timeout handling\nTask type: incident_to_remediation\nDifficulty: medium\n\nReturn a complete delivery-grade response with:\n- diagnosis or design reasoning\n- implementation\n- test plan or tests\n- rollout plan\n- rollback or compatibility note\n- verification commands\n\nRepository sketch:\nrepo/\n src/main/java/com/acme/App.java\n src/main/java/com/acme/Service.java\n src/test/java/com/acme/AppTest.java\n pom.xml\n\nFocus: Focus on shipping production software with rollout safety, acceptance criteria, telemetry, and maintenance quality.\n\nassistant: Diagnosis:\n- Root cause or delivery blocker: streaming timeout handling needs both implementation work and a safe shipping plan.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```java\nimport java.util.HashMap;\nimport java.util.Map;\n\npublic final class RequestHandler {\n public static Map handleRequest(Map payload) {\n Map clean = new HashMap<>();\n for (Map.Entry entry : payload.entrySet()) {\n if (entry.getValue() != null) clean.put(entry.getKey().trim(), entry.getValue());\n }\n if (!clean.containsKey(\"id\")) throw new IllegalArgumentException(\"missing id\");\n return Map.of(\"ok\", true, \"data\", clean);\n }\n}\n```\n\nTests:\n```java\nimport static org.junit.jupiter.api.Assertions.*;\nimport java.util.Map;\nimport org.junit.jupiter.api.Test;\n\nclass RequestHandlerTest {\n @Test\n void requiresId() {\n assertThrows(IllegalArgumentException.class, () -> RequestHandler.handleRequest(Map.of(\"name\", \"x\")));\n }\n}\n```\n\nVerification:\n- `./gradlew test`\n- `mvn test`\n\nEngineering notes:\n- Language: Java\n- Framework/tooling: JUnit\n- Stack context: Rust, Axum, SQLx, Redis, Tokio, Docker\n- Domain: reporting engine\n- Task type: incident_to_remediation\n- Difficulty: medium\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "Task type: supply_chain_security\nScenario: job scheduler\nDomain focus: distributed storage\nPrimary language: typescript\nDifficulty: expert+\nScale/SLO: 10k RPS peak\nComponent: component_bwykasmm\nConstraints: include failure modes and recovery, include backward compatibility and migration plan, include performance model and limits, include security threat model (defensive only), assume adversarial inputs; validate everything, include test vectors and fuzz strategy\nAssume partial data corruption; include scrubbing strategy.\nDeliverable: Design a supply-chain security plan: SBOM, signing, provenance, dependency policy, and CI gates.\n\nOutput: rigorous design + invariants + verification plan + implementation sketch.\n**Contract**\n- Inputs validated at the boundary; explicit error taxonomy.\n- Idempotency for side effects via request_id; deterministic replay.\n- Backward compatibility: additive changes by default; versioned breaking changes.\n**Invariants**\n- Isolation: tenant boundary enforced; no cross-tenant reads/writes.\n- Liveness: under bounded faults and stable network, progress occurs.\n- Safety: state transitions preserve invariants; no partial commit leaks.\n**Failure modes & recovery**\n- Duplicate requests: de-duplicate by (tenant, request_id) returning cached response.\n- Network partition: minority cannot commit; clients receive retriable errors.\n- Data corruption: checksums + scrubber; quarantine and rebuild from replicas/snapshots.\n**Security posture (defensive)**\n- Threat model: auth/authz, injection, replay/abuse, supply chain.\n- Least privilege; secrets in managed store; audit logs for sensitive ops.\n- Input normalization, parameterized queries, path traversal protections.\n**Verification strategy**\n- Fuzzing of parsers/framers/validators with corpus seeds.\n- Canary + shadow traffic; invariants checked in production via assertions/metrics.\n- Deterministic simulation with fault injection (crash/partition/latency).\n\n**Snippet**\n```text\nImplementation sketch: factor pure state-machine core; adapters for I/O; add deterministic replay log.\n```\nExpert+ checks: mechanized invariants (or exhaustive model checking), adversarial fuzzing, and multi-region failure drills.", "source": "WithinUsAI/Omega_Genesis_Coder_100k"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: Language: Bash\nFramework/tooling: awk\nDomain: team dashboard\nLogic challenge: timezone bug in reporting\nTask type: algorithmic_correctness\nDifficulty: hard\n\nReturn a rigorous engineering answer:\n- identify the hidden root cause or logical failure\n- present the corrected implementation\n- add tests that prove the fix\n- list verification commands\n- explain why naive fixes are insufficient when relevant\n\nRepository sketch:\nrepo/\n scripts/\n run.sh\n deploy.sh\n tests/\n smoke.sh\n\nFocus: Focus on strong structured logic with edge cases, data validation, and concurrency safety.\n\nassistant: Diagnosis:\n- Root cause: the failure around timezone bug in reporting is caused by missing validation, weak edge-case handling, or unsafe lifecycle behavior in the current implementation.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```bash\n#!/usr/bin/env bash\nset -euo pipefail\n\ninput=\"${1:-}\"\nif [[ -z \"$input\" ]]; then\n echo \"missing input\" >&2\n exit 1\nfi\n\nprintf '%s\n' \"$input\" | tr -d '\r'\n```\n\nTests:\n```bash\noutput=\"$(bash scripts/run.sh \"abc\")\"\ntest \"$output\" = \"abc\"\n```\n\nVerification:\n- `bash tests/smoke.sh`\n- `shellcheck scripts/*.sh`\n\nEngineering notes:\n- Language: Bash\n- Framework/tooling: awk\n- Stack context: Go, Gin, PostgreSQL, gRPC, Prometheus, Docker\n- Domain: team dashboard\n- Task type: algorithmic_correctness\n- Difficulty: hard\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "Fix a subtle bug in a Python module used for file synchronization.\nRequirements: explain root cause briefly, provide corrected code, and add regression tests.\nConstraints: must be streaming-friendly, stdlib-only, must avoid global state.\nDifficulty: expert. Handle empty inputs and malformed records gracefully.\n\nDeliverable: implementation + tests.\n```python\nfrom __future__ import annotations\n\nfrom dataclasses import dataclass\nfrom pathlib import Path\nfrom typing import Iterable\nimport json\n\n\nclass ValidationError(ValueError):\n \"\"\"Raised when input validation fails.\"\"\"\n\n\ndef safe_join(base: Path, *parts: str) -> Path:\n \"\"\"Join paths while preventing traversal outside base.\"\"\"\n b = base.resolve()\n p = (b / Path(*parts)).resolve()\n if p != b and b not in p.parents:\n raise ValidationError(f\"unsafe path: {p}\")\n return p\n\n\n@dataclass(frozen=True, slots=True)\nclass Record:\n key: str\n value: int\n\n\ndef parse_jsonl(lines: Iterable[str]) -> list[Record]:\n out: list[Record] = []\n for idx, line in enumerate(lines, 1):\n s = line.strip()\n if not s:\n continue\n try:\n obj = json.loads(s)\n except json.JSONDecodeError as e:\n raise ValidationError(f\"line {idx}: invalid json\") from e\n if not isinstance(obj, dict):\n raise ValidationError(f\"line {idx}: expected object\")\n key = obj.get(\"key\")\n val = obj.get(\"value\")\n if not isinstance(key, str) or not key:\n raise ValidationError(f\"line {idx}: key must be non-empty str\")\n if not isinstance(val, int):\n raise ValidationError(f\"line {idx}: value must be int\")\n out.append(Record(key, val))\n return out\n\n\ndef write_jsonl(base: Path, rel: str, records: Iterable[Record]) -> Path:\n base.mkdir(parents=True, exist_ok=True)\n dst = safe_join(base, rel)\n dst.parent.mkdir(parents=True, exist_ok=True)\n with dst.open(\"w\", encoding=\"utf-8\", newline=\"\\n\") as f:\n for r in records:\n f.write(json.dumps({\"key\": r.key, \"value\": r.value}, ensure_ascii=False) + \"\\n\")\n return dst\n```\n\n```python\n# tests (pytest-style)\nimport json\nfrom pathlib import Path\nimport pytest\nfrom module_under_test import ValidationError, Record, parse_jsonl, write_jsonl\n\ndef test_parse_ok():\n lines = [json.dumps({\"key\":\"a\",\"value\":1}), json.dumps({\"key\":\"b\",\"value\":2})]\n assert parse_jsonl(lines) == [Record(\"a\",1), Record(\"b\",2)]\n\ndef test_parse_rejects_bad_json():\n with pytest.raises(ValidationError):\n parse_jsonl([\"{not json}\"])\n\ndef test_safe_join_blocks_traversal(tmp_path: Path):\n with pytest.raises(ValidationError):\n write_jsonl(tmp_path, \"../x.jsonl\", [Record(\"a\",1)])\n```", "source": "WithinUsAI/python_GOD_coder_100k"} {"text": "Build an elite-grade solution in the domain of gpu compute for scenario: document indexing.\nPrimary language: typescript.\nDifficulty: expert.\nConstraints: assume untrusted inputs; validate and sanitize, avoid undefined behavior and data races, make the interface contract explicit.\nComponent: component_wcwimjj.\nAssume cold-start and memory limits are tight.\nTask: Provide a cross-language reference (API contract + implementation in two languages) and compatibility tests.\n\nOutput: production blueprint plus correctness arguments and test strategy.\nOutput: API contract + two implementations + compat tests.\n\n**Contract**\n- JSON schema for request/response; strict field validation; explicit version.\n\n**Example**\n- Implement validator + handler in Python and TypeScript.\n- Compatibility tests: same inputs produce equivalent outputs; reject unknown fields when in strict mode.\n\n\nExpert checks: state-machine reasoning, concurrency stress, and upgrade/rollback validated.", "source": "WithinUsAI/Elite_GOD_Coder_100k"} {"text": "Build an elite-grade solution in the domain of operating systems for scenario: job scheduler.\nPrimary language: go.\nDifficulty: medium.\nConstraints: make the interface contract explicit, provide rollout and rollback guidance, assume untrusted inputs; validate and sanitize, include tests or verification strategy, avoid undefined behavior and data races.\nComponent: component_kmcfjgf.\nAssume schema changes every sprint; must be backward compatible.\nTask: Define properties/invariants and implement property-based tests (or generative tests) with a reference model and edge-case generators.\n\nOutput: rigorous solution with invariants, failure modes, and performance notes.\nOutput: properties + reference model + generative tests.\n\n**Properties**\n- Idempotency: replayed command yields same result.\n- Monotonicity: versions only increase.\n- Conservation: for queues, produced items == consumed items (multiset) under no-loss assumption.\n\n**Approach**\n- Write a small reference model (pure function).\n- Generate random sequences of operations; compare implementation outputs to model.\n\n\nChecks: boundary validation and deterministic behavior verified.", "source": "WithinUsAI/Elite_GOD_Coder_100k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Fix a bug and add tests.\n\nFile: blnvx8zu.py\n```python\ndef nt60n5frl(n: int) -> int:\n \"\"\"Sum 1..n inclusive.\"\"\"\n if n < 0:\n raise ValueError(\"n must be non-negative\")\n total = 0\n for k in range(n): # BUG: should include n\n total += k\n return total\n```\n\nReturn unified diffs for blnvx8zu.py and test_blnvx8zu.py (pytest).\n\n*** Begin Patch\n*** Update File: blnvx8zu.py\n@@\n def nt60n5frl(n: int) -> int:\n@@\n total = 0\n- for k in range(n): # BUG: should include n\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_blnvx8zu.py\n+import pytest\n+from blnvx8zu import nt60n5frl\n+\n+def test_zero():\n+ assert nt60n5frl(0) == 0\n+\n+def test_one():\n+ assert nt60n5frl(1) == 1\n+\n+def test_small():\n+ assert nt60n5frl(7) == 28\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ nt60n5frl(-1)\n+\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Refactor to modern typed Python with immutability and tests.\n\nFile: xg8izo4y6l.py\n```python\nclass L381Aias96S:\n def __init__(self, name, values):\n self.name = name\n self.values = list(values)\n def add(self, v):\n self.values.append(v)\n def mean(self):\n s = 0\n for x in self.values:\n s += x\n return s / len(self.values)\n```\n\nReturn full new xg8izo4y6l.py and test_xg8izo4y6l.py.\n\n# xg8izo4y6l.py\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom typing import Iterable, Tuple\n\n@dataclass(frozen=True)\nclass L381Aias96S:\n name: str\n values: Tuple[float, ...]\n\n @staticmethod\n def create(name: str, values: Iterable[float]) -> \"L381Aias96S\":\n vals = tuple(float(v) for v in values)\n if not vals:\n raise ValueError(\"values must be non-empty\")\n return L381Aias96S(name=name, values=vals)\n\n def add(self, v: float) -> \"L381Aias96S\":\n return L381Aias96S(name=self.name, values=self.values + (float(v),))\n\n def mean(self) -> float:\n return sum(self.values) / len(self.values)\n\n# test_xg8izo4y6l.py\nimport pytest\nfrom xg8izo4y6l import L381Aias96S\n\ndef test_mean_and_add():\n c = L381Aias96S.create(\"a\", [1, 2, 3])\n assert c.mean() == 2.0\n assert c.add(5).mean() == (1 + 2 + 3 + 5) / 4\n\ndef test_empty_raises():\n with pytest.raises(ValueError):\n L381Aias96S.create(\"x\", [])", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: Project stack: ASP.NET Core, SQL Server, EF Core, xUnit, Docker\nLanguage: Bash\nDependency challenge: log redaction failure\nTask type: version_conflict_resolution\nDifficulty: hard\n\nFix this as a senior engineer.\nRequired:\n- identify the version or compatibility failure mode\n- produce the corrected config/code/build patch\n- explain rollback-safe migration notes\n- add regression tests or reproducibility checks\n- include concrete verification commands\n\nRepository sketch:\nrepo/\n scripts/\n run.sh\n deploy.sh\n tests/\n smoke.sh\n\nFocus: Focus on versioning, migrations, lockfiles, runtime compatibility, and secure dependency handling.\n\nassistant: Diagnosis:\n- Root cause: the issue around log redaction failure is a dependency, migration, or runtime-compatibility mismatch that needs a rollback-safe patch.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```bash\n#!/usr/bin/env bash\nset -euo pipefail\n\ninput=\"${1:-}\"\nif [[ -z \"$input\" ]]; then\n echo \"missing input\" >&2\n exit 1\nfi\n\nprintf '%s\n' \"$input\" | tr -d '\r'\n```\n\nTests:\n```bash\noutput=\"$(bash scripts/run.sh \"abc\")\"\ntest \"$output\" = \"abc\"\n```\n\nVerification:\n- `bash tests/smoke.sh`\n- `shellcheck scripts/*.sh`\n\nEngineering notes:\n- Language: Bash\n- Framework/tooling: awk\n- Stack context: ASP.NET Core, SQL Server, EF Core, xUnit, Docker\n- Domain: repo automation\n- Task type: version_conflict_resolution\n- Difficulty: hard\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Refactor to modern typed Python with immutability and tests.\n\nFile: z6_vhrrw.py\n```python\nclass Brrx0Ul8:\n def __init__(self, name, values):\n self.name = name\n self.values = list(values)\n def add(self, v):\n self.values.append(v)\n def mean(self):\n s = 0\n for x in self.values:\n s += x\n return s / len(self.values)\n```\n\nReturn full new z6_vhrrw.py and test_z6_vhrrw.py.\n\n# z6_vhrrw.py\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom typing import Iterable, Tuple\n\n@dataclass(frozen=True)\nclass Brrx0Ul8:\n name: str\n values: Tuple[float, ...]\n\n @staticmethod\n def create(name: str, values: Iterable[float]) -> \"Brrx0Ul8\":\n vals = tuple(float(v) for v in values)\n if not vals:\n raise ValueError(\"values must be non-empty\")\n return Brrx0Ul8(name=name, values=vals)\n\n def add(self, v: float) -> \"Brrx0Ul8\":\n return Brrx0Ul8(name=self.name, values=self.values + (float(v),))\n\n def mean(self) -> float:\n return sum(self.values) / len(self.values)\n\n# test_z6_vhrrw.py\nimport pytest\nfrom z6_vhrrw import Brrx0Ul8\n\ndef test_mean_and_add():\n c = Brrx0Ul8.create(\"a\", [1, 2, 3])\n assert c.mean() == 2.0\n assert c.add(5).mean() == (1 + 2 + 3 + 5) / 4\n\ndef test_empty_raises():\n with pytest.raises(ValueError):\n Brrx0Ul8.create(\"x\", [])", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Build an elite-grade solution in the domain of realtime systems for scenario: analytics pipeline.\nPrimary language: rust.\nDifficulty: expert.\nConstraints: assume untrusted inputs; validate and sanitize, provide rollout and rollback guidance, make the interface contract explicit, include tests or verification strategy.\nComponent: component_oddpnzp.\nAssume partial network partitions occur weekly.\nTask: Design an application-level protocol (framing, retries, timeouts, backpressure). Provide client/server skeleton and test vectors.\n\nOutput: production blueprint plus correctness arguments and test strategy.\nOutput: protocol framing + retry policy + client/server skeleton.\n\n**Framing**\n- Length-prefixed: uint32_be length + payload\n- Payload: msgpack/json; include request_id, type, and optional checksum\n\n**Reliability**\n- Retries only for idempotent ops; exponential backoff + jitter.\n- Timeouts: connect, read, overall; enforce max in-flight to provide backpressure.\n\n**Test vectors**\n- Corrupted length / truncated frame rejected\n- Duplicate request_id returns cached response\n- Slowloris protection by read deadlines\n\n\nExpert checks: state-machine reasoning, concurrency stress, and upgrade/rollback validated.", "source": "WithinUsAI/Elite_GOD_Coder_100k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Produce an offline-first self-evolving code assistant architecture named `h7uy030te3f`.\nMust include: module layout, patch-safety policy, evaluation gates (tests/lint/types), versioned memory index.\n\nArchitecture: `h7uy030te3f` (offline-first, self-evolving)\n\nModules\n- core/loop.py: evolve → validate → accept/reject (bounded iterations)\n- patching/: diff builder, safe apply, atomic writes, rollback points\n- policy/: allowlist paths, deny globs (.git/, __pycache__/, binaries), patch size caps\n- signals/: parse pytest/ruff/mypy into normalized findings\n- memory/index.jsonl: append-only snapshots (hashes, metrics, rationale)\n\nSafety gates\n- refuse path traversal/symlink escapes; never edit binaries\n- accept only if tests/lint/types stay green or improve", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Optimize a Python workflow for file synchronization.\nRequirements: provide an optimized implementation and a small benchmark harness.\nConstraints: must include docstrings, must be memory-efficient.\nDifficulty: hard. Support both Windows and POSIX paths correctly.\n\nDeliverable: implementation + tests.\nStrategy:\n- Avoid repeated parsing; precompile regex if needed; use local variables; stream processing.\n\n```python\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom typing import Iterable\nimport time\n\n@dataclass(frozen=True, slots=True)\nclass Stats:\n count: int\n total: int\n\ndef compute_stats_stream(values: Iterable[int]) -> Stats:\n c = 0\n t = 0\n for v in values:\n c += 1\n t += v\n return Stats(c, t)\n\ndef bench(n: int = 1_000_00) -> float:\n data = range(n)\n t0 = time.perf_counter()\n _ = compute_stats_stream(data)\n return time.perf_counter() - t0\n```\n\n```python\nfrom module_under_test import bench\ndef test_bench_runs_fast_enough():\n # Sanity: should run quickly on typical machines; adjust threshold for CI.\n assert bench(50_000) < 0.5\n```", "source": "WithinUsAI/python_GOD_coder_100k"} {"text": "Fix the bug and add pytest tests.\n\n```python\ndef f40218(n: int) -> int:\n # sum 1..n inclusive\n if n < 0: raise ValueError\n total = 0\n for k in range(n): # BUG\n total += k\n return total\n```\nReturn unified diffs for `m77174.py` and `test_m77174.py`.\n\n*** Begin Patch\n*** Update File: m77174.py\n@@\n def f40218(n: int) -> int:\n@@\n- for k in range(n): # BUG\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_m77174.py\n+import pytest\n+from m77174 import f40218\n+\n+def test_small():\n+ assert f40218(7) == 28\n+\n+def test_zero():\n+ assert f40218(0) == 0\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ f40218(-1)\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Task type: compiler_frontend\nScenario: streaming ETL\nDomain focus: distributed storage\nPrimary language: rust\nDifficulty: hard\nScale/SLO: 10k RPS peak\nComponent: component_rudefmzn\nConstraints: include deterministic replay plan, assume adversarial inputs; validate everything, avoid data races and undefined behavior, include test vectors and fuzz strategy, include security threat model (defensive only), include backward compatibility and migration plan\nAssume tight memory budget and cold-start constraints.\nDeliverable: Design a DSL language frontend: lexer/parser, AST, type checking, error reporting, and tests.\n\nOutput: elite engineering answer optimized for correctness, performance, and operability.\n**Contract**\n- Inputs validated at the boundary; explicit error taxonomy.\n- Idempotency for side effects via request_id; deterministic replay.\n- Backward compatibility: additive changes by default; versioned breaking changes.\n**Invariants**\n- Determinism: replay of the same event log yields identical outputs.\n- Isolation: tenant boundary enforced; no cross-tenant reads/writes.\n- Liveness: under bounded faults and stable network, progress occurs.\n**Failure modes & recovery**\n- Crash during commit: WAL replay completes or transaction aborts; no torn writes.\n- Data corruption: checksums + scrubber; quarantine and rebuild from replicas/snapshots.\n- Network partition: minority cannot commit; clients receive retriable errors.\n**Security posture (defensive)**\n- Threat model: auth/authz, injection, replay/abuse, supply chain.\n- Least privilege; secrets in managed store; audit logs for sensitive ops.\n- Input normalization, parameterized queries, path traversal protections.\n**Verification strategy**\n- Fuzzing of parsers/framers/validators with corpus seeds.\n- Property tests against a pure reference model (state machine).\n- Deterministic simulation with fault injection (crash/partition/latency).\n\n**Snippet**\n```text\nImplementation sketch: factor pure state-machine core; adapters for I/O; add deterministic replay log.\n```\nHard checks: fault injection tests gate merges; perf thresholds enforced in CI.", "source": "WithinUsAI/Omega_Genesis_Coder_100k"} {"text": "Build an elite-grade solution in the domain of edge/IoT for scenario: document indexing.\nPrimary language: rust.\nDifficulty: hard.\nConstraints: provide rollout and rollback guidance, design for backward compatibility and migrations, include invariants and failure modes, document performance characteristics.\nComponent: component_bfxbjjd.\nAssume strict auditability and replayable history.\nTask: Design a replication/consistency approach (e.g., leader-based, quorum reads/writes). Provide message flows, failure handling, and a minimal reference implementation skeleton.\n\nOutput: rigorous solution with invariants, failure modes, and performance notes.\nOutput: replication design + failure handling + minimal skeleton.\n\n**Model**\n- Leader-based replication with term + log index.\n- Quorum acks for durability: write committed when majority acks.\n- Read options: leader-read (linearizable) or quorum-read (monotonic if using read-index).\n\n**Message flow (write)**\n1. Client → Leader: Put(request_id, payload)\n2. Leader appends to log, sends AppendEntries to followers\n3. Followers append + ack\n4. On majority ack: commit index advances; apply to state machine; respond to client\n\n**Failure modes**\n- Leader crash: new election; uncommitted entries may be rolled back.\n- Partition: minority side cannot commit.\n- Duplicate requests: deduplicate by request_id stored in state.\n\n**Skeleton (Go pseudo)**\n```go\ntype Entry struct { Term uint64; Index uint64; Cmd []byte }\ntype Node struct {\n id int\n term uint64\n log []Entry\n commit uint64\n seen map[string][]byte // request_id -> response\n}\n```\n\n**Verification**\n- Invariant: committed index never decreases.\n- Property: if a write is committed, all future leaders contain it.\n- Test with simulated partitions and crash/restart.\n\n\nHard checks: failure injection tests and performance regressions gated.", "source": "WithinUsAI/Elite_GOD_Coder_100k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Optimize while preserving behavior.\n\nFile: j1jb7gmacb.py\n```python\ndef r1fly0rzj(xs):\n out = []\n for x in xs:\n if x not in out:\n out.append(x)\n return out\n```\n\nRequirements: preserve first-seen order; O(n) average; add types + docstring.\n\n# j1jb7gmacb.py\nfrom __future__ import annotations\nfrom typing import Iterable, List, Set, TypeVar\n\nT = TypeVar(\"T\")\n\ndef r1fly0rzj(xs: Iterable[T]) -> List[T]:\n \"\"\"Return unique items preserving first-seen order.\"\"\"\n seen: Set[T] = set()\n out: List[T] = []\n for x in xs:\n if x in seen:\n continue\n seen.add(x)\n out.append(x)\n return out", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Produce an offline-first self-evolving code assistant architecture named `m31yza9nt41`.\nMust include: module layout, patch-safety policy, evaluation gates (tests/lint/types), versioned memory index.\n\nArchitecture: `m31yza9nt41` (offline-first, self-evolving)\n\nModules\n- core/loop.py: evolve → validate → accept/reject (bounded iterations)\n- patching/: diff builder, safe apply, atomic writes, rollback points\n- policy/: allowlist paths, deny globs (.git/, __pycache__/, binaries), patch size caps\n- signals/: parse pytest/ruff/mypy into normalized findings\n- memory/index.jsonl: append-only snapshots (hashes, metrics, rationale)\n\nSafety gates\n- refuse path traversal/symlink escapes; never edit binaries\n- accept only if tests/lint/types stay green or improve", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Optimize while preserving behavior.\n\nFile: fi7wo3qh1b.py\n```python\ndef gmes_3j1kx(xs):\n out = []\n for x in xs:\n if x not in out:\n out.append(x)\n return out\n```\n\nRequirements: preserve first-seen order; O(n) average; add types + docstring.\n\n# fi7wo3qh1b.py\nfrom __future__ import annotations\nfrom typing import Iterable, List, Set, TypeVar\n\nT = TypeVar(\"T\")\n\ndef gmes_3j1kx(xs: Iterable[T]) -> List[T]:\n \"\"\"Return unique items preserving first-seen order.\"\"\"\n seen: Set[T] = set()\n out: List[T] = []\n for x in xs:\n if x in seen:\n continue\n seen.add(x)\n out.append(x)\n return out", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Refactor to modern typed Python with immutability and tests.\n\nFile: e3e1iy9q9x2y.py\n```python\nclass Joz4Nfgtv:\n def __init__(self, name, values):\n self.name = name\n self.values = list(values)\n def add(self, v):\n self.values.append(v)\n def mean(self):\n s = 0\n for x in self.values:\n s += x\n return s / len(self.values)\n```\n\nReturn full new e3e1iy9q9x2y.py and test_e3e1iy9q9x2y.py.\n\n# e3e1iy9q9x2y.py\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom typing import Iterable, Tuple\n\n@dataclass(frozen=True)\nclass Joz4Nfgtv:\n name: str\n values: Tuple[float, ...]\n\n @staticmethod\n def create(name: str, values: Iterable[float]) -> \"Joz4Nfgtv\":\n vals = tuple(float(v) for v in values)\n if not vals:\n raise ValueError(\"values must be non-empty\")\n return Joz4Nfgtv(name=name, values=vals)\n\n def add(self, v: float) -> \"Joz4Nfgtv\":\n return Joz4Nfgtv(name=self.name, values=self.values + (float(v),))\n\n def mean(self) -> float:\n return sum(self.values) / len(self.values)\n\n# test_e3e1iy9q9x2y.py\nimport pytest\nfrom e3e1iy9q9x2y import Joz4Nfgtv\n\ndef test_mean_and_add():\n c = Joz4Nfgtv.create(\"a\", [1, 2, 3])\n assert c.mean() == 2.0\n assert c.add(5).mean() == (1 + 2 + 3 + 5) / 4\n\ndef test_empty_raises():\n with pytest.raises(ValueError):\n Joz4Nfgtv.create(\"x\", [])", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: Language: C++\nFramework/tooling: Boost\nDomain: notification service\nLogic challenge: timezone bug in reporting\nTask type: cross_stack_outage_fix\nDifficulty: hard\n\nReturn a rigorous engineering answer:\n- identify the hidden root cause or logical failure\n- present the corrected implementation\n- add tests that prove the fix\n- list verification commands\n- explain why naive fixes are insufficient when relevant\n\nRepository sketch:\nrepo/\n src/main.cpp\n src/service.cpp\n include/service.h\n tests/test_service.cpp\n CMakeLists.txt\n\nFocus: Focus on staff-level problem solving with multi-file patches, rollout implications, performance and security tradeoffs.\n\nassistant: Diagnosis:\n- Staff-level diagnosis: timezone bug in reporting impacts correctness, operability, and future maintenance, so the fix must be minimal where possible but complete where necessary.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```cpp\n#include \n#include \n\nusing Payload = std::unordered_map;\n\nPayload normalize_payload(const Payload& in) {\n Payload out;\n for (const auto& [k, v] : in) {\n if (!v.empty()) out[k] = v;\n }\n return out;\n}\n```\n\nTests:\n```cpp\nTEST_CASE(\"normalize_payload filters empty values\") {\n Payload in{{\"id\",\"7\"},{\"name\",\"\"}};\n auto out = normalize_payload(in);\n REQUIRE(out.count(\"id\") == 1);\n REQUIRE(out.count(\"name\") == 0);\n}\n```\n\nVerification:\n- `cmake --build build`\n- `ctest --test-dir build`\n\nEngineering notes:\n- Language: C++\n- Framework/tooling: Boost\n- Stack context: Rust, Axum, SQLx, Redis, Tokio, Docker\n- Domain: notification service\n- Task type: cross_stack_outage_fix\n- Difficulty: hard\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "Write secure, defensive Python code for metrics aggregation.\nRequirements: input validation, safe file handling, prevent path traversal, include tests.\nConstraints: must be memory-efficient, must include tests.\nDifficulty: medium. Support both Windows and POSIX paths correctly.\n\nDeliverable: API + reference implementation + tests.\n```python\nfrom __future__ import annotations\n\nfrom dataclasses import dataclass\nfrom pathlib import Path\nfrom typing import Iterable\nimport json\n\n\nclass ValidationError(ValueError):\n \"\"\"Raised when input validation fails.\"\"\"\n\n\ndef safe_join(base: Path, *parts: str) -> Path:\n \"\"\"Join paths while preventing traversal outside base.\"\"\"\n b = base.resolve()\n p = (b / Path(*parts)).resolve()\n if p != b and b not in p.parents:\n raise ValidationError(f\"unsafe path: {p}\")\n return p\n\n\n@dataclass(frozen=True, slots=True)\nclass Record:\n key: str\n value: int\n\n\ndef parse_jsonl(lines: Iterable[str]) -> list[Record]:\n out: list[Record] = []\n for idx, line in enumerate(lines, 1):\n s = line.strip()\n if not s:\n continue\n try:\n obj = json.loads(s)\n except json.JSONDecodeError as e:\n raise ValidationError(f\"line {idx}: invalid json\") from e\n if not isinstance(obj, dict):\n raise ValidationError(f\"line {idx}: expected object\")\n key = obj.get(\"key\")\n val = obj.get(\"value\")\n if not isinstance(key, str) or not key:\n raise ValidationError(f\"line {idx}: key must be non-empty str\")\n if not isinstance(val, int):\n raise ValidationError(f\"line {idx}: value must be int\")\n out.append(Record(key, val))\n return out\n\n\ndef write_jsonl(base: Path, rel: str, records: Iterable[Record]) -> Path:\n base.mkdir(parents=True, exist_ok=True)\n dst = safe_join(base, rel)\n dst.parent.mkdir(parents=True, exist_ok=True)\n with dst.open(\"w\", encoding=\"utf-8\", newline=\"\\n\") as f:\n for r in records:\n f.write(json.dumps({\"key\": r.key, \"value\": r.value}, ensure_ascii=False) + \"\\n\")\n return dst\n```\n\n```python\n# tests (pytest-style)\nimport json\nfrom pathlib import Path\nimport pytest\nfrom module_under_test import ValidationError, Record, parse_jsonl, write_jsonl\n\ndef test_parse_ok():\n lines = [json.dumps({\"key\":\"a\",\"value\":1}), json.dumps({\"key\":\"b\",\"value\":2})]\n assert parse_jsonl(lines) == [Record(\"a\",1), Record(\"b\",2)]\n\ndef test_parse_rejects_bad_json():\n with pytest.raises(ValidationError):\n parse_jsonl([\"{not json}\"])\n\ndef test_safe_join_blocks_traversal(tmp_path: Path):\n with pytest.raises(ValidationError):\n write_jsonl(tmp_path, \"../x.jsonl\", [Record(\"a\",1)])\n```", "source": "WithinUsAI/python_GOD_coder_100k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Fix a bug and add tests.\n\nFile: d38f55wt.py\n```python\ndef bay8tr_s7r(n: int) -> int:\n \"\"\"Sum 1..n inclusive.\"\"\"\n if n < 0:\n raise ValueError(\"n must be non-negative\")\n total = 0\n for k in range(n): # BUG: should include n\n total += k\n return total\n```\n\nReturn unified diffs for d38f55wt.py and test_d38f55wt.py (pytest).\n\n*** Begin Patch\n*** Update File: d38f55wt.py\n@@\n def bay8tr_s7r(n: int) -> int:\n@@\n total = 0\n- for k in range(n): # BUG: should include n\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_d38f55wt.py\n+import pytest\n+from d38f55wt import bay8tr_s7r\n+\n+def test_zero():\n+ assert bay8tr_s7r(0) == 0\n+\n+def test_one():\n+ assert bay8tr_s7r(1) == 1\n+\n+def test_small():\n+ assert bay8tr_s7r(7) == 28\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ bay8tr_s7r(-1)\n+\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Build an elite-grade solution in the domain of edge/IoT for scenario: analytics pipeline.\nPrimary language: rust.\nDifficulty: medium.\nConstraints: provide rollout and rollback guidance, include tests or verification strategy, design for backward compatibility and migrations, make the interface contract explicit.\nComponent: component_tqzhpxu.\nAssume schema changes every sprint; must be backward compatible.\nTask: Implement or outline a storage/indexing subsystem (LSM/B-Tree, WAL, snapshots). Include transaction/consistency considerations and benchmark plan.\n\nOutput: rigorous solution with invariants, failure modes, and performance notes.\nOutput: storage design + WAL + compaction + benchmarks.\n\n**Design**\n- WAL (append-only) for durability; fsync policy configurable.\n- Memtable (in-memory) → flush to immutable SSTables.\n- LSM compaction tiers; bloom filters per SSTable for point-lookups.\n- Manifest tracks SSTable set; atomic pointer swap on updates.\n\n**Correctness**\n- Crash recovery: replay WAL to rebuild memtable; manifest ensures last consistent set.\n- Reads: merge memtable + SSTables newest→oldest; tombstones override older values.\n\n**Bench plan**\n- Workloads: write-heavy, read-heavy, mixed; measure p50/p95 latency and write amplification.\n- Track compaction debt and space amplification.\n\n**Test plan**\n- Fuzz crash points: kill after WAL append / after manifest update; verify invariants on restart.\n\n\nChecks: boundary validation and deterministic behavior verified.", "source": "WithinUsAI/Elite_GOD_Coder_100k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Refactor to modern typed Python with immutability and tests.\n\nFile: m0d7193v.py\n```python\nclass Ooekojhp4Vf:\n def __init__(self, name, values):\n self.name = name\n self.values = list(values)\n def add(self, v):\n self.values.append(v)\n def mean(self):\n s = 0\n for x in self.values:\n s += x\n return s / len(self.values)\n```\n\nReturn full new m0d7193v.py and test_m0d7193v.py.\n\n# m0d7193v.py\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom typing import Iterable, Tuple\n\n@dataclass(frozen=True)\nclass Ooekojhp4Vf:\n name: str\n values: Tuple[float, ...]\n\n @staticmethod\n def create(name: str, values: Iterable[float]) -> \"Ooekojhp4Vf\":\n vals = tuple(float(v) for v in values)\n if not vals:\n raise ValueError(\"values must be non-empty\")\n return Ooekojhp4Vf(name=name, values=vals)\n\n def add(self, v: float) -> \"Ooekojhp4Vf\":\n return Ooekojhp4Vf(name=self.name, values=self.values + (float(v),))\n\n def mean(self) -> float:\n return sum(self.values) / len(self.values)\n\n# test_m0d7193v.py\nimport pytest\nfrom m0d7193v import Ooekojhp4Vf\n\ndef test_mean_and_add():\n c = Ooekojhp4Vf.create(\"a\", [1, 2, 3])\n assert c.mean() == 2.0\n assert c.add(5).mean() == (1 + 2 + 3 + 5) / 4\n\ndef test_empty_raises():\n with pytest.raises(ValueError):\n Ooekojhp4Vf.create(\"x\", [])", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Task type: program_synthesis_safe\nScenario: edge sync\nDomain focus: fault injection & chaos engineering\nPrimary language: go\nDifficulty: hard\nScale/SLO: 10k RPS peak\nComponent: component_uopkiimf\nConstraints: assume adversarial inputs; validate everything, include failure modes and recovery, include verification strategy, avoid data races and undefined behavior, explicit contracts and invariants\nAssume hostile inputs and targeted abuse patterns.\nDeliverable: Design a program-synthesis workflow that generates code from specs safely; include guardrails and verification.\n\nOutput: elite engineering answer optimized for correctness, performance, and operability.\n**Contract**\n- Inputs validated at the boundary; explicit error taxonomy.\n- Idempotency for side effects via request_id; deterministic replay.\n- Backward compatibility: additive changes by default; versioned breaking changes.\n**Invariants**\n- Determinism: replay of the same event log yields identical outputs.\n- Liveness: under bounded faults and stable network, progress occurs.\n- Safety: state transitions preserve invariants; no partial commit leaks.\n**Failure modes & recovery**\n- Crash during commit: WAL replay completes or transaction aborts; no torn writes.\n- Network partition: minority cannot commit; clients receive retriable errors.\n- Duplicate requests: de-duplicate by (tenant, request_id) returning cached response.\n**Security posture (defensive)**\n- Threat model: auth/authz, injection, replay/abuse, supply chain.\n- Least privilege; secrets in managed store; audit logs for sensitive ops.\n- Input normalization, parameterized queries, path traversal protections.\n**Verification strategy**\n- Fuzzing of parsers/framers/validators with corpus seeds.\n- Property tests against a pure reference model (state machine).\n- Canary + shadow traffic; invariants checked in production via assertions/metrics.\n\n**Snippet**\n```text\nImplementation sketch: factor pure state-machine core; adapters for I/O; add deterministic replay log.\n```\nHard checks: fault injection tests gate merges; perf thresholds enforced in CI.", "source": "WithinUsAI/Omega_Genesis_Coder_100k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Refactor to modern typed Python with immutability and tests.\n\nFile: n7xm_f.py\n```python\nclass F25Z07Ko:\n def __init__(self, name, values):\n self.name = name\n self.values = list(values)\n def add(self, v):\n self.values.append(v)\n def mean(self):\n s = 0\n for x in self.values:\n s += x\n return s / len(self.values)\n```\n\nReturn full new n7xm_f.py and test_n7xm_f.py.\n\n# n7xm_f.py\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom typing import Iterable, Tuple\n\n@dataclass(frozen=True)\nclass F25Z07Ko:\n name: str\n values: Tuple[float, ...]\n\n @staticmethod\n def create(name: str, values: Iterable[float]) -> \"F25Z07Ko\":\n vals = tuple(float(v) for v in values)\n if not vals:\n raise ValueError(\"values must be non-empty\")\n return F25Z07Ko(name=name, values=vals)\n\n def add(self, v: float) -> \"F25Z07Ko\":\n return F25Z07Ko(name=self.name, values=self.values + (float(v),))\n\n def mean(self) -> float:\n return sum(self.values) / len(self.values)\n\n# test_n7xm_f.py\nimport pytest\nfrom n7xm_f import F25Z07Ko\n\ndef test_mean_and_add():\n c = F25Z07Ko.create(\"a\", [1, 2, 3])\n assert c.mean() == 2.0\n assert c.add(5).mean() == (1 + 2 + 3 + 5) / 4\n\ndef test_empty_raises():\n with pytest.raises(ValueError):\n F25Z07Ko.create(\"x\", [])", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Design and implement an algorithm for configuration loading.\nRequirements: define inputs/outputs, implement solution with complexity analysis, and include tests.\nConstraints: must include tests, must handle Windows paths safely, must be memory-efficient.\nDifficulty: expert. Include a small CLI example if relevant.\n\nDeliverable: production-ready reference solution.\nProblem: compute rolling sums over events (ts:int,value:int) with window W seconds. Events may be out-of-order.\n\nComplexity: sorting O(n log n); window maintenance O(n); memory O(k).\n\n```python\nfrom __future__ import annotations\nfrom collections import deque\nfrom dataclasses import dataclass\nfrom typing import Iterable, List, Tuple\n\n@dataclass(frozen=True, slots=True)\nclass Event:\n ts: int\n value: int\n\ndef rolling_sum(events: Iterable[Event], window_s: int) -> List[Tuple[int,int]]:\n if window_s < 0:\n raise ValueError(\"window_s must be >= 0\")\n evs = sorted(events, key=lambda e: e.ts)\n q: deque[Event] = deque()\n s = 0\n out: List[Tuple[int,int]] = []\n for e in evs:\n q.append(e)\n s += e.value\n cutoff = e.ts - window_s\n while q and q[0].ts < cutoff:\n old = q.popleft()\n s -= old.value\n out.append((e.ts, s))\n return out\n```\n\n```python\nimport pytest\nfrom module_under_test import Event, rolling_sum\n\ndef test_rolling_sum():\n ev = [Event(10,1), Event(11,2), Event(20,5)]\n assert rolling_sum(ev, 5) == [(10,1),(11,3),(20,5)]\n```", "source": "WithinUsAI/python_GOD_coder_100k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Produce an offline-first self-evolving code assistant architecture named `r5c1yy`.\nMust include: module layout, patch-safety policy, evaluation gates (tests/lint/types), versioned memory index.\n\nArchitecture: `r5c1yy` (offline-first, self-evolving)\n\nModules\n- core/loop.py: evolve → validate → accept/reject (bounded iterations)\n- patching/: diff builder, safe apply, atomic writes, rollback points\n- policy/: allowlist paths, deny globs (.git/, __pycache__/, binaries), patch size caps\n- signals/: parse pytest/ruff/mypy into normalized findings\n- memory/index.jsonl: append-only snapshots (hashes, metrics, rationale)\n\nSafety gates\n- refuse path traversal/symlink escapes; never edit binaries\n- accept only if tests/lint/types stay green or improve", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Optimize while preserving behavior.\n\nFile: cyaikf4s.py\n```python\ndef k88qwt4_(xs):\n out = []\n for x in xs:\n if x not in out:\n out.append(x)\n return out\n```\n\nRequirements: preserve first-seen order; O(n) average; add types + docstring.\n\n# cyaikf4s.py\nfrom __future__ import annotations\nfrom typing import Iterable, List, Set, TypeVar\n\nT = TypeVar(\"T\")\n\ndef k88qwt4_(xs: Iterable[T]) -> List[T]:\n \"\"\"Return unique items preserving first-seen order.\"\"\"\n seen: Set[T] = set()\n out: List[T] = []\n for x in xs:\n if x in seen:\n continue\n seen.add(x)\n out.append(x)\n return out", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Refactor to modern typed Python with immutability and tests.\n\nFile: v2nqx9y0xf.py\n```python\nclass S5Lcfkxykjj:\n def __init__(self, name, values):\n self.name = name\n self.values = list(values)\n def add(self, v):\n self.values.append(v)\n def mean(self):\n s = 0\n for x in self.values:\n s += x\n return s / len(self.values)\n```\n\nReturn full new v2nqx9y0xf.py and test_v2nqx9y0xf.py.\n\n# v2nqx9y0xf.py\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom typing import Iterable, Tuple\n\n@dataclass(frozen=True)\nclass S5Lcfkxykjj:\n name: str\n values: Tuple[float, ...]\n\n @staticmethod\n def create(name: str, values: Iterable[float]) -> \"S5Lcfkxykjj\":\n vals = tuple(float(v) for v in values)\n if not vals:\n raise ValueError(\"values must be non-empty\")\n return S5Lcfkxykjj(name=name, values=vals)\n\n def add(self, v: float) -> \"S5Lcfkxykjj\":\n return S5Lcfkxykjj(name=self.name, values=self.values + (float(v),))\n\n def mean(self) -> float:\n return sum(self.values) / len(self.values)\n\n# test_v2nqx9y0xf.py\nimport pytest\nfrom v2nqx9y0xf import S5Lcfkxykjj\n\ndef test_mean_and_add():\n c = S5Lcfkxykjj.create(\"a\", [1, 2, 3])\n assert c.mean() == 2.0\n assert c.add(5).mean() == (1 + 2 + 3 + 5) / 4\n\ndef test_empty_raises():\n with pytest.raises(ValueError):\n S5Lcfkxykjj.create(\"x\", [])", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Create a comprehensive test plan and automated tests for background jobs in a content moderation product.\nTarget platform: CI (GitHub Actions).\nRequirements: unit/integration tests, edge cases, load tests strategy, and CI gates.\nConstraints: must include clear error handling, must be easy to extend, must include type hints where applicable, must be performant under load, must be production-ready.\nDifficulty: expert. Assume untrusted input; validate everything.\n\nOutput: actionable implementation and verification artifacts.\nDeliverable: test plan + automation guidance.\n\n**Unit tests**\n- Validation: malformed payloads rejected with correct codes.\n- AuthZ: tenant boundary enforced.\n- Idempotency: replay returns same response; conflicting reuse yields 409.\n\n**Integration tests**\n- DB transaction behavior; unique constraints.\n- Cache behavior: correctness under concurrent requests.\n\n**Load tests**\n- 10k RPS target: measure p95 latency, error rate, saturation.\n\n**CI gates**\n- Lint + typecheck + unit tests required.\n- Coverage threshold for critical modules.\n- Block merge on flaky test detection.\n\n\nHard-mode checks: concurrency safety, idempotency, and rollback validated; add chaos tests where feasible.", "source": "WithinUsAI/GOD_Coder_100k"} {"text": "Task type: network_protocol\nScenario: multi-tenant event ingestion\nDomain focus: static analysis\nPrimary language: go\nDifficulty: hard\nScale/SLO: p99 < 150ms\nComponent: component_kmhhaata\nConstraints: explicit contracts and invariants, include failure modes and recovery, include backward compatibility and migration plan, include security threat model (defensive only), include performance model and limits, avoid data races and undefined behavior, include deterministic replay plan\nAssume hostile inputs and targeted abuse patterns.\nDeliverable: Design an application protocol: framing, retries, backpressure, timeouts; include client/server skeleton and test vectors.\n\nOutput: contract-first solution with failure modes, security posture, and test/verification strategy.\n**Contract**\n- Inputs validated at the boundary; explicit error taxonomy.\n- Idempotency for side effects via request_id; deterministic replay.\n- Backward compatibility: additive changes by default; versioned breaking changes.\n**Invariants**\n- Determinism: replay of the same event log yields identical outputs.\n- Isolation: tenant boundary enforced; no cross-tenant reads/writes.\n- Safety: state transitions preserve invariants; no partial commit leaks.\n**Failure modes & recovery**\n- Data corruption: checksums + scrubber; quarantine and rebuild from replicas/snapshots.\n- Duplicate requests: de-duplicate by (tenant, request_id) returning cached response.\n- Crash during commit: WAL replay completes or transaction aborts; no torn writes.\n**Security posture (defensive)**\n- Threat model: auth/authz, injection, replay/abuse, supply chain.\n- Least privilege; secrets in managed store; audit logs for sensitive ops.\n- Input normalization, parameterized queries, path traversal protections.\n**Verification strategy**\n- Fuzzing of parsers/framers/validators with corpus seeds.\n- Property tests against a pure reference model (state machine).\n- Canary + shadow traffic; invariants checked in production via assertions/metrics.\n\n**Snippet**\n```text\nImplementation sketch: factor pure state-machine core; adapters for I/O; add deterministic replay log.\n```\nHard checks: fault injection tests gate merges; perf thresholds enforced in CI.", "source": "WithinUsAI/Omega_Genesis_Coder_100k"} {"text": "Design a production system for gaming supporting webhooks.\nTarget platform: infra (Terraform).\nRequirements: APIs, data model, scaling strategy, failure modes, and security.\nConstraints: must be easy to extend, must include type hints where applicable, must include documentation/comments, must be production-ready, must be performant under load.\nDifficulty: hard. Assume schema evolves frequently; design for migrations.\n\nOutput: actionable implementation and verification artifacts.\nDeliverable: system design with APIs, data model, and operational plan.\n\n**High-level architecture**\n- Edge: API Gateway + WAF\n- Core service: stateless app pods behind L7 LB\n- Data: Postgres (primary), Redis (cache + rate limit tokens), Object storage (uploads if needed)\n- Async: message queue (e.g., SQS/Rabbit) + worker pool for background jobs\n- Observability: structured logs + metrics + tracing\n\n**APIs (example)**\n- `POST /v1/{resource}` create (idempotent via `Idempotency-Key`)\n- `GET /v1/{resource}/{id}` read\n- `POST /v1/{resource}/{id}:action` command endpoint when side effects exist\n\n**Data model (Postgres)**\n- `resources(id UUID PK, tenant_id UUID, status TEXT, payload JSONB, created_at, updated_at)`\n- Unique constraint for idempotency: `(tenant_id, idempotency_key)` in a separate table:\n - `idempotency(tenant_id, key TEXT, request_hash TEXT, response JSONB, created_at, PRIMARY KEY(tenant_id,key))`\n\n**Scaling**\n- App layer scales horizontally; keep sessions out of process.\n- Cache reads in Redis; write-through invalidation on mutations.\n- Use connection pooling; consider read replicas for heavy reads.\n\n**Failure modes**\n- Retries: only for safe/ idempotent operations; exponential backoff + jitter.\n- Partial failures: background jobs must be idempotent; use a de-dup key.\n\n**Security**\n- AuthN: JWT/OIDC; AuthZ: RBAC/ABAC with tenant isolation\n- Validate all inputs; enforce per-tenant quotas/rate limits.\n\n**Rollout**\n- Dark launch + feature flags; canary; rapid rollback by toggling flags.\n\n\nHard-mode checks: concurrency safety, idempotency, and rollback validated; add chaos tests where feasible.", "source": "WithinUsAI/GOD_Coder_100k"} {"text": "Add a clear docstring and type hints to this function:\n\n```python\ndef f13354(s):\n return ''.join(x for x in s if x.isalnum()).lower()\n```\n\n```python\nfrom __future__ import annotations\n\ndef f13354(s: str) -> str:\n \"\"\"Normalize a string: keep only alphanumerics and lowercase the result.\"\"\"\n return \"\".join(ch for ch in s if ch.isalnum()).lower()\n```", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Write pytest tests for `f58585`.\n\n```python\ndef f58585(a: int, b: int) -> int:\n return a*a + b*b\n```\nInclude edge cases and a property-style check.\n\n```python\nimport random\nfrom m22655 import f58585\n\ndef test_known():\n assert f58585(3,4) == 25\n\ndef test_zero():\n assert f58585(0,0) == 0\n\ndef test_property_nonnegative():\n for _ in range(200):\n a=random.randint(-50,50)\n b=random.randint(-50,50)\n assert f58585(a,b) >= 0\n```", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: System domain: data pipeline\nStack: Go, Gin, PostgreSQL, gRPC, Prometheus, Docker\nCross-layer incident: JWT refresh token rotation\nTask type: auth_session_repair\nDifficulty: hard\n\nSolve this as a complete-project engineer.\nOutput must include:\n- root cause across layers\n- final implementation patch\n- tests touching at least two layers\n- deployment or observability note\n- verification commands\n\nRepository sketch:\nrepo/\n src/App/Program.cs\n src/App/Service.cs\n tests/App.Tests/ServiceTests.cs\n App.sln\n\nFocus: Focus on multi-layer debugging across frontend, backend, database, CI, caching, and deployment.\n\nassistant: Diagnosis:\n- Root cause: JWT refresh token rotation crosses service boundaries, so the fix must align code, contracts, tests, and deployment behavior.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```csharp\nusing System;\nusing System.Collections.Generic;\n\npublic static class RequestHandler\n{\n public static Dictionary HandleRequest(Dictionary payload)\n {\n var clean = new Dictionary();\n foreach (var entry in payload)\n {\n if (entry.Value != null)\n clean[entry.Key.Trim()] = entry.Value;\n }\n if (!clean.ContainsKey(\"id\"))\n throw new ArgumentException(\"missing id\");\n return new Dictionary\n {\n [\"ok\"] = true,\n [\"data\"] = clean\n };\n }\n}\n```\n\nTests:\n```csharp\nusing System;\nusing System.Collections.Generic;\nusing Xunit;\n\npublic class RequestHandlerTests\n{\n [Fact]\n public void RequiresId()\n {\n Assert.Throws(() => RequestHandler.HandleRequest(new Dictionary { [\"name\"] = \"x\" }));\n }\n}\n```\n\nVerification:\n- `dotnet test`\n- `dotnet build`\n\nEngineering notes:\n- Language: C#\n- Framework/tooling: ASP.NET Core\n- Stack context: Go, Gin, PostgreSQL, gRPC, Prometheus, Docker\n- Domain: data pipeline\n- Task type: auth_session_repair\n- Difficulty: hard\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "Fix the bug and add pytest tests.\n\n```python\ndef f88187(n: int) -> int:\n # sum 1..n inclusive\n if n < 0: raise ValueError\n total = 0\n for k in range(n): # BUG\n total += k\n return total\n```\nReturn unified diffs for `m69741.py` and `test_m69741.py`.\n\n*** Begin Patch\n*** Update File: m69741.py\n@@\n def f88187(n: int) -> int:\n@@\n- for k in range(n): # BUG\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_m69741.py\n+import pytest\n+from m69741 import f88187\n+\n+def test_small():\n+ assert f88187(7) == 28\n+\n+def test_zero():\n+ assert f88187(0) == 0\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ f88187(-1)\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Fix the bug and add pytest tests.\n\n```python\ndef f00318(n: int) -> int:\n # sum 1..n inclusive\n if n < 0: raise ValueError\n total = 0\n for k in range(n): # BUG\n total += k\n return total\n```\nReturn unified diffs for `m71474.py` and `test_m71474.py`.\n\n*** Begin Patch\n*** Update File: m71474.py\n@@\n def f00318(n: int) -> int:\n@@\n- for k in range(n): # BUG\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_m71474.py\n+import pytest\n+from m71474 import f00318\n+\n+def test_small():\n+ assert f00318(7) == 28\n+\n+def test_zero():\n+ assert f00318(0) == 0\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ f00318(-1)\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Fix a bug and add tests.\n\nFile: gnkxrp4h.py\n```python\ndef zx5plgcq1x(n: int) -> int:\n \"\"\"Sum 1..n inclusive.\"\"\"\n if n < 0:\n raise ValueError(\"n must be non-negative\")\n total = 0\n for k in range(n): # BUG: should include n\n total += k\n return total\n```\n\nReturn unified diffs for gnkxrp4h.py and test_gnkxrp4h.py (pytest).\n\n*** Begin Patch\n*** Update File: gnkxrp4h.py\n@@\n def zx5plgcq1x(n: int) -> int:\n@@\n total = 0\n- for k in range(n): # BUG: should include n\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_gnkxrp4h.py\n+import pytest\n+from gnkxrp4h import zx5plgcq1x\n+\n+def test_zero():\n+ assert zx5plgcq1x(0) == 0\n+\n+def test_one():\n+ assert zx5plgcq1x(1) == 1\n+\n+def test_small():\n+ assert zx5plgcq1x(7) == 28\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ zx5plgcq1x(-1)\n+\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Optimize while preserving behavior.\n\nFile: kbxou6a9j5.py\n```python\ndef rj5i27s0edfv(xs):\n out = []\n for x in xs:\n if x not in out:\n out.append(x)\n return out\n```\n\nRequirements: preserve first-seen order; O(n) average; add types + docstring.\n\n# kbxou6a9j5.py\nfrom __future__ import annotations\nfrom typing import Iterable, List, Set, TypeVar\n\nT = TypeVar(\"T\")\n\ndef rj5i27s0edfv(xs: Iterable[T]) -> List[T]:\n \"\"\"Return unique items preserving first-seen order.\"\"\"\n seen: Set[T] = set()\n out: List[T] = []\n for x in xs:\n if x in seen:\n continue\n seen.add(x)\n out.append(x)\n return out", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Build an elite-grade solution in the domain of security engineering (defensive) for scenario: analytics pipeline.\nPrimary language: bash.\nDifficulty: expert.\nConstraints: avoid undefined behavior and data races, include invariants and failure modes, assume untrusted inputs; validate and sanitize.\nComponent: component_qdjmqyq.\nAssume 50k RPS and p99 < 250ms.\nTask: Define properties/invariants and implement property-based tests (or generative tests) with a reference model and edge-case generators.\n\nOutput: rigorous solution with invariants, failure modes, and performance notes.\nOutput: properties + reference model + generative tests.\n\n**Properties**\n- Idempotency: replayed command yields same result.\n- Monotonicity: versions only increase.\n- Conservation: for queues, produced items == consumed items (multiset) under no-loss assumption.\n\n**Approach**\n- Write a small reference model (pure function).\n- Generate random sequences of operations; compare implementation outputs to model.\n\n\nExpert checks: state-machine reasoning, concurrency stress, and upgrade/rollback validated.", "source": "WithinUsAI/Elite_GOD_Coder_100k"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: System domain: feature flag service\nStack: Airflow, dbt, DuckDB, MinIO, pytest\nCross-layer incident: memory leak in AST cache\nTask type: deploy_runtime_patch\nDifficulty: hard\n\nSolve this as a complete-project engineer.\nOutput must include:\n- root cause across layers\n- final implementation patch\n- tests touching at least two layers\n- deployment or observability note\n- verification commands\n\nRepository sketch:\nrepo/\n app/\n api.py\n service.py\n models.py\n tests/\n test_api.py\n pyproject.toml\n\nFocus: Focus on multi-layer debugging across frontend, backend, database, CI, caching, and deployment.\n\nassistant: Diagnosis:\n- Root cause: memory leak in AST cache crosses service boundaries, so the fix must align code, contracts, tests, and deployment behavior.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```python\nfrom __future__ import annotations\n\nfrom dataclasses import dataclass\nfrom typing import Any\n\n@dataclass\nclass ServiceResult:\n ok: bool\n data: dict[str, Any]\n error: str | None = None\n\ndef normalize_payload(payload: dict[str, Any]) -> dict[str, Any]:\n if not isinstance(payload, dict):\n raise TypeError(\"payload must be a dict\")\n clean: dict[str, Any] = {}\n for key, value in payload.items():\n if value is None:\n continue\n clean[str(key).strip()] = value\n return clean\n\ndef handle_memory_leak_in_ast_cache(payload: dict[str, Any]) -> ServiceResult:\n clean = normalize_payload(payload)\n if \"id\" not in clean:\n return ServiceResult(ok=False, data={}, error=\"missing id\")\n return ServiceResult(ok=True, data=clean)\n```\n\nTests:\n```python\nimport pytest\nfrom app.service import handle_jwt_refresh_token_rotation as handler\n\ndef test_handler_accepts_valid_payload():\n result = handler({\"id\": 7, \"name\": \"ok\", \"unused\": None})\n assert result.ok is True\n assert result.data == {\"id\": 7, \"name\": \"ok\"}\n\ndef test_handler_rejects_missing_id():\n result = handler({\"name\": \"x\"})\n assert result.ok is False\n assert result.error == \"missing id\"\n```\n\nVerification:\n- `pytest -q`\n- `ruff check .`\n- `python -m compileall .`\n\nEngineering notes:\n- Language: Python\n- Framework/tooling: FastAPI\n- Stack context: Airflow, dbt, DuckDB, MinIO, pytest\n- Domain: feature flag service\n- Task type: deploy_runtime_patch\n- Difficulty: hard\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: Project domain: model serving gateway\nImplementation stack: ASP.NET Core, SQL Server, EF Core, xUnit, Docker\nSoftware delivery problem: memory leak in AST cache\nTask type: rollback_safe_migration\nDifficulty: medium\n\nReturn a complete delivery-grade response with:\n- diagnosis or design reasoning\n- implementation\n- test plan or tests\n- rollout plan\n- rollback or compatibility note\n- verification commands\n\nRepository sketch:\nrepo/\n src/main.cpp\n src/service.cpp\n include/service.h\n tests/test_service.cpp\n CMakeLists.txt\n\nFocus: Focus on shipping production software with rollout safety, acceptance criteria, telemetry, and maintenance quality.\n\nassistant: Diagnosis:\n- Root cause or delivery blocker: memory leak in AST cache needs both implementation work and a safe shipping plan.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```cpp\n#include \n#include \n\nusing Payload = std::unordered_map;\n\nPayload normalize_payload(const Payload& in) {\n Payload out;\n for (const auto& [k, v] : in) {\n if (!v.empty()) out[k] = v;\n }\n return out;\n}\n```\n\nTests:\n```cpp\nTEST_CASE(\"normalize_payload filters empty values\") {\n Payload in{{\"id\",\"7\"},{\"name\",\"\"}};\n auto out = normalize_payload(in);\n REQUIRE(out.count(\"id\") == 1);\n REQUIRE(out.count(\"name\") == 0);\n}\n```\n\nVerification:\n- `cmake --build build`\n- `ctest --test-dir build`\n\nEngineering notes:\n- Language: C++\n- Framework/tooling: CMake\n- Stack context: ASP.NET Core, SQL Server, EF Core, xUnit, Docker\n- Domain: model serving gateway\n- Task type: rollback_safe_migration\n- Difficulty: medium\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Optimize while preserving behavior.\n\nFile: bjwbtl6v1xmd.py\n```python\ndef o6p8yxmm1y(xs):\n out = []\n for x in xs:\n if x not in out:\n out.append(x)\n return out\n```\n\nRequirements: preserve first-seen order; O(n) average; add types + docstring.\n\n# bjwbtl6v1xmd.py\nfrom __future__ import annotations\nfrom typing import Iterable, List, Set, TypeVar\n\nT = TypeVar(\"T\")\n\ndef o6p8yxmm1y(xs: Iterable[T]) -> List[T]:\n \"\"\"Return unique items preserving first-seen order.\"\"\"\n seen: Set[T] = set()\n out: List[T] = []\n for x in xs:\n if x in seen:\n continue\n seen.add(x)\n out.append(x)\n return out", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Perform a code review for a customer support PR implementing offline-first sync.\nTarget platform: data (SQL + Python).\nRequirements: list critical issues, improvements, and provide an improved patch excerpt.\nConstraints: must be performant under load, must include type hints where applicable, must be secure-by-default.\nDifficulty: hard. Assume mobile clients are occasionally offline.\n\nOutput: engineering-grade answer with edge cases covered.\nDeliverable: code review findings + improved patch excerpt.\n\n**Critical issues**\n1. Missing input validation at boundary; potential unexpected exceptions.\n2. No idempotency / retry safety for side-effecting endpoint.\n3. No tests for edge cases (empty input, duplicates, timeouts).\n4. Observability gaps: no request_id correlation, no metrics.\n\n**Improvements**\n- Add strict validation and explicit error responses.\n- Add idempotency key support for create endpoints.\n- Add unit + integration tests with CI gating.\n- Add structured logs and basic metrics.\n\nPatch excerpt (illustrative):\n```python\nif not idem_key:\n raise HTTPException(400, \"Missing Idempotency-Key\")\n```\n\n\nHard-mode checks: concurrency safety, idempotency, and rollback validated; add chaos tests where feasible.", "source": "WithinUsAI/GOD_Coder_100k"} {"text": "Build an elite-grade solution in the domain of sre/observability for scenario: document indexing.\nPrimary language: sql.\nDifficulty: medium.\nConstraints: include tests or verification strategy, design for backward compatibility and migrations, include invariants and failure modes, document performance characteristics, assume untrusted inputs; validate and sanitize.\nComponent: component_hbydubd.\nAssume strict auditability and replayable history.\nTask: Provide threat model, secure-by-default design, and defensive implementation patterns. No offensive/exploit content; focus on prevention and detection.\n\nOutput: production blueprint plus correctness arguments and test strategy.\nOutput: threat model + defensive design + detection.\n\n**Threat model**\n- Auth: token theft → short-lived tokens, rotation, audience checks\n- AuthZ: privilege escalation → centralized policy checks, tenant isolation tests\n- Input: injection → strict validation, parameterized queries, output encoding\n- Supply chain: dependencies → lockfiles, signature verification, SBOM\n\n**Defensive patterns**\n- Idempotency keys for side effects; replay-safe handlers\n- Secrets in managed store; never logs\n- Audit logging for sensitive ops; tamper-evident storage\n\n**Detection**\n- Alert on unusual auth failures, access pattern anomalies, and data exfil signals.\n\n\nChecks: boundary validation and deterministic behavior verified.", "source": "WithinUsAI/Elite_GOD_Coder_100k"} {"text": "Design a production system for fraud detection supporting multi-tenant isolation.\nTarget platform: infra (Docker + Kubernetes).\nRequirements: APIs, data model, scaling strategy, failure modes, and security.\nConstraints: must be secure-by-default, must avoid global state, must include clear error handling.\nDifficulty: expert. Assume mobile clients are occasionally offline.\n\nOutput: design + implementation guidance suitable for shipping.\nDeliverable: system design with APIs, data model, and operational plan.\n\n**High-level architecture**\n- Edge: API Gateway + WAF\n- Core service: stateless app pods behind L7 LB\n- Data: Postgres (primary), Redis (cache + rate limit tokens), Object storage (uploads if needed)\n- Async: message queue (e.g., SQS/Rabbit) + worker pool for background jobs\n- Observability: structured logs + metrics + tracing\n\n**APIs (example)**\n- `POST /v1/{resource}` create (idempotent via `Idempotency-Key`)\n- `GET /v1/{resource}/{id}` read\n- `POST /v1/{resource}/{id}:action` command endpoint when side effects exist\n\n**Data model (Postgres)**\n- `resources(id UUID PK, tenant_id UUID, status TEXT, payload JSONB, created_at, updated_at)`\n- Unique constraint for idempotency: `(tenant_id, idempotency_key)` in a separate table:\n - `idempotency(tenant_id, key TEXT, request_hash TEXT, response JSONB, created_at, PRIMARY KEY(tenant_id,key))`\n\n**Scaling**\n- App layer scales horizontally; keep sessions out of process.\n- Cache reads in Redis; write-through invalidation on mutations.\n- Use connection pooling; consider read replicas for heavy reads.\n\n**Failure modes**\n- Retries: only for safe/ idempotent operations; exponential backoff + jitter.\n- Partial failures: background jobs must be idempotent; use a de-dup key.\n\n**Security**\n- AuthN: JWT/OIDC; AuthZ: RBAC/ABAC with tenant isolation\n- Validate all inputs; enforce per-tenant quotas/rate limits.\n\n**Rollout**\n- Dark launch + feature flags; canary; rapid rollback by toggling flags.\n\n\nHard-mode checks: concurrency safety, idempotency, and rollback validated; add chaos tests where feasible.", "source": "WithinUsAI/GOD_Coder_100k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Fix a bug and add tests.\n\nFile: yfw02oq2.py\n```python\ndef ecu_g4prc(n: int) -> int:\n \"\"\"Sum 1..n inclusive.\"\"\"\n if n < 0:\n raise ValueError(\"n must be non-negative\")\n total = 0\n for k in range(n): # BUG: should include n\n total += k\n return total\n```\n\nReturn unified diffs for yfw02oq2.py and test_yfw02oq2.py (pytest).\n\n*** Begin Patch\n*** Update File: yfw02oq2.py\n@@\n def ecu_g4prc(n: int) -> int:\n@@\n total = 0\n- for k in range(n): # BUG: should include n\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_yfw02oq2.py\n+import pytest\n+from yfw02oq2 import ecu_g4prc\n+\n+def test_zero():\n+ assert ecu_g4prc(0) == 0\n+\n+def test_one():\n+ assert ecu_g4prc(1) == 1\n+\n+def test_small():\n+ assert ecu_g4prc(7) == 28\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ ecu_g4prc(-1)\n+\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Fix the bug and add pytest tests.\n\n```python\ndef f07986(n: int) -> int:\n # sum 1..n inclusive\n if n < 0: raise ValueError\n total = 0\n for k in range(n): # BUG\n total += k\n return total\n```\nReturn unified diffs for `m43998.py` and `test_m43998.py`.\n\n*** Begin Patch\n*** Update File: m43998.py\n@@\n def f07986(n: int) -> int:\n@@\n- for k in range(n): # BUG\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_m43998.py\n+import pytest\n+from m43998 import f07986\n+\n+def test_small():\n+ assert f07986(7) == 28\n+\n+def test_zero():\n+ assert f07986(0) == 0\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ f07986(-1)\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Fix a bug and add tests.\n\nFile: vdust1ygr.py\n```python\ndef w77jedi(n: int) -> int:\n \"\"\"Sum 1..n inclusive.\"\"\"\n if n < 0:\n raise ValueError(\"n must be non-negative\")\n total = 0\n for k in range(n): # BUG: should include n\n total += k\n return total\n```\n\nReturn unified diffs for vdust1ygr.py and test_vdust1ygr.py (pytest).\n\n*** Begin Patch\n*** Update File: vdust1ygr.py\n@@\n def w77jedi(n: int) -> int:\n@@\n total = 0\n- for k in range(n): # BUG: should include n\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_vdust1ygr.py\n+import pytest\n+from vdust1ygr import w77jedi\n+\n+def test_zero():\n+ assert w77jedi(0) == 0\n+\n+def test_one():\n+ assert w77jedi(1) == 1\n+\n+def test_small():\n+ assert w77jedi(7) == 28\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ w77jedi(-1)\n+\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Optimize while preserving behavior.\n\nFile: wg6ev5ezy6.py\n```python\ndef i44co2g3waoz(xs):\n out = []\n for x in xs:\n if x not in out:\n out.append(x)\n return out\n```\n\nRequirements: preserve first-seen order; O(n) average; add types + docstring.\n\n# wg6ev5ezy6.py\nfrom __future__ import annotations\nfrom typing import Iterable, List, Set, TypeVar\n\nT = TypeVar(\"T\")\n\ndef i44co2g3waoz(xs: Iterable[T]) -> List[T]:\n \"\"\"Return unique items preserving first-seen order.\"\"\"\n seen: Set[T] = set()\n out: List[T] = []\n for x in xs:\n if x in seen:\n continue\n seen.add(x)\n out.append(x)\n return out", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Optimize while preserving behavior and order.\n\n```python\ndef f37864(xs):\n out=[]\n for x in xs:\n if x not in out: out.append(x)\n return out\n```\nReturn `m62552.py` with types and O(n) average.\n\n```python\n# m62552.py\nfrom __future__ import annotations\nfrom typing import Iterable, List, Set, TypeVar\nT=TypeVar(\"T\")\n\ndef f37864(xs: Iterable[T]) -> List[T]:\n \"\"\"Unique items preserving first-seen order.\"\"\"\n seen: Set[T]=set()\n out: List[T]=[]\n for x in xs:\n if x in seen: continue\n seen.add(x); out.append(x)\n return out\n```", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Optimize while preserving behavior and order.\n\n```python\ndef f35372(xs):\n out=[]\n for x in xs:\n if x not in out: out.append(x)\n return out\n```\nReturn `m62196.py` with types and O(n) average.\n\n```python\n# m62196.py\nfrom __future__ import annotations\nfrom typing import Iterable, List, Set, TypeVar\nT=TypeVar(\"T\")\n\ndef f35372(xs: Iterable[T]) -> List[T]:\n \"\"\"Unique items preserving first-seen order.\"\"\"\n seen: Set[T]=set()\n out: List[T]=[]\n for x in xs:\n if x in seen: continue\n seen.add(x); out.append(x)\n return out\n```", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Build an elite-grade solution in the domain of gpu compute for scenario: multi-tenant SaaS.\nPrimary language: rust.\nDifficulty: hard.\nConstraints: make the interface contract explicit, document performance characteristics, assume untrusted inputs; validate and sanitize, include invariants and failure modes, provide rollout and rollback guidance.\nComponent: component_srigctf.\nAssume schema changes every sprint; must be backward compatible.\nTask: Define an API and evolving schema strategy (versioning, migrations, compatibility rules). Provide example schemas and validation tests.\n\nOutput: production blueprint plus correctness arguments and test strategy.\nOutput: GPU pipeline design for throughput and tail-latency.\n\n**Pipeline**\n- Request batching with max batch size + max wait (e.g., 5ms) to control p99.\n- Separate CPU pre/post-processing threads; pin memory for transfers if available.\n- Model warmup; cache weights in VRAM; use concurrency limits.\n\n**Monitoring**\n- GPU utilization, queue wait time, batch size distribution, OOM events.\n\n**Fallback**\n- Graceful degradation to smaller batch size; circuit breaker on repeated OOM.\n\n\nHard checks: failure injection tests and performance regressions gated.", "source": "WithinUsAI/Elite_GOD_Coder_100k"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: System domain: team dashboard\nStack: GitHub Actions, Docker Compose, Kubernetes, Terraform\nCross-layer incident: migration ordering failure\nTask type: auth_session_repair\nDifficulty: hard\n\nSolve this as a complete-project engineer.\nOutput must include:\n- root cause across layers\n- final implementation patch\n- tests touching at least two layers\n- deployment or observability note\n- verification commands\n\nRepository sketch:\nrepo/\n src/main.cpp\n src/service.cpp\n include/service.h\n tests/test_service.cpp\n CMakeLists.txt\n\nFocus: Focus on multi-layer debugging across frontend, backend, database, CI, caching, and deployment.\n\nassistant: Diagnosis:\n- Root cause: migration ordering failure crosses service boundaries, so the fix must align code, contracts, tests, and deployment behavior.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```cpp\n#include \n#include \n\nusing Payload = std::unordered_map;\n\nPayload normalize_payload(const Payload& in) {\n Payload out;\n for (const auto& [k, v] : in) {\n if (!v.empty()) out[k] = v;\n }\n return out;\n}\n```\n\nTests:\n```cpp\nTEST_CASE(\"normalize_payload filters empty values\") {\n Payload in{{\"id\",\"7\"},{\"name\",\"\"}};\n auto out = normalize_payload(in);\n REQUIRE(out.count(\"id\") == 1);\n REQUIRE(out.count(\"name\") == 0);\n}\n```\n\nVerification:\n- `cmake --build build`\n- `ctest --test-dir build`\n\nEngineering notes:\n- Language: C++\n- Framework/tooling: Catch2\n- Stack context: GitHub Actions, Docker Compose, Kubernetes, Terraform\n- Domain: team dashboard\n- Task type: auth_session_repair\n- Difficulty: hard\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: System domain: benchmark harness\nStack: Rust, Axum, SQLx, Redis, Tokio, Docker\nCross-layer incident: schema drift during deployment\nTask type: auth_session_repair\nDifficulty: hard\n\nSolve this as a complete-project engineer.\nOutput must include:\n- root cause across layers\n- final implementation patch\n- tests touching at least two layers\n- deployment or observability note\n- verification commands\n\nRepository sketch:\nrepo/\n src/main.cpp\n src/service.cpp\n include/service.h\n tests/test_service.cpp\n CMakeLists.txt\n\nFocus: Focus on multi-layer debugging across frontend, backend, database, CI, caching, and deployment.\n\nassistant: Diagnosis:\n- Root cause: schema drift during deployment crosses service boundaries, so the fix must align code, contracts, tests, and deployment behavior.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```cpp\n#include \n#include \n\nusing Payload = std::unordered_map;\n\nPayload normalize_payload(const Payload& in) {\n Payload out;\n for (const auto& [k, v] : in) {\n if (!v.empty()) out[k] = v;\n }\n return out;\n}\n```\n\nTests:\n```cpp\nTEST_CASE(\"normalize_payload filters empty values\") {\n Payload in{{\"id\",\"7\"},{\"name\",\"\"}};\n auto out = normalize_payload(in);\n REQUIRE(out.count(\"id\") == 1);\n REQUIRE(out.count(\"name\") == 0);\n}\n```\n\nVerification:\n- `cmake --build build`\n- `ctest --test-dir build`\n\nEngineering notes:\n- Language: C++\n- Framework/tooling: Catch2\n- Stack context: Rust, Axum, SQLx, Redis, Tokio, Docker\n- Domain: benchmark harness\n- Task type: auth_session_repair\n- Difficulty: hard\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "Task type: lockfree_primitive\nScenario: graph query service\nDomain focus: network protocols\nPrimary language: rust\nDifficulty: expert\nScale/SLO: p99 < 150ms\nComponent: component_bdhmfkwy\nConstraints: include verification strategy, include performance model and limits, include test vectors and fuzz strategy, include backward compatibility and migration plan, include security threat model (defensive only), avoid data races and undefined behavior, include deterministic replay plan\nAssume strict auditability and replayable history.\nDeliverable: Design a lock-free primitive with memory ordering reasoning and stress tests (no UB).\n\nOutput: rigorous design + invariants + verification plan + implementation sketch.\n**Contract**\n- Inputs validated at the boundary; explicit error taxonomy.\n- Idempotency for side effects via request_id; deterministic replay.\n- Backward compatibility: additive changes by default; versioned breaking changes.\n**Invariants**\n- Determinism: replay of the same event log yields identical outputs.\n- Safety: state transitions preserve invariants; no partial commit leaks.\n- Liveness: under bounded faults and stable network, progress occurs.\n**Failure modes & recovery**\n- Crash during commit: WAL replay completes or transaction aborts; no torn writes.\n- Network partition: minority cannot commit; clients receive retriable errors.\n- Duplicate requests: de-duplicate by (tenant, request_id) returning cached response.\n**Security posture (defensive)**\n- Threat model: auth/authz, injection, replay/abuse, supply chain.\n- Least privilege; secrets in managed store; audit logs for sensitive ops.\n- Input normalization, parameterized queries, path traversal protections.\n**Verification strategy**\n- Deterministic simulation with fault injection (crash/partition/latency).\n- Canary + shadow traffic; invariants checked in production via assertions/metrics.\n- Fuzzing of parsers/framers/validators with corpus seeds.\n\n**Snippet**\n```rust\n// Skeleton: SPSC ring buffer with acquire/release (outline)\nuse std::sync::atomic::{AtomicUsize, Ordering};\n\npub struct Ring {\n buf: Vec>,\n head: AtomicUsize,\n tail: AtomicUsize,\n cap: usize,\n}\n\n// Correctness sketch: producer uses Release on tail store, consumer uses Acquire on tail load.\n```\n\nExpert checks: state-machine proof sketch + model checking; upgrade/rollback rehearsed.", "source": "WithinUsAI/Omega_Genesis_Coder_100k"} {"text": "Task type: network_protocol\nScenario: job scheduler\nDomain focus: secure enclaves (defensive)\nPrimary language: bash\nDifficulty: expert\nScale/SLO: p99 < 50ms\nComponent: component_paxnwvgv\nConstraints: assume adversarial inputs; validate everything, include failure modes and recovery, avoid data races and undefined behavior, include deterministic replay plan, include performance model and limits\nAssume partial data corruption; include scrubbing strategy.\nDeliverable: Design an application protocol: framing, retries, backpressure, timeouts; include client/server skeleton and test vectors.\n\nOutput: contract-first solution with failure modes, security posture, and test/verification strategy.\n**Contract**\n- Inputs validated at the boundary; explicit error taxonomy.\n- Idempotency for side effects via request_id; deterministic replay.\n- Backward compatibility: additive changes by default; versioned breaking changes.\n**Invariants**\n- Isolation: tenant boundary enforced; no cross-tenant reads/writes.\n- Liveness: under bounded faults and stable network, progress occurs.\n- Determinism: replay of the same event log yields identical outputs.\n**Failure modes & recovery**\n- Data corruption: checksums + scrubber; quarantine and rebuild from replicas/snapshots.\n- Duplicate requests: de-duplicate by (tenant, request_id) returning cached response.\n- Network partition: minority cannot commit; clients receive retriable errors.\n**Security posture (defensive)**\n- Threat model: auth/authz, injection, replay/abuse, supply chain.\n- Least privilege; secrets in managed store; audit logs for sensitive ops.\n- Input normalization, parameterized queries, path traversal protections.\n**Verification strategy**\n- Fuzzing of parsers/framers/validators with corpus seeds.\n- Deterministic simulation with fault injection (crash/partition/latency).\n- Canary + shadow traffic; invariants checked in production via assertions/metrics.\n\n**Snippet**\n```text\nImplementation sketch: factor pure state-machine core; adapters for I/O; add deterministic replay log.\n```\nExpert checks: state-machine proof sketch + model checking; upgrade/rollback rehearsed.", "source": "WithinUsAI/Omega_Genesis_Coder_100k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Refactor to modern typed Python with immutability and tests.\n\nFile: er_mnrc5.py\n```python\nclass Bvw1Qscim:\n def __init__(self, name, values):\n self.name = name\n self.values = list(values)\n def add(self, v):\n self.values.append(v)\n def mean(self):\n s = 0\n for x in self.values:\n s += x\n return s / len(self.values)\n```\n\nReturn full new er_mnrc5.py and test_er_mnrc5.py.\n\n# er_mnrc5.py\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom typing import Iterable, Tuple\n\n@dataclass(frozen=True)\nclass Bvw1Qscim:\n name: str\n values: Tuple[float, ...]\n\n @staticmethod\n def create(name: str, values: Iterable[float]) -> \"Bvw1Qscim\":\n vals = tuple(float(v) for v in values)\n if not vals:\n raise ValueError(\"values must be non-empty\")\n return Bvw1Qscim(name=name, values=vals)\n\n def add(self, v: float) -> \"Bvw1Qscim\":\n return Bvw1Qscim(name=self.name, values=self.values + (float(v),))\n\n def mean(self) -> float:\n return sum(self.values) / len(self.values)\n\n# test_er_mnrc5.py\nimport pytest\nfrom er_mnrc5 import Bvw1Qscim\n\ndef test_mean_and_add():\n c = Bvw1Qscim.create(\"a\", [1, 2, 3])\n assert c.mean() == 2.0\n assert c.add(5).mean() == (1 + 2 + 3 + 5) / 4\n\ndef test_empty_raises():\n with pytest.raises(ValueError):\n Bvw1Qscim.create(\"x\", [])", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Refactor to typed, mostly-immutable Python and add minimal tests.\n\n```python\nclass C16618:\n def __init__(self, values): self.values=list(values)\n def mean(self): return sum(self.values)/len(self.values)\n```\nReturn `m93586.py` and `test_m93586.py`.\n\n```python\n# m93586.py\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom typing import Iterable, Tuple\n\n@dataclass(frozen=True)\nclass C16618:\n values: Tuple[float, ...]\n\n @staticmethod\n def create(values: Iterable[float]) -> \"C16618\":\n vals = tuple(float(v) for v in values)\n if not vals: raise ValueError(\"empty\")\n return C16618(vals)\n\n def mean(self) -> float:\n return sum(self.values)/len(self.values)\n```\n\n```python\n# test_m93586.py\nimport pytest\nfrom m93586 import C16618\n\ndef test_mean():\n assert C16618.create([1,2,3]).mean() == 2.0\ndef test_empty():\n with pytest.raises(ValueError):\n C16618.create([])\n```", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Refactor to typed, mostly-immutable Python and add minimal tests.\n\n```python\nclass C29801:\n def __init__(self, values): self.values=list(values)\n def mean(self): return sum(self.values)/len(self.values)\n```\nReturn `m17677.py` and `test_m17677.py`.\n\n```python\n# m17677.py\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom typing import Iterable, Tuple\n\n@dataclass(frozen=True)\nclass C29801:\n values: Tuple[float, ...]\n\n @staticmethod\n def create(values: Iterable[float]) -> \"C29801\":\n vals = tuple(float(v) for v in values)\n if not vals: raise ValueError(\"empty\")\n return C29801(vals)\n\n def mean(self) -> float:\n return sum(self.values)/len(self.values)\n```\n\n```python\n# test_m17677.py\nimport pytest\nfrom m17677 import C29801\n\ndef test_mean():\n assert C29801.create([1,2,3]).mean() == 2.0\ndef test_empty():\n with pytest.raises(ValueError):\n C29801.create([])\n```", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Design and implement an algorithm for task scheduling.\nRequirements: define inputs/outputs, implement solution with complexity analysis, and include tests.\nConstraints: stdlib-only, must be easy to extend.\nDifficulty: easy. Ensure the API is testable via dependency injection.\n\nDeliverable: API + reference implementation + tests.\nProblem: compute rolling sums over events (ts:int,value:int) with window W seconds. Events may be out-of-order.\n\nComplexity: sorting O(n log n); window maintenance O(n); memory O(k).\n\n```python\nfrom __future__ import annotations\nfrom collections import deque\nfrom dataclasses import dataclass\nfrom typing import Iterable, List, Tuple\n\n@dataclass(frozen=True, slots=True)\nclass Event:\n ts: int\n value: int\n\ndef rolling_sum(events: Iterable[Event], window_s: int) -> List[Tuple[int,int]]:\n if window_s < 0:\n raise ValueError(\"window_s must be >= 0\")\n evs = sorted(events, key=lambda e: e.ts)\n q: deque[Event] = deque()\n s = 0\n out: List[Tuple[int,int]] = []\n for e in evs:\n q.append(e)\n s += e.value\n cutoff = e.ts - window_s\n while q and q[0].ts < cutoff:\n old = q.popleft()\n s -= old.value\n out.append((e.ts, s))\n return out\n```\n\n```python\nimport pytest\nfrom module_under_test import Event, rolling_sum\n\ndef test_rolling_sum():\n ev = [Event(10,1), Event(11,2), Event(20,5)]\n assert rolling_sum(ev, 5) == [(10,1),(11,3),(20,5)]\n```", "source": "WithinUsAI/python_GOD_coder_100k"} {"text": "Optimize while preserving behavior and order.\n\n```python\ndef f00510(xs):\n out=[]\n for x in xs:\n if x not in out: out.append(x)\n return out\n```\nReturn `m42930.py` with types and O(n) average.\n\n```python\n# m42930.py\nfrom __future__ import annotations\nfrom typing import Iterable, List, Set, TypeVar\nT=TypeVar(\"T\")\n\ndef f00510(xs: Iterable[T]) -> List[T]:\n \"\"\"Unique items preserving first-seen order.\"\"\"\n seen: Set[T]=set()\n out: List[T]=[]\n for x in xs:\n if x in seen: continue\n seen.add(x); out.append(x)\n return out\n```", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Design and implement an algorithm for metrics aggregation.\nRequirements: define inputs/outputs, implement solution with complexity analysis, and include tests.\nConstraints: must include docstrings, must be easy to extend, must provide clear error messages.\nDifficulty: expert. Provide helpful exceptions with actionable messages.\n\nDeliverable: implementation + tests.\nProblem: compute rolling sums over events (ts:int,value:int) with window W seconds. Events may be out-of-order.\n\nComplexity: sorting O(n log n); window maintenance O(n); memory O(k).\n\n```python\nfrom __future__ import annotations\nfrom collections import deque\nfrom dataclasses import dataclass\nfrom typing import Iterable, List, Tuple\n\n@dataclass(frozen=True, slots=True)\nclass Event:\n ts: int\n value: int\n\ndef rolling_sum(events: Iterable[Event], window_s: int) -> List[Tuple[int,int]]:\n if window_s < 0:\n raise ValueError(\"window_s must be >= 0\")\n evs = sorted(events, key=lambda e: e.ts)\n q: deque[Event] = deque()\n s = 0\n out: List[Tuple[int,int]] = []\n for e in evs:\n q.append(e)\n s += e.value\n cutoff = e.ts - window_s\n while q and q[0].ts < cutoff:\n old = q.popleft()\n s -= old.value\n out.append((e.ts, s))\n return out\n```\n\n```python\nimport pytest\nfrom module_under_test import Event, rolling_sum\n\ndef test_rolling_sum():\n ev = [Event(10,1), Event(11,2), Event(20,5)]\n assert rolling_sum(ev, 5) == [(10,1),(11,3),(20,5)]\n```", "source": "WithinUsAI/python_GOD_coder_100k"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: Project domain: feature flag service\nImplementation stack: ASP.NET Core, SQL Server, EF Core, xUnit, Docker\nSoftware delivery problem: log redaction failure\nTask type: test_strategy_implementation\nDifficulty: medium\n\nReturn a complete delivery-grade response with:\n- diagnosis or design reasoning\n- implementation\n- test plan or tests\n- rollout plan\n- rollback or compatibility note\n- verification commands\n\nRepository sketch:\nrepo/\n src/main/java/com/acme/App.java\n src/main/java/com/acme/Service.java\n src/test/java/com/acme/AppTest.java\n pom.xml\n\nFocus: Focus on shipping production software with rollout safety, acceptance criteria, telemetry, and maintenance quality.\n\nassistant: Diagnosis:\n- Root cause or delivery blocker: log redaction failure needs both implementation work and a safe shipping plan.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```java\nimport java.util.HashMap;\nimport java.util.Map;\n\npublic final class RequestHandler {\n public static Map handleRequest(Map payload) {\n Map clean = new HashMap<>();\n for (Map.Entry entry : payload.entrySet()) {\n if (entry.getValue() != null) clean.put(entry.getKey().trim(), entry.getValue());\n }\n if (!clean.containsKey(\"id\")) throw new IllegalArgumentException(\"missing id\");\n return Map.of(\"ok\", true, \"data\", clean);\n }\n}\n```\n\nTests:\n```java\nimport static org.junit.jupiter.api.Assertions.*;\nimport java.util.Map;\nimport org.junit.jupiter.api.Test;\n\nclass RequestHandlerTest {\n @Test\n void requiresId() {\n assertThrows(IllegalArgumentException.class, () -> RequestHandler.handleRequest(Map.of(\"name\", \"x\")));\n }\n}\n```\n\nVerification:\n- `./gradlew test`\n- `mvn test`\n\nEngineering notes:\n- Language: Java\n- Framework/tooling: Hibernate\n- Stack context: ASP.NET Core, SQL Server, EF Core, xUnit, Docker\n- Domain: feature flag service\n- Task type: test_strategy_implementation\n- Difficulty: medium\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Fix a bug and add tests.\n\nFile: e00nfwb5qrp.py\n```python\ndef as5htu4x(n: int) -> int:\n \"\"\"Sum 1..n inclusive.\"\"\"\n if n < 0:\n raise ValueError(\"n must be non-negative\")\n total = 0\n for k in range(n): # BUG: should include n\n total += k\n return total\n```\n\nReturn unified diffs for e00nfwb5qrp.py and test_e00nfwb5qrp.py (pytest).\n\n*** Begin Patch\n*** Update File: e00nfwb5qrp.py\n@@\n def as5htu4x(n: int) -> int:\n@@\n total = 0\n- for k in range(n): # BUG: should include n\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_e00nfwb5qrp.py\n+import pytest\n+from e00nfwb5qrp import as5htu4x\n+\n+def test_zero():\n+ assert as5htu4x(0) == 0\n+\n+def test_one():\n+ assert as5htu4x(1) == 1\n+\n+def test_small():\n+ assert as5htu4x(7) == 28\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ as5htu4x(-1)\n+\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Write pytest tests for `f17288`.\n\n```python\ndef f17288(a: int, b: int) -> int:\n return a*a + b*b\n```\nInclude edge cases and a property-style check.\n\n```python\nimport random\nfrom m88184 import f17288\n\ndef test_known():\n assert f17288(3,4) == 25\n\ndef test_zero():\n assert f17288(0,0) == 0\n\ndef test_property_nonnegative():\n for _ in range(200):\n a=random.randint(-50,50)\n b=random.randint(-50,50)\n assert f17288(a,b) >= 0\n```", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Fix the bug and add pytest tests.\n\n```python\ndef f35006(n: int) -> int:\n # sum 1..n inclusive\n if n < 0: raise ValueError\n total = 0\n for k in range(n): # BUG\n total += k\n return total\n```\nReturn unified diffs for `m47858.py` and `test_m47858.py`.\n\n*** Begin Patch\n*** Update File: m47858.py\n@@\n def f35006(n: int) -> int:\n@@\n- for k in range(n): # BUG\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_m47858.py\n+import pytest\n+from m47858 import f35006\n+\n+def test_small():\n+ assert f35006(7) == 28\n+\n+def test_zero():\n+ assert f35006(0) == 0\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ f35006(-1)\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Task type: gpu_serving_pipeline\nScenario: time-series metrics store\nDomain focus: high-frequency trading systems (safe engineering)\nPrimary language: typescript\nDifficulty: hard\nScale/SLO: 100k RPS peak\nComponent: component_xebeiupw\nConstraints: include verification strategy, include security threat model (defensive only), assume adversarial inputs; validate everything, avoid data races and undefined behavior, include performance model and limits\nAssume crash-only processes; recovery must be deterministic.\nDeliverable: Design a GPU inference serving pipeline: batching, scheduling, memory management, tail-latency control, and monitoring.\n\nOutput: elite engineering answer optimized for correctness, performance, and operability.\n**Contract**\n- Inputs validated at the boundary; explicit error taxonomy.\n- Idempotency for side effects via request_id; deterministic replay.\n- Backward compatibility: additive changes by default; versioned breaking changes.\n**Invariants**\n- Isolation: tenant boundary enforced; no cross-tenant reads/writes.\n- Liveness: under bounded faults and stable network, progress occurs.\n- Determinism: replay of the same event log yields identical outputs.\n**Failure modes & recovery**\n- Crash during commit: WAL replay completes or transaction aborts; no torn writes.\n- Data corruption: checksums + scrubber; quarantine and rebuild from replicas/snapshots.\n- Network partition: minority cannot commit; clients receive retriable errors.\n**Security posture (defensive)**\n- Threat model: auth/authz, injection, replay/abuse, supply chain.\n- Least privilege; secrets in managed store; audit logs for sensitive ops.\n- Input normalization, parameterized queries, path traversal protections.\n**Verification strategy**\n- Property tests against a pure reference model (state machine).\n- Deterministic simulation with fault injection (crash/partition/latency).\n- Canary + shadow traffic; invariants checked in production via assertions/metrics.\n\n**Snippet**\n```text\nImplementation sketch: factor pure state-machine core; adapters for I/O; add deterministic replay log.\n```\nHard checks: fault injection tests gate merges; perf thresholds enforced in CI.", "source": "WithinUsAI/Omega_Genesis_Coder_100k"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: Language: YAML\nFramework/tooling: GitHub Actions\nDomain: team dashboard\nLogic challenge: path traversal on downloads\nTask type: security_logic_interaction\nDifficulty: hard\n\nReturn a rigorous engineering answer:\n- identify the hidden root cause or logical failure\n- present the corrected implementation\n- add tests that prove the fix\n- list verification commands\n- explain why naive fixes are insufficient when relevant\n\nRepository sketch:\nrepo/\n .github/workflows/ci.yml\n docker-compose.yml\n deploy/\n app.yaml\n\nFocus: Focus on ambiguity, misleading symptoms, hidden root causes, and high-stakes debugging.\n\nassistant: Diagnosis:\n- Hidden root cause: path traversal on downloads presents misleading symptoms, so the patch must target the actual logic boundary rather than the first visible failure.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```yaml\nname: ci\non: [push, pull_request]\njobs:\n test:\n runs-on: ubuntu-latest\n steps:\n - uses: actions/checkout@v4\n - name: Validate\n run: echo \"validated\"\n```\n\nTests:\n```yaml\n# Verification:\n# - validate syntax\n# - run smoke workflow\n# - fail fast on broken config\n```\n\nVerification:\n- `validate workflow syntax`\n- `run CI smoke job`\n\nEngineering notes:\n- Language: YAML\n- Framework/tooling: GitHub Actions\n- Stack context: Next.js, Node.js, Prisma, PostgreSQL, Playwright, Docker\n- Domain: team dashboard\n- Task type: security_logic_interaction\n- Difficulty: hard\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "Refactor an existing codebase in e-commerce to support rate limiting cleanly.\nTarget platform: infra (Terraform).\nRequirements: propose new modules/layers, dependency boundaries, and migration plan.\nConstraints: must include type hints where applicable, must be observable (logs/metrics/traces), must include clear error handling, must be performant under load, must be production-ready.\nDifficulty: expert. Assume GDPR-style deletion requests must be supported.\n\nOutput: production-oriented blueprint with code where appropriate.\nDeliverable: refactor plan + module boundaries.\n\n**Proposed modules**\n- `domain/` pure business logic (no I/O)\n- `adapters/` DB, cache, external APIs\n- `api/` request/response validation and routing\n- `observability/` logging/metrics/tracing\n- `tests/` unit + integration suites\n\n**Migration plan**\n1. Introduce new interfaces + adapters behind feature flags.\n2. Dual-write or read-compat layer if schema changes.\n3. Incremental cutover; deprecate legacy module.\n\nKey rule: dependencies flow inward; domain has no framework imports.\n\n\nHard-mode checks: concurrency safety, idempotency, and rollback validated; add chaos tests where feasible.", "source": "WithinUsAI/GOD_Coder_100k"} {"text": "Design CI/CD for a customer support service delivering event-driven workflows.\nTarget platform: mobile (iOS Swift).\nRequirements: pipelines, checks, artifact strategy, deployments, and rollbacks.\nConstraints: must be observable (logs/metrics/traces), must be performant under load, must be production-ready, must avoid global state, must include tests.\nDifficulty: expert. Assume 10k RPS peak traffic.\n\nOutput: production-oriented blueprint with code where appropriate.\nDeliverable: CI/CD pipeline (GitHub Actions) with quality gates.\n\n```yaml\nname: ci\non:\n pull_request:\n push:\n branches: [main]\n\njobs:\n test:\n runs-on: ubuntu-latest\n steps:\n - uses: actions/checkout@v4\n - uses: actions/setup-python@v5\n with:\n python-version: \"3.11\"\n - run: python -m pip install -U pip\n - run: pip install -r requirements.txt\n - run: pip install -r requirements-dev.txt\n - run: ruff check .\n - run: mypy .\n - run: pytest -q --maxfail=1 --disable-warnings\n\n docker:\n needs: test\n runs-on: ubuntu-latest\n steps:\n - uses: actions/checkout@v4\n - uses: docker/setup-buildx-action@v3\n - run: docker build -t app:${{ github.sha }} .\n```\n\nDeployment strategy:\n- main → build → deploy to staging → smoke tests → canary to prod.\n- Rollback: redeploy previous image + DB migration rollback plan.\n\n\nHard-mode checks: concurrency safety, idempotency, and rollback validated; add chaos tests where feasible.", "source": "WithinUsAI/GOD_Coder_100k"} {"text": "Design CI/CD for a social media service delivering analytics pipeline.\nTarget platform: backend (Go).\nRequirements: pipelines, checks, artifact strategy, deployments, and rollbacks.\nConstraints: must avoid global state, must include type hints where applicable, must include tests, must be observable (logs/metrics/traces).\nDifficulty: hard. Assume strict latency budget (p95 < 200ms).\n\nOutput: production-oriented blueprint with code where appropriate.\nDeliverable: CI/CD pipeline (GitHub Actions) with quality gates.\n\n```yaml\nname: ci\non:\n pull_request:\n push:\n branches: [main]\n\njobs:\n test:\n runs-on: ubuntu-latest\n steps:\n - uses: actions/checkout@v4\n - uses: actions/setup-python@v5\n with:\n python-version: \"3.11\"\n - run: python -m pip install -U pip\n - run: pip install -r requirements.txt\n - run: pip install -r requirements-dev.txt\n - run: ruff check .\n - run: mypy .\n - run: pytest -q --maxfail=1 --disable-warnings\n\n docker:\n needs: test\n runs-on: ubuntu-latest\n steps:\n - uses: actions/checkout@v4\n - uses: docker/setup-buildx-action@v3\n - run: docker build -t app:${{ github.sha }} .\n```\n\nDeployment strategy:\n- main → build → deploy to staging → smoke tests → canary to prod.\n- Rollback: redeploy previous image + DB migration rollback plan.\n\n\nHard-mode checks: concurrency safety, idempotency, and rollback validated; add chaos tests where feasible.", "source": "WithinUsAI/GOD_Coder_100k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Fix a bug and add tests.\n\nFile: pv_kai4.py\n```python\ndef z5g964v(n: int) -> int:\n \"\"\"Sum 1..n inclusive.\"\"\"\n if n < 0:\n raise ValueError(\"n must be non-negative\")\n total = 0\n for k in range(n): # BUG: should include n\n total += k\n return total\n```\n\nReturn unified diffs for pv_kai4.py and test_pv_kai4.py (pytest).\n\n*** Begin Patch\n*** Update File: pv_kai4.py\n@@\n def z5g964v(n: int) -> int:\n@@\n total = 0\n- for k in range(n): # BUG: should include n\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_pv_kai4.py\n+import pytest\n+from pv_kai4 import z5g964v\n+\n+def test_zero():\n+ assert z5g964v(0) == 0\n+\n+def test_one():\n+ assert z5g964v(1) == 1\n+\n+def test_small():\n+ assert z5g964v(7) == 28\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ z5g964v(-1)\n+\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Build an elite-grade solution in the domain of gpu compute for scenario: event ingestion.\nPrimary language: go.\nDifficulty: expert.\nConstraints: avoid undefined behavior and data races, assume untrusted inputs; validate and sanitize, include invariants and failure modes, provide rollout and rollback guidance.\nComponent: component_eaqamxf.\nAssume crash-only design; recovery must be deterministic.\nTask: Optimize a hot path with profiling-driven approach; propose micro/meso optimizations, and supply a benchmark harness with acceptance thresholds.\n\nOutput: production blueprint plus correctness arguments and test strategy.\nOutput: profiling-first optimization + benchmark harness.\n\n**Plan**\n1. Establish baseline with microbench + representative dataset.\n2. Profile (CPU, allocations, syscalls).\n3. Apply optimizations: reduce allocations, reuse buffers, batch I/O, vectorize parsing where safe.\n4. Validate with regression suite and perf thresholds.\n\n**Benchmark guidance**\n- Use p50/p95 and throughput; pin CPU frequency if possible.\n- Acceptance: p95 improves ≥ X% with no correctness regressions.\n\n\nExpert checks: state-machine reasoning, concurrency stress, and upgrade/rollback validated.", "source": "WithinUsAI/Elite_GOD_Coder_100k"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: Language: SQL\nFramework/tooling: MySQL\nDomain: notification service\nLogic challenge: unsafe deserialization\nTask type: monorepo_toolchain_recovery\nDifficulty: hard\n\nReturn a rigorous engineering answer:\n- identify the hidden root cause or logical failure\n- present the corrected implementation\n- add tests that prove the fix\n- list verification commands\n- explain why naive fixes are insufficient when relevant\n\nRepository sketch:\nrepo/\n migrations/\n 001_init.sql\n 002_add_index.sql\n queries/\n report.sql\n tests/\n report_cases.md\n\nFocus: Focus on staff-level problem solving with multi-file patches, rollout implications, performance and security tradeoffs.\n\nassistant: Diagnosis:\n- Staff-level diagnosis: unsafe deserialization impacts correctness, operability, and future maintenance, so the fix must be minimal where possible but complete where necessary.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```sql\nWITH ranked AS (\n SELECT\n user_id,\n created_at,\n amount,\n ROW_NUMBER() OVER (PARTITION BY user_id ORDER BY created_at DESC, id DESC) AS rn\n FROM orders\n)\nSELECT user_id, created_at, amount\nFROM ranked\nWHERE rn = 1;\n```\n\nTests:\n```sql\n-- Correctness checks:\n-- 1) multiple rows per user\n-- 2) identical timestamps require deterministic tie-breaker\n-- 3) null values handled by business rules\n```\n\nVerification:\n- `run migration checks`\n- `run query correctness cases`\n\nEngineering notes:\n- Language: SQL\n- Framework/tooling: MySQL\n- Stack context: Rust, Axum, SQLx, Redis, Tokio, Docker\n- Domain: notification service\n- Task type: monorepo_toolchain_recovery\n- Difficulty: hard\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Produce an offline-first self-evolving code assistant architecture named `eupwupk`.\nMust include: module layout, patch-safety policy, evaluation gates (tests/lint/types), versioned memory index.\n\nArchitecture: `eupwupk` (offline-first, self-evolving)\n\nModules\n- core/loop.py: evolve → validate → accept/reject (bounded iterations)\n- patching/: diff builder, safe apply, atomic writes, rollback points\n- policy/: allowlist paths, deny globs (.git/, __pycache__/, binaries), patch size caps\n- signals/: parse pytest/ruff/mypy into normalized findings\n- memory/index.jsonl: append-only snapshots (hashes, metrics, rationale)\n\nSafety gates\n- refuse path traversal/symlink escapes; never edit binaries\n- accept only if tests/lint/types stay green or improve", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Write pytest tests for `f64337`.\n\n```python\ndef f64337(a: int, b: int) -> int:\n return a*a + b*b\n```\nInclude edge cases and a property-style check.\n\n```python\nimport random\nfrom m09191 import f64337\n\ndef test_known():\n assert f64337(3,4) == 25\n\ndef test_zero():\n assert f64337(0,0) == 0\n\ndef test_property_nonnegative():\n for _ in range(200):\n a=random.randint(-50,50)\n b=random.randint(-50,50)\n assert f64337(a,b) >= 0\n```", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Build an elite-grade solution in the domain of databases for scenario: chat messaging.\nPrimary language: go.\nDifficulty: medium.\nConstraints: include tests or verification strategy, design for backward compatibility and migrations, make the interface contract explicit, provide rollout and rollback guidance.\nComponent: component_jqcbzdy.\nAssume schema changes every sprint; must be backward compatible.\nTask: Define properties/invariants and implement property-based tests (or generative tests) with a reference model and edge-case generators.\n\nOutput: rigorous solution with invariants, failure modes, and performance notes.\nOutput: properties + reference model + generative tests.\n\n**Properties**\n- Idempotency: replayed command yields same result.\n- Monotonicity: versions only increase.\n- Conservation: for queues, produced items == consumed items (multiset) under no-loss assumption.\n\n**Approach**\n- Write a small reference model (pure function).\n- Generate random sequences of operations; compare implementation outputs to model.\n\n\nChecks: boundary validation and deterministic behavior verified.", "source": "WithinUsAI/Elite_GOD_Coder_100k"} {"text": "Build an elite-grade solution in the domain of operating systems for scenario: edge sync.\nPrimary language: python.\nDifficulty: hard.\nConstraints: include tests or verification strategy, document performance characteristics, include invariants and failure modes.\nComponent: component_huxfsnj.\nAssume crash-only design; recovery must be deterministic.\nTask: Optimize a hot path with profiling-driven approach; propose micro/meso optimizations, and supply a benchmark harness with acceptance thresholds.\n\nOutput: elite-grade engineering answer with contracts, edge cases, and verification.\nOutput: profiling-first optimization + benchmark harness.\n\n**Plan**\n1. Establish baseline with microbench + representative dataset.\n2. Profile (CPU, allocations, syscalls).\n3. Apply optimizations: reduce allocations, reuse buffers, batch I/O, vectorize parsing where safe.\n4. Validate with regression suite and perf thresholds.\n\n**Benchmark guidance**\n- Use p50/p95 and throughput; pin CPU frequency if possible.\n- Acceptance: p95 improves ≥ X% with no correctness regressions.\n\n\nHard checks: failure injection tests and performance regressions gated.", "source": "WithinUsAI/Elite_GOD_Coder_100k"} {"text": "Task type: distributed_algorithm\nScenario: edge sync\nDomain focus: observability platforms\nPrimary language: sql\nDifficulty: expert\nScale/SLO: multi-region active-active\nComponent: component_awmieazw\nConstraints: include failure modes and recovery, include performance model and limits, explicit contracts and invariants, include security threat model (defensive only), include verification strategy, assume adversarial inputs; validate everything, include deterministic replay plan\nAssume crash-only processes; recovery must be deterministic.\nDeliverable: Design an algorithm with message flows and correctness arguments (safety + liveness). Include failure handling and a minimal reference implementation skeleton.\n\nOutput: contract-first solution with failure modes, security posture, and test/verification strategy.\n**Contract**\n- Inputs validated at the boundary; explicit error taxonomy.\n- Idempotency for side effects via request_id; deterministic replay.\n- Backward compatibility: additive changes by default; versioned breaking changes.\n**Invariants**\n- Safety: state transitions preserve invariants; no partial commit leaks.\n- Isolation: tenant boundary enforced; no cross-tenant reads/writes.\n- Liveness: under bounded faults and stable network, progress occurs.\n**Failure modes & recovery**\n- Data corruption: checksums + scrubber; quarantine and rebuild from replicas/snapshots.\n- Network partition: minority cannot commit; clients receive retriable errors.\n- Duplicate requests: de-duplicate by (tenant, request_id) returning cached response.\n**Security posture (defensive)**\n- Threat model: auth/authz, injection, replay/abuse, supply chain.\n- Least privilege; secrets in managed store; audit logs for sensitive ops.\n- Input normalization, parameterized queries, path traversal protections.\n**Verification strategy**\n- Fuzzing of parsers/framers/validators with corpus seeds.\n- Canary + shadow traffic; invariants checked in production via assertions/metrics.\n- Property tests against a pure reference model (state machine).\n\n**Snippet**\n```text\nImplementation sketch: factor pure state-machine core; adapters for I/O; add deterministic replay log.\n```\nExpert checks: state-machine proof sketch + model checking; upgrade/rollback rehearsed.", "source": "WithinUsAI/Omega_Genesis_Coder_100k"} {"text": "Write pytest tests for `f85624`.\n\n```python\ndef f85624(a: int, b: int) -> int:\n return a*a + b*b\n```\nInclude edge cases and a property-style check.\n\n```python\nimport random\nfrom m12232 import f85624\n\ndef test_known():\n assert f85624(3,4) == 25\n\ndef test_zero():\n assert f85624(0,0) == 0\n\ndef test_property_nonnegative():\n for _ in range(200):\n a=random.randint(-50,50)\n b=random.randint(-50,50)\n assert f85624(a,b) >= 0\n```", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Refactor to modern typed Python with immutability and tests.\n\nFile: qbedk5mwpy2.py\n```python\nclass Rowt489A5O:\n def __init__(self, name, values):\n self.name = name\n self.values = list(values)\n def add(self, v):\n self.values.append(v)\n def mean(self):\n s = 0\n for x in self.values:\n s += x\n return s / len(self.values)\n```\n\nReturn full new qbedk5mwpy2.py and test_qbedk5mwpy2.py.\n\n# qbedk5mwpy2.py\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom typing import Iterable, Tuple\n\n@dataclass(frozen=True)\nclass Rowt489A5O:\n name: str\n values: Tuple[float, ...]\n\n @staticmethod\n def create(name: str, values: Iterable[float]) -> \"Rowt489A5O\":\n vals = tuple(float(v) for v in values)\n if not vals:\n raise ValueError(\"values must be non-empty\")\n return Rowt489A5O(name=name, values=vals)\n\n def add(self, v: float) -> \"Rowt489A5O\":\n return Rowt489A5O(name=self.name, values=self.values + (float(v),))\n\n def mean(self) -> float:\n return sum(self.values) / len(self.values)\n\n# test_qbedk5mwpy2.py\nimport pytest\nfrom qbedk5mwpy2 import Rowt489A5O\n\ndef test_mean_and_add():\n c = Rowt489A5O.create(\"a\", [1, 2, 3])\n assert c.mean() == 2.0\n assert c.add(5).mean() == (1 + 2 + 3 + 5) / 4\n\ndef test_empty_raises():\n with pytest.raises(ValueError):\n Rowt489A5O.create(\"x\", [])", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Add a clear docstring and type hints to this function:\n\n```python\ndef f80506(s):\n return ''.join(x for x in s if x.isalnum()).lower()\n```\n\n```python\nfrom __future__ import annotations\n\ndef f80506(s: str) -> str:\n \"\"\"Normalize a string: keep only alphanumerics and lowercase the result.\"\"\"\n return \"\".join(ch for ch in s if ch.isalnum()).lower()\n```", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: Language: Bash\nFramework/tooling: sed\nDomain: benchmark harness\nLogic challenge: gRPC retry storm\nTask type: parser_validation_logic\nDifficulty: hard\n\nReturn a rigorous engineering answer:\n- identify the hidden root cause or logical failure\n- present the corrected implementation\n- add tests that prove the fix\n- list verification commands\n- explain why naive fixes are insufficient when relevant\n\nRepository sketch:\nrepo/\n scripts/\n run.sh\n deploy.sh\n tests/\n smoke.sh\n\nFocus: Focus on strong structured logic with edge cases, data validation, and concurrency safety.\n\nassistant: Diagnosis:\n- Root cause: the failure around gRPC retry storm is caused by missing validation, weak edge-case handling, or unsafe lifecycle behavior in the current implementation.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```bash\n#!/usr/bin/env bash\nset -euo pipefail\n\ninput=\"${1:-}\"\nif [[ -z \"$input\" ]]; then\n echo \"missing input\" >&2\n exit 1\nfi\n\nprintf '%s\n' \"$input\" | tr -d '\r'\n```\n\nTests:\n```bash\noutput=\"$(bash scripts/run.sh \"abc\")\"\ntest \"$output\" = \"abc\"\n```\n\nVerification:\n- `bash tests/smoke.sh`\n- `shellcheck scripts/*.sh`\n\nEngineering notes:\n- Language: Bash\n- Framework/tooling: sed\n- Stack context: ASP.NET Core, SQL Server, EF Core, xUnit, Docker\n- Domain: benchmark harness\n- Task type: parser_validation_logic\n- Difficulty: hard\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Optimize while preserving behavior.\n\nFile: h2oj_233.py\n```python\ndef zsc2moj3np2(xs):\n out = []\n for x in xs:\n if x not in out:\n out.append(x)\n return out\n```\n\nRequirements: preserve first-seen order; O(n) average; add types + docstring.\n\n# h2oj_233.py\nfrom __future__ import annotations\nfrom typing import Iterable, List, Set, TypeVar\n\nT = TypeVar(\"T\")\n\ndef zsc2moj3np2(xs: Iterable[T]) -> List[T]:\n \"\"\"Return unique items preserving first-seen order.\"\"\"\n seen: Set[T] = set()\n out: List[T] = []\n for x in xs:\n if x in seen:\n continue\n seen.add(x)\n out.append(x)\n return out", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Optimize while preserving behavior and order.\n\n```python\ndef f53586(xs):\n out=[]\n for x in xs:\n if x not in out: out.append(x)\n return out\n```\nReturn `m64798.py` with types and O(n) average.\n\n```python\n# m64798.py\nfrom __future__ import annotations\nfrom typing import Iterable, List, Set, TypeVar\nT=TypeVar(\"T\")\n\ndef f53586(xs: Iterable[T]) -> List[T]:\n \"\"\"Unique items preserving first-seen order.\"\"\"\n seen: Set[T]=set()\n out: List[T]=[]\n for x in xs:\n if x in seen: continue\n seen.add(x); out.append(x)\n return out\n```", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Optimize while preserving behavior.\n\nFile: s1p4i8o_9p.py\n```python\ndef dupt73j(xs):\n out = []\n for x in xs:\n if x not in out:\n out.append(x)\n return out\n```\n\nRequirements: preserve first-seen order; O(n) average; add types + docstring.\n\n# s1p4i8o_9p.py\nfrom __future__ import annotations\nfrom typing import Iterable, List, Set, TypeVar\n\nT = TypeVar(\"T\")\n\ndef dupt73j(xs: Iterable[T]) -> List[T]:\n \"\"\"Return unique items preserving first-seen order.\"\"\"\n seen: Set[T] = set()\n out: List[T] = []\n for x in xs:\n if x in seen:\n continue\n seen.add(x)\n out.append(x)\n return out", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Task type: mechanized_spec\nScenario: rate limit gateway\nDomain focus: runtime systems\nPrimary language: lean\nDifficulty: hard\nScale/SLO: 10k RPS peak\nComponent: component_udbbouaq\nConstraints: explicit contracts and invariants, avoid data races and undefined behavior, include test vectors and fuzz strategy, include failure modes and recovery, include backward compatibility and migration plan, include verification strategy, assume adversarial inputs; validate everything\nAssume schema changes every sprint; must be backward compatible.\nDeliverable: Provide a mechanized-style spec outline (Lean-like), key definitions, and a proof plan. Include executable reference code skeleton and tests.\n\nOutput: contract-first solution with failure modes, security posture, and test/verification strategy.\n**Contract**\n- Inputs validated at the boundary; explicit error taxonomy.\n- Idempotency for side effects via request_id; deterministic replay.\n- Backward compatibility: additive changes by default; versioned breaking changes.\n**Invariants**\n- Determinism: replay of the same event log yields identical outputs.\n- Isolation: tenant boundary enforced; no cross-tenant reads/writes.\n- Safety: state transitions preserve invariants; no partial commit leaks.\n**Failure modes & recovery**\n- Duplicate requests: de-duplicate by (tenant, request_id) returning cached response.\n- Data corruption: checksums + scrubber; quarantine and rebuild from replicas/snapshots.\n- Crash during commit: WAL replay completes or transaction aborts; no torn writes.\n**Security posture (defensive)**\n- Threat model: auth/authz, injection, replay/abuse, supply chain.\n- Least privilege; secrets in managed store; audit logs for sensitive ops.\n- Input normalization, parameterized queries, path traversal protections.\n**Verification strategy**\n- Property tests against a pure reference model (state machine).\n- Deterministic simulation with fault injection (crash/partition/latency).\n- Fuzzing of parsers/framers/validators with corpus seeds.\n\n**Snippet**\n```lean\n-- Pseudo-Lean outline\nstructure State where\n ver : Nat\n val : Option ByteArray\n\ndef invariant (s : State) : Prop := True\n\ntheorem step_preserves_invariant :\n ∀ s, invariant s → ∀ s', Step s s' → invariant s' := by\n intro s hs s' hstep\n -- proof plan: case analysis on transition; trivial here\n trivial\n```\n\nHard checks: fault injection tests gate merges; perf thresholds enforced in CI.", "source": "WithinUsAI/Omega_Genesis_Coder_100k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Fix a bug and add tests.\n\nFile: ka5b37u.py\n```python\ndef i4gsk5za(n: int) -> int:\n \"\"\"Sum 1..n inclusive.\"\"\"\n if n < 0:\n raise ValueError(\"n must be non-negative\")\n total = 0\n for k in range(n): # BUG: should include n\n total += k\n return total\n```\n\nReturn unified diffs for ka5b37u.py and test_ka5b37u.py (pytest).\n\n*** Begin Patch\n*** Update File: ka5b37u.py\n@@\n def i4gsk5za(n: int) -> int:\n@@\n total = 0\n- for k in range(n): # BUG: should include n\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_ka5b37u.py\n+import pytest\n+from ka5b37u import i4gsk5za\n+\n+def test_zero():\n+ assert i4gsk5za(0) == 0\n+\n+def test_one():\n+ assert i4gsk5za(1) == 1\n+\n+def test_small():\n+ assert i4gsk5za(7) == 28\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ i4gsk5za(-1)\n+\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Task type: network_protocol\nScenario: edge sync\nDomain focus: real-time scheduling\nPrimary language: go\nDifficulty: hard\nScale/SLO: 100k RPS peak\nComponent: component_jjanavep\nConstraints: include verification strategy, include failure modes and recovery, avoid data races and undefined behavior, explicit contracts and invariants, include security threat model (defensive only), include test vectors and fuzz strategy\nAssume weekly network partitions.\nDeliverable: Design an application protocol: framing, retries, backpressure, timeouts; include client/server skeleton and test vectors.\n\nOutput: rigorous design + invariants + verification plan + implementation sketch.\n**Contract**\n- Inputs validated at the boundary; explicit error taxonomy.\n- Idempotency for side effects via request_id; deterministic replay.\n- Backward compatibility: additive changes by default; versioned breaking changes.\n**Invariants**\n- Liveness: under bounded faults and stable network, progress occurs.\n- Safety: state transitions preserve invariants; no partial commit leaks.\n- Isolation: tenant boundary enforced; no cross-tenant reads/writes.\n**Failure modes & recovery**\n- Network partition: minority cannot commit; clients receive retriable errors.\n- Duplicate requests: de-duplicate by (tenant, request_id) returning cached response.\n- Data corruption: checksums + scrubber; quarantine and rebuild from replicas/snapshots.\n**Security posture (defensive)**\n- Threat model: auth/authz, injection, replay/abuse, supply chain.\n- Least privilege; secrets in managed store; audit logs for sensitive ops.\n- Input normalization, parameterized queries, path traversal protections.\n**Verification strategy**\n- Deterministic simulation with fault injection (crash/partition/latency).\n- Fuzzing of parsers/framers/validators with corpus seeds.\n- Canary + shadow traffic; invariants checked in production via assertions/metrics.\n\n**Snippet**\n```text\nImplementation sketch: factor pure state-machine core; adapters for I/O; add deterministic replay log.\n```\nHard checks: fault injection tests gate merges; perf thresholds enforced in CI.", "source": "WithinUsAI/Omega_Genesis_Coder_100k"} {"text": "Task type: storage_engine\nScenario: job scheduler\nDomain focus: consensus & replication\nPrimary language: rust\nDifficulty: expert\nScale/SLO: p99 < 150ms\nComponent: component_grfzxgce\nConstraints: include test vectors and fuzz strategy, explicit contracts and invariants, assume adversarial inputs; validate everything, include deterministic replay plan, include performance model and limits\nAssume hostile inputs and targeted abuse patterns.\nDeliverable: Design a storage engine subsystem (WAL, snapshots, compaction). Include crash recovery invariants and a benchmark plan.\n\nOutput: elite engineering answer optimized for correctness, performance, and operability.\n**Contract**\n- Inputs validated at the boundary; explicit error taxonomy.\n- Idempotency for side effects via request_id; deterministic replay.\n- Backward compatibility: additive changes by default; versioned breaking changes.\n**Invariants**\n- Liveness: under bounded faults and stable network, progress occurs.\n- Safety: state transitions preserve invariants; no partial commit leaks.\n- Isolation: tenant boundary enforced; no cross-tenant reads/writes.\n**Failure modes & recovery**\n- Crash during commit: WAL replay completes or transaction aborts; no torn writes.\n- Duplicate requests: de-duplicate by (tenant, request_id) returning cached response.\n- Network partition: minority cannot commit; clients receive retriable errors.\n**Security posture (defensive)**\n- Threat model: auth/authz, injection, replay/abuse, supply chain.\n- Least privilege; secrets in managed store; audit logs for sensitive ops.\n- Input normalization, parameterized queries, path traversal protections.\n**Verification strategy**\n- Fuzzing of parsers/framers/validators with corpus seeds.\n- Canary + shadow traffic; invariants checked in production via assertions/metrics.\n- Property tests against a pure reference model (state machine).\n\n**Snippet**\n```text\nImplementation sketch: factor pure state-machine core; adapters for I/O; add deterministic replay log.\n```\nExpert checks: state-machine proof sketch + model checking; upgrade/rollback rehearsed.", "source": "WithinUsAI/Omega_Genesis_Coder_100k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Produce an offline-first self-evolving code assistant architecture named `i8q1cs78fxyi`.\nMust include: module layout, patch-safety policy, evaluation gates (tests/lint/types), versioned memory index.\n\nArchitecture: `i8q1cs78fxyi` (offline-first, self-evolving)\n\nModules\n- core/loop.py: evolve → validate → accept/reject (bounded iterations)\n- patching/: diff builder, safe apply, atomic writes, rollback points\n- policy/: allowlist paths, deny globs (.git/, __pycache__/, binaries), patch size caps\n- signals/: parse pytest/ruff/mypy into normalized findings\n- memory/index.jsonl: append-only snapshots (hashes, metrics, rationale)\n\nSafety gates\n- refuse path traversal/symlink escapes; never edit binaries\n- accept only if tests/lint/types stay green or improve", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Task type: lockfree_primitive\nScenario: graph query service\nDomain focus: fault injection & chaos engineering\nPrimary language: cpp\nDifficulty: expert\nScale/SLO: p99 < 150ms\nComponent: component_ljuovxgi\nConstraints: include test vectors and fuzz strategy, include verification strategy, explicit contracts and invariants, include performance model and limits, include backward compatibility and migration plan, include security threat model (defensive only)\nAssume hostile inputs and targeted abuse patterns.\nDeliverable: Design a lock-free primitive with memory ordering reasoning and stress tests (no UB).\n\nOutput: rigorous design + invariants + verification plan + implementation sketch.\n**Contract**\n- Inputs validated at the boundary; explicit error taxonomy.\n- Idempotency for side effects via request_id; deterministic replay.\n- Backward compatibility: additive changes by default; versioned breaking changes.\n**Invariants**\n- Isolation: tenant boundary enforced; no cross-tenant reads/writes.\n- Liveness: under bounded faults and stable network, progress occurs.\n- Safety: state transitions preserve invariants; no partial commit leaks.\n**Failure modes & recovery**\n- Duplicate requests: de-duplicate by (tenant, request_id) returning cached response.\n- Network partition: minority cannot commit; clients receive retriable errors.\n- Data corruption: checksums + scrubber; quarantine and rebuild from replicas/snapshots.\n**Security posture (defensive)**\n- Threat model: auth/authz, injection, replay/abuse, supply chain.\n- Least privilege; secrets in managed store; audit logs for sensitive ops.\n- Input normalization, parameterized queries, path traversal protections.\n**Verification strategy**\n- Canary + shadow traffic; invariants checked in production via assertions/metrics.\n- Deterministic simulation with fault injection (crash/partition/latency).\n- Property tests against a pure reference model (state machine).\n\n**Snippet**\n```rust\n// Skeleton: SPSC ring buffer with acquire/release (outline)\nuse std::sync::atomic::{AtomicUsize, Ordering};\n\npub struct Ring {\n buf: Vec>,\n head: AtomicUsize,\n tail: AtomicUsize,\n cap: usize,\n}\n\n// Correctness sketch: producer uses Release on tail store, consumer uses Acquire on tail load.\n```\n\nExpert checks: state-machine proof sketch + model checking; upgrade/rollback rehearsed.", "source": "WithinUsAI/Omega_Genesis_Coder_100k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Refactor to modern typed Python with immutability and tests.\n\nFile: cl2cyx9z1.py\n```python\nclass E9Uxnu4Afruk:\n def __init__(self, name, values):\n self.name = name\n self.values = list(values)\n def add(self, v):\n self.values.append(v)\n def mean(self):\n s = 0\n for x in self.values:\n s += x\n return s / len(self.values)\n```\n\nReturn full new cl2cyx9z1.py and test_cl2cyx9z1.py.\n\n# cl2cyx9z1.py\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom typing import Iterable, Tuple\n\n@dataclass(frozen=True)\nclass E9Uxnu4Afruk:\n name: str\n values: Tuple[float, ...]\n\n @staticmethod\n def create(name: str, values: Iterable[float]) -> \"E9Uxnu4Afruk\":\n vals = tuple(float(v) for v in values)\n if not vals:\n raise ValueError(\"values must be non-empty\")\n return E9Uxnu4Afruk(name=name, values=vals)\n\n def add(self, v: float) -> \"E9Uxnu4Afruk\":\n return E9Uxnu4Afruk(name=self.name, values=self.values + (float(v),))\n\n def mean(self) -> float:\n return sum(self.values) / len(self.values)\n\n# test_cl2cyx9z1.py\nimport pytest\nfrom cl2cyx9z1 import E9Uxnu4Afruk\n\ndef test_mean_and_add():\n c = E9Uxnu4Afruk.create(\"a\", [1, 2, 3])\n assert c.mean() == 2.0\n assert c.add(5).mean() == (1 + 2 + 3 + 5) / 4\n\ndef test_empty_raises():\n with pytest.raises(ValueError):\n E9Uxnu4Afruk.create(\"x\", [])", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Refactor to modern typed Python with immutability and tests.\n\nFile: dvx7un.py\n```python\nclass L98Yuazem:\n def __init__(self, name, values):\n self.name = name\n self.values = list(values)\n def add(self, v):\n self.values.append(v)\n def mean(self):\n s = 0\n for x in self.values:\n s += x\n return s / len(self.values)\n```\n\nReturn full new dvx7un.py and test_dvx7un.py.\n\n# dvx7un.py\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom typing import Iterable, Tuple\n\n@dataclass(frozen=True)\nclass L98Yuazem:\n name: str\n values: Tuple[float, ...]\n\n @staticmethod\n def create(name: str, values: Iterable[float]) -> \"L98Yuazem\":\n vals = tuple(float(v) for v in values)\n if not vals:\n raise ValueError(\"values must be non-empty\")\n return L98Yuazem(name=name, values=vals)\n\n def add(self, v: float) -> \"L98Yuazem\":\n return L98Yuazem(name=self.name, values=self.values + (float(v),))\n\n def mean(self) -> float:\n return sum(self.values) / len(self.values)\n\n# test_dvx7un.py\nimport pytest\nfrom dvx7un import L98Yuazem\n\ndef test_mean_and_add():\n c = L98Yuazem.create(\"a\", [1, 2, 3])\n assert c.mean() == 2.0\n assert c.add(5).mean() == (1 + 2 + 3 + 5) / 4\n\ndef test_empty_raises():\n with pytest.raises(ValueError):\n L98Yuazem.create(\"x\", [])", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Build an elite-grade solution in the domain of distributed systems for scenario: event ingestion.\nPrimary language: rust.\nDifficulty: medium.\nConstraints: include tests or verification strategy, make the interface contract explicit, document performance characteristics.\nComponent: component_yxujzbj.\nAssume crash-only design; recovery must be deterministic.\nTask: Provide threat model, secure-by-default design, and defensive implementation patterns. No offensive/exploit content; focus on prevention and detection.\n\nOutput: production blueprint plus correctness arguments and test strategy.\nOutput: threat model + defensive design + detection.\n\n**Threat model**\n- Auth: token theft → short-lived tokens, rotation, audience checks\n- AuthZ: privilege escalation → centralized policy checks, tenant isolation tests\n- Input: injection → strict validation, parameterized queries, output encoding\n- Supply chain: dependencies → lockfiles, signature verification, SBOM\n\n**Defensive patterns**\n- Idempotency keys for side effects; replay-safe handlers\n- Secrets in managed store; never logs\n- Audit logging for sensitive ops; tamper-evident storage\n\n**Detection**\n- Alert on unusual auth failures, access pattern anomalies, and data exfil signals.\n\n\nChecks: boundary validation and deterministic behavior verified.", "source": "WithinUsAI/Elite_GOD_Coder_100k"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: Language: TypeScript\nFramework/tooling: Prisma\nDomain: payments platform\nLogic challenge: transaction boundary bug\nTask type: state_machine_patch\nDifficulty: medium\n\nReturn a rigorous engineering answer:\n- identify the hidden root cause or logical failure\n- present the corrected implementation\n- add tests that prove the fix\n- list verification commands\n- explain why naive fixes are insufficient when relevant\n\nRepository sketch:\nrepo/\n src/\n api.ts\n service.ts\n schema.ts\n tests/\n api.test.ts\n package.json\n\nFocus: Focus on strong structured logic with edge cases, data validation, and concurrency safety.\n\nassistant: Diagnosis:\n- Root cause: the failure around transaction boundary bug is caused by missing validation, weak edge-case handling, or unsafe lifecycle behavior in the current implementation.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```ts\ntype Payload = Record;\n\nexport function normalizePayload(payload: Payload): Payload {\n if (!payload || typeof payload !== \"object\" || Array.isArray(payload)) {\n throw new TypeError(\"payload must be a plain object\");\n }\n return Object.fromEntries(\n Object.entries(payload)\n .filter(([, value]) => value !== null && value !== undefined)\n .map(([key, value]) => [String(key).trim(), value])\n );\n}\n\nexport function handleTransactionBoundaryBug(payload: Payload) {\n const clean = normalizePayload(payload);\n if (!(\"id\" in clean)) {\n return { ok: false, data: {}, error: \"missing id\" };\n }\n return { ok: true, data: clean, error: null };\n}\n```\n\nTests:\n```ts\nimport { describe, it, expect } from \"vitest\";\nimport { handleTransactionBoundaryBug } from \"../src/service\";\n\ndescribe(\"handler\", () => {\n it(\"accepts valid input\", () => {\n expect(handleTransactionBoundaryBug({ id: 7, name: \"ok\", unused: null })).toEqual({\n ok: true,\n data: { id: 7, name: \"ok\" },\n error: null\n });\n });\n\n it(\"rejects missing id\", () => {\n expect(handleTransactionBoundaryBug({ name: \"x\" }).error).toMatch(/missing id/);\n });\n});\n```\n\nVerification:\n- `npm test`\n- `npm run typecheck`\n- `npm run lint`\n\nEngineering notes:\n- Language: TypeScript\n- Framework/tooling: Prisma\n- Stack context: Airflow, dbt, DuckDB, MinIO, pytest\n- Domain: payments platform\n- Task type: state_machine_patch\n- Difficulty: medium\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "Optimize while preserving behavior and order.\n\n```python\ndef f56268(xs):\n out=[]\n for x in xs:\n if x not in out: out.append(x)\n return out\n```\nReturn `m22324.py` with types and O(n) average.\n\n```python\n# m22324.py\nfrom __future__ import annotations\nfrom typing import Iterable, List, Set, TypeVar\nT=TypeVar(\"T\")\n\ndef f56268(xs: Iterable[T]) -> List[T]:\n \"\"\"Unique items preserving first-seen order.\"\"\"\n seen: Set[T]=set()\n out: List[T]=[]\n for x in xs:\n if x in seen: continue\n seen.add(x); out.append(x)\n return out\n```", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Build an elite-grade solution in the domain of security engineering (defensive) for scenario: multi-tenant SaaS.\nPrimary language: rust.\nDifficulty: expert.\nConstraints: include tests or verification strategy, include invariants and failure modes, provide rollout and rollback guidance, avoid undefined behavior and data races, assume untrusted inputs; validate and sanitize.\nComponent: component_xnswzsj.\nAssume strict auditability and replayable history.\nTask: Define an API and evolving schema strategy (versioning, migrations, compatibility rules). Provide example schemas and validation tests.\n\nOutput: production blueprint plus correctness arguments and test strategy.\nOutput: GPU pipeline design for throughput and tail-latency.\n\n**Pipeline**\n- Request batching with max batch size + max wait (e.g., 5ms) to control p99.\n- Separate CPU pre/post-processing threads; pin memory for transfers if available.\n- Model warmup; cache weights in VRAM; use concurrency limits.\n\n**Monitoring**\n- GPU utilization, queue wait time, batch size distribution, OOM events.\n\n**Fallback**\n- Graceful degradation to smaller batch size; circuit breaker on repeated OOM.\n\n\nExpert checks: state-machine reasoning, concurrency stress, and upgrade/rollback validated.", "source": "WithinUsAI/Elite_GOD_Coder_100k"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: Language: SQL\nFramework/tooling: MySQL\nDomain: artifact registry\nLogic challenge: unsafe deserialization\nTask type: misleading_symptom_debug\nDifficulty: hard\n\nReturn a rigorous engineering answer:\n- identify the hidden root cause or logical failure\n- present the corrected implementation\n- add tests that prove the fix\n- list verification commands\n- explain why naive fixes are insufficient when relevant\n\nRepository sketch:\nrepo/\n migrations/\n 001_init.sql\n 002_add_index.sql\n queries/\n report.sql\n tests/\n report_cases.md\n\nFocus: Focus on ambiguity, misleading symptoms, hidden root causes, and high-stakes debugging.\n\nassistant: Diagnosis:\n- Hidden root cause: unsafe deserialization presents misleading symptoms, so the patch must target the actual logic boundary rather than the first visible failure.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```sql\nWITH ranked AS (\n SELECT\n user_id,\n created_at,\n amount,\n ROW_NUMBER() OVER (PARTITION BY user_id ORDER BY created_at DESC, id DESC) AS rn\n FROM orders\n)\nSELECT user_id, created_at, amount\nFROM ranked\nWHERE rn = 1;\n```\n\nTests:\n```sql\n-- Correctness checks:\n-- 1) multiple rows per user\n-- 2) identical timestamps require deterministic tie-breaker\n-- 3) null values handled by business rules\n```\n\nVerification:\n- `run migration checks`\n- `run query correctness cases`\n\nEngineering notes:\n- Language: SQL\n- Framework/tooling: MySQL\n- Stack context: Rust, Axum, SQLx, Redis, Tokio, Docker\n- Domain: artifact registry\n- Task type: misleading_symptom_debug\n- Difficulty: hard\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "Build an elite-grade solution in the domain of edge/IoT for scenario: chat messaging.\nPrimary language: sql.\nDifficulty: hard.\nConstraints: assume untrusted inputs; validate and sanitize, include invariants and failure modes, include tests or verification strategy, design for backward compatibility and migrations, provide rollout and rollback guidance.\nComponent: component_ekizexd.\nAssume strict auditability and replayable history.\nTask: Optimize a hot path with profiling-driven approach; propose micro/meso optimizations, and supply a benchmark harness with acceptance thresholds.\n\nOutput: elite-grade engineering answer with contracts, edge cases, and verification.\nOutput: profiling-first optimization + benchmark harness.\n\n**Plan**\n1. Establish baseline with microbench + representative dataset.\n2. Profile (CPU, allocations, syscalls).\n3. Apply optimizations: reduce allocations, reuse buffers, batch I/O, vectorize parsing where safe.\n4. Validate with regression suite and perf thresholds.\n\n**Benchmark guidance**\n- Use p50/p95 and throughput; pin CPU frequency if possible.\n- Acceptance: p95 improves ≥ X% with no correctness regressions.\n\n\nHard checks: failure injection tests and performance regressions gated.", "source": "WithinUsAI/Elite_GOD_Coder_100k"} {"text": "Task type: ml_system_design\nScenario: feature-flag evaluation\nDomain focus: query planning\nPrimary language: bash\nDifficulty: expert+\nScale/SLO: 99.99% availability\nComponent: component_rwbuadwb\nConstraints: include backward compatibility and migration plan, explicit contracts and invariants, assume adversarial inputs; validate everything, avoid data races and undefined behavior, include verification strategy\nAssume tight memory budget and cold-start constraints.\nDeliverable: Design end-to-end ML system: data contracts, training, evaluation, registry, serving, monitoring, and rollback.\n\nOutput: contract-first solution with failure modes, security posture, and test/verification strategy.\n**Contract**\n- Inputs validated at the boundary; explicit error taxonomy.\n- Idempotency for side effects via request_id; deterministic replay.\n- Backward compatibility: additive changes by default; versioned breaking changes.\n**Invariants**\n- Determinism: replay of the same event log yields identical outputs.\n- Safety: state transitions preserve invariants; no partial commit leaks.\n- Liveness: under bounded faults and stable network, progress occurs.\n**Failure modes & recovery**\n- Crash during commit: WAL replay completes or transaction aborts; no torn writes.\n- Network partition: minority cannot commit; clients receive retriable errors.\n- Data corruption: checksums + scrubber; quarantine and rebuild from replicas/snapshots.\n**Security posture (defensive)**\n- Threat model: auth/authz, injection, replay/abuse, supply chain.\n- Least privilege; secrets in managed store; audit logs for sensitive ops.\n- Input normalization, parameterized queries, path traversal protections.\n**Verification strategy**\n- Property tests against a pure reference model (state machine).\n- Fuzzing of parsers/framers/validators with corpus seeds.\n- Canary + shadow traffic; invariants checked in production via assertions/metrics.\n\n**Snippet**\n```text\nImplementation sketch: factor pure state-machine core; adapters for I/O; add deterministic replay log.\n```\nExpert+ checks: mechanized invariants (or exhaustive model checking), adversarial fuzzing, and multi-region failure drills.", "source": "WithinUsAI/Omega_Genesis_Coder_100k"} {"text": "Implement a concurrent Python solution for caching layer.\nRequirements: choose appropriate concurrency model, handle cancellation/timeouts, include tests.\nConstraints: must handle Windows paths safely, must be memory-efficient, must provide clear error messages, must include tests.\nDifficulty: easy. Avoid quadratic behavior on large inputs.\n\nDeliverable: production-ready reference solution.\n```python\nfrom __future__ import annotations\nimport asyncio\nfrom dataclasses import dataclass\nfrom typing import Awaitable, Callable, Iterable, Optional\n\n@dataclass(frozen=True, slots=True)\nclass JobResult:\n ok: bool\n value: Optional[int]\n error: Optional[str]\n\nasync def run_bounded(\n factories: Iterable[Callable[[], Awaitable[int]]],\n *,\n limit: int = 10,\n timeout_s: float = 5.0,\n) -> list[JobResult]:\n if limit <= 0:\n raise ValueError(\"limit must be > 0\")\n sem = asyncio.Semaphore(limit)\n results: list[JobResult] = []\n\n async def one(factory: Callable[[], Awaitable[int]]) -> None:\n async with sem:\n try:\n v = await asyncio.wait_for(factory(), timeout=timeout_s)\n results.append(JobResult(True, v, None))\n except Exception as e:\n results.append(JobResult(False, None, str(e)))\n\n tasks = [asyncio.create_task(one(f)) for f in factories]\n try:\n await asyncio.gather(*tasks)\n finally:\n for t in tasks:\n if not t.done():\n t.cancel()\n return results\n```\n\n```python\nimport asyncio\nimport pytest\nfrom module_under_test import run_bounded\n\n@pytest.mark.asyncio\nasync def test_run_bounded_collects():\n async def work(x: int) -> int:\n await asyncio.sleep(0.01)\n return x\n fs = [(lambda i=i: work(i)) for i in range(30)]\n out = await run_bounded(fs, limit=5, timeout_s=1.0)\n assert len(out) == 30\n assert all(r.ok for r in out)\n```", "source": "WithinUsAI/python_GOD_coder_100k"} {"text": "Implement an ML engineering workflow for IoT telemetry focusing on caching.\nTarget platform: ML (training + serving).\nRequirements: data contract, training loop, evaluation, model registry, serving API, monitoring.\nConstraints: must avoid global state, must include documentation/comments, must be easy to extend.\nDifficulty: easy. Assume PII must be protected.\n\nOutput: actionable implementation and verification artifacts.\nDeliverable: ML engineering blueprint (training + serving + monitoring), safe and production-oriented.\n\n**Data contract**\n- Define feature schema + ranges; validate at training and serving.\n\n**Training**\n- Deterministic split; baseline model; track metrics (AUC/F1/latency).\n- Store artifacts: model, config, feature stats.\n\n**Registry**\n- Promote models via approval gates; record lineage.\n\n**Serving**\n- Separate inference service with `/predict`.\n- Input validation + default handling; timeouts.\n\n**Monitoring**\n- Data drift: feature distribution checks.\n- Performance: online metrics + periodic labels; alert on regression.\n\nMinimal serving skeleton (FastAPI-ish):\n```python\n# validate input -> vectorize -> model.predict_proba -> return\n```\n\n\nChecks: input validation, tests, and safe defaults included.", "source": "WithinUsAI/GOD_Coder_100k"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: Language: YAML\nFramework/tooling: Helm\nDomain: reporting engine\nLogic challenge: S3-compatible upload inconsistency\nTask type: backwards_compatible_redesign\nDifficulty: hard\n\nReturn a rigorous engineering answer:\n- identify the hidden root cause or logical failure\n- present the corrected implementation\n- add tests that prove the fix\n- list verification commands\n- explain why naive fixes are insufficient when relevant\n\nRepository sketch:\nrepo/\n .github/workflows/ci.yml\n docker-compose.yml\n deploy/\n app.yaml\n\nFocus: Focus on staff-level problem solving with multi-file patches, rollout implications, performance and security tradeoffs.\n\nassistant: Diagnosis:\n- Staff-level diagnosis: S3-compatible upload inconsistency impacts correctness, operability, and future maintenance, so the fix must be minimal where possible but complete where necessary.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```yaml\nname: ci\non: [push, pull_request]\njobs:\n test:\n runs-on: ubuntu-latest\n steps:\n - uses: actions/checkout@v4\n - name: Validate\n run: echo \"validated\"\n```\n\nTests:\n```yaml\n# Verification:\n# - validate syntax\n# - run smoke workflow\n# - fail fast on broken config\n```\n\nVerification:\n- `validate workflow syntax`\n- `run CI smoke job`\n\nEngineering notes:\n- Language: YAML\n- Framework/tooling: Helm\n- Stack context: GitHub Actions, Docker Compose, Kubernetes, Terraform\n- Domain: reporting engine\n- Task type: backwards_compatible_redesign\n- Difficulty: hard\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "Write pytest tests for `f83677`.\n\n```python\ndef f83677(a: int, b: int) -> int:\n return a*a + b*b\n```\nInclude edge cases and a property-style check.\n\n```python\nimport random\nfrom m54811 import f83677\n\ndef test_known():\n assert f83677(3,4) == 25\n\ndef test_zero():\n assert f83677(0,0) == 0\n\ndef test_property_nonnegative():\n for _ in range(200):\n a=random.randint(-50,50)\n b=random.randint(-50,50)\n assert f83677(a,b) >= 0\n```", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Fix a subtle bug in a Python module used for file synchronization.\nRequirements: explain root cause briefly, provide corrected code, and add regression tests.\nConstraints: must include docstrings, must include tests, must include type hints.\nDifficulty: easy. Ensure the API is testable via dependency injection.\n\nDeliverable: API + reference implementation + tests.\n```python\nfrom __future__ import annotations\n\nfrom dataclasses import dataclass\nfrom pathlib import Path\nfrom typing import Iterable\nimport json\n\n\nclass ValidationError(ValueError):\n \"\"\"Raised when input validation fails.\"\"\"\n\n\ndef safe_join(base: Path, *parts: str) -> Path:\n \"\"\"Join paths while preventing traversal outside base.\"\"\"\n b = base.resolve()\n p = (b / Path(*parts)).resolve()\n if p != b and b not in p.parents:\n raise ValidationError(f\"unsafe path: {p}\")\n return p\n\n\n@dataclass(frozen=True, slots=True)\nclass Record:\n key: str\n value: int\n\n\ndef parse_jsonl(lines: Iterable[str]) -> list[Record]:\n out: list[Record] = []\n for idx, line in enumerate(lines, 1):\n s = line.strip()\n if not s:\n continue\n try:\n obj = json.loads(s)\n except json.JSONDecodeError as e:\n raise ValidationError(f\"line {idx}: invalid json\") from e\n if not isinstance(obj, dict):\n raise ValidationError(f\"line {idx}: expected object\")\n key = obj.get(\"key\")\n val = obj.get(\"value\")\n if not isinstance(key, str) or not key:\n raise ValidationError(f\"line {idx}: key must be non-empty str\")\n if not isinstance(val, int):\n raise ValidationError(f\"line {idx}: value must be int\")\n out.append(Record(key, val))\n return out\n\n\ndef write_jsonl(base: Path, rel: str, records: Iterable[Record]) -> Path:\n base.mkdir(parents=True, exist_ok=True)\n dst = safe_join(base, rel)\n dst.parent.mkdir(parents=True, exist_ok=True)\n with dst.open(\"w\", encoding=\"utf-8\", newline=\"\\n\") as f:\n for r in records:\n f.write(json.dumps({\"key\": r.key, \"value\": r.value}, ensure_ascii=False) + \"\\n\")\n return dst\n```\n\n```python\n# tests (pytest-style)\nimport json\nfrom pathlib import Path\nimport pytest\nfrom module_under_test import ValidationError, Record, parse_jsonl, write_jsonl\n\ndef test_parse_ok():\n lines = [json.dumps({\"key\":\"a\",\"value\":1}), json.dumps({\"key\":\"b\",\"value\":2})]\n assert parse_jsonl(lines) == [Record(\"a\",1), Record(\"b\",2)]\n\ndef test_parse_rejects_bad_json():\n with pytest.raises(ValidationError):\n parse_jsonl([\"{not json}\"])\n\ndef test_safe_join_blocks_traversal(tmp_path: Path):\n with pytest.raises(ValidationError):\n write_jsonl(tmp_path, \"../x.jsonl\", [Record(\"a\",1)])\n```", "source": "WithinUsAI/python_GOD_coder_100k"} {"text": "Perform a code review for a customer support PR implementing search + pagination.\nTarget platform: backend (Python FastAPI).\nRequirements: list critical issues, improvements, and provide an improved patch excerpt.\nConstraints: must be easy to extend, must be production-ready, must include clear error handling, must be secure-by-default.\nDifficulty: expert. Assume strict latency budget (p95 < 200ms).\n\nOutput: design + implementation guidance suitable for shipping.\nDeliverable: code review findings + improved patch excerpt.\n\n**Critical issues**\n1. Missing input validation at boundary; potential unexpected exceptions.\n2. No idempotency / retry safety for side-effecting endpoint.\n3. No tests for edge cases (empty input, duplicates, timeouts).\n4. Observability gaps: no request_id correlation, no metrics.\n\n**Improvements**\n- Add strict validation and explicit error responses.\n- Add idempotency key support for create endpoints.\n- Add unit + integration tests with CI gating.\n- Add structured logs and basic metrics.\n\nPatch excerpt (illustrative):\n```python\nif not idem_key:\n raise HTTPException(400, \"Missing Idempotency-Key\")\n```\n\n\nHard-mode checks: concurrency safety, idempotency, and rollback validated; add chaos tests where feasible.", "source": "WithinUsAI/GOD_Coder_100k"} {"text": "Write secure, defensive Python code for caching layer.\nRequirements: input validation, safe file handling, prevent path traversal, include tests.\nConstraints: must include docstrings, must be memory-efficient, must handle Windows paths safely, must be streaming-friendly.\nDifficulty: easy. Include a small CLI example if relevant.\n\nDeliverable: corrected code and verification tests.\n```python\nfrom __future__ import annotations\n\nfrom dataclasses import dataclass\nfrom pathlib import Path\nfrom typing import Iterable\nimport json\n\n\nclass ValidationError(ValueError):\n \"\"\"Raised when input validation fails.\"\"\"\n\n\ndef safe_join(base: Path, *parts: str) -> Path:\n \"\"\"Join paths while preventing traversal outside base.\"\"\"\n b = base.resolve()\n p = (b / Path(*parts)).resolve()\n if p != b and b not in p.parents:\n raise ValidationError(f\"unsafe path: {p}\")\n return p\n\n\n@dataclass(frozen=True, slots=True)\nclass Record:\n key: str\n value: int\n\n\ndef parse_jsonl(lines: Iterable[str]) -> list[Record]:\n out: list[Record] = []\n for idx, line in enumerate(lines, 1):\n s = line.strip()\n if not s:\n continue\n try:\n obj = json.loads(s)\n except json.JSONDecodeError as e:\n raise ValidationError(f\"line {idx}: invalid json\") from e\n if not isinstance(obj, dict):\n raise ValidationError(f\"line {idx}: expected object\")\n key = obj.get(\"key\")\n val = obj.get(\"value\")\n if not isinstance(key, str) or not key:\n raise ValidationError(f\"line {idx}: key must be non-empty str\")\n if not isinstance(val, int):\n raise ValidationError(f\"line {idx}: value must be int\")\n out.append(Record(key, val))\n return out\n\n\ndef write_jsonl(base: Path, rel: str, records: Iterable[Record]) -> Path:\n base.mkdir(parents=True, exist_ok=True)\n dst = safe_join(base, rel)\n dst.parent.mkdir(parents=True, exist_ok=True)\n with dst.open(\"w\", encoding=\"utf-8\", newline=\"\\n\") as f:\n for r in records:\n f.write(json.dumps({\"key\": r.key, \"value\": r.value}, ensure_ascii=False) + \"\\n\")\n return dst\n```\n\n```python\n# tests (pytest-style)\nimport json\nfrom pathlib import Path\nimport pytest\nfrom module_under_test import ValidationError, Record, parse_jsonl, write_jsonl\n\ndef test_parse_ok():\n lines = [json.dumps({\"key\":\"a\",\"value\":1}), json.dumps({\"key\":\"b\",\"value\":2})]\n assert parse_jsonl(lines) == [Record(\"a\",1), Record(\"b\",2)]\n\ndef test_parse_rejects_bad_json():\n with pytest.raises(ValidationError):\n parse_jsonl([\"{not json}\"])\n\ndef test_safe_join_blocks_traversal(tmp_path: Path):\n with pytest.raises(ValidationError):\n write_jsonl(tmp_path, \"../x.jsonl\", [Record(\"a\",1)])\n```", "source": "WithinUsAI/python_GOD_coder_100k"} {"text": "Fix the bug and add pytest tests.\n\n```python\ndef f09106(n: int) -> int:\n # sum 1..n inclusive\n if n < 0: raise ValueError\n total = 0\n for k in range(n): # BUG\n total += k\n return total\n```\nReturn unified diffs for `m44158.py` and `test_m44158.py`.\n\n*** Begin Patch\n*** Update File: m44158.py\n@@\n def f09106(n: int) -> int:\n@@\n- for k in range(n): # BUG\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_m44158.py\n+import pytest\n+from m44158 import f09106\n+\n+def test_small():\n+ assert f09106(7) == 28\n+\n+def test_zero():\n+ assert f09106(0) == 0\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ f09106(-1)\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Fix a bug and add tests.\n\nFile: wv9gpm00bi_.py\n```python\ndef nx0lmjku(n: int) -> int:\n \"\"\"Sum 1..n inclusive.\"\"\"\n if n < 0:\n raise ValueError(\"n must be non-negative\")\n total = 0\n for k in range(n): # BUG: should include n\n total += k\n return total\n```\n\nReturn unified diffs for wv9gpm00bi_.py and test_wv9gpm00bi_.py (pytest).\n\n*** Begin Patch\n*** Update File: wv9gpm00bi_.py\n@@\n def nx0lmjku(n: int) -> int:\n@@\n total = 0\n- for k in range(n): # BUG: should include n\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_wv9gpm00bi_.py\n+import pytest\n+from wv9gpm00bi_ import nx0lmjku\n+\n+def test_zero():\n+ assert nx0lmjku(0) == 0\n+\n+def test_one():\n+ assert nx0lmjku(1) == 1\n+\n+def test_small():\n+ assert nx0lmjku(7) == 28\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ nx0lmjku(-1)\n+\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Build an elite-grade solution in the domain of security engineering (defensive) for scenario: chat messaging.\nPrimary language: python.\nDifficulty: medium.\nConstraints: assume untrusted inputs; validate and sanitize, include tests or verification strategy, design for backward compatibility and migrations, include invariants and failure modes.\nComponent: component_dmpxnow.\nAssume 50k RPS and p99 < 250ms.\nTask: Design an application-level protocol (framing, retries, timeouts, backpressure). Provide client/server skeleton and test vectors.\n\nOutput: rigorous solution with invariants, failure modes, and performance notes.\nOutput: protocol framing + retry policy + client/server skeleton.\n\n**Framing**\n- Length-prefixed: uint32_be length + payload\n- Payload: msgpack/json; include request_id, type, and optional checksum\n\n**Reliability**\n- Retries only for idempotent ops; exponential backoff + jitter.\n- Timeouts: connect, read, overall; enforce max in-flight to provide backpressure.\n\n**Test vectors**\n- Corrupted length / truncated frame rejected\n- Duplicate request_id returns cached response\n- Slowloris protection by read deadlines\n\n\nChecks: boundary validation and deterministic behavior verified.", "source": "WithinUsAI/Elite_GOD_Coder_100k"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: Project domain: model serving gateway\nImplementation stack: GitHub Actions, Docker Compose, Kubernetes, Terraform\nSoftware delivery problem: dead-letter queue replay\nTask type: release_engineering_fix\nDifficulty: hard\n\nReturn a complete delivery-grade response with:\n- diagnosis or design reasoning\n- implementation\n- test plan or tests\n- rollout plan\n- rollback or compatibility note\n- verification commands\n\nRepository sketch:\nrepo/\n scripts/\n run.sh\n deploy.sh\n tests/\n smoke.sh\n\nFocus: Focus on shipping production software with rollout safety, acceptance criteria, telemetry, and maintenance quality.\n\nassistant: Diagnosis:\n- Root cause or delivery blocker: dead-letter queue replay needs both implementation work and a safe shipping plan.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```bash\n#!/usr/bin/env bash\nset -euo pipefail\n\ninput=\"${1:-}\"\nif [[ -z \"$input\" ]]; then\n echo \"missing input\" >&2\n exit 1\nfi\n\nprintf '%s\n' \"$input\" | tr -d '\r'\n```\n\nTests:\n```bash\noutput=\"$(bash scripts/run.sh \"abc\")\"\ntest \"$output\" = \"abc\"\n```\n\nVerification:\n- `bash tests/smoke.sh`\n- `shellcheck scripts/*.sh`\n\nEngineering notes:\n- Language: Bash\n- Framework/tooling: GNU coreutils\n- Stack context: GitHub Actions, Docker Compose, Kubernetes, Terraform\n- Domain: model serving gateway\n- Task type: release_engineering_fix\n- Difficulty: hard\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Optimize while preserving behavior.\n\nFile: gt9jsek1kedq.py\n```python\ndef xrov_0rivsn(xs):\n out = []\n for x in xs:\n if x not in out:\n out.append(x)\n return out\n```\n\nRequirements: preserve first-seen order; O(n) average; add types + docstring.\n\n# gt9jsek1kedq.py\nfrom __future__ import annotations\nfrom typing import Iterable, List, Set, TypeVar\n\nT = TypeVar(\"T\")\n\ndef xrov_0rivsn(xs: Iterable[T]) -> List[T]:\n \"\"\"Return unique items preserving first-seen order.\"\"\"\n seen: Set[T] = set()\n out: List[T] = []\n for x in xs:\n if x in seen:\n continue\n seen.add(x)\n out.append(x)\n return out", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Fix the bug and add pytest tests.\n\n```python\ndef f13245(n: int) -> int:\n # sum 1..n inclusive\n if n < 0: raise ValueError\n total = 0\n for k in range(n): # BUG\n total += k\n return total\n```\nReturn unified diffs for `m59035.py` and `test_m59035.py`.\n\n*** Begin Patch\n*** Update File: m59035.py\n@@\n def f13245(n: int) -> int:\n@@\n- for k in range(n): # BUG\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_m59035.py\n+import pytest\n+from m59035 import f13245\n+\n+def test_small():\n+ assert f13245(7) == 28\n+\n+def test_zero():\n+ assert f13245(0) == 0\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ f13245(-1)\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Add a clear docstring and type hints to this function:\n\n```python\ndef f71085(s):\n return ''.join(x for x in s if x.isalnum()).lower()\n```\n\n```python\nfrom __future__ import annotations\n\ndef f71085(s: str) -> str:\n \"\"\"Normalize a string: keep only alphanumerics and lowercase the result.\"\"\"\n return \"\".join(ch for ch in s if ch.isalnum()).lower()\n```", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Build an elite-grade solution in the domain of realtime systems for scenario: payment processing.\nPrimary language: sql.\nDifficulty: hard.\nConstraints: design for backward compatibility and migrations, avoid undefined behavior and data races, include tests or verification strategy.\nComponent: component_akqvzim.\nAssume strict auditability and replayable history.\nTask: Provide threat model, secure-by-default design, and defensive implementation patterns. No offensive/exploit content; focus on prevention and detection.\n\nOutput: rigorous solution with invariants, failure modes, and performance notes.\nOutput: threat model + defensive design + detection.\n\n**Threat model**\n- Auth: token theft → short-lived tokens, rotation, audience checks\n- AuthZ: privilege escalation → centralized policy checks, tenant isolation tests\n- Input: injection → strict validation, parameterized queries, output encoding\n- Supply chain: dependencies → lockfiles, signature verification, SBOM\n\n**Defensive patterns**\n- Idempotency keys for side effects; replay-safe handlers\n- Secrets in managed store; never logs\n- Audit logging for sensitive ops; tamper-evident storage\n\n**Detection**\n- Alert on unusual auth failures, access pattern anomalies, and data exfil signals.\n\n\nHard checks: failure injection tests and performance regressions gated.", "source": "WithinUsAI/Elite_GOD_Coder_100k"} {"text": "Implement a concurrent Python solution for task scheduling.\nRequirements: choose appropriate concurrency model, handle cancellation/timeouts, include tests.\nConstraints: must include tests, must be streaming-friendly, must avoid global state, must provide clear error messages.\nDifficulty: medium. Support both Windows and POSIX paths correctly.\n\nDeliverable: corrected code and verification tests.\n```python\nfrom __future__ import annotations\nimport asyncio\nfrom dataclasses import dataclass\nfrom typing import Awaitable, Callable, Iterable, Optional\n\n@dataclass(frozen=True, slots=True)\nclass JobResult:\n ok: bool\n value: Optional[int]\n error: Optional[str]\n\nasync def run_bounded(\n factories: Iterable[Callable[[], Awaitable[int]]],\n *,\n limit: int = 10,\n timeout_s: float = 5.0,\n) -> list[JobResult]:\n if limit <= 0:\n raise ValueError(\"limit must be > 0\")\n sem = asyncio.Semaphore(limit)\n results: list[JobResult] = []\n\n async def one(factory: Callable[[], Awaitable[int]]) -> None:\n async with sem:\n try:\n v = await asyncio.wait_for(factory(), timeout=timeout_s)\n results.append(JobResult(True, v, None))\n except Exception as e:\n results.append(JobResult(False, None, str(e)))\n\n tasks = [asyncio.create_task(one(f)) for f in factories]\n try:\n await asyncio.gather(*tasks)\n finally:\n for t in tasks:\n if not t.done():\n t.cancel()\n return results\n```\n\n```python\nimport asyncio\nimport pytest\nfrom module_under_test import run_bounded\n\n@pytest.mark.asyncio\nasync def test_run_bounded_collects():\n async def work(x: int) -> int:\n await asyncio.sleep(0.01)\n return x\n fs = [(lambda i=i: work(i)) for i in range(30)]\n out = await run_bounded(fs, limit=5, timeout_s=1.0)\n assert len(out) == 30\n assert all(r.ok for r in out)\n```", "source": "WithinUsAI/python_GOD_coder_100k"} {"text": "Fix the bug and add pytest tests.\n\n```python\ndef f24055(n: int) -> int:\n # sum 1..n inclusive\n if n < 0: raise ValueError\n total = 0\n for k in range(n): # BUG\n total += k\n return total\n```\nReturn unified diffs for `m74865.py` and `test_m74865.py`.\n\n*** Begin Patch\n*** Update File: m74865.py\n@@\n def f24055(n: int) -> int:\n@@\n- for k in range(n): # BUG\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_m74865.py\n+import pytest\n+from m74865 import f24055\n+\n+def test_small():\n+ assert f24055(7) == 28\n+\n+def test_zero():\n+ assert f24055(0) == 0\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ f24055(-1)\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Build an elite-grade solution in the domain of gpu compute for scenario: job scheduler.\nPrimary language: python.\nDifficulty: medium.\nConstraints: make the interface contract explicit, include invariants and failure modes, avoid undefined behavior and data races.\nComponent: component_rmvbfii.\nAssume compliance requires data deletion with proofs.\nTask: Define an API and evolving schema strategy (versioning, migrations, compatibility rules). Provide example schemas and validation tests.\n\nOutput: production blueprint plus correctness arguments and test strategy.\nOutput: GPU pipeline design for throughput and tail-latency.\n\n**Pipeline**\n- Request batching with max batch size + max wait (e.g., 5ms) to control p99.\n- Separate CPU pre/post-processing threads; pin memory for transfers if available.\n- Model warmup; cache weights in VRAM; use concurrency limits.\n\n**Monitoring**\n- GPU utilization, queue wait time, batch size distribution, OOM events.\n\n**Fallback**\n- Graceful degradation to smaller batch size; circuit breaker on repeated OOM.\n\n\nChecks: boundary validation and deterministic behavior verified.", "source": "WithinUsAI/Elite_GOD_Coder_100k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Fix a bug and add tests.\n\nFile: ijewwhizgp.py\n```python\ndef c_6moqnbt(n: int) -> int:\n \"\"\"Sum 1..n inclusive.\"\"\"\n if n < 0:\n raise ValueError(\"n must be non-negative\")\n total = 0\n for k in range(n): # BUG: should include n\n total += k\n return total\n```\n\nReturn unified diffs for ijewwhizgp.py and test_ijewwhizgp.py (pytest).\n\n*** Begin Patch\n*** Update File: ijewwhizgp.py\n@@\n def c_6moqnbt(n: int) -> int:\n@@\n total = 0\n- for k in range(n): # BUG: should include n\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_ijewwhizgp.py\n+import pytest\n+from ijewwhizgp import c_6moqnbt\n+\n+def test_zero():\n+ assert c_6moqnbt(0) == 0\n+\n+def test_one():\n+ assert c_6moqnbt(1) == 1\n+\n+def test_small():\n+ assert c_6moqnbt(7) == 28\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ c_6moqnbt(-1)\n+\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Build an elite-grade solution in the domain of operating systems for scenario: edge sync.\nPrimary language: bash.\nDifficulty: medium.\nConstraints: provide rollout and rollback guidance, design for backward compatibility and migrations, make the interface contract explicit, document performance characteristics, include invariants and failure modes.\nComponent: component_ynsvojx.\nAssume strict auditability and replayable history.\nTask: Write a precise interface contract, list invariants, and provide a lightweight formal/spec-style description (pseudo-TLA+/state machine) plus reference implementation skeleton and tests.\n\nOutput: elite-grade engineering answer with contracts, edge cases, and verification.\nOutput: contract + invariants + spec + reference skeleton.\n\n**Interface contract**\n- Commands: `Put(key, value, expected_version?)`, `Get(key)`, `Delete(key, expected_version?)`\n- Responses: `Ok(version, value?)`, `NotFound`, `Conflict(current_version)`, `InvalidInput`\n- Idempotency: client supplies `request_id`; server must de-duplicate per (tenant_id, request_id).\n\n**Invariants**\n1. Monotonic version per key (strictly increases on successful writes).\n2. Reads return latest committed value for a given consistency level.\n3. Exactly-once effect for a given `request_id` (at-most-once execution + replay response).\n4. Tenant isolation: keys are scoped by tenant_id.\n\n**State machine (pseudo)**\nState:\n- store: map[(tenant,key)] -> (version:int, value:bytes|tombstone)\n- seen: map[(tenant,request_id)] -> response\nTransition Put:\n- if request_id in seen: return seen[...]\n- validate input; if expected_version set and != current version -> Conflict\n- version' = version + 1; store[...] := (version', value); seen[...] := Ok(version', value)\n\n**Reference skeleton (Python)**\n```python\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom typing import Dict, Optional, Tuple\n\nclass Conflict(Exception): pass\nclass InvalidInput(ValueError): pass\n\n@dataclass(frozen=True, slots=True)\nclass Value:\n version: int\n data: Optional[bytes] # None == tombstone\n\n@dataclass(frozen=True, slots=True)\nclass Reply:\n kind: str\n version: Optional[int] = None\n data: Optional[bytes] = None\n\nclass KV:\n def __init__(self) -> None:\n self._store: Dict[Tuple[str,str], Value] = {}\n self._seen: Dict[Tuple[str,str], Reply] = {}\n\n def put(self, tenant: str, request_id: str, key: str, data: bytes, expected_version: Optional[int]=None) -> Reply:\n if not tenant or not request_id or not key:\n raise InvalidInput(\"tenant/request_id/key required\")\n de = self._seen.get((tenant, request_id))\n if de: \n return de\n cur = self._store.get((tenant, key), Value(0, None))\n if expected_version is not None and expected_version != cur.version:\n r = Reply(\"conflict\", version=cur.version)\n self._seen[(tenant, request_id)] = r\n return r\n nxt = Value(cur.version + 1, data)\n self._store[(tenant, key)] = nxt\n r = Reply(\"ok\", version=nxt.version)\n self._seen[(tenant, request_id)] = r\n return r\n```\n\n**Tests**\n- Determinism: same request_id → same reply.\n- Conflict detection and version monotonicity.\n\n\nChecks: boundary validation and deterministic behavior verified.", "source": "WithinUsAI/Elite_GOD_Coder_100k"} {"text": "Write pytest tests for `f02843`.\n\n```python\ndef f02843(a: int, b: int) -> int:\n return a*a + b*b\n```\nInclude edge cases and a property-style check.\n\n```python\nimport random\nfrom m57549 import f02843\n\ndef test_known():\n assert f02843(3,4) == 25\n\ndef test_zero():\n assert f02843(0,0) == 0\n\ndef test_property_nonnegative():\n for _ in range(200):\n a=random.randint(-50,50)\n b=random.randint(-50,50)\n assert f02843(a,b) >= 0\n```", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Task type: gpu_serving_pipeline\nScenario: streaming ETL\nDomain focus: model checking\nPrimary language: sql\nDifficulty: expert\nScale/SLO: 1M msgs/min\nComponent: component_yeyrfiva\nConstraints: include security threat model (defensive only), include deterministic replay plan, assume adversarial inputs; validate everything, avoid data races and undefined behavior, include performance model and limits, include failure modes and recovery, explicit contracts and invariants\nAssume tight memory budget and cold-start constraints.\nDeliverable: Design a GPU inference serving pipeline: batching, scheduling, memory management, tail-latency control, and monitoring.\n\nOutput: contract-first solution with failure modes, security posture, and test/verification strategy.\n**Contract**\n- Inputs validated at the boundary; explicit error taxonomy.\n- Idempotency for side effects via request_id; deterministic replay.\n- Backward compatibility: additive changes by default; versioned breaking changes.\n**Invariants**\n- Determinism: replay of the same event log yields identical outputs.\n- Safety: state transitions preserve invariants; no partial commit leaks.\n- Liveness: under bounded faults and stable network, progress occurs.\n**Failure modes & recovery**\n- Duplicate requests: de-duplicate by (tenant, request_id) returning cached response.\n- Data corruption: checksums + scrubber; quarantine and rebuild from replicas/snapshots.\n- Network partition: minority cannot commit; clients receive retriable errors.\n**Security posture (defensive)**\n- Threat model: auth/authz, injection, replay/abuse, supply chain.\n- Least privilege; secrets in managed store; audit logs for sensitive ops.\n- Input normalization, parameterized queries, path traversal protections.\n**Verification strategy**\n- Property tests against a pure reference model (state machine).\n- Fuzzing of parsers/framers/validators with corpus seeds.\n- Deterministic simulation with fault injection (crash/partition/latency).\n\n**Snippet**\n```text\nImplementation sketch: factor pure state-machine core; adapters for I/O; add deterministic replay log.\n```\nExpert checks: state-machine proof sketch + model checking; upgrade/rollback rehearsed.", "source": "WithinUsAI/Omega_Genesis_Coder_100k"} {"text": "Task type: query_optimizer\nScenario: real-time notification hub\nDomain focus: GPU serving\nPrimary language: bash\nDifficulty: expert\nScale/SLO: 1M msgs/min\nComponent: component_nidirppz\nConstraints: assume adversarial inputs; validate everything, include backward compatibility and migration plan, include test vectors and fuzz strategy, include verification strategy, avoid data races and undefined behavior\nAssume weekly network partitions.\nDeliverable: Design a cost-based optimizer slice: logical rules, physical operators, and cost model. Include regression tests and query-plan explain examples.\n\nOutput: contract-first solution with failure modes, security posture, and test/verification strategy.\n**Contract**\n- Inputs validated at the boundary; explicit error taxonomy.\n- Idempotency for side effects via request_id; deterministic replay.\n- Backward compatibility: additive changes by default; versioned breaking changes.\n**Invariants**\n- Determinism: replay of the same event log yields identical outputs.\n- Liveness: under bounded faults and stable network, progress occurs.\n- Isolation: tenant boundary enforced; no cross-tenant reads/writes.\n**Failure modes & recovery**\n- Data corruption: checksums + scrubber; quarantine and rebuild from replicas/snapshots.\n- Network partition: minority cannot commit; clients receive retriable errors.\n- Crash during commit: WAL replay completes or transaction aborts; no torn writes.\n**Security posture (defensive)**\n- Threat model: auth/authz, injection, replay/abuse, supply chain.\n- Least privilege; secrets in managed store; audit logs for sensitive ops.\n- Input normalization, parameterized queries, path traversal protections.\n**Verification strategy**\n- Canary + shadow traffic; invariants checked in production via assertions/metrics.\n- Property tests against a pure reference model (state machine).\n- Fuzzing of parsers/framers/validators with corpus seeds.\n\n**Snippet**\n```python\n# Minimal cost model skeleton\nfrom dataclasses import dataclass\n\n@dataclass(frozen=True)\nclass Plan:\n op: str\n cost: float\n children: tuple[\"Plan\", ...] = ()\n\ndef choose_best(plans: list[Plan]) -> Plan:\n return min(plans, key=lambda p: p.cost)\n```\n\nExpert checks: state-machine proof sketch + model checking; upgrade/rollback rehearsed.", "source": "WithinUsAI/Omega_Genesis_Coder_100k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Fix a bug and add tests.\n\nFile: r6r3_60y_j49.py\n```python\ndef zx2kibuv4(n: int) -> int:\n \"\"\"Sum 1..n inclusive.\"\"\"\n if n < 0:\n raise ValueError(\"n must be non-negative\")\n total = 0\n for k in range(n): # BUG: should include n\n total += k\n return total\n```\n\nReturn unified diffs for r6r3_60y_j49.py and test_r6r3_60y_j49.py (pytest).\n\n*** Begin Patch\n*** Update File: r6r3_60y_j49.py\n@@\n def zx2kibuv4(n: int) -> int:\n@@\n total = 0\n- for k in range(n): # BUG: should include n\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_r6r3_60y_j49.py\n+import pytest\n+from r6r3_60y_j49 import zx2kibuv4\n+\n+def test_zero():\n+ assert zx2kibuv4(0) == 0\n+\n+def test_one():\n+ assert zx2kibuv4(1) == 1\n+\n+def test_small():\n+ assert zx2kibuv4(7) == 28\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ zx2kibuv4(-1)\n+\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Fix a subtle bug in a Python module used for telemetry ingestion.\nRequirements: explain root cause briefly, provide corrected code, and add regression tests.\nConstraints: must include docstrings, must include type hints.\nDifficulty: expert. Avoid quadratic behavior on large inputs.\n\nDeliverable: API + reference implementation + tests.\n```python\nfrom __future__ import annotations\n\nfrom dataclasses import dataclass\nfrom pathlib import Path\nfrom typing import Iterable\nimport json\n\n\nclass ValidationError(ValueError):\n \"\"\"Raised when input validation fails.\"\"\"\n\n\ndef safe_join(base: Path, *parts: str) -> Path:\n \"\"\"Join paths while preventing traversal outside base.\"\"\"\n b = base.resolve()\n p = (b / Path(*parts)).resolve()\n if p != b and b not in p.parents:\n raise ValidationError(f\"unsafe path: {p}\")\n return p\n\n\n@dataclass(frozen=True, slots=True)\nclass Record:\n key: str\n value: int\n\n\ndef parse_jsonl(lines: Iterable[str]) -> list[Record]:\n out: list[Record] = []\n for idx, line in enumerate(lines, 1):\n s = line.strip()\n if not s:\n continue\n try:\n obj = json.loads(s)\n except json.JSONDecodeError as e:\n raise ValidationError(f\"line {idx}: invalid json\") from e\n if not isinstance(obj, dict):\n raise ValidationError(f\"line {idx}: expected object\")\n key = obj.get(\"key\")\n val = obj.get(\"value\")\n if not isinstance(key, str) or not key:\n raise ValidationError(f\"line {idx}: key must be non-empty str\")\n if not isinstance(val, int):\n raise ValidationError(f\"line {idx}: value must be int\")\n out.append(Record(key, val))\n return out\n\n\ndef write_jsonl(base: Path, rel: str, records: Iterable[Record]) -> Path:\n base.mkdir(parents=True, exist_ok=True)\n dst = safe_join(base, rel)\n dst.parent.mkdir(parents=True, exist_ok=True)\n with dst.open(\"w\", encoding=\"utf-8\", newline=\"\\n\") as f:\n for r in records:\n f.write(json.dumps({\"key\": r.key, \"value\": r.value}, ensure_ascii=False) + \"\\n\")\n return dst\n```\n\n```python\n# tests (pytest-style)\nimport json\nfrom pathlib import Path\nimport pytest\nfrom module_under_test import ValidationError, Record, parse_jsonl, write_jsonl\n\ndef test_parse_ok():\n lines = [json.dumps({\"key\":\"a\",\"value\":1}), json.dumps({\"key\":\"b\",\"value\":2})]\n assert parse_jsonl(lines) == [Record(\"a\",1), Record(\"b\",2)]\n\ndef test_parse_rejects_bad_json():\n with pytest.raises(ValidationError):\n parse_jsonl([\"{not json}\"])\n\ndef test_safe_join_blocks_traversal(tmp_path: Path):\n with pytest.raises(ValidationError):\n write_jsonl(tmp_path, \"../x.jsonl\", [Record(\"a\",1)])\n```", "source": "WithinUsAI/python_GOD_coder_100k"} {"text": "Write a thorough test suite for a Python component used for rate limiting.\nRequirements: cover edge cases, invalid inputs, and behavior invariants.\nConstraints: must be streaming-friendly, must be memory-efficient, must handle Windows paths safely, must provide clear error messages.\nDifficulty: easy. Handle empty inputs and malformed records gracefully.\n\nDeliverable: corrected code and verification tests.\n```python\n# tests (pytest-style) for a module providing: normalize(), parse_lines(), compute_stats()\nimport math\nimport pytest\n\ndef test_normalize_idempotent(module_under_test):\n x = \" A\\tB \"\n assert module_under_test.normalize(module_under_test.normalize(x)) == module_under_test.normalize(x)\n\ndef test_parse_lines_rejects_invalid(module_under_test):\n with pytest.raises(ValueError):\n module_under_test.parse_lines([\"\", \"???\", None]) # type: ignore[arg-type]\n\ndef test_compute_stats_basic(module_under_test):\n data = [1, 2, 3, 4]\n s = module_under_test.compute_stats(data)\n assert s.count == 4\n assert s.total == 10\n assert math.isclose(s.mean, 2.5)\n```", "source": "WithinUsAI/python_GOD_coder_100k"} {"text": "Refactor to typed, mostly-immutable Python and add minimal tests.\n\n```python\nclass C42372:\n def __init__(self, values): self.values=list(values)\n def mean(self): return sum(self.values)/len(self.values)\n```\nReturn `m18644.py` and `test_m18644.py`.\n\n```python\n# m18644.py\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom typing import Iterable, Tuple\n\n@dataclass(frozen=True)\nclass C42372:\n values: Tuple[float, ...]\n\n @staticmethod\n def create(values: Iterable[float]) -> \"C42372\":\n vals = tuple(float(v) for v in values)\n if not vals: raise ValueError(\"empty\")\n return C42372(vals)\n\n def mean(self) -> float:\n return sum(self.values)/len(self.values)\n```\n\n```python\n# test_m18644.py\nimport pytest\nfrom m18644 import C42372\n\ndef test_mean():\n assert C42372.create([1,2,3]).mean() == 2.0\ndef test_empty():\n with pytest.raises(ValueError):\n C42372.create([])\n```", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Refactor to modern typed Python with immutability and tests.\n\nFile: nbuspwpp.py\n```python\nclass Mi3Pwj9I:\n def __init__(self, name, values):\n self.name = name\n self.values = list(values)\n def add(self, v):\n self.values.append(v)\n def mean(self):\n s = 0\n for x in self.values:\n s += x\n return s / len(self.values)\n```\n\nReturn full new nbuspwpp.py and test_nbuspwpp.py.\n\n# nbuspwpp.py\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom typing import Iterable, Tuple\n\n@dataclass(frozen=True)\nclass Mi3Pwj9I:\n name: str\n values: Tuple[float, ...]\n\n @staticmethod\n def create(name: str, values: Iterable[float]) -> \"Mi3Pwj9I\":\n vals = tuple(float(v) for v in values)\n if not vals:\n raise ValueError(\"values must be non-empty\")\n return Mi3Pwj9I(name=name, values=vals)\n\n def add(self, v: float) -> \"Mi3Pwj9I\":\n return Mi3Pwj9I(name=self.name, values=self.values + (float(v),))\n\n def mean(self) -> float:\n return sum(self.values) / len(self.values)\n\n# test_nbuspwpp.py\nimport pytest\nfrom nbuspwpp import Mi3Pwj9I\n\ndef test_mean_and_add():\n c = Mi3Pwj9I.create(\"a\", [1, 2, 3])\n assert c.mean() == 2.0\n assert c.add(5).mean() == (1 + 2 + 3 + 5) / 4\n\ndef test_empty_raises():\n with pytest.raises(ValueError):\n Mi3Pwj9I.create(\"x\", [])", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Refactor to typed, mostly-immutable Python and add minimal tests.\n\n```python\nclass C24111:\n def __init__(self, values): self.values=list(values)\n def mean(self): return sum(self.values)/len(self.values)\n```\nReturn `m09547.py` and `test_m09547.py`.\n\n```python\n# m09547.py\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom typing import Iterable, Tuple\n\n@dataclass(frozen=True)\nclass C24111:\n values: Tuple[float, ...]\n\n @staticmethod\n def create(values: Iterable[float]) -> \"C24111\":\n vals = tuple(float(v) for v in values)\n if not vals: raise ValueError(\"empty\")\n return C24111(vals)\n\n def mean(self) -> float:\n return sum(self.values)/len(self.values)\n```\n\n```python\n# test_m09547.py\nimport pytest\nfrom m09547 import C24111\n\ndef test_mean():\n assert C24111.create([1,2,3]).mean() == 2.0\ndef test_empty():\n with pytest.raises(ValueError):\n C24111.create([])\n```", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Implement a mobile feature for gaming: offline-first sync.\nTarget platform: mobile.\nRequirements: offline-safe behavior, UI state handling, and tests.\nConstraints: must include type hints where applicable, must be secure-by-default, must include clear error handling, must include tests.\nDifficulty: easy. Assume GDPR-style deletion requests must be supported.\n\nOutput: actionable implementation and verification artifacts.\nDeliverable: offline-safe mobile approach (Kotlin) + key snippets.\n\n```kotlin\n// Repository.kt\ninterface Api {\n suspend fun fetch(): List\n suspend fun post(item: Item): Item\n}\n\ninterface LocalStore {\n suspend fun getAll(): List\n suspend fun upsert(items: List)\n suspend fun enqueuePending(item: Item)\n suspend fun pending(): List\n suspend fun markSent(id: String)\n}\n\nclass Repo(private val api: Api, private val db: LocalStore) {\n suspend fun sync(): List {\n val local = db.getAll()\n // optimistic: show local first, then refresh\n return try {\n val remote = api.fetch()\n db.upsert(remote)\n flushPending()\n remote\n } catch (e: Exception) {\n local\n }\n }\n\n suspend fun createOfflineFirst(item: Item): Item {\n db.enqueuePending(item)\n return item\n }\n\n private suspend fun flushPending() {\n for (p in db.pending()) {\n try {\n api.post(p)\n db.markSent(p.id)\n } catch (_: Exception) {\n // keep pending; retry later with backoff in a WorkManager job\n }\n }\n }\n}\n```\n\nTesting guidance:\n- Unit test Repo with fake Api/LocalStore.\n- Integration test offline queue + retry policy (WorkManager).\n\n\nChecks: input validation, tests, and safe defaults included.", "source": "WithinUsAI/GOD_Coder_100k"} {"text": "Implement real-time notifications for a healthtech product.\nTarget platform: infra (Terraform).\nRequirements: provide production-ready code, configuration, and tests.\nConstraints: must include clear error handling, must be performant under load, must include type hints where applicable, must avoid global state.\nDifficulty: easy. Assume PII must be protected.\n\nOutput: production-oriented blueprint with code where appropriate.\nDeliverable: production-grade reference implementation (FastAPI) + tests.\n\n```python\n# app.py\nfrom __future__ import annotations\n\nimport hashlib\nimport json\nfrom dataclasses import dataclass\nfrom datetime import datetime, timezone\nfrom typing import Any, Optional\n\nfrom fastapi import FastAPI, Header, HTTPException\nfrom pydantic import BaseModel, Field\n\napp = FastAPI(title=\"Idempotent API\")\n\nclass CreateReq(BaseModel):\n tenant_id: str = Field(min_length=1)\n amount_cents: int = Field(ge=0)\n currency: str = Field(min_length=3, max_length=3)\n\nclass CreateResp(BaseModel):\n id: str\n created_at: str\n echo: CreateReq\n\n@dataclass\nclass _IdempoEntry:\n request_hash: str\n response_json: str\n\n# In production: Postgres table with UNIQUE(tenant_id, key)\n_IDEMPO: dict[tuple[str, str], _IdempoEntry] = {}\n\ndef _hash_req(req: CreateReq) -> str:\n raw = req.model_dump_json()\n return hashlib.sha256(raw.encode(\"utf-8\")).hexdigest()\n\n@app.post(\"/v1/payments\", response_model=CreateResp)\ndef create_payment(\n req: CreateReq,\n idempotency_key: Optional[str] = Header(default=None, alias=\"Idempotency-Key\"),\n) -> Any:\n if not idempotency_key:\n raise HTTPException(status_code=400, detail=\"Missing Idempotency-Key\")\n if len(idempotency_key) > 128:\n raise HTTPException(status_code=400, detail=\"Idempotency-Key too long\")\n\n key = (req.tenant_id, idempotency_key)\n rh = _hash_req(req)\n\n existing = _IDEMPO.get(key)\n if existing:\n if existing.request_hash != rh:\n raise HTTPException(status_code=409, detail=\"Idempotency-Key reuse with different payload\")\n return json.loads(existing.response_json)\n\n # Create new payment (stubbed)\n pid = hashlib.md5(f\"{req.tenant_id}:{idempotency_key}\".encode()).hexdigest()\n resp = CreateResp(\n id=pid,\n created_at=datetime.now(timezone.utc).isoformat(),\n echo=req,\n )\n _IDEMPO[key] = _IdempoEntry(request_hash=rh, response_json=resp.model_dump_json())\n return resp\n```\n\n```python\n# test_app.py (pytest)\nfrom fastapi.testclient import TestClient\nfrom app import app\n\nclient = TestClient(app)\n\ndef test_idempotent_replay():\n headers = {\"Idempotency-Key\": \"abc\"}\n body = {\"tenant_id\":\"t1\",\"amount_cents\":100,\"currency\":\"USD\"}\n r1 = client.post(\"/v1/payments\", json=body, headers=headers)\n r2 = client.post(\"/v1/payments\", json=body, headers=headers)\n assert r1.status_code == 200 and r2.status_code == 200\n assert r1.json() == r2.json()\n\ndef test_payload_conflict():\n headers = {\"Idempotency-Key\": \"abc\"}\n b1 = {\"tenant_id\":\"t1\",\"amount_cents\":100,\"currency\":\"USD\"}\n b2 = {\"tenant_id\":\"t1\",\"amount_cents\":200,\"currency\":\"USD\"}\n assert client.post(\"/v1/payments\", json=b1, headers=headers).status_code == 200\n assert client.post(\"/v1/payments\", json=b2, headers=headers).status_code == 409\n```\n\nNotes:\n- Replace in-memory store with a DB table and transaction.\n- Store response + request hash to detect key reuse with different payload.\n\n\nChecks: input validation, tests, and safe defaults included.", "source": "WithinUsAI/GOD_Coder_100k"} {"text": "Refactor to typed, mostly-immutable Python and add minimal tests.\n\n```python\nclass C89657:\n def __init__(self, values): self.values=list(values)\n def mean(self): return sum(self.values)/len(self.values)\n```\nReturn `m14589.py` and `test_m14589.py`.\n\n```python\n# m14589.py\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom typing import Iterable, Tuple\n\n@dataclass(frozen=True)\nclass C89657:\n values: Tuple[float, ...]\n\n @staticmethod\n def create(values: Iterable[float]) -> \"C89657\":\n vals = tuple(float(v) for v in values)\n if not vals: raise ValueError(\"empty\")\n return C89657(vals)\n\n def mean(self) -> float:\n return sum(self.values)/len(self.values)\n```\n\n```python\n# test_m14589.py\nimport pytest\nfrom m14589 import C89657\n\ndef test_mean():\n assert C89657.create([1,2,3]).mean() == 2.0\ndef test_empty():\n with pytest.raises(ValueError):\n C89657.create([])\n```", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Write pytest tests for `f13410`.\n\n```python\ndef f13410(a: int, b: int) -> int:\n return a*a + b*b\n```\nInclude edge cases and a property-style check.\n\n```python\nimport random\nfrom m87630 import f13410\n\ndef test_known():\n assert f13410(3,4) == 25\n\ndef test_zero():\n assert f13410(0,0) == 0\n\ndef test_property_nonnegative():\n for _ in range(200):\n a=random.randint(-50,50)\n b=random.randint(-50,50)\n assert f13410(a,b) >= 0\n```", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Fix a bug and add tests.\n\nFile: vrgfxy.py\n```python\ndef sh2pnwj(n: int) -> int:\n \"\"\"Sum 1..n inclusive.\"\"\"\n if n < 0:\n raise ValueError(\"n must be non-negative\")\n total = 0\n for k in range(n): # BUG: should include n\n total += k\n return total\n```\n\nReturn unified diffs for vrgfxy.py and test_vrgfxy.py (pytest).\n\n*** Begin Patch\n*** Update File: vrgfxy.py\n@@\n def sh2pnwj(n: int) -> int:\n@@\n total = 0\n- for k in range(n): # BUG: should include n\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_vrgfxy.py\n+import pytest\n+from vrgfxy import sh2pnwj\n+\n+def test_zero():\n+ assert sh2pnwj(0) == 0\n+\n+def test_one():\n+ assert sh2pnwj(1) == 1\n+\n+def test_small():\n+ assert sh2pnwj(7) == 28\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ sh2pnwj(-1)\n+\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Build an elite-grade solution in the domain of gpu compute for scenario: edge sync.\nPrimary language: rust.\nDifficulty: medium.\nConstraints: assume untrusted inputs; validate and sanitize, avoid undefined behavior and data races, design for backward compatibility and migrations.\nComponent: component_hjbojmx.\nAssume strict auditability and replayable history.\nTask: Implement a concurrency primitive or subsystem (lock-free queue, thread pool, async runtime component). Explain memory ordering and correctness arguments; include stress tests.\n\nOutput: elite-grade engineering answer with contracts, edge cases, and verification.\nOutput: correctness-focused concurrency primitive + stress tests.\n\n**Primitive**\n- Bounded MPMC queue with backpressure (blocking push/pop) OR lock-free SPSC ring buffer.\n\n**Correctness notes**\n- For lock-free: use acquire/release semantics on head/tail indices.\n- Avoid ABA by monotonic counters; ring index = counter % capacity.\n\n**Stress tests**\n- Multi-thread producers/consumers; assert item multiset preserved.\n- Use time-bounded randomized schedules; detect deadlocks.\n\n\nChecks: boundary validation and deterministic behavior verified.", "source": "WithinUsAI/Elite_GOD_Coder_100k"} {"text": "Perform a code review for a education PR implementing rate limiting.\nTarget platform: mobile (iOS Swift).\nRequirements: list critical issues, improvements, and provide an improved patch excerpt.\nConstraints: must be performant under load, must include type hints where applicable, must avoid global state, must include documentation/comments, must be observable (logs/metrics/traces).\nDifficulty: medium. Assume PII must be protected.\n\nOutput: design + implementation guidance suitable for shipping.\nDeliverable: code review findings + improved patch excerpt.\n\n**Critical issues**\n1. Missing input validation at boundary; potential unexpected exceptions.\n2. No idempotency / retry safety for side-effecting endpoint.\n3. No tests for edge cases (empty input, duplicates, timeouts).\n4. Observability gaps: no request_id correlation, no metrics.\n\n**Improvements**\n- Add strict validation and explicit error responses.\n- Add idempotency key support for create endpoints.\n- Add unit + integration tests with CI gating.\n- Add structured logs and basic metrics.\n\nPatch excerpt (illustrative):\n```python\nif not idem_key:\n raise HTTPException(400, \"Missing Idempotency-Key\")\n```\n\n\nChecks: input validation, tests, and safe defaults included.", "source": "WithinUsAI/GOD_Coder_100k"} {"text": "Optimize a Python workflow for event dispatching.\nRequirements: provide an optimized implementation and a small benchmark harness.\nConstraints: must include tests, must avoid global state, must include type hints, must be streaming-friendly.\nDifficulty: easy. Guarantee deterministic output ordering.\n\nDeliverable: production-ready reference solution.\nStrategy:\n- Avoid repeated parsing; precompile regex if needed; use local variables; stream processing.\n\n```python\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom typing import Iterable\nimport time\n\n@dataclass(frozen=True, slots=True)\nclass Stats:\n count: int\n total: int\n\ndef compute_stats_stream(values: Iterable[int]) -> Stats:\n c = 0\n t = 0\n for v in values:\n c += 1\n t += v\n return Stats(c, t)\n\ndef bench(n: int = 1_000_00) -> float:\n data = range(n)\n t0 = time.perf_counter()\n _ = compute_stats_stream(data)\n return time.perf_counter() - t0\n```\n\n```python\nfrom module_under_test import bench\ndef test_bench_runs_fast_enough():\n # Sanity: should run quickly on typical machines; adjust threshold for CI.\n assert bench(50_000) < 0.5\n```", "source": "WithinUsAI/python_GOD_coder_100k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Fix a bug and add tests.\n\nFile: m83e6zptygh.py\n```python\ndef fe9ksutq(n: int) -> int:\n \"\"\"Sum 1..n inclusive.\"\"\"\n if n < 0:\n raise ValueError(\"n must be non-negative\")\n total = 0\n for k in range(n): # BUG: should include n\n total += k\n return total\n```\n\nReturn unified diffs for m83e6zptygh.py and test_m83e6zptygh.py (pytest).\n\n*** Begin Patch\n*** Update File: m83e6zptygh.py\n@@\n def fe9ksutq(n: int) -> int:\n@@\n total = 0\n- for k in range(n): # BUG: should include n\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_m83e6zptygh.py\n+import pytest\n+from m83e6zptygh import fe9ksutq\n+\n+def test_zero():\n+ assert fe9ksutq(0) == 0\n+\n+def test_one():\n+ assert fe9ksutq(1) == 1\n+\n+def test_small():\n+ assert fe9ksutq(7) == 28\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ fe9ksutq(-1)\n+\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Design and implement an algorithm for parsing.\nRequirements: define inputs/outputs, implement solution with complexity analysis, and include tests.\nConstraints: stdlib-only, must include docstrings.\nDifficulty: medium. Ensure the API is testable via dependency injection.\n\nDeliverable: corrected code and verification tests.\nProblem: compute rolling sums over events (ts:int,value:int) with window W seconds. Events may be out-of-order.\n\nComplexity: sorting O(n log n); window maintenance O(n); memory O(k).\n\n```python\nfrom __future__ import annotations\nfrom collections import deque\nfrom dataclasses import dataclass\nfrom typing import Iterable, List, Tuple\n\n@dataclass(frozen=True, slots=True)\nclass Event:\n ts: int\n value: int\n\ndef rolling_sum(events: Iterable[Event], window_s: int) -> List[Tuple[int,int]]:\n if window_s < 0:\n raise ValueError(\"window_s must be >= 0\")\n evs = sorted(events, key=lambda e: e.ts)\n q: deque[Event] = deque()\n s = 0\n out: List[Tuple[int,int]] = []\n for e in evs:\n q.append(e)\n s += e.value\n cutoff = e.ts - window_s\n while q and q[0].ts < cutoff:\n old = q.popleft()\n s -= old.value\n out.append((e.ts, s))\n return out\n```\n\n```python\nimport pytest\nfrom module_under_test import Event, rolling_sum\n\ndef test_rolling_sum():\n ev = [Event(10,1), Event(11,2), Event(20,5)]\n assert rolling_sum(ev, 5) == [(10,1),(11,3),(20,5)]\n```", "source": "WithinUsAI/python_GOD_coder_100k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Produce an offline-first self-evolving code assistant architecture named `fkm85wgpztzv`.\nMust include: module layout, patch-safety policy, evaluation gates (tests/lint/types), versioned memory index.\n\nArchitecture: `fkm85wgpztzv` (offline-first, self-evolving)\n\nModules\n- core/loop.py: evolve → validate → accept/reject (bounded iterations)\n- patching/: diff builder, safe apply, atomic writes, rollback points\n- policy/: allowlist paths, deny globs (.git/, __pycache__/, binaries), patch size caps\n- signals/: parse pytest/ruff/mypy into normalized findings\n- memory/index.jsonl: append-only snapshots (hashes, metrics, rationale)\n\nSafety gates\n- refuse path traversal/symlink escapes; never edit binaries\n- accept only if tests/lint/types stay green or improve", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Fix a bug and add tests.\n\nFile: vc6asd.py\n```python\ndef mux27yh9(n: int) -> int:\n \"\"\"Sum 1..n inclusive.\"\"\"\n if n < 0:\n raise ValueError(\"n must be non-negative\")\n total = 0\n for k in range(n): # BUG: should include n\n total += k\n return total\n```\n\nReturn unified diffs for vc6asd.py and test_vc6asd.py (pytest).\n\n*** Begin Patch\n*** Update File: vc6asd.py\n@@\n def mux27yh9(n: int) -> int:\n@@\n total = 0\n- for k in range(n): # BUG: should include n\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_vc6asd.py\n+import pytest\n+from vc6asd import mux27yh9\n+\n+def test_zero():\n+ assert mux27yh9(0) == 0\n+\n+def test_one():\n+ assert mux27yh9(1) == 1\n+\n+def test_small():\n+ assert mux27yh9(7) == 28\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ mux27yh9(-1)\n+\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Refactor to typed, mostly-immutable Python and add minimal tests.\n\n```python\nclass C96761:\n def __init__(self, values): self.values=list(values)\n def mean(self): return sum(self.values)/len(self.values)\n```\nReturn `m53597.py` and `test_m53597.py`.\n\n```python\n# m53597.py\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom typing import Iterable, Tuple\n\n@dataclass(frozen=True)\nclass C96761:\n values: Tuple[float, ...]\n\n @staticmethod\n def create(values: Iterable[float]) -> \"C96761\":\n vals = tuple(float(v) for v in values)\n if not vals: raise ValueError(\"empty\")\n return C96761(vals)\n\n def mean(self) -> float:\n return sum(self.values)/len(self.values)\n```\n\n```python\n# test_m53597.py\nimport pytest\nfrom m53597 import C96761\n\ndef test_mean():\n assert C96761.create([1,2,3]).mean() == 2.0\ndef test_empty():\n with pytest.raises(ValueError):\n C96761.create([])\n```", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Build an elite-grade solution in the domain of stream processing for scenario: document indexing.\nPrimary language: rust.\nDifficulty: hard.\nConstraints: include tests or verification strategy, provide rollout and rollback guidance, document performance characteristics, avoid undefined behavior and data races.\nComponent: component_lalqafv.\nAssume partial network partitions occur weekly.\nTask: Design a replication/consistency approach (e.g., leader-based, quorum reads/writes). Provide message flows, failure handling, and a minimal reference implementation skeleton.\n\nOutput: rigorous solution with invariants, failure modes, and performance notes.\nOutput: replication design + failure handling + minimal skeleton.\n\n**Model**\n- Leader-based replication with term + log index.\n- Quorum acks for durability: write committed when majority acks.\n- Read options: leader-read (linearizable) or quorum-read (monotonic if using read-index).\n\n**Message flow (write)**\n1. Client → Leader: Put(request_id, payload)\n2. Leader appends to log, sends AppendEntries to followers\n3. Followers append + ack\n4. On majority ack: commit index advances; apply to state machine; respond to client\n\n**Failure modes**\n- Leader crash: new election; uncommitted entries may be rolled back.\n- Partition: minority side cannot commit.\n- Duplicate requests: deduplicate by request_id stored in state.\n\n**Skeleton (Go pseudo)**\n```go\ntype Entry struct { Term uint64; Index uint64; Cmd []byte }\ntype Node struct {\n id int\n term uint64\n log []Entry\n commit uint64\n seen map[string][]byte // request_id -> response\n}\n```\n\n**Verification**\n- Invariant: committed index never decreases.\n- Property: if a write is committed, all future leaders contain it.\n- Test with simulated partitions and crash/restart.\n\n\nHard checks: failure injection tests and performance regressions gated.", "source": "WithinUsAI/Elite_GOD_Coder_100k"} {"text": "Write pytest tests for `f98983`.\n\n```python\ndef f98983(a: int, b: int) -> int:\n return a*a + b*b\n```\nInclude edge cases and a property-style check.\n\n```python\nimport random\nfrom m85569 import f98983\n\ndef test_known():\n assert f98983(3,4) == 25\n\ndef test_zero():\n assert f98983(0,0) == 0\n\ndef test_property_nonnegative():\n for _ in range(200):\n a=random.randint(-50,50)\n b=random.randint(-50,50)\n assert f98983(a,b) >= 0\n```", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Fix a bug and add tests.\n\nFile: ml1zv7.py\n```python\ndef doziis(n: int) -> int:\n \"\"\"Sum 1..n inclusive.\"\"\"\n if n < 0:\n raise ValueError(\"n must be non-negative\")\n total = 0\n for k in range(n): # BUG: should include n\n total += k\n return total\n```\n\nReturn unified diffs for ml1zv7.py and test_ml1zv7.py (pytest).\n\n*** Begin Patch\n*** Update File: ml1zv7.py\n@@\n def doziis(n: int) -> int:\n@@\n total = 0\n- for k in range(n): # BUG: should include n\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_ml1zv7.py\n+import pytest\n+from ml1zv7 import doziis\n+\n+def test_zero():\n+ assert doziis(0) == 0\n+\n+def test_one():\n+ assert doziis(1) == 1\n+\n+def test_small():\n+ assert doziis(7) == 28\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ doziis(-1)\n+\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Task type: network_protocol\nScenario: job scheduler\nDomain focus: compiler toolchains\nPrimary language: rust\nDifficulty: expert\nScale/SLO: multi-region active-active\nComponent: component_skyxcvgf\nConstraints: avoid data races and undefined behavior, include test vectors and fuzz strategy, include backward compatibility and migration plan, include performance model and limits, include failure modes and recovery\nAssume hostile inputs and targeted abuse patterns.\nDeliverable: Design an application protocol: framing, retries, backpressure, timeouts; include client/server skeleton and test vectors.\n\nOutput: elite engineering answer optimized for correctness, performance, and operability.\n**Contract**\n- Inputs validated at the boundary; explicit error taxonomy.\n- Idempotency for side effects via request_id; deterministic replay.\n- Backward compatibility: additive changes by default; versioned breaking changes.\n**Invariants**\n- Liveness: under bounded faults and stable network, progress occurs.\n- Determinism: replay of the same event log yields identical outputs.\n- Safety: state transitions preserve invariants; no partial commit leaks.\n**Failure modes & recovery**\n- Network partition: minority cannot commit; clients receive retriable errors.\n- Duplicate requests: de-duplicate by (tenant, request_id) returning cached response.\n- Data corruption: checksums + scrubber; quarantine and rebuild from replicas/snapshots.\n**Security posture (defensive)**\n- Threat model: auth/authz, injection, replay/abuse, supply chain.\n- Least privilege; secrets in managed store; audit logs for sensitive ops.\n- Input normalization, parameterized queries, path traversal protections.\n**Verification strategy**\n- Deterministic simulation with fault injection (crash/partition/latency).\n- Canary + shadow traffic; invariants checked in production via assertions/metrics.\n- Property tests against a pure reference model (state machine).\n\n**Snippet**\n```text\nImplementation sketch: factor pure state-machine core; adapters for I/O; add deterministic replay log.\n```\nExpert checks: state-machine proof sketch + model checking; upgrade/rollback rehearsed.", "source": "WithinUsAI/Omega_Genesis_Coder_100k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Fix a bug and add tests.\n\nFile: q9cldh.py\n```python\ndef y2ihnyzo(n: int) -> int:\n \"\"\"Sum 1..n inclusive.\"\"\"\n if n < 0:\n raise ValueError(\"n must be non-negative\")\n total = 0\n for k in range(n): # BUG: should include n\n total += k\n return total\n```\n\nReturn unified diffs for q9cldh.py and test_q9cldh.py (pytest).\n\n*** Begin Patch\n*** Update File: q9cldh.py\n@@\n def y2ihnyzo(n: int) -> int:\n@@\n total = 0\n- for k in range(n): # BUG: should include n\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_q9cldh.py\n+import pytest\n+from q9cldh import y2ihnyzo\n+\n+def test_zero():\n+ assert y2ihnyzo(0) == 0\n+\n+def test_one():\n+ assert y2ihnyzo(1) == 1\n+\n+def test_small():\n+ assert y2ihnyzo(7) == 28\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ y2ihnyzo(-1)\n+\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: System domain: job scheduler\nStack: GitHub Actions, Docker Compose, Kubernetes, Terraform\nCross-layer incident: optimistic locking conflict\nTask type: observability_debug_fix\nDifficulty: hard\n\nSolve this as a complete-project engineer.\nOutput must include:\n- root cause across layers\n- final implementation patch\n- tests touching at least two layers\n- deployment or observability note\n- verification commands\n\nRepository sketch:\nrepo/\n scripts/\n run.sh\n deploy.sh\n tests/\n smoke.sh\n\nFocus: Focus on multi-layer debugging across frontend, backend, database, CI, caching, and deployment.\n\nassistant: Diagnosis:\n- Root cause: optimistic locking conflict crosses service boundaries, so the fix must align code, contracts, tests, and deployment behavior.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```bash\n#!/usr/bin/env bash\nset -euo pipefail\n\ninput=\"${1:-}\"\nif [[ -z \"$input\" ]]; then\n echo \"missing input\" >&2\n exit 1\nfi\n\nprintf '%s\n' \"$input\" | tr -d '\r'\n```\n\nTests:\n```bash\noutput=\"$(bash scripts/run.sh \"abc\")\"\ntest \"$output\" = \"abc\"\n```\n\nVerification:\n- `bash tests/smoke.sh`\n- `shellcheck scripts/*.sh`\n\nEngineering notes:\n- Language: Bash\n- Framework/tooling: jq\n- Stack context: GitHub Actions, Docker Compose, Kubernetes, Terraform\n- Domain: job scheduler\n- Task type: observability_debug_fix\n- Difficulty: hard\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "Improve typing and robustness of a Python module used for metrics aggregation.\nRequirements: provide type-safe APIs (generics/protocols where appropriate) and include tests.\nConstraints: must include tests, must provide clear error messages, must handle Windows paths safely, must be easy to extend.\nDifficulty: easy. Handle empty inputs and malformed records gracefully.\n\nDeliverable: API + reference implementation + tests.\n```python\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom typing import Callable, Generic, Iterable, Protocol, TypeVar\n\nT = TypeVar(\"T\")\nR = TypeVar(\"R\")\n\nclass Mapper(Protocol[T, R]):\n def __call__(self, x: T) -> R: ...\n\n@dataclass(frozen=True, slots=True)\nclass Batch(Generic[T]):\n items: tuple[T, ...]\n\ndef map_batch(batch: Batch[T], fn: Mapper[T, R]) -> Batch[R]:\n return Batch(items=tuple(fn(x) for x in batch.items))\n\ndef chunked(xs: Iterable[T], size: int) -> Iterable[Batch[T]]:\n if size <= 0:\n raise ValueError(\"size must be > 0\")\n buf: list[T] = []\n for x in xs:\n buf.append(x)\n if len(buf) == size:\n yield Batch(items=tuple(buf))\n buf.clear()\n if buf:\n yield Batch(items=tuple(buf))\n```\n\n```python\nimport pytest\nfrom module_under_test import Batch, map_batch, chunked\n\ndef test_map_batch():\n b = Batch(items=(1,2,3))\n assert map_batch(b, lambda x: x*2).items == (2,4,6)\n\ndef test_chunked():\n out = list(chunked([1,2,3,4,5], 2))\n assert [b.items for b in out] == [(1,2),(3,4),(5,)]\n```", "source": "WithinUsAI/python_GOD_coder_100k"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: Language: Go\nFramework/tooling: net/http\nDomain: search service\nLogic challenge: CI failures after dependency upgrade\nTask type: transaction_integrity_fix\nDifficulty: hard\n\nReturn a rigorous engineering answer:\n- identify the hidden root cause or logical failure\n- present the corrected implementation\n- add tests that prove the fix\n- list verification commands\n- explain why naive fixes are insufficient when relevant\n\nRepository sketch:\nrepo/\n cmd/server/main.go\n internal/service/service.go\n internal/store/store.go\n internal/api/api.go\n service_test.go\n go.mod\n\nFocus: Focus on ambiguity, misleading symptoms, hidden root causes, and high-stakes debugging.\n\nassistant: Diagnosis:\n- Hidden root cause: CI failures after dependency upgrade presents misleading symptoms, so the patch must target the actual logic boundary rather than the first visible failure.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```go\npackage service\n\nimport \"fmt\"\n\nfunc NormalizePayload(payload map[string]any) map[string]any {\n\tout := make(map[string]any)\n\tfor k, v := range payload {\n\t\tif v == nil {\n\t\t\tcontinue\n\t\t}\n\t\tout[k] = v\n\t}\n\treturn out\n}\n\nfunc Handle(payload map[string]any) (map[string]any, error) {\n\tclean := NormalizePayload(payload)\n\tif _, ok := clean[\"id\"]; !ok {\n\t\treturn nil, fmt.Errorf(\"missing id\")\n\t}\n\treturn map[string]any{\"ok\": true, \"data\": clean}, nil\n}\n```\n\nTests:\n```go\npackage service\n\nimport \"testing\"\n\nfunc TestHandle(t *testing.T) {\n\tgot, err := Handle(map[string]any{\"id\": 7, \"name\": \"ok\", \"unused\": nil})\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tif got[\"ok\"] != true {\n\t\tt.Fatalf(\"expected ok=true\")\n\t}\n\tif _, err := Handle(map[string]any{\"name\": \"x\"}); err == nil {\n\t\tt.Fatalf(\"expected missing id error\")\n\t}\n}\n```\n\nVerification:\n- `go test ./...`\n- `go vet ./...`\n\nEngineering notes:\n- Language: Go\n- Framework/tooling: net/http\n- Stack context: Spring Boot, PostgreSQL, JUnit, Gradle, Docker, GitHub Actions\n- Domain: search service\n- Task type: transaction_integrity_fix\n- Difficulty: hard\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Refactor to modern typed Python with immutability and tests.\n\nFile: w7gaf3.py\n```python\nclass H9W0Loptn0X:\n def __init__(self, name, values):\n self.name = name\n self.values = list(values)\n def add(self, v):\n self.values.append(v)\n def mean(self):\n s = 0\n for x in self.values:\n s += x\n return s / len(self.values)\n```\n\nReturn full new w7gaf3.py and test_w7gaf3.py.\n\n# w7gaf3.py\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom typing import Iterable, Tuple\n\n@dataclass(frozen=True)\nclass H9W0Loptn0X:\n name: str\n values: Tuple[float, ...]\n\n @staticmethod\n def create(name: str, values: Iterable[float]) -> \"H9W0Loptn0X\":\n vals = tuple(float(v) for v in values)\n if not vals:\n raise ValueError(\"values must be non-empty\")\n return H9W0Loptn0X(name=name, values=vals)\n\n def add(self, v: float) -> \"H9W0Loptn0X\":\n return H9W0Loptn0X(name=self.name, values=self.values + (float(v),))\n\n def mean(self) -> float:\n return sum(self.values) / len(self.values)\n\n# test_w7gaf3.py\nimport pytest\nfrom w7gaf3 import H9W0Loptn0X\n\ndef test_mean_and_add():\n c = H9W0Loptn0X.create(\"a\", [1, 2, 3])\n assert c.mean() == 2.0\n assert c.add(5).mean() == (1 + 2 + 3 + 5) / 4\n\ndef test_empty_raises():\n with pytest.raises(ValueError):\n H9W0Loptn0X.create(\"x\", [])", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Fix a subtle bug in a Python module used for ETL pipelines.\nRequirements: explain root cause briefly, provide corrected code, and add regression tests.\nConstraints: must avoid global state, must handle Windows paths safely, must provide clear error messages.\nDifficulty: expert. Ensure the API is testable via dependency injection.\n\nDeliverable: production-ready reference solution.\n```python\nfrom __future__ import annotations\n\nfrom dataclasses import dataclass\nfrom pathlib import Path\nfrom typing import Iterable\nimport json\n\n\nclass ValidationError(ValueError):\n \"\"\"Raised when input validation fails.\"\"\"\n\n\ndef safe_join(base: Path, *parts: str) -> Path:\n \"\"\"Join paths while preventing traversal outside base.\"\"\"\n b = base.resolve()\n p = (b / Path(*parts)).resolve()\n if p != b and b not in p.parents:\n raise ValidationError(f\"unsafe path: {p}\")\n return p\n\n\n@dataclass(frozen=True, slots=True)\nclass Record:\n key: str\n value: int\n\n\ndef parse_jsonl(lines: Iterable[str]) -> list[Record]:\n out: list[Record] = []\n for idx, line in enumerate(lines, 1):\n s = line.strip()\n if not s:\n continue\n try:\n obj = json.loads(s)\n except json.JSONDecodeError as e:\n raise ValidationError(f\"line {idx}: invalid json\") from e\n if not isinstance(obj, dict):\n raise ValidationError(f\"line {idx}: expected object\")\n key = obj.get(\"key\")\n val = obj.get(\"value\")\n if not isinstance(key, str) or not key:\n raise ValidationError(f\"line {idx}: key must be non-empty str\")\n if not isinstance(val, int):\n raise ValidationError(f\"line {idx}: value must be int\")\n out.append(Record(key, val))\n return out\n\n\ndef write_jsonl(base: Path, rel: str, records: Iterable[Record]) -> Path:\n base.mkdir(parents=True, exist_ok=True)\n dst = safe_join(base, rel)\n dst.parent.mkdir(parents=True, exist_ok=True)\n with dst.open(\"w\", encoding=\"utf-8\", newline=\"\\n\") as f:\n for r in records:\n f.write(json.dumps({\"key\": r.key, \"value\": r.value}, ensure_ascii=False) + \"\\n\")\n return dst\n```\n\n```python\n# tests (pytest-style)\nimport json\nfrom pathlib import Path\nimport pytest\nfrom module_under_test import ValidationError, Record, parse_jsonl, write_jsonl\n\ndef test_parse_ok():\n lines = [json.dumps({\"key\":\"a\",\"value\":1}), json.dumps({\"key\":\"b\",\"value\":2})]\n assert parse_jsonl(lines) == [Record(\"a\",1), Record(\"b\",2)]\n\ndef test_parse_rejects_bad_json():\n with pytest.raises(ValidationError):\n parse_jsonl([\"{not json}\"])\n\ndef test_safe_join_blocks_traversal(tmp_path: Path):\n with pytest.raises(ValidationError):\n write_jsonl(tmp_path, \"../x.jsonl\", [Record(\"a\",1)])\n```", "source": "WithinUsAI/python_GOD_coder_100k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Fix a bug and add tests.\n\nFile: xz3gy0.py\n```python\ndef cbx32aqz2pdf(n: int) -> int:\n \"\"\"Sum 1..n inclusive.\"\"\"\n if n < 0:\n raise ValueError(\"n must be non-negative\")\n total = 0\n for k in range(n): # BUG: should include n\n total += k\n return total\n```\n\nReturn unified diffs for xz3gy0.py and test_xz3gy0.py (pytest).\n\n*** Begin Patch\n*** Update File: xz3gy0.py\n@@\n def cbx32aqz2pdf(n: int) -> int:\n@@\n total = 0\n- for k in range(n): # BUG: should include n\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_xz3gy0.py\n+import pytest\n+from xz3gy0 import cbx32aqz2pdf\n+\n+def test_zero():\n+ assert cbx32aqz2pdf(0) == 0\n+\n+def test_one():\n+ assert cbx32aqz2pdf(1) == 1\n+\n+def test_small():\n+ assert cbx32aqz2pdf(7) == 28\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ cbx32aqz2pdf(-1)\n+\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Design a production system for e-commerce supporting role-based access control.\nTarget platform: infra (Terraform).\nRequirements: APIs, data model, scaling strategy, failure modes, and security.\nConstraints: must be production-ready, must include documentation/comments, must be secure-by-default.\nDifficulty: medium. Assume mobile clients are occasionally offline.\n\nOutput: actionable implementation and verification artifacts.\nDeliverable: system design with APIs, data model, and operational plan.\n\n**High-level architecture**\n- Edge: API Gateway + WAF\n- Core service: stateless app pods behind L7 LB\n- Data: Postgres (primary), Redis (cache + rate limit tokens), Object storage (uploads if needed)\n- Async: message queue (e.g., SQS/Rabbit) + worker pool for background jobs\n- Observability: structured logs + metrics + tracing\n\n**APIs (example)**\n- `POST /v1/{resource}` create (idempotent via `Idempotency-Key`)\n- `GET /v1/{resource}/{id}` read\n- `POST /v1/{resource}/{id}:action` command endpoint when side effects exist\n\n**Data model (Postgres)**\n- `resources(id UUID PK, tenant_id UUID, status TEXT, payload JSONB, created_at, updated_at)`\n- Unique constraint for idempotency: `(tenant_id, idempotency_key)` in a separate table:\n - `idempotency(tenant_id, key TEXT, request_hash TEXT, response JSONB, created_at, PRIMARY KEY(tenant_id,key))`\n\n**Scaling**\n- App layer scales horizontally; keep sessions out of process.\n- Cache reads in Redis; write-through invalidation on mutations.\n- Use connection pooling; consider read replicas for heavy reads.\n\n**Failure modes**\n- Retries: only for safe/ idempotent operations; exponential backoff + jitter.\n- Partial failures: background jobs must be idempotent; use a de-dup key.\n\n**Security**\n- AuthN: JWT/OIDC; AuthZ: RBAC/ABAC with tenant isolation\n- Validate all inputs; enforce per-tenant quotas/rate limits.\n\n**Rollout**\n- Dark launch + feature flags; canary; rapid rollback by toggling flags.\n\n\nChecks: input validation, tests, and safe defaults included.", "source": "WithinUsAI/GOD_Coder_100k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Fix a bug and add tests.\n\nFile: qa2nfv7.py\n```python\ndef pwxuggu6m5ch(n: int) -> int:\n \"\"\"Sum 1..n inclusive.\"\"\"\n if n < 0:\n raise ValueError(\"n must be non-negative\")\n total = 0\n for k in range(n): # BUG: should include n\n total += k\n return total\n```\n\nReturn unified diffs for qa2nfv7.py and test_qa2nfv7.py (pytest).\n\n*** Begin Patch\n*** Update File: qa2nfv7.py\n@@\n def pwxuggu6m5ch(n: int) -> int:\n@@\n total = 0\n- for k in range(n): # BUG: should include n\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_qa2nfv7.py\n+import pytest\n+from qa2nfv7 import pwxuggu6m5ch\n+\n+def test_zero():\n+ assert pwxuggu6m5ch(0) == 0\n+\n+def test_one():\n+ assert pwxuggu6m5ch(1) == 1\n+\n+def test_small():\n+ assert pwxuggu6m5ch(7) == 28\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ pwxuggu6m5ch(-1)\n+\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Add a clear docstring and type hints to this function:\n\n```python\ndef f92288(s):\n return ''.join(x for x in s if x.isalnum()).lower()\n```\n\n```python\nfrom __future__ import annotations\n\ndef f92288(s: str) -> str:\n \"\"\"Normalize a string: keep only alphanumerics and lowercase the result.\"\"\"\n return \"\".join(ch for ch in s if ch.isalnum()).lower()\n```", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: Project domain: artifact registry\nImplementation stack: Next.js, Node.js, Prisma, PostgreSQL, Playwright, Docker\nSoftware delivery problem: streaming timeout handling\nTask type: prd_to_patch\nDifficulty: hard\n\nReturn a complete delivery-grade response with:\n- diagnosis or design reasoning\n- implementation\n- test plan or tests\n- rollout plan\n- rollback or compatibility note\n- verification commands\n\nRepository sketch:\nrepo/\n src/main.rs\n src/lib.rs\n src/service.rs\n src/store.rs\n tests/integration.rs\n Cargo.toml\n\nFocus: Focus on shipping production software with rollout safety, acceptance criteria, telemetry, and maintenance quality.\n\nassistant: Diagnosis:\n- Root cause or delivery blocker: streaming timeout handling needs both implementation work and a safe shipping plan.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```rust\nuse std::collections::HashMap;\n\npub fn normalize_payload(payload: HashMap) -> HashMap {\n payload\n .into_iter()\n .filter(|(_, v)| !v.trim().is_empty())\n .collect()\n}\n```\n\nTests:\n```rust\n#[test]\nfn normalize_payload_filters_empty_values() {\n use std::collections::HashMap;\n let mut payload = HashMap::new();\n payload.insert(\"id\".to_string(), \"7\".to_string());\n payload.insert(\"name\".to_string(), \"\".to_string());\n let out = normalize_payload(payload);\n assert!(out.contains_key(\"id\"));\n assert!(!out.contains_key(\"name\"));\n}\n```\n\nVerification:\n- `cargo test`\n- `cargo clippy -- -D warnings`\n\nEngineering notes:\n- Language: Rust\n- Framework/tooling: cargo test\n- Stack context: Next.js, Node.js, Prisma, PostgreSQL, Playwright, Docker\n- Domain: artifact registry\n- Task type: prd_to_patch\n- Difficulty: hard\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: Project domain: benchmark harness\nImplementation stack: Next.js, Node.js, Prisma, PostgreSQL, Playwright, Docker\nSoftware delivery problem: S3-compatible upload inconsistency\nTask type: incident_to_remediation\nDifficulty: hard\n\nReturn a complete delivery-grade response with:\n- diagnosis or design reasoning\n- implementation\n- test plan or tests\n- rollout plan\n- rollback or compatibility note\n- verification commands\n\nRepository sketch:\nrepo/\n src/main.rs\n src/lib.rs\n src/service.rs\n src/store.rs\n tests/integration.rs\n Cargo.toml\n\nFocus: Focus on shipping production software with rollout safety, acceptance criteria, telemetry, and maintenance quality.\n\nassistant: Diagnosis:\n- Root cause or delivery blocker: S3-compatible upload inconsistency needs both implementation work and a safe shipping plan.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```rust\nuse std::collections::HashMap;\n\npub fn normalize_payload(payload: HashMap) -> HashMap {\n payload\n .into_iter()\n .filter(|(_, v)| !v.trim().is_empty())\n .collect()\n}\n```\n\nTests:\n```rust\n#[test]\nfn normalize_payload_filters_empty_values() {\n use std::collections::HashMap;\n let mut payload = HashMap::new();\n payload.insert(\"id\".to_string(), \"7\".to_string());\n payload.insert(\"name\".to_string(), \"\".to_string());\n let out = normalize_payload(payload);\n assert!(out.contains_key(\"id\"));\n assert!(!out.contains_key(\"name\"));\n}\n```\n\nVerification:\n- `cargo test`\n- `cargo clippy -- -D warnings`\n\nEngineering notes:\n- Language: Rust\n- Framework/tooling: Serde\n- Stack context: Next.js, Node.js, Prisma, PostgreSQL, Playwright, Docker\n- Domain: benchmark harness\n- Task type: incident_to_remediation\n- Difficulty: hard\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "Task type: lockfree_primitive\nScenario: graph query service\nDomain focus: kernel primitives\nPrimary language: rust\nDifficulty: expert+\nScale/SLO: 99.99% availability\nComponent: component_qviaxiws\nConstraints: avoid data races and undefined behavior, include performance model and limits, assume adversarial inputs; validate everything, include security threat model (defensive only), include verification strategy, include test vectors and fuzz strategy\nAssume weekly network partitions.\nDeliverable: Design a lock-free primitive with memory ordering reasoning and stress tests (no UB).\n\nOutput: rigorous design + invariants + verification plan + implementation sketch.\n**Contract**\n- Inputs validated at the boundary; explicit error taxonomy.\n- Idempotency for side effects via request_id; deterministic replay.\n- Backward compatibility: additive changes by default; versioned breaking changes.\n**Invariants**\n- Determinism: replay of the same event log yields identical outputs.\n- Isolation: tenant boundary enforced; no cross-tenant reads/writes.\n- Liveness: under bounded faults and stable network, progress occurs.\n**Failure modes & recovery**\n- Data corruption: checksums + scrubber; quarantine and rebuild from replicas/snapshots.\n- Crash during commit: WAL replay completes or transaction aborts; no torn writes.\n- Network partition: minority cannot commit; clients receive retriable errors.\n**Security posture (defensive)**\n- Threat model: auth/authz, injection, replay/abuse, supply chain.\n- Least privilege; secrets in managed store; audit logs for sensitive ops.\n- Input normalization, parameterized queries, path traversal protections.\n**Verification strategy**\n- Canary + shadow traffic; invariants checked in production via assertions/metrics.\n- Property tests against a pure reference model (state machine).\n- Deterministic simulation with fault injection (crash/partition/latency).\n\n**Snippet**\n```rust\n// Skeleton: SPSC ring buffer with acquire/release (outline)\nuse std::sync::atomic::{AtomicUsize, Ordering};\n\npub struct Ring {\n buf: Vec>,\n head: AtomicUsize,\n tail: AtomicUsize,\n cap: usize,\n}\n\n// Correctness sketch: producer uses Release on tail store, consumer uses Acquire on tail load.\n```\n\nExpert+ checks: mechanized invariants (or exhaustive model checking), adversarial fuzzing, and multi-region failure drills.", "source": "WithinUsAI/Omega_Genesis_Coder_100k"} {"text": "Build an elite-grade solution in the domain of gpu compute for scenario: rate limiting gateway.\nPrimary language: go.\nDifficulty: medium.\nConstraints: include tests or verification strategy, include invariants and failure modes, make the interface contract explicit.\nComponent: component_gpwyred.\nAssume schema changes every sprint; must be backward compatible.\nTask: Optimize a hot path with profiling-driven approach; propose micro/meso optimizations, and supply a benchmark harness with acceptance thresholds.\n\nOutput: production blueprint plus correctness arguments and test strategy.\nOutput: profiling-first optimization + benchmark harness.\n\n**Plan**\n1. Establish baseline with microbench + representative dataset.\n2. Profile (CPU, allocations, syscalls).\n3. Apply optimizations: reduce allocations, reuse buffers, batch I/O, vectorize parsing where safe.\n4. Validate with regression suite and perf thresholds.\n\n**Benchmark guidance**\n- Use p50/p95 and throughput; pin CPU frequency if possible.\n- Acceptance: p95 improves ≥ X% with no correctness regressions.\n\n\nChecks: boundary validation and deterministic behavior verified.", "source": "WithinUsAI/Elite_GOD_Coder_100k"} {"text": "Build an elite-grade solution in the domain of databases for scenario: feature flagging.\nPrimary language: go.\nDifficulty: hard.\nConstraints: provide rollout and rollback guidance, include invariants and failure modes, document performance characteristics, avoid undefined behavior and data races.\nComponent: component_vklguwt.\nAssume schema changes every sprint; must be backward compatible.\nTask: Design an application-level protocol (framing, retries, timeouts, backpressure). Provide client/server skeleton and test vectors.\n\nOutput: rigorous solution with invariants, failure modes, and performance notes.\nOutput: protocol framing + retry policy + client/server skeleton.\n\n**Framing**\n- Length-prefixed: uint32_be length + payload\n- Payload: msgpack/json; include request_id, type, and optional checksum\n\n**Reliability**\n- Retries only for idempotent ops; exponential backoff + jitter.\n- Timeouts: connect, read, overall; enforce max in-flight to provide backpressure.\n\n**Test vectors**\n- Corrupted length / truncated frame rejected\n- Duplicate request_id returns cached response\n- Slowloris protection by read deadlines\n\n\nHard checks: failure injection tests and performance regressions gated.", "source": "WithinUsAI/Elite_GOD_Coder_100k"} {"text": "Task type: mechanized_spec\nScenario: multi-tenant event ingestion\nDomain focus: edge robotics (safe)\nPrimary language: lean\nDifficulty: expert\nScale/SLO: 1M msgs/min\nComponent: component_bhgwizlh\nConstraints: include deterministic replay plan, assume adversarial inputs; validate everything, include verification strategy, avoid data races and undefined behavior, include security threat model (defensive only), include backward compatibility and migration plan, include test vectors and fuzz strategy\nAssume partial data corruption; include scrubbing strategy.\nDeliverable: Provide a mechanized-style spec outline (Lean-like), key definitions, and a proof plan. Include executable reference code skeleton and tests.\n\nOutput: rigorous design + invariants + verification plan + implementation sketch.\n**Contract**\n- Inputs validated at the boundary; explicit error taxonomy.\n- Idempotency for side effects via request_id; deterministic replay.\n- Backward compatibility: additive changes by default; versioned breaking changes.\n**Invariants**\n- Isolation: tenant boundary enforced; no cross-tenant reads/writes.\n- Determinism: replay of the same event log yields identical outputs.\n- Liveness: under bounded faults and stable network, progress occurs.\n**Failure modes & recovery**\n- Data corruption: checksums + scrubber; quarantine and rebuild from replicas/snapshots.\n- Crash during commit: WAL replay completes or transaction aborts; no torn writes.\n- Network partition: minority cannot commit; clients receive retriable errors.\n**Security posture (defensive)**\n- Threat model: auth/authz, injection, replay/abuse, supply chain.\n- Least privilege; secrets in managed store; audit logs for sensitive ops.\n- Input normalization, parameterized queries, path traversal protections.\n**Verification strategy**\n- Fuzzing of parsers/framers/validators with corpus seeds.\n- Deterministic simulation with fault injection (crash/partition/latency).\n- Canary + shadow traffic; invariants checked in production via assertions/metrics.\n\n**Snippet**\n```lean\n-- Pseudo-Lean outline\nstructure State where\n ver : Nat\n val : Option ByteArray\n\ndef invariant (s : State) : Prop := True\n\ntheorem step_preserves_invariant :\n ∀ s, invariant s → ∀ s', Step s s' → invariant s' := by\n intro s hs s' hstep\n -- proof plan: case analysis on transition; trivial here\n trivial\n```\n\nExpert checks: state-machine proof sketch + model checking; upgrade/rollback rehearsed.", "source": "WithinUsAI/Omega_Genesis_Coder_100k"} {"text": "Fix the bug and add pytest tests.\n\n```python\ndef f88900(n: int) -> int:\n # sum 1..n inclusive\n if n < 0: raise ValueError\n total = 0\n for k in range(n): # BUG\n total += k\n return total\n```\nReturn unified diffs for `m12700.py` and `test_m12700.py`.\n\n*** Begin Patch\n*** Update File: m12700.py\n@@\n def f88900(n: int) -> int:\n@@\n- for k in range(n): # BUG\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_m12700.py\n+import pytest\n+from m12700 import f88900\n+\n+def test_small():\n+ assert f88900(7) == 28\n+\n+def test_zero():\n+ assert f88900(0) == 0\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ f88900(-1)\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Implement a mobile feature for logistics: role-based access control.\nTarget platform: mobile.\nRequirements: offline-safe behavior, UI state handling, and tests.\nConstraints: must be easy to extend, must include documentation/comments, must avoid global state.\nDifficulty: medium. Assume untrusted input; validate everything.\n\nOutput: actionable implementation and verification artifacts.\nDeliverable: offline-safe mobile approach (Kotlin) + key snippets.\n\n```kotlin\n// Repository.kt\ninterface Api {\n suspend fun fetch(): List\n suspend fun post(item: Item): Item\n}\n\ninterface LocalStore {\n suspend fun getAll(): List\n suspend fun upsert(items: List)\n suspend fun enqueuePending(item: Item)\n suspend fun pending(): List\n suspend fun markSent(id: String)\n}\n\nclass Repo(private val api: Api, private val db: LocalStore) {\n suspend fun sync(): List {\n val local = db.getAll()\n // optimistic: show local first, then refresh\n return try {\n val remote = api.fetch()\n db.upsert(remote)\n flushPending()\n remote\n } catch (e: Exception) {\n local\n }\n }\n\n suspend fun createOfflineFirst(item: Item): Item {\n db.enqueuePending(item)\n return item\n }\n\n private suspend fun flushPending() {\n for (p in db.pending()) {\n try {\n api.post(p)\n db.markSent(p.id)\n } catch (_: Exception) {\n // keep pending; retry later with backoff in a WorkManager job\n }\n }\n }\n}\n```\n\nTesting guidance:\n- Unit test Repo with fake Api/LocalStore.\n- Integration test offline queue + retry policy (WorkManager).\n\n\nChecks: input validation, tests, and safe defaults included.", "source": "WithinUsAI/GOD_Coder_100k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Optimize while preserving behavior.\n\nFile: cx78p7thzltt.py\n```python\ndef w9p71mx(xs):\n out = []\n for x in xs:\n if x not in out:\n out.append(x)\n return out\n```\n\nRequirements: preserve first-seen order; O(n) average; add types + docstring.\n\n# cx78p7thzltt.py\nfrom __future__ import annotations\nfrom typing import Iterable, List, Set, TypeVar\n\nT = TypeVar(\"T\")\n\ndef w9p71mx(xs: Iterable[T]) -> List[T]:\n \"\"\"Return unique items preserving first-seen order.\"\"\"\n seen: Set[T] = set()\n out: List[T] = []\n for x in xs:\n if x in seen:\n continue\n seen.add(x)\n out.append(x)\n return out", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Write pytest tests for `f96221`.\n\n```python\ndef f96221(a: int, b: int) -> int:\n return a*a + b*b\n```\nInclude edge cases and a property-style check.\n\n```python\nimport random\nfrom m56603 import f96221\n\ndef test_known():\n assert f96221(3,4) == 25\n\ndef test_zero():\n assert f96221(0,0) == 0\n\ndef test_property_nonnegative():\n for _ in range(200):\n a=random.randint(-50,50)\n b=random.randint(-50,50)\n assert f96221(a,b) >= 0\n```", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Produce an offline-first self-evolving code assistant architecture named `bwrb30xnb`.\nMust include: module layout, patch-safety policy, evaluation gates (tests/lint/types), versioned memory index.\n\nArchitecture: `bwrb30xnb` (offline-first, self-evolving)\n\nModules\n- core/loop.py: evolve → validate → accept/reject (bounded iterations)\n- patching/: diff builder, safe apply, atomic writes, rollback points\n- policy/: allowlist paths, deny globs (.git/, __pycache__/, binaries), patch size caps\n- signals/: parse pytest/ruff/mypy into normalized findings\n- memory/index.jsonl: append-only snapshots (hashes, metrics, rationale)\n\nSafety gates\n- refuse path traversal/symlink escapes; never edit binaries\n- accept only if tests/lint/types stay green or improve", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: System domain: developer platform\nStack: Airflow, dbt, DuckDB, MinIO, pytest\nCross-layer incident: timezone bug in reporting\nTask type: full_stack_bug_fix\nDifficulty: hard\n\nSolve this as a complete-project engineer.\nOutput must include:\n- root cause across layers\n- final implementation patch\n- tests touching at least two layers\n- deployment or observability note\n- verification commands\n\nRepository sketch:\nrepo/\n src/main.cpp\n src/service.cpp\n include/service.h\n tests/test_service.cpp\n CMakeLists.txt\n\nFocus: Focus on multi-layer debugging across frontend, backend, database, CI, caching, and deployment.\n\nassistant: Diagnosis:\n- Root cause: timezone bug in reporting crosses service boundaries, so the fix must align code, contracts, tests, and deployment behavior.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```cpp\n#include \n#include \n\nusing Payload = std::unordered_map;\n\nPayload normalize_payload(const Payload& in) {\n Payload out;\n for (const auto& [k, v] : in) {\n if (!v.empty()) out[k] = v;\n }\n return out;\n}\n```\n\nTests:\n```cpp\nTEST_CASE(\"normalize_payload filters empty values\") {\n Payload in{{\"id\",\"7\"},{\"name\",\"\"}};\n auto out = normalize_payload(in);\n REQUIRE(out.count(\"id\") == 1);\n REQUIRE(out.count(\"name\") == 0);\n}\n```\n\nVerification:\n- `cmake --build build`\n- `ctest --test-dir build`\n\nEngineering notes:\n- Language: C++\n- Framework/tooling: Boost\n- Stack context: Airflow, dbt, DuckDB, MinIO, pytest\n- Domain: developer platform\n- Task type: full_stack_bug_fix\n- Difficulty: hard\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "Optimize while preserving behavior and order.\n\n```python\ndef f43998(xs):\n out=[]\n for x in xs:\n if x not in out: out.append(x)\n return out\n```\nReturn `m77714.py` with types and O(n) average.\n\n```python\n# m77714.py\nfrom __future__ import annotations\nfrom typing import Iterable, List, Set, TypeVar\nT=TypeVar(\"T\")\n\ndef f43998(xs: Iterable[T]) -> List[T]:\n \"\"\"Unique items preserving first-seen order.\"\"\"\n seen: Set[T]=set()\n out: List[T]=[]\n for x in xs:\n if x in seen: continue\n seen.add(x); out.append(x)\n return out\n```", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: Project stack: Go, Gin, PostgreSQL, gRPC, Prometheus, Docker\nLanguage: Rust\nDependency challenge: race condition on worker shutdown\nTask type: migration_patch\nDifficulty: medium\n\nFix this as a senior engineer.\nRequired:\n- identify the version or compatibility failure mode\n- produce the corrected config/code/build patch\n- explain rollback-safe migration notes\n- add regression tests or reproducibility checks\n- include concrete verification commands\n\nRepository sketch:\nrepo/\n src/main.rs\n src/lib.rs\n src/service.rs\n src/store.rs\n tests/integration.rs\n Cargo.toml\n\nFocus: Focus on versioning, migrations, lockfiles, runtime compatibility, and secure dependency handling.\n\nassistant: Diagnosis:\n- Root cause: the issue around race condition on worker shutdown is a dependency, migration, or runtime-compatibility mismatch that needs a rollback-safe patch.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```rust\nuse std::collections::HashMap;\n\npub fn normalize_payload(payload: HashMap) -> HashMap {\n payload\n .into_iter()\n .filter(|(_, v)| !v.trim().is_empty())\n .collect()\n}\n```\n\nTests:\n```rust\n#[test]\nfn normalize_payload_filters_empty_values() {\n use std::collections::HashMap;\n let mut payload = HashMap::new();\n payload.insert(\"id\".to_string(), \"7\".to_string());\n payload.insert(\"name\".to_string(), \"\".to_string());\n let out = normalize_payload(payload);\n assert!(out.contains_key(\"id\"));\n assert!(!out.contains_key(\"name\"));\n}\n```\n\nVerification:\n- `cargo test`\n- `cargo clippy -- -D warnings`\n\nEngineering notes:\n- Language: Rust\n- Framework/tooling: Serde\n- Stack context: Go, Gin, PostgreSQL, gRPC, Prometheus, Docker\n- Domain: job scheduler\n- Task type: migration_patch\n- Difficulty: medium\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Fix a bug and add tests.\n\nFile: zpwypx.py\n```python\ndef idwmt8spyh(n: int) -> int:\n \"\"\"Sum 1..n inclusive.\"\"\"\n if n < 0:\n raise ValueError(\"n must be non-negative\")\n total = 0\n for k in range(n): # BUG: should include n\n total += k\n return total\n```\n\nReturn unified diffs for zpwypx.py and test_zpwypx.py (pytest).\n\n*** Begin Patch\n*** Update File: zpwypx.py\n@@\n def idwmt8spyh(n: int) -> int:\n@@\n total = 0\n- for k in range(n): # BUG: should include n\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_zpwypx.py\n+import pytest\n+from zpwypx import idwmt8spyh\n+\n+def test_zero():\n+ assert idwmt8spyh(0) == 0\n+\n+def test_one():\n+ assert idwmt8spyh(1) == 1\n+\n+def test_small():\n+ assert idwmt8spyh(7) == 28\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ idwmt8spyh(-1)\n+\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Optimize while preserving behavior and order.\n\n```python\ndef f66051(xs):\n out=[]\n for x in xs:\n if x not in out: out.append(x)\n return out\n```\nReturn `m52293.py` with types and O(n) average.\n\n```python\n# m52293.py\nfrom __future__ import annotations\nfrom typing import Iterable, List, Set, TypeVar\nT=TypeVar(\"T\")\n\ndef f66051(xs: Iterable[T]) -> List[T]:\n \"\"\"Unique items preserving first-seen order.\"\"\"\n seen: Set[T]=set()\n out: List[T]=[]\n for x in xs:\n if x in seen: continue\n seen.add(x); out.append(x)\n return out\n```", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Build an elite-grade solution in the domain of high-performance services for scenario: event ingestion.\nPrimary language: python.\nDifficulty: medium.\nConstraints: provide rollout and rollback guidance, document performance characteristics, design for backward compatibility and migrations.\nComponent: component_ybxrxuq.\nAssume schema changes every sprint; must be backward compatible.\nTask: Provide threat model, secure-by-default design, and defensive implementation patterns. No offensive/exploit content; focus on prevention and detection.\n\nOutput: production blueprint plus correctness arguments and test strategy.\nOutput: threat model + defensive design + detection.\n\n**Threat model**\n- Auth: token theft → short-lived tokens, rotation, audience checks\n- AuthZ: privilege escalation → centralized policy checks, tenant isolation tests\n- Input: injection → strict validation, parameterized queries, output encoding\n- Supply chain: dependencies → lockfiles, signature verification, SBOM\n\n**Defensive patterns**\n- Idempotency keys for side effects; replay-safe handlers\n- Secrets in managed store; never logs\n- Audit logging for sensitive ops; tamper-evident storage\n\n**Detection**\n- Alert on unusual auth failures, access pattern anomalies, and data exfil signals.\n\n\nChecks: boundary validation and deterministic behavior verified.", "source": "WithinUsAI/Elite_GOD_Coder_100k"} {"text": "Build an elite-grade solution in the domain of databases for scenario: job scheduler.\nPrimary language: rust.\nDifficulty: medium.\nConstraints: document performance characteristics, provide rollout and rollback guidance, avoid undefined behavior and data races, include tests or verification strategy.\nComponent: component_pfykdwl.\nAssume schema changes every sprint; must be backward compatible.\nTask: Optimize a hot path with profiling-driven approach; propose micro/meso optimizations, and supply a benchmark harness with acceptance thresholds.\n\nOutput: production blueprint plus correctness arguments and test strategy.\nOutput: profiling-first optimization + benchmark harness.\n\n**Plan**\n1. Establish baseline with microbench + representative dataset.\n2. Profile (CPU, allocations, syscalls).\n3. Apply optimizations: reduce allocations, reuse buffers, batch I/O, vectorize parsing where safe.\n4. Validate with regression suite and perf thresholds.\n\n**Benchmark guidance**\n- Use p50/p95 and throughput; pin CPU frequency if possible.\n- Acceptance: p95 improves ≥ X% with no correctness regressions.\n\n\nChecks: boundary validation and deterministic behavior verified.", "source": "WithinUsAI/Elite_GOD_Coder_100k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Refactor to modern typed Python with immutability and tests.\n\nFile: z4sbmb5.py\n```python\nclass Yca8Hxnz0Y:\n def __init__(self, name, values):\n self.name = name\n self.values = list(values)\n def add(self, v):\n self.values.append(v)\n def mean(self):\n s = 0\n for x in self.values:\n s += x\n return s / len(self.values)\n```\n\nReturn full new z4sbmb5.py and test_z4sbmb5.py.\n\n# z4sbmb5.py\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom typing import Iterable, Tuple\n\n@dataclass(frozen=True)\nclass Yca8Hxnz0Y:\n name: str\n values: Tuple[float, ...]\n\n @staticmethod\n def create(name: str, values: Iterable[float]) -> \"Yca8Hxnz0Y\":\n vals = tuple(float(v) for v in values)\n if not vals:\n raise ValueError(\"values must be non-empty\")\n return Yca8Hxnz0Y(name=name, values=vals)\n\n def add(self, v: float) -> \"Yca8Hxnz0Y\":\n return Yca8Hxnz0Y(name=self.name, values=self.values + (float(v),))\n\n def mean(self) -> float:\n return sum(self.values) / len(self.values)\n\n# test_z4sbmb5.py\nimport pytest\nfrom z4sbmb5 import Yca8Hxnz0Y\n\ndef test_mean_and_add():\n c = Yca8Hxnz0Y.create(\"a\", [1, 2, 3])\n assert c.mean() == 2.0\n assert c.add(5).mean() == (1 + 2 + 3 + 5) / 4\n\ndef test_empty_raises():\n with pytest.raises(ValueError):\n Yca8Hxnz0Y.create(\"x\", [])", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Task type: network_protocol\nScenario: streaming ETL\nDomain focus: static analysis\nPrimary language: rust\nDifficulty: hard\nScale/SLO: multi-region active-active\nComponent: component_klhrkven\nConstraints: avoid data races and undefined behavior, include performance model and limits, include backward compatibility and migration plan, assume adversarial inputs; validate everything, explicit contracts and invariants\nAssume weekly network partitions.\nDeliverable: Design an application protocol: framing, retries, backpressure, timeouts; include client/server skeleton and test vectors.\n\nOutput: contract-first solution with failure modes, security posture, and test/verification strategy.\n**Contract**\n- Inputs validated at the boundary; explicit error taxonomy.\n- Idempotency for side effects via request_id; deterministic replay.\n- Backward compatibility: additive changes by default; versioned breaking changes.\n**Invariants**\n- Determinism: replay of the same event log yields identical outputs.\n- Liveness: under bounded faults and stable network, progress occurs.\n- Safety: state transitions preserve invariants; no partial commit leaks.\n**Failure modes & recovery**\n- Duplicate requests: de-duplicate by (tenant, request_id) returning cached response.\n- Network partition: minority cannot commit; clients receive retriable errors.\n- Crash during commit: WAL replay completes or transaction aborts; no torn writes.\n**Security posture (defensive)**\n- Threat model: auth/authz, injection, replay/abuse, supply chain.\n- Least privilege; secrets in managed store; audit logs for sensitive ops.\n- Input normalization, parameterized queries, path traversal protections.\n**Verification strategy**\n- Canary + shadow traffic; invariants checked in production via assertions/metrics.\n- Deterministic simulation with fault injection (crash/partition/latency).\n- Property tests against a pure reference model (state machine).\n\n**Snippet**\n```text\nImplementation sketch: factor pure state-machine core; adapters for I/O; add deterministic replay log.\n```\nHard checks: fault injection tests gate merges; perf thresholds enforced in CI.", "source": "WithinUsAI/Omega_Genesis_Coder_100k"} {"text": "Optimize while preserving behavior and order.\n\n```python\ndef f36875(xs):\n out=[]\n for x in xs:\n if x not in out: out.append(x)\n return out\n```\nReturn `m48125.py` with types and O(n) average.\n\n```python\n# m48125.py\nfrom __future__ import annotations\nfrom typing import Iterable, List, Set, TypeVar\nT=TypeVar(\"T\")\n\ndef f36875(xs: Iterable[T]) -> List[T]:\n \"\"\"Unique items preserving first-seen order.\"\"\"\n seen: Set[T]=set()\n out: List[T]=[]\n for x in xs:\n if x in seen: continue\n seen.add(x); out.append(x)\n return out\n```", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Add a clear docstring and type hints to this function:\n\n```python\ndef f27662(s):\n return ''.join(x for x in s if x.isalnum()).lower()\n```\n\n```python\nfrom __future__ import annotations\n\ndef f27662(s: str) -> str:\n \"\"\"Normalize a string: keep only alphanumerics and lowercase the result.\"\"\"\n return \"\".join(ch for ch in s if ch.isalnum()).lower()\n```", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: Project stack: Rust, Axum, SQLx, Redis, Tokio, Docker\nLanguage: Python\nDependency challenge: timezone bug in reporting\nTask type: migration_patch\nDifficulty: hard\n\nFix this as a senior engineer.\nRequired:\n- identify the version or compatibility failure mode\n- produce the corrected config/code/build patch\n- explain rollback-safe migration notes\n- add regression tests or reproducibility checks\n- include concrete verification commands\n\nRepository sketch:\nrepo/\n app/\n api.py\n service.py\n models.py\n tests/\n test_api.py\n pyproject.toml\n\nFocus: Focus on versioning, migrations, lockfiles, runtime compatibility, and secure dependency handling.\n\nassistant: Diagnosis:\n- Root cause: the issue around timezone bug in reporting is a dependency, migration, or runtime-compatibility mismatch that needs a rollback-safe patch.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```python\nfrom __future__ import annotations\n\nfrom dataclasses import dataclass\nfrom typing import Any\n\n@dataclass\nclass ServiceResult:\n ok: bool\n data: dict[str, Any]\n error: str | None = None\n\ndef normalize_payload(payload: dict[str, Any]) -> dict[str, Any]:\n if not isinstance(payload, dict):\n raise TypeError(\"payload must be a dict\")\n clean: dict[str, Any] = {}\n for key, value in payload.items():\n if value is None:\n continue\n clean[str(key).strip()] = value\n return clean\n\ndef handle_timezone_bug_in_reporting(payload: dict[str, Any]) -> ServiceResult:\n clean = normalize_payload(payload)\n if \"id\" not in clean:\n return ServiceResult(ok=False, data={}, error=\"missing id\")\n return ServiceResult(ok=True, data=clean)\n```\n\nTests:\n```python\nimport pytest\nfrom app.service import handle_jwt_refresh_token_rotation as handler\n\ndef test_handler_accepts_valid_payload():\n result = handler({\"id\": 7, \"name\": \"ok\", \"unused\": None})\n assert result.ok is True\n assert result.data == {\"id\": 7, \"name\": \"ok\"}\n\ndef test_handler_rejects_missing_id():\n result = handler({\"name\": \"x\"})\n assert result.ok is False\n assert result.error == \"missing id\"\n```\n\nVerification:\n- `pytest -q`\n- `ruff check .`\n- `python -m compileall .`\n\nEngineering notes:\n- Language: Python\n- Framework/tooling: Celery\n- Stack context: Rust, Axum, SQLx, Redis, Tokio, Docker\n- Domain: model serving gateway\n- Task type: migration_patch\n- Difficulty: hard\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Produce an offline-first self-evolving code assistant architecture named `jm_f3fu`.\nMust include: module layout, patch-safety policy, evaluation gates (tests/lint/types), versioned memory index.\n\nArchitecture: `jm_f3fu` (offline-first, self-evolving)\n\nModules\n- core/loop.py: evolve → validate → accept/reject (bounded iterations)\n- patching/: diff builder, safe apply, atomic writes, rollback points\n- policy/: allowlist paths, deny globs (.git/, __pycache__/, binaries), patch size caps\n- signals/: parse pytest/ruff/mypy into normalized findings\n- memory/index.jsonl: append-only snapshots (hashes, metrics, rationale)\n\nSafety gates\n- refuse path traversal/symlink escapes; never edit binaries\n- accept only if tests/lint/types stay green or improve", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Fix the bug and add pytest tests.\n\n```python\ndef f74763(n: int) -> int:\n # sum 1..n inclusive\n if n < 0: raise ValueError\n total = 0\n for k in range(n): # BUG\n total += k\n return total\n```\nReturn unified diffs for `m82109.py` and `test_m82109.py`.\n\n*** Begin Patch\n*** Update File: m82109.py\n@@\n def f74763(n: int) -> int:\n@@\n- for k in range(n): # BUG\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_m82109.py\n+import pytest\n+from m82109 import f74763\n+\n+def test_small():\n+ assert f74763(7) == 28\n+\n+def test_zero():\n+ assert f74763(0) == 0\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ f74763(-1)\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Create a comprehensive test plan and automated tests for background jobs in a calendar/scheduling product.\nTarget platform: mobile (iOS Swift).\nRequirements: unit/integration tests, edge cases, load tests strategy, and CI gates.\nConstraints: must avoid global state, must be production-ready, must include type hints where applicable, must be performant under load, must be secure-by-default.\nDifficulty: medium. Assume untrusted input; validate everything.\n\nOutput: production-oriented blueprint with code where appropriate.\nDeliverable: test plan + automation guidance.\n\n**Unit tests**\n- Validation: malformed payloads rejected with correct codes.\n- AuthZ: tenant boundary enforced.\n- Idempotency: replay returns same response; conflicting reuse yields 409.\n\n**Integration tests**\n- DB transaction behavior; unique constraints.\n- Cache behavior: correctness under concurrent requests.\n\n**Load tests**\n- 10k RPS target: measure p95 latency, error rate, saturation.\n\n**CI gates**\n- Lint + typecheck + unit tests required.\n- Coverage threshold for critical modules.\n- Block merge on flaky test detection.\n\n\nChecks: input validation, tests, and safe defaults included.", "source": "WithinUsAI/GOD_Coder_100k"} {"text": "Refactor an existing codebase in customer support to support background jobs cleanly.\nTarget platform: backend (Python FastAPI).\nRequirements: propose new modules/layers, dependency boundaries, and migration plan.\nConstraints: must include tests, must include type hints where applicable, must be secure-by-default.\nDifficulty: hard. Assume mobile clients are occasionally offline.\n\nOutput: design + implementation guidance suitable for shipping.\nDeliverable: refactor plan + module boundaries.\n\n**Proposed modules**\n- `domain/` pure business logic (no I/O)\n- `adapters/` DB, cache, external APIs\n- `api/` request/response validation and routing\n- `observability/` logging/metrics/tracing\n- `tests/` unit + integration suites\n\n**Migration plan**\n1. Introduce new interfaces + adapters behind feature flags.\n2. Dual-write or read-compat layer if schema changes.\n3. Incremental cutover; deprecate legacy module.\n\nKey rule: dependencies flow inward; domain has no framework imports.\n\n\nHard-mode checks: concurrency safety, idempotency, and rollback validated; add chaos tests where feasible.", "source": "WithinUsAI/GOD_Coder_100k"} {"text": "Implement event-driven workflows for a e-commerce product.\nTarget platform: backend (Go).\nRequirements: provide production-ready code, configuration, and tests.\nConstraints: must be performant under load, must be easy to extend, must be secure-by-default.\nDifficulty: medium. Assume 10k RPS peak traffic.\n\nOutput: production-oriented blueprint with code where appropriate.\nDeliverable: production-grade reference implementation (FastAPI) + tests.\n\n```python\n# app.py\nfrom __future__ import annotations\n\nimport hashlib\nimport json\nfrom dataclasses import dataclass\nfrom datetime import datetime, timezone\nfrom typing import Any, Optional\n\nfrom fastapi import FastAPI, Header, HTTPException\nfrom pydantic import BaseModel, Field\n\napp = FastAPI(title=\"Idempotent API\")\n\nclass CreateReq(BaseModel):\n tenant_id: str = Field(min_length=1)\n amount_cents: int = Field(ge=0)\n currency: str = Field(min_length=3, max_length=3)\n\nclass CreateResp(BaseModel):\n id: str\n created_at: str\n echo: CreateReq\n\n@dataclass\nclass _IdempoEntry:\n request_hash: str\n response_json: str\n\n# In production: Postgres table with UNIQUE(tenant_id, key)\n_IDEMPO: dict[tuple[str, str], _IdempoEntry] = {}\n\ndef _hash_req(req: CreateReq) -> str:\n raw = req.model_dump_json()\n return hashlib.sha256(raw.encode(\"utf-8\")).hexdigest()\n\n@app.post(\"/v1/payments\", response_model=CreateResp)\ndef create_payment(\n req: CreateReq,\n idempotency_key: Optional[str] = Header(default=None, alias=\"Idempotency-Key\"),\n) -> Any:\n if not idempotency_key:\n raise HTTPException(status_code=400, detail=\"Missing Idempotency-Key\")\n if len(idempotency_key) > 128:\n raise HTTPException(status_code=400, detail=\"Idempotency-Key too long\")\n\n key = (req.tenant_id, idempotency_key)\n rh = _hash_req(req)\n\n existing = _IDEMPO.get(key)\n if existing:\n if existing.request_hash != rh:\n raise HTTPException(status_code=409, detail=\"Idempotency-Key reuse with different payload\")\n return json.loads(existing.response_json)\n\n # Create new payment (stubbed)\n pid = hashlib.md5(f\"{req.tenant_id}:{idempotency_key}\".encode()).hexdigest()\n resp = CreateResp(\n id=pid,\n created_at=datetime.now(timezone.utc).isoformat(),\n echo=req,\n )\n _IDEMPO[key] = _IdempoEntry(request_hash=rh, response_json=resp.model_dump_json())\n return resp\n```\n\n```python\n# test_app.py (pytest)\nfrom fastapi.testclient import TestClient\nfrom app import app\n\nclient = TestClient(app)\n\ndef test_idempotent_replay():\n headers = {\"Idempotency-Key\": \"abc\"}\n body = {\"tenant_id\":\"t1\",\"amount_cents\":100,\"currency\":\"USD\"}\n r1 = client.post(\"/v1/payments\", json=body, headers=headers)\n r2 = client.post(\"/v1/payments\", json=body, headers=headers)\n assert r1.status_code == 200 and r2.status_code == 200\n assert r1.json() == r2.json()\n\ndef test_payload_conflict():\n headers = {\"Idempotency-Key\": \"abc\"}\n b1 = {\"tenant_id\":\"t1\",\"amount_cents\":100,\"currency\":\"USD\"}\n b2 = {\"tenant_id\":\"t1\",\"amount_cents\":200,\"currency\":\"USD\"}\n assert client.post(\"/v1/payments\", json=b1, headers=headers).status_code == 200\n assert client.post(\"/v1/payments\", json=b2, headers=headers).status_code == 409\n```\n\nNotes:\n- Replace in-memory store with a DB table and transaction.\n- Store response + request hash to detect key reuse with different payload.\n\n\nChecks: input validation, tests, and safe defaults included.", "source": "WithinUsAI/GOD_Coder_100k"} {"text": "Write a thorough test suite for a Python component used for caching layer.\nRequirements: cover edge cases, invalid inputs, and behavior invariants.\nConstraints: stdlib-only, must provide clear error messages.\nDifficulty: expert. Ensure the API is testable via dependency injection.\n\nDeliverable: implementation + tests.\n```python\n# tests (pytest-style) for a module providing: normalize(), parse_lines(), compute_stats()\nimport math\nimport pytest\n\ndef test_normalize_idempotent(module_under_test):\n x = \" A\\tB \"\n assert module_under_test.normalize(module_under_test.normalize(x)) == module_under_test.normalize(x)\n\ndef test_parse_lines_rejects_invalid(module_under_test):\n with pytest.raises(ValueError):\n module_under_test.parse_lines([\"\", \"???\", None]) # type: ignore[arg-type]\n\ndef test_compute_stats_basic(module_under_test):\n data = [1, 2, 3, 4]\n s = module_under_test.compute_stats(data)\n assert s.count == 4\n assert s.total == 10\n assert math.isclose(s.mean, 2.5)\n```", "source": "WithinUsAI/python_GOD_coder_100k"} {"text": "Add observability for caching in a social media system.\nTarget platform: mobile (Android Kotlin).\nRequirements: structured logs, metrics, tracing, dashboards, and alerting rules.\nConstraints: must be secure-by-default, must include type hints where applicable, must avoid global state, must include documentation/comments.\nDifficulty: easy. Assume strict latency budget (p95 < 200ms).\n\nOutput: engineering-grade answer with edge cases covered.\nDeliverable: observability plan + example instrumentation.\n\n**Logs**\n- JSON logs with: request_id, tenant_id, route, status, latency_ms, error_code.\n\n**Metrics**\n- Counters: requests_total{route,status}, errors_total{code}\n- Histograms: request_latency_ms{route}\n- Gauges: queue_depth, db_pool_in_use\n\n**Tracing**\n- Trace ID propagated via headers; spans around DB, cache, external calls.\n\n**Alerts**\n- p95 latency breach, error rate spike, saturation (CPU/mem), queue backlog.\n\nExample (Python structured logging pseudo):\n```python\nlog.info(\"request_done\", extra={\"route\": route, \"status\": status, \"latency_ms\": ms, \"request_id\": rid})\n```\n\n\nChecks: input validation, tests, and safe defaults included.", "source": "WithinUsAI/GOD_Coder_100k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Optimize while preserving behavior.\n\nFile: p1t9o5t2blm.py\n```python\ndef uji6gjdnjx6(xs):\n out = []\n for x in xs:\n if x not in out:\n out.append(x)\n return out\n```\n\nRequirements: preserve first-seen order; O(n) average; add types + docstring.\n\n# p1t9o5t2blm.py\nfrom __future__ import annotations\nfrom typing import Iterable, List, Set, TypeVar\n\nT = TypeVar(\"T\")\n\ndef uji6gjdnjx6(xs: Iterable[T]) -> List[T]:\n \"\"\"Return unique items preserving first-seen order.\"\"\"\n seen: Set[T] = set()\n out: List[T] = []\n for x in xs:\n if x in seen:\n continue\n seen.add(x)\n out.append(x)\n return out", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Build an elite-grade solution in the domain of sre/observability for scenario: inventory & ordering.\nPrimary language: python.\nDifficulty: medium.\nConstraints: avoid undefined behavior and data races, assume untrusted inputs; validate and sanitize, include tests or verification strategy.\nComponent: component_lvjmnlg.\nAssume compliance requires data deletion with proofs.\nTask: Provide threat model, secure-by-default design, and defensive implementation patterns. No offensive/exploit content; focus on prevention and detection.\n\nOutput: production blueprint plus correctness arguments and test strategy.\nOutput: threat model + defensive design + detection.\n\n**Threat model**\n- Auth: token theft → short-lived tokens, rotation, audience checks\n- AuthZ: privilege escalation → centralized policy checks, tenant isolation tests\n- Input: injection → strict validation, parameterized queries, output encoding\n- Supply chain: dependencies → lockfiles, signature verification, SBOM\n\n**Defensive patterns**\n- Idempotency keys for side effects; replay-safe handlers\n- Secrets in managed store; never logs\n- Audit logging for sensitive ops; tamper-evident storage\n\n**Detection**\n- Alert on unusual auth failures, access pattern anomalies, and data exfil signals.\n\n\nChecks: boundary validation and deterministic behavior verified.", "source": "WithinUsAI/Elite_GOD_Coder_100k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Fix a bug and add tests.\n\nFile: qzvvr35ew.py\n```python\ndef xaa47p(n: int) -> int:\n \"\"\"Sum 1..n inclusive.\"\"\"\n if n < 0:\n raise ValueError(\"n must be non-negative\")\n total = 0\n for k in range(n): # BUG: should include n\n total += k\n return total\n```\n\nReturn unified diffs for qzvvr35ew.py and test_qzvvr35ew.py (pytest).\n\n*** Begin Patch\n*** Update File: qzvvr35ew.py\n@@\n def xaa47p(n: int) -> int:\n@@\n total = 0\n- for k in range(n): # BUG: should include n\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_qzvvr35ew.py\n+import pytest\n+from qzvvr35ew import xaa47p\n+\n+def test_zero():\n+ assert xaa47p(0) == 0\n+\n+def test_one():\n+ assert xaa47p(1) == 1\n+\n+def test_small():\n+ assert xaa47p(7) == 28\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ xaa47p(-1)\n+\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Build an elite-grade solution in the domain of high-performance services for scenario: event ingestion.\nPrimary language: rust.\nDifficulty: hard.\nConstraints: include tests or verification strategy, design for backward compatibility and migrations, assume untrusted inputs; validate and sanitize, include invariants and failure modes.\nComponent: component_solvlko.\nAssume cold-start and memory limits are tight.\nTask: Write a precise interface contract, list invariants, and provide a lightweight formal/spec-style description (pseudo-TLA+/state machine) plus reference implementation skeleton and tests.\n\nOutput: elite-grade engineering answer with contracts, edge cases, and verification.\nOutput: contract + invariants + spec + reference skeleton.\n\n**Interface contract**\n- Commands: `Put(key, value, expected_version?)`, `Get(key)`, `Delete(key, expected_version?)`\n- Responses: `Ok(version, value?)`, `NotFound`, `Conflict(current_version)`, `InvalidInput`\n- Idempotency: client supplies `request_id`; server must de-duplicate per (tenant_id, request_id).\n\n**Invariants**\n1. Monotonic version per key (strictly increases on successful writes).\n2. Reads return latest committed value for a given consistency level.\n3. Exactly-once effect for a given `request_id` (at-most-once execution + replay response).\n4. Tenant isolation: keys are scoped by tenant_id.\n\n**State machine (pseudo)**\nState:\n- store: map[(tenant,key)] -> (version:int, value:bytes|tombstone)\n- seen: map[(tenant,request_id)] -> response\nTransition Put:\n- if request_id in seen: return seen[...]\n- validate input; if expected_version set and != current version -> Conflict\n- version' = version + 1; store[...] := (version', value); seen[...] := Ok(version', value)\n\n**Reference skeleton (Python)**\n```python\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom typing import Dict, Optional, Tuple\n\nclass Conflict(Exception): pass\nclass InvalidInput(ValueError): pass\n\n@dataclass(frozen=True, slots=True)\nclass Value:\n version: int\n data: Optional[bytes] # None == tombstone\n\n@dataclass(frozen=True, slots=True)\nclass Reply:\n kind: str\n version: Optional[int] = None\n data: Optional[bytes] = None\n\nclass KV:\n def __init__(self) -> None:\n self._store: Dict[Tuple[str,str], Value] = {}\n self._seen: Dict[Tuple[str,str], Reply] = {}\n\n def put(self, tenant: str, request_id: str, key: str, data: bytes, expected_version: Optional[int]=None) -> Reply:\n if not tenant or not request_id or not key:\n raise InvalidInput(\"tenant/request_id/key required\")\n de = self._seen.get((tenant, request_id))\n if de: \n return de\n cur = self._store.get((tenant, key), Value(0, None))\n if expected_version is not None and expected_version != cur.version:\n r = Reply(\"conflict\", version=cur.version)\n self._seen[(tenant, request_id)] = r\n return r\n nxt = Value(cur.version + 1, data)\n self._store[(tenant, key)] = nxt\n r = Reply(\"ok\", version=nxt.version)\n self._seen[(tenant, request_id)] = r\n return r\n```\n\n**Tests**\n- Determinism: same request_id → same reply.\n- Conflict detection and version monotonicity.\n\n\nHard checks: failure injection tests and performance regressions gated.", "source": "WithinUsAI/Elite_GOD_Coder_100k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Refactor to modern typed Python with immutability and tests.\n\nFile: fm9xlg6c.py\n```python\nclass F9B9Syfewn:\n def __init__(self, name, values):\n self.name = name\n self.values = list(values)\n def add(self, v):\n self.values.append(v)\n def mean(self):\n s = 0\n for x in self.values:\n s += x\n return s / len(self.values)\n```\n\nReturn full new fm9xlg6c.py and test_fm9xlg6c.py.\n\n# fm9xlg6c.py\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom typing import Iterable, Tuple\n\n@dataclass(frozen=True)\nclass F9B9Syfewn:\n name: str\n values: Tuple[float, ...]\n\n @staticmethod\n def create(name: str, values: Iterable[float]) -> \"F9B9Syfewn\":\n vals = tuple(float(v) for v in values)\n if not vals:\n raise ValueError(\"values must be non-empty\")\n return F9B9Syfewn(name=name, values=vals)\n\n def add(self, v: float) -> \"F9B9Syfewn\":\n return F9B9Syfewn(name=self.name, values=self.values + (float(v),))\n\n def mean(self) -> float:\n return sum(self.values) / len(self.values)\n\n# test_fm9xlg6c.py\nimport pytest\nfrom fm9xlg6c import F9B9Syfewn\n\ndef test_mean_and_add():\n c = F9B9Syfewn.create(\"a\", [1, 2, 3])\n assert c.mean() == 2.0\n assert c.add(5).mean() == (1 + 2 + 3 + 5) / 4\n\ndef test_empty_raises():\n with pytest.raises(ValueError):\n F9B9Syfewn.create(\"x\", [])", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Fix the bug and add pytest tests.\n\n```python\ndef f85282(n: int) -> int:\n # sum 1..n inclusive\n if n < 0: raise ValueError\n total = 0\n for k in range(n): # BUG\n total += k\n return total\n```\nReturn unified diffs for `m69326.py` and `test_m69326.py`.\n\n*** Begin Patch\n*** Update File: m69326.py\n@@\n def f85282(n: int) -> int:\n@@\n- for k in range(n): # BUG\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_m69326.py\n+import pytest\n+from m69326 import f85282\n+\n+def test_small():\n+ assert f85282(7) == 28\n+\n+def test_zero():\n+ assert f85282(0) == 0\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ f85282(-1)\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Refactor to typed, mostly-immutable Python and add minimal tests.\n\n```python\nclass C66900:\n def __init__(self, values): self.values=list(values)\n def mean(self): return sum(self.values)/len(self.values)\n```\nReturn `m51300.py` and `test_m51300.py`.\n\n```python\n# m51300.py\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom typing import Iterable, Tuple\n\n@dataclass(frozen=True)\nclass C66900:\n values: Tuple[float, ...]\n\n @staticmethod\n def create(values: Iterable[float]) -> \"C66900\":\n vals = tuple(float(v) for v in values)\n if not vals: raise ValueError(\"empty\")\n return C66900(vals)\n\n def mean(self) -> float:\n return sum(self.values)/len(self.values)\n```\n\n```python\n# test_m51300.py\nimport pytest\nfrom m51300 import C66900\n\ndef test_mean():\n assert C66900.create([1,2,3]).mean() == 2.0\ndef test_empty():\n with pytest.raises(ValueError):\n C66900.create([])\n```", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Task type: compiler_backend_ir\nScenario: document indexing pipeline\nDomain focus: runtime systems\nPrimary language: rust\nDifficulty: expert\nScale/SLO: 50 TB/day ingestion\nComponent: component_toqdmqjl\nConstraints: include deterministic replay plan, include test vectors and fuzz strategy, include verification strategy, explicit contracts and invariants, include performance model and limits, include security threat model (defensive only)\nAssume partial data corruption; include scrubbing strategy.\nDeliverable: Design an IR and lowering pipeline; include an optimization pass and correctness checks. Provide minimal code skeleton and tests.\n\nOutput: contract-first solution with failure modes, security posture, and test/verification strategy.\n**Contract**\n- Inputs validated at the boundary; explicit error taxonomy.\n- Idempotency for side effects via request_id; deterministic replay.\n- Backward compatibility: additive changes by default; versioned breaking changes.\n**Invariants**\n- Determinism: replay of the same event log yields identical outputs.\n- Safety: state transitions preserve invariants; no partial commit leaks.\n- Liveness: under bounded faults and stable network, progress occurs.\n**Failure modes & recovery**\n- Network partition: minority cannot commit; clients receive retriable errors.\n- Crash during commit: WAL replay completes or transaction aborts; no torn writes.\n- Duplicate requests: de-duplicate by (tenant, request_id) returning cached response.\n**Security posture (defensive)**\n- Threat model: auth/authz, injection, replay/abuse, supply chain.\n- Least privilege; secrets in managed store; audit logs for sensitive ops.\n- Input normalization, parameterized queries, path traversal protections.\n**Verification strategy**\n- Fuzzing of parsers/framers/validators with corpus seeds.\n- Canary + shadow traffic; invariants checked in production via assertions/metrics.\n- Deterministic simulation with fault injection (crash/partition/latency).\n\n**Snippet**\n```text\nImplementation sketch: factor pure state-machine core; adapters for I/O; add deterministic replay log.\n```\nExpert checks: state-machine proof sketch + model checking; upgrade/rollback rehearsed.", "source": "WithinUsAI/Omega_Genesis_Coder_100k"} {"text": "Refactor to typed, mostly-immutable Python and add minimal tests.\n\n```python\nclass C41771:\n def __init__(self, values): self.values=list(values)\n def mean(self): return sum(self.values)/len(self.values)\n```\nReturn `m49367.py` and `test_m49367.py`.\n\n```python\n# m49367.py\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom typing import Iterable, Tuple\n\n@dataclass(frozen=True)\nclass C41771:\n values: Tuple[float, ...]\n\n @staticmethod\n def create(values: Iterable[float]) -> \"C41771\":\n vals = tuple(float(v) for v in values)\n if not vals: raise ValueError(\"empty\")\n return C41771(vals)\n\n def mean(self) -> float:\n return sum(self.values)/len(self.values)\n```\n\n```python\n# test_m49367.py\nimport pytest\nfrom m49367 import C41771\n\ndef test_mean():\n assert C41771.create([1,2,3]).mean() == 2.0\ndef test_empty():\n with pytest.raises(ValueError):\n C41771.create([])\n```", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Fix a bug and add tests.\n\nFile: k58p7pacb.py\n```python\ndef c48w6i8ttpu(n: int) -> int:\n \"\"\"Sum 1..n inclusive.\"\"\"\n if n < 0:\n raise ValueError(\"n must be non-negative\")\n total = 0\n for k in range(n): # BUG: should include n\n total += k\n return total\n```\n\nReturn unified diffs for k58p7pacb.py and test_k58p7pacb.py (pytest).\n\n*** Begin Patch\n*** Update File: k58p7pacb.py\n@@\n def c48w6i8ttpu(n: int) -> int:\n@@\n total = 0\n- for k in range(n): # BUG: should include n\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_k58p7pacb.py\n+import pytest\n+from k58p7pacb import c48w6i8ttpu\n+\n+def test_zero():\n+ assert c48w6i8ttpu(0) == 0\n+\n+def test_one():\n+ assert c48w6i8ttpu(1) == 1\n+\n+def test_small():\n+ assert c48w6i8ttpu(7) == 28\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ c48w6i8ttpu(-1)\n+\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: Language: Go\nFramework/tooling: gRPC\nDomain: document processing API\nLogic challenge: dead-letter queue replay\nTask type: distributed_debug\nDifficulty: hard\n\nReturn a rigorous engineering answer:\n- identify the hidden root cause or logical failure\n- present the corrected implementation\n- add tests that prove the fix\n- list verification commands\n- explain why naive fixes are insufficient when relevant\n\nRepository sketch:\nrepo/\n cmd/server/main.go\n internal/service/service.go\n internal/store/store.go\n internal/api/api.go\n service_test.go\n go.mod\n\nFocus: Focus on ambiguity, misleading symptoms, hidden root causes, and high-stakes debugging.\n\nassistant: Diagnosis:\n- Hidden root cause: dead-letter queue replay presents misleading symptoms, so the patch must target the actual logic boundary rather than the first visible failure.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```go\npackage service\n\nimport \"fmt\"\n\nfunc NormalizePayload(payload map[string]any) map[string]any {\n\tout := make(map[string]any)\n\tfor k, v := range payload {\n\t\tif v == nil {\n\t\t\tcontinue\n\t\t}\n\t\tout[k] = v\n\t}\n\treturn out\n}\n\nfunc Handle(payload map[string]any) (map[string]any, error) {\n\tclean := NormalizePayload(payload)\n\tif _, ok := clean[\"id\"]; !ok {\n\t\treturn nil, fmt.Errorf(\"missing id\")\n\t}\n\treturn map[string]any{\"ok\": true, \"data\": clean}, nil\n}\n```\n\nTests:\n```go\npackage service\n\nimport \"testing\"\n\nfunc TestHandle(t *testing.T) {\n\tgot, err := Handle(map[string]any{\"id\": 7, \"name\": \"ok\", \"unused\": nil})\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tif got[\"ok\"] != true {\n\t\tt.Fatalf(\"expected ok=true\")\n\t}\n\tif _, err := Handle(map[string]any{\"name\": \"x\"}); err == nil {\n\t\tt.Fatalf(\"expected missing id error\")\n\t}\n}\n```\n\nVerification:\n- `go test ./...`\n- `go vet ./...`\n\nEngineering notes:\n- Language: Go\n- Framework/tooling: gRPC\n- Stack context: GitHub Actions, Docker Compose, Kubernetes, Terraform\n- Domain: document processing API\n- Task type: distributed_debug\n- Difficulty: hard\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: Repository domain: observability collector\nPrimary language: SQL\nFramework/tooling: MySQL\nReported problem: path traversal on downloads\nTask type: code_review_fix\nDifficulty: hard\n\nProduce a complete professional engineering response:\n1. Diagnose the root cause.\n2. Provide the corrected implementation or patch.\n3. Add tests.\n4. Add verification commands.\n5. Note edge cases and any migration or rollback risk.\n\nRepository sketch:\nrepo/\n migrations/\n 001_init.sql\n 002_add_index.sql\n queries/\n report.sql\n tests/\n report_cases.md\n\nQuality target:\n- Minimal diff unless redesign is clearly required\n- Production-ready code\n- No placeholders\n- Secure defaults\n- Clear acceptance of failure cases\n\nFocus: Focus on complete implementation quality, patch correctness, tests, and production readiness.\n\nassistant: Diagnosis:\n- Root cause: the failure around path traversal on downloads is caused by missing validation, weak edge-case handling, or unsafe lifecycle behavior in the current implementation.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```sql\nWITH ranked AS (\n SELECT\n user_id,\n created_at,\n amount,\n ROW_NUMBER() OVER (PARTITION BY user_id ORDER BY created_at DESC, id DESC) AS rn\n FROM orders\n)\nSELECT user_id, created_at, amount\nFROM ranked\nWHERE rn = 1;\n```\n\nTests:\n```sql\n-- Correctness checks:\n-- 1) multiple rows per user\n-- 2) identical timestamps require deterministic tie-breaker\n-- 3) null values handled by business rules\n```\n\nVerification:\n- `run migration checks`\n- `run query correctness cases`\n\nEngineering notes:\n- Language: SQL\n- Framework/tooling: MySQL\n- Stack context: GitHub Actions, Docker Compose, Kubernetes, Terraform\n- Domain: observability collector\n- Task type: code_review_fix\n- Difficulty: hard\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Fix a bug and add tests.\n\nFile: y__7whiz.py\n```python\ndef kmp_u9(n: int) -> int:\n \"\"\"Sum 1..n inclusive.\"\"\"\n if n < 0:\n raise ValueError(\"n must be non-negative\")\n total = 0\n for k in range(n): # BUG: should include n\n total += k\n return total\n```\n\nReturn unified diffs for y__7whiz.py and test_y__7whiz.py (pytest).\n\n*** Begin Patch\n*** Update File: y__7whiz.py\n@@\n def kmp_u9(n: int) -> int:\n@@\n total = 0\n- for k in range(n): # BUG: should include n\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_y__7whiz.py\n+import pytest\n+from y__7whiz import kmp_u9\n+\n+def test_zero():\n+ assert kmp_u9(0) == 0\n+\n+def test_one():\n+ assert kmp_u9(1) == 1\n+\n+def test_small():\n+ assert kmp_u9(7) == 28\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ kmp_u9(-1)\n+\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Refactor to modern typed Python with immutability and tests.\n\nFile: yzsqjvl.py\n```python\nclass Gxnfqfbyz:\n def __init__(self, name, values):\n self.name = name\n self.values = list(values)\n def add(self, v):\n self.values.append(v)\n def mean(self):\n s = 0\n for x in self.values:\n s += x\n return s / len(self.values)\n```\n\nReturn full new yzsqjvl.py and test_yzsqjvl.py.\n\n# yzsqjvl.py\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom typing import Iterable, Tuple\n\n@dataclass(frozen=True)\nclass Gxnfqfbyz:\n name: str\n values: Tuple[float, ...]\n\n @staticmethod\n def create(name: str, values: Iterable[float]) -> \"Gxnfqfbyz\":\n vals = tuple(float(v) for v in values)\n if not vals:\n raise ValueError(\"values must be non-empty\")\n return Gxnfqfbyz(name=name, values=vals)\n\n def add(self, v: float) -> \"Gxnfqfbyz\":\n return Gxnfqfbyz(name=self.name, values=self.values + (float(v),))\n\n def mean(self) -> float:\n return sum(self.values) / len(self.values)\n\n# test_yzsqjvl.py\nimport pytest\nfrom yzsqjvl import Gxnfqfbyz\n\ndef test_mean_and_add():\n c = Gxnfqfbyz.create(\"a\", [1, 2, 3])\n assert c.mean() == 2.0\n assert c.add(5).mean() == (1 + 2 + 3 + 5) / 4\n\ndef test_empty_raises():\n with pytest.raises(ValueError):\n Gxnfqfbyz.create(\"x\", [])", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: Project domain: job scheduler\nImplementation stack: Go, Gin, PostgreSQL, gRPC, Prometheus, Docker\nSoftware delivery problem: CI failures after dependency upgrade\nTask type: prd_to_patch\nDifficulty: medium\n\nReturn a complete delivery-grade response with:\n- diagnosis or design reasoning\n- implementation\n- test plan or tests\n- rollout plan\n- rollback or compatibility note\n- verification commands\n\nRepository sketch:\nrepo/\n src/\n api.ts\n service.ts\n schema.ts\n tests/\n api.test.ts\n package.json\n\nFocus: Focus on shipping production software with rollout safety, acceptance criteria, telemetry, and maintenance quality.\n\nassistant: Diagnosis:\n- Root cause or delivery blocker: CI failures after dependency upgrade needs both implementation work and a safe shipping plan.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```ts\ntype Payload = Record;\n\nexport function normalizePayload(payload: Payload): Payload {\n if (!payload || typeof payload !== \"object\" || Array.isArray(payload)) {\n throw new TypeError(\"payload must be a plain object\");\n }\n return Object.fromEntries(\n Object.entries(payload)\n .filter(([, value]) => value !== null && value !== undefined)\n .map(([key, value]) => [String(key).trim(), value])\n );\n}\n\nexport function handleCiFailuresAfterDependencyUpgrade(payload: Payload) {\n const clean = normalizePayload(payload);\n if (!(\"id\" in clean)) {\n return { ok: false, data: {}, error: \"missing id\" };\n }\n return { ok: true, data: clean, error: null };\n}\n```\n\nTests:\n```ts\nimport { describe, it, expect } from \"vitest\";\nimport { handleCiFailuresAfterDependencyUpgrade } from \"../src/service\";\n\ndescribe(\"handler\", () => {\n it(\"accepts valid input\", () => {\n expect(handleCiFailuresAfterDependencyUpgrade({ id: 7, name: \"ok\", unused: null })).toEqual({\n ok: true,\n data: { id: 7, name: \"ok\" },\n error: null\n });\n });\n\n it(\"rejects missing id\", () => {\n expect(handleCiFailuresAfterDependencyUpgrade({ name: \"x\" }).error).toMatch(/missing id/);\n });\n});\n```\n\nVerification:\n- `npm test`\n- `npm run typecheck`\n- `npm run lint`\n\nEngineering notes:\n- Language: TypeScript\n- Framework/tooling: Prisma\n- Stack context: Go, Gin, PostgreSQL, gRPC, Prometheus, Docker\n- Domain: job scheduler\n- Task type: prd_to_patch\n- Difficulty: medium\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "Fix the bug and add pytest tests.\n\n```python\ndef f80669(n: int) -> int:\n # sum 1..n inclusive\n if n < 0: raise ValueError\n total = 0\n for k in range(n): # BUG\n total += k\n return total\n```\nReturn unified diffs for `m68667.py` and `test_m68667.py`.\n\n*** Begin Patch\n*** Update File: m68667.py\n@@\n def f80669(n: int) -> int:\n@@\n- for k in range(n): # BUG\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_m68667.py\n+import pytest\n+from m68667 import f80669\n+\n+def test_small():\n+ assert f80669(7) == 28\n+\n+def test_zero():\n+ assert f80669(0) == 0\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ f80669(-1)\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: Language: C#\nFramework/tooling: ASP.NET Core\nDomain: repo automation\nLogic challenge: unsafe deserialization\nTask type: backwards_compatible_redesign\nDifficulty: hard\n\nReturn a rigorous engineering answer:\n- identify the hidden root cause or logical failure\n- present the corrected implementation\n- add tests that prove the fix\n- list verification commands\n- explain why naive fixes are insufficient when relevant\n\nRepository sketch:\nrepo/\n src/App/Program.cs\n src/App/Service.cs\n tests/App.Tests/ServiceTests.cs\n App.sln\n\nFocus: Focus on staff-level problem solving with multi-file patches, rollout implications, performance and security tradeoffs.\n\nassistant: Diagnosis:\n- Staff-level diagnosis: unsafe deserialization impacts correctness, operability, and future maintenance, so the fix must be minimal where possible but complete where necessary.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```csharp\nusing System;\nusing System.Collections.Generic;\n\npublic static class RequestHandler\n{\n public static Dictionary HandleRequest(Dictionary payload)\n {\n var clean = new Dictionary();\n foreach (var entry in payload)\n {\n if (entry.Value != null)\n clean[entry.Key.Trim()] = entry.Value;\n }\n if (!clean.ContainsKey(\"id\"))\n throw new ArgumentException(\"missing id\");\n return new Dictionary\n {\n [\"ok\"] = true,\n [\"data\"] = clean\n };\n }\n}\n```\n\nTests:\n```csharp\nusing System;\nusing System.Collections.Generic;\nusing Xunit;\n\npublic class RequestHandlerTests\n{\n [Fact]\n public void RequiresId()\n {\n Assert.Throws(() => RequestHandler.HandleRequest(new Dictionary { [\"name\"] = \"x\" }));\n }\n}\n```\n\nVerification:\n- `dotnet test`\n- `dotnet build`\n\nEngineering notes:\n- Language: C#\n- Framework/tooling: ASP.NET Core\n- Stack context: GitHub Actions, Docker Compose, Kubernetes, Terraform\n- Domain: repo automation\n- Task type: backwards_compatible_redesign\n- Difficulty: hard\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Optimize while preserving behavior.\n\nFile: b_tuq3z7a7.py\n```python\ndef v4irzhv(xs):\n out = []\n for x in xs:\n if x not in out:\n out.append(x)\n return out\n```\n\nRequirements: preserve first-seen order; O(n) average; add types + docstring.\n\n# b_tuq3z7a7.py\nfrom __future__ import annotations\nfrom typing import Iterable, List, Set, TypeVar\n\nT = TypeVar(\"T\")\n\ndef v4irzhv(xs: Iterable[T]) -> List[T]:\n \"\"\"Return unique items preserving first-seen order.\"\"\"\n seen: Set[T] = set()\n out: List[T] = []\n for x in xs:\n if x in seen:\n continue\n seen.add(x)\n out.append(x)\n return out", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Build an elite-grade solution in the domain of high-performance services for scenario: chat messaging.\nPrimary language: go.\nDifficulty: expert.\nConstraints: assume untrusted inputs; validate and sanitize, include tests or verification strategy, design for backward compatibility and migrations, avoid undefined behavior and data races.\nComponent: component_ezastuu.\nAssume 50k RPS and p99 < 250ms.\nTask: Implement or outline a storage/indexing subsystem (LSM/B-Tree, WAL, snapshots). Include transaction/consistency considerations and benchmark plan.\n\nOutput: rigorous solution with invariants, failure modes, and performance notes.\nOutput: storage design + WAL + compaction + benchmarks.\n\n**Design**\n- WAL (append-only) for durability; fsync policy configurable.\n- Memtable (in-memory) → flush to immutable SSTables.\n- LSM compaction tiers; bloom filters per SSTable for point-lookups.\n- Manifest tracks SSTable set; atomic pointer swap on updates.\n\n**Correctness**\n- Crash recovery: replay WAL to rebuild memtable; manifest ensures last consistent set.\n- Reads: merge memtable + SSTables newest→oldest; tombstones override older values.\n\n**Bench plan**\n- Workloads: write-heavy, read-heavy, mixed; measure p50/p95 latency and write amplification.\n- Track compaction debt and space amplification.\n\n**Test plan**\n- Fuzz crash points: kill after WAL append / after manifest update; verify invariants on restart.\n\n\nExpert checks: state-machine reasoning, concurrency stress, and upgrade/rollback validated.", "source": "WithinUsAI/Elite_GOD_Coder_100k"} {"text": "Write secure, defensive Python code for parsing.\nRequirements: input validation, safe file handling, prevent path traversal, include tests.\nConstraints: must be streaming-friendly, must be easy to extend, must avoid global state, must be memory-efficient.\nDifficulty: easy. Guarantee deterministic output ordering.\n\nDeliverable: corrected code and verification tests.\n```python\nfrom __future__ import annotations\n\nfrom dataclasses import dataclass\nfrom pathlib import Path\nfrom typing import Iterable\nimport json\n\n\nclass ValidationError(ValueError):\n \"\"\"Raised when input validation fails.\"\"\"\n\n\ndef safe_join(base: Path, *parts: str) -> Path:\n \"\"\"Join paths while preventing traversal outside base.\"\"\"\n b = base.resolve()\n p = (b / Path(*parts)).resolve()\n if p != b and b not in p.parents:\n raise ValidationError(f\"unsafe path: {p}\")\n return p\n\n\n@dataclass(frozen=True, slots=True)\nclass Record:\n key: str\n value: int\n\n\ndef parse_jsonl(lines: Iterable[str]) -> list[Record]:\n out: list[Record] = []\n for idx, line in enumerate(lines, 1):\n s = line.strip()\n if not s:\n continue\n try:\n obj = json.loads(s)\n except json.JSONDecodeError as e:\n raise ValidationError(f\"line {idx}: invalid json\") from e\n if not isinstance(obj, dict):\n raise ValidationError(f\"line {idx}: expected object\")\n key = obj.get(\"key\")\n val = obj.get(\"value\")\n if not isinstance(key, str) or not key:\n raise ValidationError(f\"line {idx}: key must be non-empty str\")\n if not isinstance(val, int):\n raise ValidationError(f\"line {idx}: value must be int\")\n out.append(Record(key, val))\n return out\n\n\ndef write_jsonl(base: Path, rel: str, records: Iterable[Record]) -> Path:\n base.mkdir(parents=True, exist_ok=True)\n dst = safe_join(base, rel)\n dst.parent.mkdir(parents=True, exist_ok=True)\n with dst.open(\"w\", encoding=\"utf-8\", newline=\"\\n\") as f:\n for r in records:\n f.write(json.dumps({\"key\": r.key, \"value\": r.value}, ensure_ascii=False) + \"\\n\")\n return dst\n```\n\n```python\n# tests (pytest-style)\nimport json\nfrom pathlib import Path\nimport pytest\nfrom module_under_test import ValidationError, Record, parse_jsonl, write_jsonl\n\ndef test_parse_ok():\n lines = [json.dumps({\"key\":\"a\",\"value\":1}), json.dumps({\"key\":\"b\",\"value\":2})]\n assert parse_jsonl(lines) == [Record(\"a\",1), Record(\"b\",2)]\n\ndef test_parse_rejects_bad_json():\n with pytest.raises(ValidationError):\n parse_jsonl([\"{not json}\"])\n\ndef test_safe_join_blocks_traversal(tmp_path: Path):\n with pytest.raises(ValidationError):\n write_jsonl(tmp_path, \"../x.jsonl\", [Record(\"a\",1)])\n```", "source": "WithinUsAI/python_GOD_coder_100k"} {"text": "Design and implement an algorithm for data modeling.\nRequirements: define inputs/outputs, implement solution with complexity analysis, and include tests.\nConstraints: must provide clear error messages, must be memory-efficient, stdlib-only.\nDifficulty: easy. Support both Windows and POSIX paths correctly.\n\nDeliverable: production-ready reference solution.\nProblem: compute rolling sums over events (ts:int,value:int) with window W seconds. Events may be out-of-order.\n\nComplexity: sorting O(n log n); window maintenance O(n); memory O(k).\n\n```python\nfrom __future__ import annotations\nfrom collections import deque\nfrom dataclasses import dataclass\nfrom typing import Iterable, List, Tuple\n\n@dataclass(frozen=True, slots=True)\nclass Event:\n ts: int\n value: int\n\ndef rolling_sum(events: Iterable[Event], window_s: int) -> List[Tuple[int,int]]:\n if window_s < 0:\n raise ValueError(\"window_s must be >= 0\")\n evs = sorted(events, key=lambda e: e.ts)\n q: deque[Event] = deque()\n s = 0\n out: List[Tuple[int,int]] = []\n for e in evs:\n q.append(e)\n s += e.value\n cutoff = e.ts - window_s\n while q and q[0].ts < cutoff:\n old = q.popleft()\n s -= old.value\n out.append((e.ts, s))\n return out\n```\n\n```python\nimport pytest\nfrom module_under_test import Event, rolling_sum\n\ndef test_rolling_sum():\n ev = [Event(10,1), Event(11,2), Event(20,5)]\n assert rolling_sum(ev, 5) == [(10,1),(11,3),(20,5)]\n```", "source": "WithinUsAI/python_GOD_coder_100k"} {"text": "Add a clear docstring and type hints to this function:\n\n```python\ndef f42724(s):\n return ''.join(x for x in s if x.isalnum()).lower()\n```\n\n```python\nfrom __future__ import annotations\n\ndef f42724(s: str) -> str:\n \"\"\"Normalize a string: keep only alphanumerics and lowercase the result.\"\"\"\n return \"\".join(ch for ch in s if ch.isalnum()).lower()\n```", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Produce an offline-first self-evolving code assistant architecture named `ynmbbu95siyd`.\nMust include: module layout, patch-safety policy, evaluation gates (tests/lint/types), versioned memory index.\n\nArchitecture: `ynmbbu95siyd` (offline-first, self-evolving)\n\nModules\n- core/loop.py: evolve → validate → accept/reject (bounded iterations)\n- patching/: diff builder, safe apply, atomic writes, rollback points\n- policy/: allowlist paths, deny globs (.git/, __pycache__/, binaries), patch size caps\n- signals/: parse pytest/ruff/mypy into normalized findings\n- memory/index.jsonl: append-only snapshots (hashes, metrics, rationale)\n\nSafety gates\n- refuse path traversal/symlink escapes; never edit binaries\n- accept only if tests/lint/types stay green or improve", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: Repository domain: reporting engine\nPrimary language: Python\nFramework/tooling: pandas\nReported problem: partial checkpoint corruption\nTask type: test_repair\nDifficulty: medium\n\nProduce a complete professional engineering response:\n1. Diagnose the root cause.\n2. Provide the corrected implementation or patch.\n3. Add tests.\n4. Add verification commands.\n5. Note edge cases and any migration or rollback risk.\n\nRepository sketch:\nrepo/\n app/\n api.py\n service.py\n models.py\n tests/\n test_api.py\n pyproject.toml\n\nQuality target:\n- Minimal diff unless redesign is clearly required\n- Production-ready code\n- No placeholders\n- Secure defaults\n- Clear acceptance of failure cases\n\nFocus: Focus on complete implementation quality, patch correctness, tests, and production readiness.\n\nassistant: Diagnosis:\n- Root cause: the failure around partial checkpoint corruption is caused by missing validation, weak edge-case handling, or unsafe lifecycle behavior in the current implementation.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```python\nfrom __future__ import annotations\n\nfrom dataclasses import dataclass\nfrom typing import Any\n\n@dataclass\nclass ServiceResult:\n ok: bool\n data: dict[str, Any]\n error: str | None = None\n\ndef normalize_payload(payload: dict[str, Any]) -> dict[str, Any]:\n if not isinstance(payload, dict):\n raise TypeError(\"payload must be a dict\")\n clean: dict[str, Any] = {}\n for key, value in payload.items():\n if value is None:\n continue\n clean[str(key).strip()] = value\n return clean\n\ndef handle_partial_checkpoint_corruption(payload: dict[str, Any]) -> ServiceResult:\n clean = normalize_payload(payload)\n if \"id\" not in clean:\n return ServiceResult(ok=False, data={}, error=\"missing id\")\n return ServiceResult(ok=True, data=clean)\n```\n\nTests:\n```python\nimport pytest\nfrom app.service import handle_jwt_refresh_token_rotation as handler\n\ndef test_handler_accepts_valid_payload():\n result = handler({\"id\": 7, \"name\": \"ok\", \"unused\": None})\n assert result.ok is True\n assert result.data == {\"id\": 7, \"name\": \"ok\"}\n\ndef test_handler_rejects_missing_id():\n result = handler({\"name\": \"x\"})\n assert result.ok is False\n assert result.error == \"missing id\"\n```\n\nVerification:\n- `pytest -q`\n- `ruff check .`\n- `python -m compileall .`\n\nEngineering notes:\n- Language: Python\n- Framework/tooling: pandas\n- Stack context: FastAPI, PostgreSQL, Redis, Celery, pytest, Docker\n- Domain: reporting engine\n- Task type: test_repair\n- Difficulty: medium\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Optimize while preserving behavior.\n\nFile: tnfrhgq7fg.py\n```python\ndef uzx3k_msy(xs):\n out = []\n for x in xs:\n if x not in out:\n out.append(x)\n return out\n```\n\nRequirements: preserve first-seen order; O(n) average; add types + docstring.\n\n# tnfrhgq7fg.py\nfrom __future__ import annotations\nfrom typing import Iterable, List, Set, TypeVar\n\nT = TypeVar(\"T\")\n\ndef uzx3k_msy(xs: Iterable[T]) -> List[T]:\n \"\"\"Return unique items preserving first-seen order.\"\"\"\n seen: Set[T] = set()\n out: List[T] = []\n for x in xs:\n if x in seen:\n continue\n seen.add(x)\n out.append(x)\n return out", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Optimize while preserving behavior and order.\n\n```python\ndef f69366(xs):\n out=[]\n for x in xs:\n if x not in out: out.append(x)\n return out\n```\nReturn `m81338.py` with types and O(n) average.\n\n```python\n# m81338.py\nfrom __future__ import annotations\nfrom typing import Iterable, List, Set, TypeVar\nT=TypeVar(\"T\")\n\ndef f69366(xs: Iterable[T]) -> List[T]:\n \"\"\"Unique items preserving first-seen order.\"\"\"\n seen: Set[T]=set()\n out: List[T]=[]\n for x in xs:\n if x in seen: continue\n seen.add(x); out.append(x)\n return out\n```", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Task type: query_optimizer\nScenario: job scheduler\nDomain focus: real-time scheduling\nPrimary language: python\nDifficulty: hard\nScale/SLO: 99.99% availability\nComponent: component_hnfprxoa\nConstraints: include performance model and limits, include verification strategy, include deterministic replay plan, include failure modes and recovery, assume adversarial inputs; validate everything, include security threat model (defensive only), explicit contracts and invariants\nAssume weekly network partitions.\nDeliverable: Design a cost-based optimizer slice: logical rules, physical operators, and cost model. Include regression tests and query-plan explain examples.\n\nOutput: contract-first solution with failure modes, security posture, and test/verification strategy.\n**Contract**\n- Inputs validated at the boundary; explicit error taxonomy.\n- Idempotency for side effects via request_id; deterministic replay.\n- Backward compatibility: additive changes by default; versioned breaking changes.\n**Invariants**\n- Isolation: tenant boundary enforced; no cross-tenant reads/writes.\n- Safety: state transitions preserve invariants; no partial commit leaks.\n- Determinism: replay of the same event log yields identical outputs.\n**Failure modes & recovery**\n- Data corruption: checksums + scrubber; quarantine and rebuild from replicas/snapshots.\n- Crash during commit: WAL replay completes or transaction aborts; no torn writes.\n- Network partition: minority cannot commit; clients receive retriable errors.\n**Security posture (defensive)**\n- Threat model: auth/authz, injection, replay/abuse, supply chain.\n- Least privilege; secrets in managed store; audit logs for sensitive ops.\n- Input normalization, parameterized queries, path traversal protections.\n**Verification strategy**\n- Canary + shadow traffic; invariants checked in production via assertions/metrics.\n- Fuzzing of parsers/framers/validators with corpus seeds.\n- Property tests against a pure reference model (state machine).\n\n**Snippet**\n```python\n# Minimal cost model skeleton\nfrom dataclasses import dataclass\n\n@dataclass(frozen=True)\nclass Plan:\n op: str\n cost: float\n children: tuple[\"Plan\", ...] = ()\n\ndef choose_best(plans: list[Plan]) -> Plan:\n return min(plans, key=lambda p: p.cost)\n```\n\nHard checks: fault injection tests gate merges; perf thresholds enforced in CI.", "source": "WithinUsAI/Omega_Genesis_Coder_100k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Refactor to modern typed Python with immutability and tests.\n\nFile: suapq1.py\n```python\nclass G8Wo3E:\n def __init__(self, name, values):\n self.name = name\n self.values = list(values)\n def add(self, v):\n self.values.append(v)\n def mean(self):\n s = 0\n for x in self.values:\n s += x\n return s / len(self.values)\n```\n\nReturn full new suapq1.py and test_suapq1.py.\n\n# suapq1.py\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom typing import Iterable, Tuple\n\n@dataclass(frozen=True)\nclass G8Wo3E:\n name: str\n values: Tuple[float, ...]\n\n @staticmethod\n def create(name: str, values: Iterable[float]) -> \"G8Wo3E\":\n vals = tuple(float(v) for v in values)\n if not vals:\n raise ValueError(\"values must be non-empty\")\n return G8Wo3E(name=name, values=vals)\n\n def add(self, v: float) -> \"G8Wo3E\":\n return G8Wo3E(name=self.name, values=self.values + (float(v),))\n\n def mean(self) -> float:\n return sum(self.values) / len(self.values)\n\n# test_suapq1.py\nimport pytest\nfrom suapq1 import G8Wo3E\n\ndef test_mean_and_add():\n c = G8Wo3E.create(\"a\", [1, 2, 3])\n assert c.mean() == 2.0\n assert c.add(5).mean() == (1 + 2 + 3 + 5) / 4\n\ndef test_empty_raises():\n with pytest.raises(ValueError):\n G8Wo3E.create(\"x\", [])", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: Project domain: repo automation\nImplementation stack: Airflow, dbt, DuckDB, MinIO, pytest\nSoftware delivery problem: mismatched API contract\nTask type: prd_to_patch\nDifficulty: medium\n\nReturn a complete delivery-grade response with:\n- diagnosis or design reasoning\n- implementation\n- test plan or tests\n- rollout plan\n- rollback or compatibility note\n- verification commands\n\nRepository sketch:\nrepo/\n src/\n api.js\n service.js\n utils.js\n tests/\n api.test.js\n package.json\n\nFocus: Focus on shipping production software with rollout safety, acceptance criteria, telemetry, and maintenance quality.\n\nassistant: Diagnosis:\n- Root cause or delivery blocker: mismatched API contract needs both implementation work and a safe shipping plan.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```javascript\ntype Payload = Record;\n\nexport function normalizePayload(payload: Payload): Payload {\n if (!payload || typeof payload !== \"object\" || Array.isArray(payload)) {\n throw new TypeError(\"payload must be a plain object\");\n }\n return Object.fromEntries(\n Object.entries(payload)\n .filter(([, value]) => value !== null && value !== undefined)\n .map(([key, value]) => [String(key).trim(), value])\n );\n}\n\nexport function handleMismatchedApiContract(payload: Payload) {\n const clean = normalizePayload(payload);\n if (!(\"id\" in clean)) {\n return { ok: false, data: {}, error: \"missing id\" };\n }\n return { ok: true, data: clean, error: null };\n}\n```\n\nTests:\n```javascript\nimport { describe, it, expect } from \"vitest\";\nimport { handleMismatchedApiContract } from \"../src/service\";\n\ndescribe(\"handler\", () => {\n it(\"accepts valid input\", () => {\n expect(handleMismatchedApiContract({ id: 7, name: \"ok\", unused: null })).toEqual({\n ok: true,\n data: { id: 7, name: \"ok\" },\n error: null\n });\n });\n\n it(\"rejects missing id\", () => {\n expect(handleMismatchedApiContract({ name: \"x\" }).error).toMatch(/missing id/);\n });\n});\n```\n\nVerification:\n- `npm test`\n- `npm run lint`\n\nEngineering notes:\n- Language: JavaScript\n- Framework/tooling: Playwright\n- Stack context: Airflow, dbt, DuckDB, MinIO, pytest\n- Domain: repo automation\n- Task type: prd_to_patch\n- Difficulty: medium\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "Build an elite-grade solution in the domain of realtime systems for scenario: multi-tenant SaaS.\nPrimary language: python.\nDifficulty: medium.\nConstraints: include invariants and failure modes, make the interface contract explicit, include tests or verification strategy, provide rollout and rollback guidance.\nComponent: component_zoyxcik.\nAssume cold-start and memory limits are tight.\nTask: Define an API and evolving schema strategy (versioning, migrations, compatibility rules). Provide example schemas and validation tests.\n\nOutput: production blueprint plus correctness arguments and test strategy.\nOutput: GPU pipeline design for throughput and tail-latency.\n\n**Pipeline**\n- Request batching with max batch size + max wait (e.g., 5ms) to control p99.\n- Separate CPU pre/post-processing threads; pin memory for transfers if available.\n- Model warmup; cache weights in VRAM; use concurrency limits.\n\n**Monitoring**\n- GPU utilization, queue wait time, batch size distribution, OOM events.\n\n**Fallback**\n- Graceful degradation to smaller batch size; circuit breaker on repeated OOM.\n\n\nChecks: boundary validation and deterministic behavior verified.", "source": "WithinUsAI/Elite_GOD_Coder_100k"} {"text": "Add a clear docstring and type hints to this function:\n\n```python\ndef f88021(s):\n return ''.join(x for x in s if x.isalnum()).lower()\n```\n\n```python\nfrom __future__ import annotations\n\ndef f88021(s: str) -> str:\n \"\"\"Normalize a string: keep only alphanumerics and lowercase the result.\"\"\"\n return \"\".join(ch for ch in s if ch.isalnum()).lower()\n```", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Design and implement an algorithm for rate limiting.\nRequirements: define inputs/outputs, implement solution with complexity analysis, and include tests.\nConstraints: must include type hints, stdlib-only, must avoid global state, must handle Windows paths safely.\nDifficulty: expert. Guarantee deterministic output ordering.\n\nDeliverable: corrected code and verification tests.\nProblem: compute rolling sums over events (ts:int,value:int) with window W seconds. Events may be out-of-order.\n\nComplexity: sorting O(n log n); window maintenance O(n); memory O(k).\n\n```python\nfrom __future__ import annotations\nfrom collections import deque\nfrom dataclasses import dataclass\nfrom typing import Iterable, List, Tuple\n\n@dataclass(frozen=True, slots=True)\nclass Event:\n ts: int\n value: int\n\ndef rolling_sum(events: Iterable[Event], window_s: int) -> List[Tuple[int,int]]:\n if window_s < 0:\n raise ValueError(\"window_s must be >= 0\")\n evs = sorted(events, key=lambda e: e.ts)\n q: deque[Event] = deque()\n s = 0\n out: List[Tuple[int,int]] = []\n for e in evs:\n q.append(e)\n s += e.value\n cutoff = e.ts - window_s\n while q and q[0].ts < cutoff:\n old = q.popleft()\n s -= old.value\n out.append((e.ts, s))\n return out\n```\n\n```python\nimport pytest\nfrom module_under_test import Event, rolling_sum\n\ndef test_rolling_sum():\n ev = [Event(10,1), Event(11,2), Event(20,5)]\n assert rolling_sum(ev, 5) == [(10,1),(11,3),(20,5)]\n```", "source": "WithinUsAI/python_GOD_coder_100k"} {"text": "Task type: compiler_frontend\nScenario: document indexing pipeline\nDomain focus: kernel primitives\nPrimary language: rust\nDifficulty: hard\nScale/SLO: 100k RPS peak\nComponent: component_pqlfcqwy\nConstraints: assume adversarial inputs; validate everything, include test vectors and fuzz strategy, include performance model and limits, include security threat model (defensive only), include failure modes and recovery, explicit contracts and invariants\nAssume tight memory budget and cold-start constraints.\nDeliverable: Design a DSL language frontend: lexer/parser, AST, type checking, error reporting, and tests.\n\nOutput: elite engineering answer optimized for correctness, performance, and operability.\n**Contract**\n- Inputs validated at the boundary; explicit error taxonomy.\n- Idempotency for side effects via request_id; deterministic replay.\n- Backward compatibility: additive changes by default; versioned breaking changes.\n**Invariants**\n- Liveness: under bounded faults and stable network, progress occurs.\n- Safety: state transitions preserve invariants; no partial commit leaks.\n- Determinism: replay of the same event log yields identical outputs.\n**Failure modes & recovery**\n- Duplicate requests: de-duplicate by (tenant, request_id) returning cached response.\n- Data corruption: checksums + scrubber; quarantine and rebuild from replicas/snapshots.\n- Crash during commit: WAL replay completes or transaction aborts; no torn writes.\n**Security posture (defensive)**\n- Threat model: auth/authz, injection, replay/abuse, supply chain.\n- Least privilege; secrets in managed store; audit logs for sensitive ops.\n- Input normalization, parameterized queries, path traversal protections.\n**Verification strategy**\n- Deterministic simulation with fault injection (crash/partition/latency).\n- Property tests against a pure reference model (state machine).\n- Canary + shadow traffic; invariants checked in production via assertions/metrics.\n\n**Snippet**\n```text\nImplementation sketch: factor pure state-machine core; adapters for I/O; add deterministic replay log.\n```\nHard checks: fault injection tests gate merges; perf thresholds enforced in CI.", "source": "WithinUsAI/Omega_Genesis_Coder_100k"} {"text": "Design CI/CD for a logistics service delivering file uploads.\nTarget platform: infra (Terraform).\nRequirements: pipelines, checks, artifact strategy, deployments, and rollbacks.\nConstraints: must include type hints where applicable, must be performant under load, must avoid global state, must be production-ready.\nDifficulty: expert. Assume 10k RPS peak traffic.\n\nOutput: engineering-grade answer with edge cases covered.\nDeliverable: CI/CD pipeline (GitHub Actions) with quality gates.\n\n```yaml\nname: ci\non:\n pull_request:\n push:\n branches: [main]\n\njobs:\n test:\n runs-on: ubuntu-latest\n steps:\n - uses: actions/checkout@v4\n - uses: actions/setup-python@v5\n with:\n python-version: \"3.11\"\n - run: python -m pip install -U pip\n - run: pip install -r requirements.txt\n - run: pip install -r requirements-dev.txt\n - run: ruff check .\n - run: mypy .\n - run: pytest -q --maxfail=1 --disable-warnings\n\n docker:\n needs: test\n runs-on: ubuntu-latest\n steps:\n - uses: actions/checkout@v4\n - uses: docker/setup-buildx-action@v3\n - run: docker build -t app:${{ github.sha }} .\n```\n\nDeployment strategy:\n- main → build → deploy to staging → smoke tests → canary to prod.\n- Rollback: redeploy previous image + DB migration rollback plan.\n\n\nHard-mode checks: concurrency safety, idempotency, and rollback validated; add chaos tests where feasible.", "source": "WithinUsAI/GOD_Coder_100k"} {"text": "Write pytest tests for `f55051`.\n\n```python\ndef f55051(a: int, b: int) -> int:\n return a*a + b*b\n```\nInclude edge cases and a property-style check.\n\n```python\nimport random\nfrom m79293 import f55051\n\ndef test_known():\n assert f55051(3,4) == 25\n\ndef test_zero():\n assert f55051(0,0) == 0\n\ndef test_property_nonnegative():\n for _ in range(200):\n a=random.randint(-50,50)\n b=random.randint(-50,50)\n assert f55051(a,b) >= 0\n```", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Refactor to modern typed Python with immutability and tests.\n\nFile: icwzg39s7txy.py\n```python\nclass C6G2Dqjhb52:\n def __init__(self, name, values):\n self.name = name\n self.values = list(values)\n def add(self, v):\n self.values.append(v)\n def mean(self):\n s = 0\n for x in self.values:\n s += x\n return s / len(self.values)\n```\n\nReturn full new icwzg39s7txy.py and test_icwzg39s7txy.py.\n\n# icwzg39s7txy.py\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom typing import Iterable, Tuple\n\n@dataclass(frozen=True)\nclass C6G2Dqjhb52:\n name: str\n values: Tuple[float, ...]\n\n @staticmethod\n def create(name: str, values: Iterable[float]) -> \"C6G2Dqjhb52\":\n vals = tuple(float(v) for v in values)\n if not vals:\n raise ValueError(\"values must be non-empty\")\n return C6G2Dqjhb52(name=name, values=vals)\n\n def add(self, v: float) -> \"C6G2Dqjhb52\":\n return C6G2Dqjhb52(name=self.name, values=self.values + (float(v),))\n\n def mean(self) -> float:\n return sum(self.values) / len(self.values)\n\n# test_icwzg39s7txy.py\nimport pytest\nfrom icwzg39s7txy import C6G2Dqjhb52\n\ndef test_mean_and_add():\n c = C6G2Dqjhb52.create(\"a\", [1, 2, 3])\n assert c.mean() == 2.0\n assert c.add(5).mean() == (1 + 2 + 3 + 5) / 4\n\ndef test_empty_raises():\n with pytest.raises(ValueError):\n C6G2Dqjhb52.create(\"x\", [])", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Fix a bug and add tests.\n\nFile: h5ph75.py\n```python\ndef vdhjpa4(n: int) -> int:\n \"\"\"Sum 1..n inclusive.\"\"\"\n if n < 0:\n raise ValueError(\"n must be non-negative\")\n total = 0\n for k in range(n): # BUG: should include n\n total += k\n return total\n```\n\nReturn unified diffs for h5ph75.py and test_h5ph75.py (pytest).\n\n*** Begin Patch\n*** Update File: h5ph75.py\n@@\n def vdhjpa4(n: int) -> int:\n@@\n total = 0\n- for k in range(n): # BUG: should include n\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_h5ph75.py\n+import pytest\n+from h5ph75 import vdhjpa4\n+\n+def test_zero():\n+ assert vdhjpa4(0) == 0\n+\n+def test_one():\n+ assert vdhjpa4(1) == 1\n+\n+def test_small():\n+ assert vdhjpa4(7) == 28\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ vdhjpa4(-1)\n+\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Refactor to modern typed Python with immutability and tests.\n\nFile: zbf3bmeb7lw.py\n```python\nclass Hzsw3H:\n def __init__(self, name, values):\n self.name = name\n self.values = list(values)\n def add(self, v):\n self.values.append(v)\n def mean(self):\n s = 0\n for x in self.values:\n s += x\n return s / len(self.values)\n```\n\nReturn full new zbf3bmeb7lw.py and test_zbf3bmeb7lw.py.\n\n# zbf3bmeb7lw.py\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom typing import Iterable, Tuple\n\n@dataclass(frozen=True)\nclass Hzsw3H:\n name: str\n values: Tuple[float, ...]\n\n @staticmethod\n def create(name: str, values: Iterable[float]) -> \"Hzsw3H\":\n vals = tuple(float(v) for v in values)\n if not vals:\n raise ValueError(\"values must be non-empty\")\n return Hzsw3H(name=name, values=vals)\n\n def add(self, v: float) -> \"Hzsw3H\":\n return Hzsw3H(name=self.name, values=self.values + (float(v),))\n\n def mean(self) -> float:\n return sum(self.values) / len(self.values)\n\n# test_zbf3bmeb7lw.py\nimport pytest\nfrom zbf3bmeb7lw import Hzsw3H\n\ndef test_mean_and_add():\n c = Hzsw3H.create(\"a\", [1, 2, 3])\n assert c.mean() == 2.0\n assert c.add(5).mean() == (1 + 2 + 3 + 5) / 4\n\ndef test_empty_raises():\n with pytest.raises(ValueError):\n Hzsw3H.create(\"x\", [])", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Design and implement an algorithm for data modeling.\nRequirements: define inputs/outputs, implement solution with complexity analysis, and include tests.\nConstraints: must handle Windows paths safely, must include docstrings, must include type hints, must avoid global state.\nDifficulty: easy. Support both Windows and POSIX paths correctly.\n\nDeliverable: API + reference implementation + tests.\nProblem: compute rolling sums over events (ts:int,value:int) with window W seconds. Events may be out-of-order.\n\nComplexity: sorting O(n log n); window maintenance O(n); memory O(k).\n\n```python\nfrom __future__ import annotations\nfrom collections import deque\nfrom dataclasses import dataclass\nfrom typing import Iterable, List, Tuple\n\n@dataclass(frozen=True, slots=True)\nclass Event:\n ts: int\n value: int\n\ndef rolling_sum(events: Iterable[Event], window_s: int) -> List[Tuple[int,int]]:\n if window_s < 0:\n raise ValueError(\"window_s must be >= 0\")\n evs = sorted(events, key=lambda e: e.ts)\n q: deque[Event] = deque()\n s = 0\n out: List[Tuple[int,int]] = []\n for e in evs:\n q.append(e)\n s += e.value\n cutoff = e.ts - window_s\n while q and q[0].ts < cutoff:\n old = q.popleft()\n s -= old.value\n out.append((e.ts, s))\n return out\n```\n\n```python\nimport pytest\nfrom module_under_test import Event, rolling_sum\n\ndef test_rolling_sum():\n ev = [Event(10,1), Event(11,2), Event(20,5)]\n assert rolling_sum(ev, 5) == [(10,1),(11,3),(20,5)]\n```", "source": "WithinUsAI/python_GOD_coder_100k"} {"text": "Build an elite-grade solution in the domain of stream processing for scenario: multi-tenant SaaS.\nPrimary language: rust.\nDifficulty: medium.\nConstraints: include tests or verification strategy, assume untrusted inputs; validate and sanitize, make the interface contract explicit, provide rollout and rollback guidance.\nComponent: component_jrtfqgm.\nAssume cold-start and memory limits are tight.\nTask: Design a replication/consistency approach (e.g., leader-based, quorum reads/writes). Provide message flows, failure handling, and a minimal reference implementation skeleton.\n\nOutput: rigorous solution with invariants, failure modes, and performance notes.\nOutput: replication design + failure handling + minimal skeleton.\n\n**Model**\n- Leader-based replication with term + log index.\n- Quorum acks for durability: write committed when majority acks.\n- Read options: leader-read (linearizable) or quorum-read (monotonic if using read-index).\n\n**Message flow (write)**\n1. Client → Leader: Put(request_id, payload)\n2. Leader appends to log, sends AppendEntries to followers\n3. Followers append + ack\n4. On majority ack: commit index advances; apply to state machine; respond to client\n\n**Failure modes**\n- Leader crash: new election; uncommitted entries may be rolled back.\n- Partition: minority side cannot commit.\n- Duplicate requests: deduplicate by request_id stored in state.\n\n**Skeleton (Go pseudo)**\n```go\ntype Entry struct { Term uint64; Index uint64; Cmd []byte }\ntype Node struct {\n id int\n term uint64\n log []Entry\n commit uint64\n seen map[string][]byte // request_id -> response\n}\n```\n\n**Verification**\n- Invariant: committed index never decreases.\n- Property: if a write is committed, all future leaders contain it.\n- Test with simulated partitions and crash/restart.\n\n\nChecks: boundary validation and deterministic behavior verified.", "source": "WithinUsAI/Elite_GOD_Coder_100k"} {"text": "Refactor a Python module used for report generation into a clean, extensible design.\nRequirements: outline the new architecture briefly, then provide the refactored code and tests.\nConstraints: must be memory-efficient, must be easy to extend.\nDifficulty: easy. Ensure the API is testable via dependency injection.\n\nDeliverable: API + reference implementation + tests.\nArchitecture:\n- Public facade class coordinating concerns (parsing, validation, persistence)\n- Small pure functions for testability\n- No global state; dependency injection for filesystem I/O\n\n```python\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom pathlib import Path\nfrom typing import Protocol, Iterable\nimport json\n\nclass Store(Protocol):\n def write_text(self, path: Path, data: str) -> None: ...\n\nclass FSStore:\n def write_text(self, path: Path, data: str) -> None:\n path.parent.mkdir(parents=True, exist_ok=True)\n path.write_text(data, encoding=\"utf-8\")\n\n@dataclass(frozen=True, slots=True)\nclass Item:\n name: str\n qty: int\n\ndef parse_items(lines: Iterable[str]) -> list[Item]:\n out: list[Item] = []\n for i, line in enumerate(lines, 1):\n s = line.strip()\n if not s:\n continue\n obj = json.loads(s)\n if not isinstance(obj, dict):\n raise ValueError(f\"line {i}: expected object\")\n name = obj.get(\"name\")\n qty = obj.get(\"qty\")\n if not isinstance(name, str) or not name:\n raise ValueError(f\"line {i}: name must be str\")\n if not isinstance(qty, int) or qty < 0:\n raise ValueError(f\"line {i}: qty must be non-negative int\")\n out.append(Item(name, qty))\n return out\n\nclass InventoryWriter:\n def __init__(self, base_dir: Path, store: Store | None = None) -> None:\n self._base = base_dir\n self._store: Store = store or FSStore()\n\n def write(self, rel_path: str, items: list[Item]) -> Path:\n dst = (self._base / rel_path).resolve()\n base = self._base.resolve()\n if dst != base and base not in dst.parents:\n raise ValueError(\"unsafe path traversal\")\n payload = json.dumps([item.__dict__ for item in items], ensure_ascii=False)\n self._store.write_text(dst, payload)\n return dst\n```\n\n```python\nimport json\nfrom pathlib import Path\nimport pytest\nfrom module_under_test import InventoryWriter, parse_items\n\ndef test_parse_items_valid():\n lines = [json.dumps({\"name\":\"x\",\"qty\":1})]\n assert parse_items(lines)[0].name == \"x\"\n\ndef test_writer_blocks_traversal(tmp_path: Path):\n w = InventoryWriter(tmp_path)\n with pytest.raises(ValueError):\n w.write(\"../evil.json\", [])\n```", "source": "WithinUsAI/python_GOD_coder_100k"} {"text": "Task type: query_optimizer\nScenario: rate limit gateway\nDomain focus: formal verification\nPrimary language: bash\nDifficulty: expert+\nScale/SLO: 50 TB/day ingestion\nComponent: component_tyonsasd\nConstraints: explicit contracts and invariants, include performance model and limits, include test vectors and fuzz strategy, include backward compatibility and migration plan, avoid data races and undefined behavior, include failure modes and recovery, include security threat model (defensive only)\nAssume hostile inputs and targeted abuse patterns.\nDeliverable: Design a cost-based optimizer slice: logical rules, physical operators, and cost model. Include regression tests and query-plan explain examples.\n\nOutput: elite engineering answer optimized for correctness, performance, and operability.\n**Contract**\n- Inputs validated at the boundary; explicit error taxonomy.\n- Idempotency for side effects via request_id; deterministic replay.\n- Backward compatibility: additive changes by default; versioned breaking changes.\n**Invariants**\n- Safety: state transitions preserve invariants; no partial commit leaks.\n- Determinism: replay of the same event log yields identical outputs.\n- Isolation: tenant boundary enforced; no cross-tenant reads/writes.\n**Failure modes & recovery**\n- Crash during commit: WAL replay completes or transaction aborts; no torn writes.\n- Network partition: minority cannot commit; clients receive retriable errors.\n- Data corruption: checksums + scrubber; quarantine and rebuild from replicas/snapshots.\n**Security posture (defensive)**\n- Threat model: auth/authz, injection, replay/abuse, supply chain.\n- Least privilege; secrets in managed store; audit logs for sensitive ops.\n- Input normalization, parameterized queries, path traversal protections.\n**Verification strategy**\n- Property tests against a pure reference model (state machine).\n- Fuzzing of parsers/framers/validators with corpus seeds.\n- Canary + shadow traffic; invariants checked in production via assertions/metrics.\n\n**Snippet**\n```python\n# Minimal cost model skeleton\nfrom dataclasses import dataclass\n\n@dataclass(frozen=True)\nclass Plan:\n op: str\n cost: float\n children: tuple[\"Plan\", ...] = ()\n\ndef choose_best(plans: list[Plan]) -> Plan:\n return min(plans, key=lambda p: p.cost)\n```\n\nExpert+ checks: mechanized invariants (or exhaustive model checking), adversarial fuzzing, and multi-region failure drills.", "source": "WithinUsAI/Omega_Genesis_Coder_100k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Refactor to modern typed Python with immutability and tests.\n\nFile: f4rah5_03p.py\n```python\nclass Bgt0Hv37Q:\n def __init__(self, name, values):\n self.name = name\n self.values = list(values)\n def add(self, v):\n self.values.append(v)\n def mean(self):\n s = 0\n for x in self.values:\n s += x\n return s / len(self.values)\n```\n\nReturn full new f4rah5_03p.py and test_f4rah5_03p.py.\n\n# f4rah5_03p.py\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom typing import Iterable, Tuple\n\n@dataclass(frozen=True)\nclass Bgt0Hv37Q:\n name: str\n values: Tuple[float, ...]\n\n @staticmethod\n def create(name: str, values: Iterable[float]) -> \"Bgt0Hv37Q\":\n vals = tuple(float(v) for v in values)\n if not vals:\n raise ValueError(\"values must be non-empty\")\n return Bgt0Hv37Q(name=name, values=vals)\n\n def add(self, v: float) -> \"Bgt0Hv37Q\":\n return Bgt0Hv37Q(name=self.name, values=self.values + (float(v),))\n\n def mean(self) -> float:\n return sum(self.values) / len(self.values)\n\n# test_f4rah5_03p.py\nimport pytest\nfrom f4rah5_03p import Bgt0Hv37Q\n\ndef test_mean_and_add():\n c = Bgt0Hv37Q.create(\"a\", [1, 2, 3])\n assert c.mean() == 2.0\n assert c.add(5).mean() == (1 + 2 + 3 + 5) / 4\n\ndef test_empty_raises():\n with pytest.raises(ValueError):\n Bgt0Hv37Q.create(\"x\", [])", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Fix the bug and add pytest tests.\n\n```python\ndef f90668(n: int) -> int:\n # sum 1..n inclusive\n if n < 0: raise ValueError\n total = 0\n for k in range(n): # BUG\n total += k\n return total\n```\nReturn unified diffs for `m41524.py` and `test_m41524.py`.\n\n*** Begin Patch\n*** Update File: m41524.py\n@@\n def f90668(n: int) -> int:\n@@\n- for k in range(n): # BUG\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_m41524.py\n+import pytest\n+from m41524 import f90668\n+\n+def test_small():\n+ assert f90668(7) == 28\n+\n+def test_zero():\n+ assert f90668(0) == 0\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ f90668(-1)\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Fix the bug and add pytest tests.\n\n```python\ndef f05704(n: int) -> int:\n # sum 1..n inclusive\n if n < 0: raise ValueError\n total = 0\n for k in range(n): # BUG\n total += k\n return total\n```\nReturn unified diffs for `m43672.py` and `test_m43672.py`.\n\n*** Begin Patch\n*** Update File: m43672.py\n@@\n def f05704(n: int) -> int:\n@@\n- for k in range(n): # BUG\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_m43672.py\n+import pytest\n+from m43672 import f05704\n+\n+def test_small():\n+ assert f05704(7) == 28\n+\n+def test_zero():\n+ assert f05704(0) == 0\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ f05704(-1)\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Refactor to typed, mostly-immutable Python and add minimal tests.\n\n```python\nclass C84109:\n def __init__(self, values): self.values=list(values)\n def mean(self): return sum(self.values)/len(self.values)\n```\nReturn `m83393.py` and `test_m83393.py`.\n\n```python\n# m83393.py\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom typing import Iterable, Tuple\n\n@dataclass(frozen=True)\nclass C84109:\n values: Tuple[float, ...]\n\n @staticmethod\n def create(values: Iterable[float]) -> \"C84109\":\n vals = tuple(float(v) for v in values)\n if not vals: raise ValueError(\"empty\")\n return C84109(vals)\n\n def mean(self) -> float:\n return sum(self.values)/len(self.values)\n```\n\n```python\n# test_m83393.py\nimport pytest\nfrom m83393 import C84109\n\ndef test_mean():\n assert C84109.create([1,2,3]).mean() == 2.0\ndef test_empty():\n with pytest.raises(ValueError):\n C84109.create([])\n```", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Produce an offline-first self-evolving code assistant architecture named `zqdx6p7`.\nMust include: module layout, patch-safety policy, evaluation gates (tests/lint/types), versioned memory index.\n\nArchitecture: `zqdx6p7` (offline-first, self-evolving)\n\nModules\n- core/loop.py: evolve → validate → accept/reject (bounded iterations)\n- patching/: diff builder, safe apply, atomic writes, rollback points\n- policy/: allowlist paths, deny globs (.git/, __pycache__/, binaries), patch size caps\n- signals/: parse pytest/ruff/mypy into normalized findings\n- memory/index.jsonl: append-only snapshots (hashes, metrics, rationale)\n\nSafety gates\n- refuse path traversal/symlink escapes; never edit binaries\n- accept only if tests/lint/types stay green or improve", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Fix the bug and add pytest tests.\n\n```python\ndef f87106(n: int) -> int:\n # sum 1..n inclusive\n if n < 0: raise ValueError\n total = 0\n for k in range(n): # BUG\n total += k\n return total\n```\nReturn unified diffs for `m98158.py` and `test_m98158.py`.\n\n*** Begin Patch\n*** Update File: m98158.py\n@@\n def f87106(n: int) -> int:\n@@\n- for k in range(n): # BUG\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_m98158.py\n+import pytest\n+from m98158 import f87106\n+\n+def test_small():\n+ assert f87106(7) == 28\n+\n+def test_zero():\n+ assert f87106(0) == 0\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ f87106(-1)\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Task type: lockfree_primitive\nScenario: job scheduler\nDomain focus: stream processing\nPrimary language: cpp\nDifficulty: expert\nScale/SLO: 1M msgs/min\nComponent: component_gbtdhmlz\nConstraints: explicit contracts and invariants, include failure modes and recovery, include backward compatibility and migration plan, include test vectors and fuzz strategy, include security threat model (defensive only), include deterministic replay plan, include verification strategy\nAssume hostile inputs and targeted abuse patterns.\nDeliverable: Design a lock-free primitive with memory ordering reasoning and stress tests (no UB).\n\nOutput: elite engineering answer optimized for correctness, performance, and operability.\n**Contract**\n- Inputs validated at the boundary; explicit error taxonomy.\n- Idempotency for side effects via request_id; deterministic replay.\n- Backward compatibility: additive changes by default; versioned breaking changes.\n**Invariants**\n- Determinism: replay of the same event log yields identical outputs.\n- Liveness: under bounded faults and stable network, progress occurs.\n- Isolation: tenant boundary enforced; no cross-tenant reads/writes.\n**Failure modes & recovery**\n- Data corruption: checksums + scrubber; quarantine and rebuild from replicas/snapshots.\n- Duplicate requests: de-duplicate by (tenant, request_id) returning cached response.\n- Crash during commit: WAL replay completes or transaction aborts; no torn writes.\n**Security posture (defensive)**\n- Threat model: auth/authz, injection, replay/abuse, supply chain.\n- Least privilege; secrets in managed store; audit logs for sensitive ops.\n- Input normalization, parameterized queries, path traversal protections.\n**Verification strategy**\n- Canary + shadow traffic; invariants checked in production via assertions/metrics.\n- Deterministic simulation with fault injection (crash/partition/latency).\n- Property tests against a pure reference model (state machine).\n\n**Snippet**\n```rust\n// Skeleton: SPSC ring buffer with acquire/release (outline)\nuse std::sync::atomic::{AtomicUsize, Ordering};\n\npub struct Ring {\n buf: Vec>,\n head: AtomicUsize,\n tail: AtomicUsize,\n cap: usize,\n}\n\n// Correctness sketch: producer uses Release on tail store, consumer uses Acquire on tail load.\n```\n\nExpert checks: state-machine proof sketch + model checking; upgrade/rollback rehearsed.", "source": "WithinUsAI/Omega_Genesis_Coder_100k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Refactor to modern typed Python with immutability and tests.\n\nFile: qyts8fk_k1.py\n```python\nclass Kt96Ek1:\n def __init__(self, name, values):\n self.name = name\n self.values = list(values)\n def add(self, v):\n self.values.append(v)\n def mean(self):\n s = 0\n for x in self.values:\n s += x\n return s / len(self.values)\n```\n\nReturn full new qyts8fk_k1.py and test_qyts8fk_k1.py.\n\n# qyts8fk_k1.py\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom typing import Iterable, Tuple\n\n@dataclass(frozen=True)\nclass Kt96Ek1:\n name: str\n values: Tuple[float, ...]\n\n @staticmethod\n def create(name: str, values: Iterable[float]) -> \"Kt96Ek1\":\n vals = tuple(float(v) for v in values)\n if not vals:\n raise ValueError(\"values must be non-empty\")\n return Kt96Ek1(name=name, values=vals)\n\n def add(self, v: float) -> \"Kt96Ek1\":\n return Kt96Ek1(name=self.name, values=self.values + (float(v),))\n\n def mean(self) -> float:\n return sum(self.values) / len(self.values)\n\n# test_qyts8fk_k1.py\nimport pytest\nfrom qyts8fk_k1 import Kt96Ek1\n\ndef test_mean_and_add():\n c = Kt96Ek1.create(\"a\", [1, 2, 3])\n assert c.mean() == 2.0\n assert c.add(5).mean() == (1 + 2 + 3 + 5) / 4\n\ndef test_empty_raises():\n with pytest.raises(ValueError):\n Kt96Ek1.create(\"x\", [])", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Write pytest tests for `f63524`.\n\n```python\ndef f63524(a: int, b: int) -> int:\n return a*a + b*b\n```\nInclude edge cases and a property-style check.\n\n```python\nimport random\nfrom m51932 import f63524\n\ndef test_known():\n assert f63524(3,4) == 25\n\ndef test_zero():\n assert f63524(0,0) == 0\n\ndef test_property_nonnegative():\n for _ in range(200):\n a=random.randint(-50,50)\n b=random.randint(-50,50)\n assert f63524(a,b) >= 0\n```", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Build an elite-grade solution in the domain of networking for scenario: multi-tenant SaaS.\nPrimary language: rust.\nDifficulty: medium.\nConstraints: avoid undefined behavior and data races, include tests or verification strategy, assume untrusted inputs; validate and sanitize, provide rollout and rollback guidance.\nComponent: component_wvtbhiz.\nAssume schema changes every sprint; must be backward compatible.\nTask: Implement a concurrency primitive or subsystem (lock-free queue, thread pool, async runtime component). Explain memory ordering and correctness arguments; include stress tests.\n\nOutput: elite-grade engineering answer with contracts, edge cases, and verification.\nOutput: correctness-focused concurrency primitive + stress tests.\n\n**Primitive**\n- Bounded MPMC queue with backpressure (blocking push/pop) OR lock-free SPSC ring buffer.\n\n**Correctness notes**\n- For lock-free: use acquire/release semantics on head/tail indices.\n- Avoid ABA by monotonic counters; ring index = counter % capacity.\n\n**Stress tests**\n- Multi-thread producers/consumers; assert item multiset preserved.\n- Use time-bounded randomized schedules; detect deadlocks.\n\n\nChecks: boundary validation and deterministic behavior verified.", "source": "WithinUsAI/Elite_GOD_Coder_100k"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: Project stack: ASP.NET Core, SQL Server, EF Core, xUnit, Docker\nLanguage: SQL\nDependency challenge: build reproducibility failure\nTask type: build_reproducibility_fix\nDifficulty: medium\n\nFix this as a senior engineer.\nRequired:\n- identify the version or compatibility failure mode\n- produce the corrected config/code/build patch\n- explain rollback-safe migration notes\n- add regression tests or reproducibility checks\n- include concrete verification commands\n\nRepository sketch:\nrepo/\n migrations/\n 001_init.sql\n 002_add_index.sql\n queries/\n report.sql\n tests/\n report_cases.md\n\nFocus: Focus on versioning, migrations, lockfiles, runtime compatibility, and secure dependency handling.\n\nassistant: Diagnosis:\n- Root cause: the issue around build reproducibility failure is a dependency, migration, or runtime-compatibility mismatch that needs a rollback-safe patch.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```sql\nWITH ranked AS (\n SELECT\n user_id,\n created_at,\n amount,\n ROW_NUMBER() OVER (PARTITION BY user_id ORDER BY created_at DESC, id DESC) AS rn\n FROM orders\n)\nSELECT user_id, created_at, amount\nFROM ranked\nWHERE rn = 1;\n```\n\nTests:\n```sql\n-- Correctness checks:\n-- 1) multiple rows per user\n-- 2) identical timestamps require deterministic tie-breaker\n-- 3) null values handled by business rules\n```\n\nVerification:\n- `run migration checks`\n- `run query correctness cases`\n\nEngineering notes:\n- Language: SQL\n- Framework/tooling: DuckDB\n- Stack context: ASP.NET Core, SQL Server, EF Core, xUnit, Docker\n- Domain: data pipeline\n- Task type: build_reproducibility_fix\n- Difficulty: medium\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "Build an elite-grade solution in the domain of databases for scenario: time-series metrics.\nPrimary language: typescript.\nDifficulty: medium.\nConstraints: document performance characteristics, include invariants and failure modes, assume untrusted inputs; validate and sanitize.\nComponent: component_uerqokd.\nAssume compliance requires data deletion with proofs.\nTask: Provide SLOs, alerting, dashboards, runbooks, and incident playbook. Include chaos testing and safe rollout strategy.\n\nOutput: rigorous solution with invariants, failure modes, and performance notes.\nOutput: SLOs + alerts + runbooks + chaos strategy.\n\n**SLOs**\n- Availability: 99.9% monthly\n- Latency: p95 < 200ms, p99 < 400ms\n- Error rate: < 0.1%\n\n**Alerts**\n- Burn-rate alerts for SLOs (fast/slow windows)\n- Saturation: CPU, memory, queue depth, DB connections\n- Dependency health: cache hit rate drop, downstream timeouts\n\n**Runbooks**\n- Triage: identify blast radius, feature-flag rollback, capacity mitigation\n- Post-incident: timeline, contributing factors, action items\n\n**Chaos**\n- Inject latency, partial outages, and restarts in staging; verify steady-state SLOs.\n\n\nChecks: boundary validation and deterministic behavior verified.", "source": "WithinUsAI/Elite_GOD_Coder_100k"} {"text": "Refactor to typed, mostly-immutable Python and add minimal tests.\n\n```python\nclass C11535:\n def __init__(self, values): self.values=list(values)\n def mean(self): return sum(self.values)/len(self.values)\n```\nReturn `m93195.py` and `test_m93195.py`.\n\n```python\n# m93195.py\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom typing import Iterable, Tuple\n\n@dataclass(frozen=True)\nclass C11535:\n values: Tuple[float, ...]\n\n @staticmethod\n def create(values: Iterable[float]) -> \"C11535\":\n vals = tuple(float(v) for v in values)\n if not vals: raise ValueError(\"empty\")\n return C11535(vals)\n\n def mean(self) -> float:\n return sum(self.values)/len(self.values)\n```\n\n```python\n# test_m93195.py\nimport pytest\nfrom m93195 import C11535\n\ndef test_mean():\n assert C11535.create([1,2,3]).mean() == 2.0\ndef test_empty():\n with pytest.raises(ValueError):\n C11535.create([])\n```", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Refactor to modern typed Python with immutability and tests.\n\nFile: vgzjw3ws1oo.py\n```python\nclass Cf5Kfk:\n def __init__(self, name, values):\n self.name = name\n self.values = list(values)\n def add(self, v):\n self.values.append(v)\n def mean(self):\n s = 0\n for x in self.values:\n s += x\n return s / len(self.values)\n```\n\nReturn full new vgzjw3ws1oo.py and test_vgzjw3ws1oo.py.\n\n# vgzjw3ws1oo.py\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom typing import Iterable, Tuple\n\n@dataclass(frozen=True)\nclass Cf5Kfk:\n name: str\n values: Tuple[float, ...]\n\n @staticmethod\n def create(name: str, values: Iterable[float]) -> \"Cf5Kfk\":\n vals = tuple(float(v) for v in values)\n if not vals:\n raise ValueError(\"values must be non-empty\")\n return Cf5Kfk(name=name, values=vals)\n\n def add(self, v: float) -> \"Cf5Kfk\":\n return Cf5Kfk(name=self.name, values=self.values + (float(v),))\n\n def mean(self) -> float:\n return sum(self.values) / len(self.values)\n\n# test_vgzjw3ws1oo.py\nimport pytest\nfrom vgzjw3ws1oo import Cf5Kfk\n\ndef test_mean_and_add():\n c = Cf5Kfk.create(\"a\", [1, 2, 3])\n assert c.mean() == 2.0\n assert c.add(5).mean() == (1 + 2 + 3 + 5) / 4\n\ndef test_empty_raises():\n with pytest.raises(ValueError):\n Cf5Kfk.create(\"x\", [])", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: Language: TypeScript\nFramework/tooling: Node.js\nDomain: payments platform\nLogic challenge: idempotent retry design\nTask type: edge_case_hardening\nDifficulty: medium\n\nReturn a rigorous engineering answer:\n- identify the hidden root cause or logical failure\n- present the corrected implementation\n- add tests that prove the fix\n- list verification commands\n- explain why naive fixes are insufficient when relevant\n\nRepository sketch:\nrepo/\n src/\n api.ts\n service.ts\n schema.ts\n tests/\n api.test.ts\n package.json\n\nFocus: Focus on strong structured logic with edge cases, data validation, and concurrency safety.\n\nassistant: Diagnosis:\n- Root cause: the failure around idempotent retry design is caused by missing validation, weak edge-case handling, or unsafe lifecycle behavior in the current implementation.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```ts\ntype Payload = Record;\n\nexport function normalizePayload(payload: Payload): Payload {\n if (!payload || typeof payload !== \"object\" || Array.isArray(payload)) {\n throw new TypeError(\"payload must be a plain object\");\n }\n return Object.fromEntries(\n Object.entries(payload)\n .filter(([, value]) => value !== null && value !== undefined)\n .map(([key, value]) => [String(key).trim(), value])\n );\n}\n\nexport function handleIdempotentRetryDesign(payload: Payload) {\n const clean = normalizePayload(payload);\n if (!(\"id\" in clean)) {\n return { ok: false, data: {}, error: \"missing id\" };\n }\n return { ok: true, data: clean, error: null };\n}\n```\n\nTests:\n```ts\nimport { describe, it, expect } from \"vitest\";\nimport { handleIdempotentRetryDesign } from \"../src/service\";\n\ndescribe(\"handler\", () => {\n it(\"accepts valid input\", () => {\n expect(handleIdempotentRetryDesign({ id: 7, name: \"ok\", unused: null })).toEqual({\n ok: true,\n data: { id: 7, name: \"ok\" },\n error: null\n });\n });\n\n it(\"rejects missing id\", () => {\n expect(handleIdempotentRetryDesign({ name: \"x\" }).error).toMatch(/missing id/);\n });\n});\n```\n\nVerification:\n- `npm test`\n- `npm run typecheck`\n- `npm run lint`\n\nEngineering notes:\n- Language: TypeScript\n- Framework/tooling: Node.js\n- Stack context: Go, Gin, PostgreSQL, gRPC, Prometheus, Docker\n- Domain: payments platform\n- Task type: edge_case_hardening\n- Difficulty: medium\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "Fix the bug and add pytest tests.\n\n```python\ndef f79531(n: int) -> int:\n # sum 1..n inclusive\n if n < 0: raise ValueError\n total = 0\n for k in range(n): # BUG\n total += k\n return total\n```\nReturn unified diffs for `m39933.py` and `test_m39933.py`.\n\n*** Begin Patch\n*** Update File: m39933.py\n@@\n def f79531(n: int) -> int:\n@@\n- for k in range(n): # BUG\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_m39933.py\n+import pytest\n+from m39933 import f79531\n+\n+def test_small():\n+ assert f79531(7) == 28\n+\n+def test_zero():\n+ assert f79531(0) == 0\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ f79531(-1)\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Refactor to modern typed Python with immutability and tests.\n\nFile: ouzmee7pyxc.py\n```python\nclass N76A8Ttb:\n def __init__(self, name, values):\n self.name = name\n self.values = list(values)\n def add(self, v):\n self.values.append(v)\n def mean(self):\n s = 0\n for x in self.values:\n s += x\n return s / len(self.values)\n```\n\nReturn full new ouzmee7pyxc.py and test_ouzmee7pyxc.py.\n\n# ouzmee7pyxc.py\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom typing import Iterable, Tuple\n\n@dataclass(frozen=True)\nclass N76A8Ttb:\n name: str\n values: Tuple[float, ...]\n\n @staticmethod\n def create(name: str, values: Iterable[float]) -> \"N76A8Ttb\":\n vals = tuple(float(v) for v in values)\n if not vals:\n raise ValueError(\"values must be non-empty\")\n return N76A8Ttb(name=name, values=vals)\n\n def add(self, v: float) -> \"N76A8Ttb\":\n return N76A8Ttb(name=self.name, values=self.values + (float(v),))\n\n def mean(self) -> float:\n return sum(self.values) / len(self.values)\n\n# test_ouzmee7pyxc.py\nimport pytest\nfrom ouzmee7pyxc import N76A8Ttb\n\ndef test_mean_and_add():\n c = N76A8Ttb.create(\"a\", [1, 2, 3])\n assert c.mean() == 2.0\n assert c.add(5).mean() == (1 + 2 + 3 + 5) / 4\n\ndef test_empty_raises():\n with pytest.raises(ValueError):\n N76A8Ttb.create(\"x\", [])", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Optimize while preserving behavior.\n\nFile: jeixky.py\n```python\ndef vnlftda(xs):\n out = []\n for x in xs:\n if x not in out:\n out.append(x)\n return out\n```\n\nRequirements: preserve first-seen order; O(n) average; add types + docstring.\n\n# jeixky.py\nfrom __future__ import annotations\nfrom typing import Iterable, List, Set, TypeVar\n\nT = TypeVar(\"T\")\n\ndef vnlftda(xs: Iterable[T]) -> List[T]:\n \"\"\"Return unique items preserving first-seen order.\"\"\"\n seen: Set[T] = set()\n out: List[T] = []\n for x in xs:\n if x in seen:\n continue\n seen.add(x)\n out.append(x)\n return out", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: System domain: job scheduler\nStack: Spring Boot, PostgreSQL, JUnit, Gradle, Docker, GitHub Actions\nCross-layer incident: monorepo toolchain skew\nTask type: cache_consistency_patch\nDifficulty: hard\n\nSolve this as a complete-project engineer.\nOutput must include:\n- root cause across layers\n- final implementation patch\n- tests touching at least two layers\n- deployment or observability note\n- verification commands\n\nRepository sketch:\nrepo/\n src/main/java/com/acme/App.java\n src/main/java/com/acme/Service.java\n src/test/java/com/acme/AppTest.java\n pom.xml\n\nFocus: Focus on multi-layer debugging across frontend, backend, database, CI, caching, and deployment.\n\nassistant: Diagnosis:\n- Root cause: monorepo toolchain skew crosses service boundaries, so the fix must align code, contracts, tests, and deployment behavior.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```java\nimport java.util.HashMap;\nimport java.util.Map;\n\npublic final class RequestHandler {\n public static Map handleRequest(Map payload) {\n Map clean = new HashMap<>();\n for (Map.Entry entry : payload.entrySet()) {\n if (entry.getValue() != null) clean.put(entry.getKey().trim(), entry.getValue());\n }\n if (!clean.containsKey(\"id\")) throw new IllegalArgumentException(\"missing id\");\n return Map.of(\"ok\", true, \"data\", clean);\n }\n}\n```\n\nTests:\n```java\nimport static org.junit.jupiter.api.Assertions.*;\nimport java.util.Map;\nimport org.junit.jupiter.api.Test;\n\nclass RequestHandlerTest {\n @Test\n void requiresId() {\n assertThrows(IllegalArgumentException.class, () -> RequestHandler.handleRequest(Map.of(\"name\", \"x\")));\n }\n}\n```\n\nVerification:\n- `./gradlew test`\n- `mvn test`\n\nEngineering notes:\n- Language: Java\n- Framework/tooling: JUnit\n- Stack context: Spring Boot, PostgreSQL, JUnit, Gradle, Docker, GitHub Actions\n- Domain: job scheduler\n- Task type: cache_consistency_patch\n- Difficulty: hard\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: System domain: benchmark harness\nStack: ASP.NET Core, SQL Server, EF Core, xUnit, Docker\nCross-layer incident: schema drift during deployment\nTask type: full_stack_bug_fix\nDifficulty: hard\n\nSolve this as a complete-project engineer.\nOutput must include:\n- root cause across layers\n- final implementation patch\n- tests touching at least two layers\n- deployment or observability note\n- verification commands\n\nRepository sketch:\nrepo/\n src/main.rs\n src/lib.rs\n src/service.rs\n src/store.rs\n tests/integration.rs\n Cargo.toml\n\nFocus: Focus on multi-layer debugging across frontend, backend, database, CI, caching, and deployment.\n\nassistant: Diagnosis:\n- Root cause: schema drift during deployment crosses service boundaries, so the fix must align code, contracts, tests, and deployment behavior.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```rust\nuse std::collections::HashMap;\n\npub fn normalize_payload(payload: HashMap) -> HashMap {\n payload\n .into_iter()\n .filter(|(_, v)| !v.trim().is_empty())\n .collect()\n}\n```\n\nTests:\n```rust\n#[test]\nfn normalize_payload_filters_empty_values() {\n use std::collections::HashMap;\n let mut payload = HashMap::new();\n payload.insert(\"id\".to_string(), \"7\".to_string());\n payload.insert(\"name\".to_string(), \"\".to_string());\n let out = normalize_payload(payload);\n assert!(out.contains_key(\"id\"));\n assert!(!out.contains_key(\"name\"));\n}\n```\n\nVerification:\n- `cargo test`\n- `cargo clippy -- -D warnings`\n\nEngineering notes:\n- Language: Rust\n- Framework/tooling: Axum\n- Stack context: ASP.NET Core, SQL Server, EF Core, xUnit, Docker\n- Domain: benchmark harness\n- Task type: full_stack_bug_fix\n- Difficulty: hard\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: Project domain: observability collector\nImplementation stack: Airflow, dbt, DuckDB, MinIO, pytest\nSoftware delivery problem: streaming timeout handling\nTask type: test_strategy_implementation\nDifficulty: hard\n\nReturn a complete delivery-grade response with:\n- diagnosis or design reasoning\n- implementation\n- test plan or tests\n- rollout plan\n- rollback or compatibility note\n- verification commands\n\nRepository sketch:\nrepo/\n app/\n api.py\n service.py\n models.py\n tests/\n test_api.py\n pyproject.toml\n\nFocus: Focus on shipping production software with rollout safety, acceptance criteria, telemetry, and maintenance quality.\n\nassistant: Diagnosis:\n- Root cause or delivery blocker: streaming timeout handling needs both implementation work and a safe shipping plan.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```python\nfrom __future__ import annotations\n\nfrom dataclasses import dataclass\nfrom typing import Any\n\n@dataclass\nclass ServiceResult:\n ok: bool\n data: dict[str, Any]\n error: str | None = None\n\ndef normalize_payload(payload: dict[str, Any]) -> dict[str, Any]:\n if not isinstance(payload, dict):\n raise TypeError(\"payload must be a dict\")\n clean: dict[str, Any] = {}\n for key, value in payload.items():\n if value is None:\n continue\n clean[str(key).strip()] = value\n return clean\n\ndef handle_streaming_timeout_handling(payload: dict[str, Any]) -> ServiceResult:\n clean = normalize_payload(payload)\n if \"id\" not in clean:\n return ServiceResult(ok=False, data={}, error=\"missing id\")\n return ServiceResult(ok=True, data=clean)\n```\n\nTests:\n```python\nimport pytest\nfrom app.service import handle_jwt_refresh_token_rotation as handler\n\ndef test_handler_accepts_valid_payload():\n result = handler({\"id\": 7, \"name\": \"ok\", \"unused\": None})\n assert result.ok is True\n assert result.data == {\"id\": 7, \"name\": \"ok\"}\n\ndef test_handler_rejects_missing_id():\n result = handler({\"name\": \"x\"})\n assert result.ok is False\n assert result.error == \"missing id\"\n```\n\nVerification:\n- `pytest -q`\n- `ruff check .`\n- `python -m compileall .`\n\nEngineering notes:\n- Language: Python\n- Framework/tooling: Celery\n- Stack context: Airflow, dbt, DuckDB, MinIO, pytest\n- Domain: observability collector\n- Task type: test_strategy_implementation\n- Difficulty: hard\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "Optimize while preserving behavior and order.\n\n```python\ndef f66701(xs):\n out=[]\n for x in xs:\n if x not in out: out.append(x)\n return out\n```\nReturn `m95243.py` with types and O(n) average.\n\n```python\n# m95243.py\nfrom __future__ import annotations\nfrom typing import Iterable, List, Set, TypeVar\nT=TypeVar(\"T\")\n\ndef f66701(xs: Iterable[T]) -> List[T]:\n \"\"\"Unique items preserving first-seen order.\"\"\"\n seen: Set[T]=set()\n out: List[T]=[]\n for x in xs:\n if x in seen: continue\n seen.add(x); out.append(x)\n return out\n```", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Optimize while preserving behavior and order.\n\n```python\ndef f69219(xs):\n out=[]\n for x in xs:\n if x not in out: out.append(x)\n return out\n```\nReturn `m81317.py` with types and O(n) average.\n\n```python\n# m81317.py\nfrom __future__ import annotations\nfrom typing import Iterable, List, Set, TypeVar\nT=TypeVar(\"T\")\n\ndef f69219(xs: Iterable[T]) -> List[T]:\n \"\"\"Unique items preserving first-seen order.\"\"\"\n seen: Set[T]=set()\n out: List[T]=[]\n for x in xs:\n if x in seen: continue\n seen.add(x); out.append(x)\n return out\n```", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Optimize while preserving behavior and order.\n\n```python\ndef f30763(xs):\n out=[]\n for x in xs:\n if x not in out: out.append(x)\n return out\n```\nReturn `m90109.py` with types and O(n) average.\n\n```python\n# m90109.py\nfrom __future__ import annotations\nfrom typing import Iterable, List, Set, TypeVar\nT=TypeVar(\"T\")\n\ndef f30763(xs: Iterable[T]) -> List[T]:\n \"\"\"Unique items preserving first-seen order.\"\"\"\n seen: Set[T]=set()\n out: List[T]=[]\n for x in xs:\n if x in seen: continue\n seen.add(x); out.append(x)\n return out\n```", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Write pytest tests for `f17378`.\n\n```python\ndef f17378(a: int, b: int) -> int:\n return a*a + b*b\n```\nInclude edge cases and a property-style check.\n\n```python\nimport random\nfrom m31054 import f17378\n\ndef test_known():\n assert f17378(3,4) == 25\n\ndef test_zero():\n assert f17378(0,0) == 0\n\ndef test_property_nonnegative():\n for _ in range(200):\n a=random.randint(-50,50)\n b=random.randint(-50,50)\n assert f17378(a,b) >= 0\n```", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Optimize while preserving behavior.\n\nFile: ppwppuz.py\n```python\ndef uaj5noj3(xs):\n out = []\n for x in xs:\n if x not in out:\n out.append(x)\n return out\n```\n\nRequirements: preserve first-seen order; O(n) average; add types + docstring.\n\n# ppwppuz.py\nfrom __future__ import annotations\nfrom typing import Iterable, List, Set, TypeVar\n\nT = TypeVar(\"T\")\n\ndef uaj5noj3(xs: Iterable[T]) -> List[T]:\n \"\"\"Return unique items preserving first-seen order.\"\"\"\n seen: Set[T] = set()\n out: List[T] = []\n for x in xs:\n if x in seen:\n continue\n seen.add(x)\n out.append(x)\n return out", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Fix a bug and add tests.\n\nFile: gu3ag4.py\n```python\ndef ar2awc_64xyx(n: int) -> int:\n \"\"\"Sum 1..n inclusive.\"\"\"\n if n < 0:\n raise ValueError(\"n must be non-negative\")\n total = 0\n for k in range(n): # BUG: should include n\n total += k\n return total\n```\n\nReturn unified diffs for gu3ag4.py and test_gu3ag4.py (pytest).\n\n*** Begin Patch\n*** Update File: gu3ag4.py\n@@\n def ar2awc_64xyx(n: int) -> int:\n@@\n total = 0\n- for k in range(n): # BUG: should include n\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_gu3ag4.py\n+import pytest\n+from gu3ag4 import ar2awc_64xyx\n+\n+def test_zero():\n+ assert ar2awc_64xyx(0) == 0\n+\n+def test_one():\n+ assert ar2awc_64xyx(1) == 1\n+\n+def test_small():\n+ assert ar2awc_64xyx(7) == 28\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ ar2awc_64xyx(-1)\n+\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Create a comprehensive test plan and automated tests for webhooks in a enterprise SaaS product.\nTarget platform: CI (GitHub Actions).\nRequirements: unit/integration tests, edge cases, load tests strategy, and CI gates.\nConstraints: must avoid global state, must include documentation/comments, must be secure-by-default.\nDifficulty: easy. Include rollback strategy.\n\nOutput: actionable implementation and verification artifacts.\nDeliverable: test plan + automation guidance.\n\n**Unit tests**\n- Validation: malformed payloads rejected with correct codes.\n- AuthZ: tenant boundary enforced.\n- Idempotency: replay returns same response; conflicting reuse yields 409.\n\n**Integration tests**\n- DB transaction behavior; unique constraints.\n- Cache behavior: correctness under concurrent requests.\n\n**Load tests**\n- 10k RPS target: measure p95 latency, error rate, saturation.\n\n**CI gates**\n- Lint + typecheck + unit tests required.\n- Coverage threshold for critical modules.\n- Block merge on flaky test detection.\n\n\nChecks: input validation, tests, and safe defaults included.", "source": "WithinUsAI/GOD_Coder_100k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Fix a bug and add tests.\n\nFile: b_g7os5v6rgp.py\n```python\ndef h48yngb(n: int) -> int:\n \"\"\"Sum 1..n inclusive.\"\"\"\n if n < 0:\n raise ValueError(\"n must be non-negative\")\n total = 0\n for k in range(n): # BUG: should include n\n total += k\n return total\n```\n\nReturn unified diffs for b_g7os5v6rgp.py and test_b_g7os5v6rgp.py (pytest).\n\n*** Begin Patch\n*** Update File: b_g7os5v6rgp.py\n@@\n def h48yngb(n: int) -> int:\n@@\n total = 0\n- for k in range(n): # BUG: should include n\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_b_g7os5v6rgp.py\n+import pytest\n+from b_g7os5v6rgp import h48yngb\n+\n+def test_zero():\n+ assert h48yngb(0) == 0\n+\n+def test_one():\n+ assert h48yngb(1) == 1\n+\n+def test_small():\n+ assert h48yngb(7) == 28\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ h48yngb(-1)\n+\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Build an elite-grade solution in the domain of networking for scenario: rate limiting gateway.\nPrimary language: rust.\nDifficulty: expert.\nConstraints: avoid undefined behavior and data races, include tests or verification strategy, include invariants and failure modes, assume untrusted inputs; validate and sanitize.\nComponent: component_gubnuyn.\nAssume schema changes every sprint; must be backward compatible.\nTask: Design a replication/consistency approach (e.g., leader-based, quorum reads/writes). Provide message flows, failure handling, and a minimal reference implementation skeleton.\n\nOutput: elite-grade engineering answer with contracts, edge cases, and verification.\nOutput: replication design + failure handling + minimal skeleton.\n\n**Model**\n- Leader-based replication with term + log index.\n- Quorum acks for durability: write committed when majority acks.\n- Read options: leader-read (linearizable) or quorum-read (monotonic if using read-index).\n\n**Message flow (write)**\n1. Client → Leader: Put(request_id, payload)\n2. Leader appends to log, sends AppendEntries to followers\n3. Followers append + ack\n4. On majority ack: commit index advances; apply to state machine; respond to client\n\n**Failure modes**\n- Leader crash: new election; uncommitted entries may be rolled back.\n- Partition: minority side cannot commit.\n- Duplicate requests: deduplicate by request_id stored in state.\n\n**Skeleton (Go pseudo)**\n```go\ntype Entry struct { Term uint64; Index uint64; Cmd []byte }\ntype Node struct {\n id int\n term uint64\n log []Entry\n commit uint64\n seen map[string][]byte // request_id -> response\n}\n```\n\n**Verification**\n- Invariant: committed index never decreases.\n- Property: if a write is committed, all future leaders contain it.\n- Test with simulated partitions and crash/restart.\n\n\nExpert checks: state-machine reasoning, concurrency stress, and upgrade/rollback validated.", "source": "WithinUsAI/Elite_GOD_Coder_100k"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: System domain: search service\nStack: Next.js, Node.js, Prisma, PostgreSQL, Playwright, Docker\nCross-layer incident: migration ordering failure\nTask type: full_stack_bug_fix\nDifficulty: hard\n\nSolve this as a complete-project engineer.\nOutput must include:\n- root cause across layers\n- final implementation patch\n- tests touching at least two layers\n- deployment or observability note\n- verification commands\n\nRepository sketch:\nrepo/\n src/App/Program.cs\n src/App/Service.cs\n tests/App.Tests/ServiceTests.cs\n App.sln\n\nFocus: Focus on multi-layer debugging across frontend, backend, database, CI, caching, and deployment.\n\nassistant: Diagnosis:\n- Root cause: migration ordering failure crosses service boundaries, so the fix must align code, contracts, tests, and deployment behavior.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```csharp\nusing System;\nusing System.Collections.Generic;\n\npublic static class RequestHandler\n{\n public static Dictionary HandleRequest(Dictionary payload)\n {\n var clean = new Dictionary();\n foreach (var entry in payload)\n {\n if (entry.Value != null)\n clean[entry.Key.Trim()] = entry.Value;\n }\n if (!clean.ContainsKey(\"id\"))\n throw new ArgumentException(\"missing id\");\n return new Dictionary\n {\n [\"ok\"] = true,\n [\"data\"] = clean\n };\n }\n}\n```\n\nTests:\n```csharp\nusing System;\nusing System.Collections.Generic;\nusing Xunit;\n\npublic class RequestHandlerTests\n{\n [Fact]\n public void RequiresId()\n {\n Assert.Throws(() => RequestHandler.HandleRequest(new Dictionary { [\"name\"] = \"x\" }));\n }\n}\n```\n\nVerification:\n- `dotnet test`\n- `dotnet build`\n\nEngineering notes:\n- Language: C#\n- Framework/tooling: ASP.NET Core\n- Stack context: Next.js, Node.js, Prisma, PostgreSQL, Playwright, Docker\n- Domain: search service\n- Task type: full_stack_bug_fix\n- Difficulty: hard\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: Repository domain: job scheduler\nPrimary language: Java\nFramework/tooling: Hibernate\nReported problem: JWT refresh token rotation\nTask type: code_review_fix\nDifficulty: medium\n\nProduce a complete professional engineering response:\n1. Diagnose the root cause.\n2. Provide the corrected implementation or patch.\n3. Add tests.\n4. Add verification commands.\n5. Note edge cases and any migration or rollback risk.\n\nRepository sketch:\nrepo/\n src/main/java/com/acme/App.java\n src/main/java/com/acme/Service.java\n src/test/java/com/acme/AppTest.java\n pom.xml\n\nQuality target:\n- Minimal diff unless redesign is clearly required\n- Production-ready code\n- No placeholders\n- Secure defaults\n- Clear acceptance of failure cases\n\nFocus: Focus on complete implementation quality, patch correctness, tests, and production readiness.\n\nassistant: Diagnosis:\n- Root cause: the failure around JWT refresh token rotation is caused by missing validation, weak edge-case handling, or unsafe lifecycle behavior in the current implementation.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```java\nimport java.util.HashMap;\nimport java.util.Map;\n\npublic final class RequestHandler {\n public static Map handleRequest(Map payload) {\n Map clean = new HashMap<>();\n for (Map.Entry entry : payload.entrySet()) {\n if (entry.getValue() != null) clean.put(entry.getKey().trim(), entry.getValue());\n }\n if (!clean.containsKey(\"id\")) throw new IllegalArgumentException(\"missing id\");\n return Map.of(\"ok\", true, \"data\", clean);\n }\n}\n```\n\nTests:\n```java\nimport static org.junit.jupiter.api.Assertions.*;\nimport java.util.Map;\nimport org.junit.jupiter.api.Test;\n\nclass RequestHandlerTest {\n @Test\n void requiresId() {\n assertThrows(IllegalArgumentException.class, () -> RequestHandler.handleRequest(Map.of(\"name\", \"x\")));\n }\n}\n```\n\nVerification:\n- `./gradlew test`\n- `mvn test`\n\nEngineering notes:\n- Language: Java\n- Framework/tooling: Hibernate\n- Stack context: Airflow, dbt, DuckDB, MinIO, pytest\n- Domain: job scheduler\n- Task type: code_review_fix\n- Difficulty: medium\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Fix a bug and add tests.\n\nFile: zfd33a.py\n```python\ndef ga7txb9(n: int) -> int:\n \"\"\"Sum 1..n inclusive.\"\"\"\n if n < 0:\n raise ValueError(\"n must be non-negative\")\n total = 0\n for k in range(n): # BUG: should include n\n total += k\n return total\n```\n\nReturn unified diffs for zfd33a.py and test_zfd33a.py (pytest).\n\n*** Begin Patch\n*** Update File: zfd33a.py\n@@\n def ga7txb9(n: int) -> int:\n@@\n total = 0\n- for k in range(n): # BUG: should include n\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_zfd33a.py\n+import pytest\n+from zfd33a import ga7txb9\n+\n+def test_zero():\n+ assert ga7txb9(0) == 0\n+\n+def test_one():\n+ assert ga7txb9(1) == 1\n+\n+def test_small():\n+ assert ga7txb9(7) == 28\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ ga7txb9(-1)\n+\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: Repository domain: notification service\nPrimary language: JavaScript\nFramework/tooling: React\nReported problem: S3-compatible upload inconsistency\nTask type: code_review_fix\nDifficulty: medium\n\nProduce a complete professional engineering response:\n1. Diagnose the root cause.\n2. Provide the corrected implementation or patch.\n3. Add tests.\n4. Add verification commands.\n5. Note edge cases and any migration or rollback risk.\n\nRepository sketch:\nrepo/\n src/\n api.js\n service.js\n utils.js\n tests/\n api.test.js\n package.json\n\nQuality target:\n- Minimal diff unless redesign is clearly required\n- Production-ready code\n- No placeholders\n- Secure defaults\n- Clear acceptance of failure cases\n\nFocus: Focus on complete implementation quality, patch correctness, tests, and production readiness.\n\nassistant: Diagnosis:\n- Root cause: the failure around S3-compatible upload inconsistency is caused by missing validation, weak edge-case handling, or unsafe lifecycle behavior in the current implementation.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```javascript\ntype Payload = Record;\n\nexport function normalizePayload(payload: Payload): Payload {\n if (!payload || typeof payload !== \"object\" || Array.isArray(payload)) {\n throw new TypeError(\"payload must be a plain object\");\n }\n return Object.fromEntries(\n Object.entries(payload)\n .filter(([, value]) => value !== null && value !== undefined)\n .map(([key, value]) => [String(key).trim(), value])\n );\n}\n\nexport function handleS3CompatibleUploadInconsistency(payload: Payload) {\n const clean = normalizePayload(payload);\n if (!(\"id\" in clean)) {\n return { ok: false, data: {}, error: \"missing id\" };\n }\n return { ok: true, data: clean, error: null };\n}\n```\n\nTests:\n```javascript\nimport { describe, it, expect } from \"vitest\";\nimport { handleS3CompatibleUploadInconsistency } from \"../src/service\";\n\ndescribe(\"handler\", () => {\n it(\"accepts valid input\", () => {\n expect(handleS3CompatibleUploadInconsistency({ id: 7, name: \"ok\", unused: null })).toEqual({\n ok: true,\n data: { id: 7, name: \"ok\" },\n error: null\n });\n });\n\n it(\"rejects missing id\", () => {\n expect(handleS3CompatibleUploadInconsistency({ name: \"x\" }).error).toMatch(/missing id/);\n });\n});\n```\n\nVerification:\n- `npm test`\n- `npm run lint`\n\nEngineering notes:\n- Language: JavaScript\n- Framework/tooling: React\n- Stack context: Next.js, Node.js, Prisma, PostgreSQL, Playwright, Docker\n- Domain: notification service\n- Task type: code_review_fix\n- Difficulty: medium\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "Fix a subtle bug in a Python module used for data modeling.\nRequirements: explain root cause briefly, provide corrected code, and add regression tests.\nConstraints: must include tests, stdlib-only, must be streaming-friendly, must include docstrings.\nDifficulty: easy. Provide helpful exceptions with actionable messages.\n\nDeliverable: production-ready reference solution.\n```python\nfrom __future__ import annotations\n\nfrom dataclasses import dataclass\nfrom pathlib import Path\nfrom typing import Iterable\nimport json\n\n\nclass ValidationError(ValueError):\n \"\"\"Raised when input validation fails.\"\"\"\n\n\ndef safe_join(base: Path, *parts: str) -> Path:\n \"\"\"Join paths while preventing traversal outside base.\"\"\"\n b = base.resolve()\n p = (b / Path(*parts)).resolve()\n if p != b and b not in p.parents:\n raise ValidationError(f\"unsafe path: {p}\")\n return p\n\n\n@dataclass(frozen=True, slots=True)\nclass Record:\n key: str\n value: int\n\n\ndef parse_jsonl(lines: Iterable[str]) -> list[Record]:\n out: list[Record] = []\n for idx, line in enumerate(lines, 1):\n s = line.strip()\n if not s:\n continue\n try:\n obj = json.loads(s)\n except json.JSONDecodeError as e:\n raise ValidationError(f\"line {idx}: invalid json\") from e\n if not isinstance(obj, dict):\n raise ValidationError(f\"line {idx}: expected object\")\n key = obj.get(\"key\")\n val = obj.get(\"value\")\n if not isinstance(key, str) or not key:\n raise ValidationError(f\"line {idx}: key must be non-empty str\")\n if not isinstance(val, int):\n raise ValidationError(f\"line {idx}: value must be int\")\n out.append(Record(key, val))\n return out\n\n\ndef write_jsonl(base: Path, rel: str, records: Iterable[Record]) -> Path:\n base.mkdir(parents=True, exist_ok=True)\n dst = safe_join(base, rel)\n dst.parent.mkdir(parents=True, exist_ok=True)\n with dst.open(\"w\", encoding=\"utf-8\", newline=\"\\n\") as f:\n for r in records:\n f.write(json.dumps({\"key\": r.key, \"value\": r.value}, ensure_ascii=False) + \"\\n\")\n return dst\n```\n\n```python\n# tests (pytest-style)\nimport json\nfrom pathlib import Path\nimport pytest\nfrom module_under_test import ValidationError, Record, parse_jsonl, write_jsonl\n\ndef test_parse_ok():\n lines = [json.dumps({\"key\":\"a\",\"value\":1}), json.dumps({\"key\":\"b\",\"value\":2})]\n assert parse_jsonl(lines) == [Record(\"a\",1), Record(\"b\",2)]\n\ndef test_parse_rejects_bad_json():\n with pytest.raises(ValidationError):\n parse_jsonl([\"{not json}\"])\n\ndef test_safe_join_blocks_traversal(tmp_path: Path):\n with pytest.raises(ValidationError):\n write_jsonl(tmp_path, \"../x.jsonl\", [Record(\"a\",1)])\n```", "source": "WithinUsAI/python_GOD_coder_100k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Fix a bug and add tests.\n\nFile: hktb_ucap8u.py\n```python\ndef x8k3z7p_h3m5(n: int) -> int:\n \"\"\"Sum 1..n inclusive.\"\"\"\n if n < 0:\n raise ValueError(\"n must be non-negative\")\n total = 0\n for k in range(n): # BUG: should include n\n total += k\n return total\n```\n\nReturn unified diffs for hktb_ucap8u.py and test_hktb_ucap8u.py (pytest).\n\n*** Begin Patch\n*** Update File: hktb_ucap8u.py\n@@\n def x8k3z7p_h3m5(n: int) -> int:\n@@\n total = 0\n- for k in range(n): # BUG: should include n\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_hktb_ucap8u.py\n+import pytest\n+from hktb_ucap8u import x8k3z7p_h3m5\n+\n+def test_zero():\n+ assert x8k3z7p_h3m5(0) == 0\n+\n+def test_one():\n+ assert x8k3z7p_h3m5(1) == 1\n+\n+def test_small():\n+ assert x8k3z7p_h3m5(7) == 28\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ x8k3z7p_h3m5(-1)\n+\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Optimize while preserving behavior and order.\n\n```python\ndef f70137(xs):\n out=[]\n for x in xs:\n if x not in out: out.append(x)\n return out\n```\nReturn `m38591.py` with types and O(n) average.\n\n```python\n# m38591.py\nfrom __future__ import annotations\nfrom typing import Iterable, List, Set, TypeVar\nT=TypeVar(\"T\")\n\ndef f70137(xs: Iterable[T]) -> List[T]:\n \"\"\"Unique items preserving first-seen order.\"\"\"\n seen: Set[T]=set()\n out: List[T]=[]\n for x in xs:\n if x in seen: continue\n seen.add(x); out.append(x)\n return out\n```", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Design a production system for calendar/scheduling supporting offline-first sync.\nTarget platform: backend (Node.js).\nRequirements: APIs, data model, scaling strategy, failure modes, and security.\nConstraints: must include clear error handling, must include tests, must include documentation/comments, must avoid global state.\nDifficulty: expert. Assume PII must be protected.\n\nOutput: design + implementation guidance suitable for shipping.\nDeliverable: system design with APIs, data model, and operational plan.\n\n**High-level architecture**\n- Edge: API Gateway + WAF\n- Core service: stateless app pods behind L7 LB\n- Data: Postgres (primary), Redis (cache + rate limit tokens), Object storage (uploads if needed)\n- Async: message queue (e.g., SQS/Rabbit) + worker pool for background jobs\n- Observability: structured logs + metrics + tracing\n\n**APIs (example)**\n- `POST /v1/{resource}` create (idempotent via `Idempotency-Key`)\n- `GET /v1/{resource}/{id}` read\n- `POST /v1/{resource}/{id}:action` command endpoint when side effects exist\n\n**Data model (Postgres)**\n- `resources(id UUID PK, tenant_id UUID, status TEXT, payload JSONB, created_at, updated_at)`\n- Unique constraint for idempotency: `(tenant_id, idempotency_key)` in a separate table:\n - `idempotency(tenant_id, key TEXT, request_hash TEXT, response JSONB, created_at, PRIMARY KEY(tenant_id,key))`\n\n**Scaling**\n- App layer scales horizontally; keep sessions out of process.\n- Cache reads in Redis; write-through invalidation on mutations.\n- Use connection pooling; consider read replicas for heavy reads.\n\n**Failure modes**\n- Retries: only for safe/ idempotent operations; exponential backoff + jitter.\n- Partial failures: background jobs must be idempotent; use a de-dup key.\n\n**Security**\n- AuthN: JWT/OIDC; AuthZ: RBAC/ABAC with tenant isolation\n- Validate all inputs; enforce per-tenant quotas/rate limits.\n\n**Rollout**\n- Dark launch + feature flags; canary; rapid rollback by toggling flags.\n\n\nHard-mode checks: concurrency safety, idempotency, and rollback validated; add chaos tests where feasible.", "source": "WithinUsAI/GOD_Coder_100k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Refactor to modern typed Python with immutability and tests.\n\nFile: msgkp4q.py\n```python\nclass Jyj7Wveb:\n def __init__(self, name, values):\n self.name = name\n self.values = list(values)\n def add(self, v):\n self.values.append(v)\n def mean(self):\n s = 0\n for x in self.values:\n s += x\n return s / len(self.values)\n```\n\nReturn full new msgkp4q.py and test_msgkp4q.py.\n\n# msgkp4q.py\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom typing import Iterable, Tuple\n\n@dataclass(frozen=True)\nclass Jyj7Wveb:\n name: str\n values: Tuple[float, ...]\n\n @staticmethod\n def create(name: str, values: Iterable[float]) -> \"Jyj7Wveb\":\n vals = tuple(float(v) for v in values)\n if not vals:\n raise ValueError(\"values must be non-empty\")\n return Jyj7Wveb(name=name, values=vals)\n\n def add(self, v: float) -> \"Jyj7Wveb\":\n return Jyj7Wveb(name=self.name, values=self.values + (float(v),))\n\n def mean(self) -> float:\n return sum(self.values) / len(self.values)\n\n# test_msgkp4q.py\nimport pytest\nfrom msgkp4q import Jyj7Wveb\n\ndef test_mean_and_add():\n c = Jyj7Wveb.create(\"a\", [1, 2, 3])\n assert c.mean() == 2.0\n assert c.add(5).mean() == (1 + 2 + 3 + 5) / 4\n\ndef test_empty_raises():\n with pytest.raises(ValueError):\n Jyj7Wveb.create(\"x\", [])", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: Language: Bash\nFramework/tooling: sed\nDomain: observability collector\nLogic challenge: websocket reconnect storm\nTask type: backwards_compatible_redesign\nDifficulty: hard\n\nReturn a rigorous engineering answer:\n- identify the hidden root cause or logical failure\n- present the corrected implementation\n- add tests that prove the fix\n- list verification commands\n- explain why naive fixes are insufficient when relevant\n\nRepository sketch:\nrepo/\n scripts/\n run.sh\n deploy.sh\n tests/\n smoke.sh\n\nFocus: Focus on staff-level problem solving with multi-file patches, rollout implications, performance and security tradeoffs.\n\nassistant: Diagnosis:\n- Staff-level diagnosis: websocket reconnect storm impacts correctness, operability, and future maintenance, so the fix must be minimal where possible but complete where necessary.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```bash\n#!/usr/bin/env bash\nset -euo pipefail\n\ninput=\"${1:-}\"\nif [[ -z \"$input\" ]]; then\n echo \"missing input\" >&2\n exit 1\nfi\n\nprintf '%s\n' \"$input\" | tr -d '\r'\n```\n\nTests:\n```bash\noutput=\"$(bash scripts/run.sh \"abc\")\"\ntest \"$output\" = \"abc\"\n```\n\nVerification:\n- `bash tests/smoke.sh`\n- `shellcheck scripts/*.sh`\n\nEngineering notes:\n- Language: Bash\n- Framework/tooling: sed\n- Stack context: FastAPI, PostgreSQL, Redis, Celery, pytest, Docker\n- Domain: observability collector\n- Task type: backwards_compatible_redesign\n- Difficulty: hard\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "Write pytest tests for `f70829`.\n\n```python\ndef f70829(a: int, b: int) -> int:\n return a*a + b*b\n```\nInclude edge cases and a property-style check.\n\n```python\nimport random\nfrom m81547 import f70829\n\ndef test_known():\n assert f70829(3,4) == 25\n\ndef test_zero():\n assert f70829(0,0) == 0\n\ndef test_property_nonnegative():\n for _ in range(200):\n a=random.randint(-50,50)\n b=random.randint(-50,50)\n assert f70829(a,b) >= 0\n```", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Task type: storage_engine\nScenario: graph query service\nDomain focus: distributed storage\nPrimary language: typescript\nDifficulty: hard\nScale/SLO: 1M msgs/min\nComponent: component_mqjvipkt\nConstraints: include test vectors and fuzz strategy, include failure modes and recovery, explicit contracts and invariants, avoid data races and undefined behavior, include security threat model (defensive only), include deterministic replay plan\nAssume hostile inputs and targeted abuse patterns.\nDeliverable: Design a storage engine subsystem (WAL, snapshots, compaction). Include crash recovery invariants and a benchmark plan.\n\nOutput: elite engineering answer optimized for correctness, performance, and operability.\n**Contract**\n- Inputs validated at the boundary; explicit error taxonomy.\n- Idempotency for side effects via request_id; deterministic replay.\n- Backward compatibility: additive changes by default; versioned breaking changes.\n**Invariants**\n- Isolation: tenant boundary enforced; no cross-tenant reads/writes.\n- Determinism: replay of the same event log yields identical outputs.\n- Safety: state transitions preserve invariants; no partial commit leaks.\n**Failure modes & recovery**\n- Duplicate requests: de-duplicate by (tenant, request_id) returning cached response.\n- Crash during commit: WAL replay completes or transaction aborts; no torn writes.\n- Data corruption: checksums + scrubber; quarantine and rebuild from replicas/snapshots.\n**Security posture (defensive)**\n- Threat model: auth/authz, injection, replay/abuse, supply chain.\n- Least privilege; secrets in managed store; audit logs for sensitive ops.\n- Input normalization, parameterized queries, path traversal protections.\n**Verification strategy**\n- Canary + shadow traffic; invariants checked in production via assertions/metrics.\n- Property tests against a pure reference model (state machine).\n- Deterministic simulation with fault injection (crash/partition/latency).\n\n**Snippet**\n```text\nImplementation sketch: factor pure state-machine core; adapters for I/O; add deterministic replay log.\n```\nHard checks: fault injection tests gate merges; perf thresholds enforced in CI.", "source": "WithinUsAI/Omega_Genesis_Coder_100k"} {"text": "Build an elite-grade solution in the domain of realtime systems for scenario: multi-tenant SaaS.\nPrimary language: python.\nDifficulty: hard.\nConstraints: document performance characteristics, design for backward compatibility and migrations, avoid undefined behavior and data races, provide rollout and rollback guidance, assume untrusted inputs; validate and sanitize.\nComponent: component_ommmmql.\nAssume strict auditability and replayable history.\nTask: Design a replication/consistency approach (e.g., leader-based, quorum reads/writes). Provide message flows, failure handling, and a minimal reference implementation skeleton.\n\nOutput: elite-grade engineering answer with contracts, edge cases, and verification.\nOutput: replication design + failure handling + minimal skeleton.\n\n**Model**\n- Leader-based replication with term + log index.\n- Quorum acks for durability: write committed when majority acks.\n- Read options: leader-read (linearizable) or quorum-read (monotonic if using read-index).\n\n**Message flow (write)**\n1. Client → Leader: Put(request_id, payload)\n2. Leader appends to log, sends AppendEntries to followers\n3. Followers append + ack\n4. On majority ack: commit index advances; apply to state machine; respond to client\n\n**Failure modes**\n- Leader crash: new election; uncommitted entries may be rolled back.\n- Partition: minority side cannot commit.\n- Duplicate requests: deduplicate by request_id stored in state.\n\n**Skeleton (Go pseudo)**\n```go\ntype Entry struct { Term uint64; Index uint64; Cmd []byte }\ntype Node struct {\n id int\n term uint64\n log []Entry\n commit uint64\n seen map[string][]byte // request_id -> response\n}\n```\n\n**Verification**\n- Invariant: committed index never decreases.\n- Property: if a write is committed, all future leaders contain it.\n- Test with simulated partitions and crash/restart.\n\n\nHard checks: failure injection tests and performance regressions gated.", "source": "WithinUsAI/Elite_GOD_Coder_100k"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: Language: Go\nFramework/tooling: Fiber\nDomain: document processing API\nLogic challenge: monorepo toolchain skew\nTask type: distributed_debug\nDifficulty: hard\n\nReturn a rigorous engineering answer:\n- identify the hidden root cause or logical failure\n- present the corrected implementation\n- add tests that prove the fix\n- list verification commands\n- explain why naive fixes are insufficient when relevant\n\nRepository sketch:\nrepo/\n cmd/server/main.go\n internal/service/service.go\n internal/store/store.go\n internal/api/api.go\n service_test.go\n go.mod\n\nFocus: Focus on ambiguity, misleading symptoms, hidden root causes, and high-stakes debugging.\n\nassistant: Diagnosis:\n- Hidden root cause: monorepo toolchain skew presents misleading symptoms, so the patch must target the actual logic boundary rather than the first visible failure.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```go\npackage service\n\nimport \"fmt\"\n\nfunc NormalizePayload(payload map[string]any) map[string]any {\n\tout := make(map[string]any)\n\tfor k, v := range payload {\n\t\tif v == nil {\n\t\t\tcontinue\n\t\t}\n\t\tout[k] = v\n\t}\n\treturn out\n}\n\nfunc Handle(payload map[string]any) (map[string]any, error) {\n\tclean := NormalizePayload(payload)\n\tif _, ok := clean[\"id\"]; !ok {\n\t\treturn nil, fmt.Errorf(\"missing id\")\n\t}\n\treturn map[string]any{\"ok\": true, \"data\": clean}, nil\n}\n```\n\nTests:\n```go\npackage service\n\nimport \"testing\"\n\nfunc TestHandle(t *testing.T) {\n\tgot, err := Handle(map[string]any{\"id\": 7, \"name\": \"ok\", \"unused\": nil})\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tif got[\"ok\"] != true {\n\t\tt.Fatalf(\"expected ok=true\")\n\t}\n\tif _, err := Handle(map[string]any{\"name\": \"x\"}); err == nil {\n\t\tt.Fatalf(\"expected missing id error\")\n\t}\n}\n```\n\nVerification:\n- `go test ./...`\n- `go vet ./...`\n\nEngineering notes:\n- Language: Go\n- Framework/tooling: Fiber\n- Stack context: FastAPI, PostgreSQL, Redis, Celery, pytest, Docker\n- Domain: document processing API\n- Task type: distributed_debug\n- Difficulty: hard\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "Refactor to typed, mostly-immutable Python and add minimal tests.\n\n```python\nclass C25046:\n def __init__(self, values): self.values=list(values)\n def mean(self): return sum(self.values)/len(self.values)\n```\nReturn `m86542.py` and `test_m86542.py`.\n\n```python\n# m86542.py\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom typing import Iterable, Tuple\n\n@dataclass(frozen=True)\nclass C25046:\n values: Tuple[float, ...]\n\n @staticmethod\n def create(values: Iterable[float]) -> \"C25046\":\n vals = tuple(float(v) for v in values)\n if not vals: raise ValueError(\"empty\")\n return C25046(vals)\n\n def mean(self) -> float:\n return sum(self.values)/len(self.values)\n```\n\n```python\n# test_m86542.py\nimport pytest\nfrom m86542 import C25046\n\ndef test_mean():\n assert C25046.create([1,2,3]).mean() == 2.0\ndef test_empty():\n with pytest.raises(ValueError):\n C25046.create([])\n```", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Optimize while preserving behavior.\n\nFile: n9wak9bhf.py\n```python\ndef d764fgiz1(xs):\n out = []\n for x in xs:\n if x not in out:\n out.append(x)\n return out\n```\n\nRequirements: preserve first-seen order; O(n) average; add types + docstring.\n\n# n9wak9bhf.py\nfrom __future__ import annotations\nfrom typing import Iterable, List, Set, TypeVar\n\nT = TypeVar(\"T\")\n\ndef d764fgiz1(xs: Iterable[T]) -> List[T]:\n \"\"\"Return unique items preserving first-seen order.\"\"\"\n seen: Set[T] = set()\n out: List[T] = []\n for x in xs:\n if x in seen:\n continue\n seen.add(x)\n out.append(x)\n return out", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Optimize while preserving behavior and order.\n\n```python\ndef f93695(xs):\n out=[]\n for x in xs:\n if x not in out: out.append(x)\n return out\n```\nReturn `m13385.py` with types and O(n) average.\n\n```python\n# m13385.py\nfrom __future__ import annotations\nfrom typing import Iterable, List, Set, TypeVar\nT=TypeVar(\"T\")\n\ndef f93695(xs: Iterable[T]) -> List[T]:\n \"\"\"Unique items preserving first-seen order.\"\"\"\n seen: Set[T]=set()\n out: List[T]=[]\n for x in xs:\n if x in seen: continue\n seen.add(x); out.append(x)\n return out\n```", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Task type: kernel_syscall_design\nScenario: payment ledger\nDomain focus: constraint solving\nPrimary language: c\nDifficulty: expert\nScale/SLO: 1M msgs/min\nComponent: component_enkkgwec\nConstraints: include security threat model (defensive only), include verification strategy, avoid data races and undefined behavior, include performance model and limits, include backward compatibility and migration plan, include failure modes and recovery, include test vectors and fuzz strategy\nAssume crash-only processes; recovery must be deterministic.\nDeliverable: Design a safe syscall/API boundary: ABI, validation, error codes, and compatibility; include tests and fuzz plan.\n\nOutput: rigorous design + invariants + verification plan + implementation sketch.\n**Contract**\n- Inputs validated at the boundary; explicit error taxonomy.\n- Idempotency for side effects via request_id; deterministic replay.\n- Backward compatibility: additive changes by default; versioned breaking changes.\n**Invariants**\n- Liveness: under bounded faults and stable network, progress occurs.\n- Safety: state transitions preserve invariants; no partial commit leaks.\n- Determinism: replay of the same event log yields identical outputs.\n**Failure modes & recovery**\n- Duplicate requests: de-duplicate by (tenant, request_id) returning cached response.\n- Data corruption: checksums + scrubber; quarantine and rebuild from replicas/snapshots.\n- Network partition: minority cannot commit; clients receive retriable errors.\n**Security posture (defensive)**\n- Threat model: auth/authz, injection, replay/abuse, supply chain.\n- Least privilege; secrets in managed store; audit logs for sensitive ops.\n- Input normalization, parameterized queries, path traversal protections.\n**Verification strategy**\n- Canary + shadow traffic; invariants checked in production via assertions/metrics.\n- Deterministic simulation with fault injection (crash/partition/latency).\n- Fuzzing of parsers/framers/validators with corpus seeds.\n\n**Snippet**\n```text\nImplementation sketch: factor pure state-machine core; adapters for I/O; add deterministic replay log.\n```\nExpert checks: state-machine proof sketch + model checking; upgrade/rollback rehearsed.", "source": "WithinUsAI/Omega_Genesis_Coder_100k"} {"text": "Debug and fix a subtle production bug related to real-time notifications in a logistics service.\nTarget platform: backend (Node.js).\nRequirements: identify root cause, provide patch, and add regression tests.\nConstraints: must be secure-by-default, must be observable (logs/metrics/traces), must include tests, must be production-ready.\nDifficulty: hard. Assume untrusted input; validate everything.\n\nOutput: actionable implementation and verification artifacts.\nDeliverable: production-grade reference implementation (FastAPI) + tests.\n\n```python\n# app.py\nfrom __future__ import annotations\n\nimport hashlib\nimport json\nfrom dataclasses import dataclass\nfrom datetime import datetime, timezone\nfrom typing import Any, Optional\n\nfrom fastapi import FastAPI, Header, HTTPException\nfrom pydantic import BaseModel, Field\n\napp = FastAPI(title=\"Idempotent API\")\n\nclass CreateReq(BaseModel):\n tenant_id: str = Field(min_length=1)\n amount_cents: int = Field(ge=0)\n currency: str = Field(min_length=3, max_length=3)\n\nclass CreateResp(BaseModel):\n id: str\n created_at: str\n echo: CreateReq\n\n@dataclass\nclass _IdempoEntry:\n request_hash: str\n response_json: str\n\n# In production: Postgres table with UNIQUE(tenant_id, key)\n_IDEMPO: dict[tuple[str, str], _IdempoEntry] = {}\n\ndef _hash_req(req: CreateReq) -> str:\n raw = req.model_dump_json()\n return hashlib.sha256(raw.encode(\"utf-8\")).hexdigest()\n\n@app.post(\"/v1/payments\", response_model=CreateResp)\ndef create_payment(\n req: CreateReq,\n idempotency_key: Optional[str] = Header(default=None, alias=\"Idempotency-Key\"),\n) -> Any:\n if not idempotency_key:\n raise HTTPException(status_code=400, detail=\"Missing Idempotency-Key\")\n if len(idempotency_key) > 128:\n raise HTTPException(status_code=400, detail=\"Idempotency-Key too long\")\n\n key = (req.tenant_id, idempotency_key)\n rh = _hash_req(req)\n\n existing = _IDEMPO.get(key)\n if existing:\n if existing.request_hash != rh:\n raise HTTPException(status_code=409, detail=\"Idempotency-Key reuse with different payload\")\n return json.loads(existing.response_json)\n\n # Create new payment (stubbed)\n pid = hashlib.md5(f\"{req.tenant_id}:{idempotency_key}\".encode()).hexdigest()\n resp = CreateResp(\n id=pid,\n created_at=datetime.now(timezone.utc).isoformat(),\n echo=req,\n )\n _IDEMPO[key] = _IdempoEntry(request_hash=rh, response_json=resp.model_dump_json())\n return resp\n```\n\n```python\n# test_app.py (pytest)\nfrom fastapi.testclient import TestClient\nfrom app import app\n\nclient = TestClient(app)\n\ndef test_idempotent_replay():\n headers = {\"Idempotency-Key\": \"abc\"}\n body = {\"tenant_id\":\"t1\",\"amount_cents\":100,\"currency\":\"USD\"}\n r1 = client.post(\"/v1/payments\", json=body, headers=headers)\n r2 = client.post(\"/v1/payments\", json=body, headers=headers)\n assert r1.status_code == 200 and r2.status_code == 200\n assert r1.json() == r2.json()\n\ndef test_payload_conflict():\n headers = {\"Idempotency-Key\": \"abc\"}\n b1 = {\"tenant_id\":\"t1\",\"amount_cents\":100,\"currency\":\"USD\"}\n b2 = {\"tenant_id\":\"t1\",\"amount_cents\":200,\"currency\":\"USD\"}\n assert client.post(\"/v1/payments\", json=b1, headers=headers).status_code == 200\n assert client.post(\"/v1/payments\", json=b2, headers=headers).status_code == 409\n```\n\nNotes:\n- Replace in-memory store with a DB table and transaction.\n- Store response + request hash to detect key reuse with different payload.\n\n\nHard-mode checks: concurrency safety, idempotency, and rollback validated; add chaos tests where feasible.", "source": "WithinUsAI/GOD_Coder_100k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Fix a bug and add tests.\n\nFile: pe5mhehf.py\n```python\ndef fcdop_(n: int) -> int:\n \"\"\"Sum 1..n inclusive.\"\"\"\n if n < 0:\n raise ValueError(\"n must be non-negative\")\n total = 0\n for k in range(n): # BUG: should include n\n total += k\n return total\n```\n\nReturn unified diffs for pe5mhehf.py and test_pe5mhehf.py (pytest).\n\n*** Begin Patch\n*** Update File: pe5mhehf.py\n@@\n def fcdop_(n: int) -> int:\n@@\n total = 0\n- for k in range(n): # BUG: should include n\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_pe5mhehf.py\n+import pytest\n+from pe5mhehf import fcdop_\n+\n+def test_zero():\n+ assert fcdop_(0) == 0\n+\n+def test_one():\n+ assert fcdop_(1) == 1\n+\n+def test_small():\n+ assert fcdop_(7) == 28\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ fcdop_(-1)\n+\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Build an elite-grade solution in the domain of stream processing for scenario: analytics pipeline.\nPrimary language: go.\nDifficulty: medium.\nConstraints: provide rollout and rollback guidance, include invariants and failure modes, include tests or verification strategy, avoid undefined behavior and data races.\nComponent: component_nvmowge.\nAssume 50k RPS and p99 < 250ms.\nTask: Implement a concurrency primitive or subsystem (lock-free queue, thread pool, async runtime component). Explain memory ordering and correctness arguments; include stress tests.\n\nOutput: elite-grade engineering answer with contracts, edge cases, and verification.\nOutput: correctness-focused concurrency primitive + stress tests.\n\n**Primitive**\n- Bounded MPMC queue with backpressure (blocking push/pop) OR lock-free SPSC ring buffer.\n\n**Correctness notes**\n- For lock-free: use acquire/release semantics on head/tail indices.\n- Avoid ABA by monotonic counters; ring index = counter % capacity.\n\n**Stress tests**\n- Multi-thread producers/consumers; assert item multiset preserved.\n- Use time-bounded randomized schedules; detect deadlocks.\n\n\nChecks: boundary validation and deterministic behavior verified.", "source": "WithinUsAI/Elite_GOD_Coder_100k"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: Repository domain: document processing API\nPrimary language: Go\nFramework/tooling: sqlc\nReported problem: idempotent retry design\nTask type: bug_fix\nDifficulty: medium\n\nProduce a complete professional engineering response:\n1. Diagnose the root cause.\n2. Provide the corrected implementation or patch.\n3. Add tests.\n4. Add verification commands.\n5. Note edge cases and any migration or rollback risk.\n\nRepository sketch:\nrepo/\n cmd/server/main.go\n internal/service/service.go\n internal/store/store.go\n internal/api/api.go\n service_test.go\n go.mod\n\nQuality target:\n- Minimal diff unless redesign is clearly required\n- Production-ready code\n- No placeholders\n- Secure defaults\n- Clear acceptance of failure cases\n\nFocus: Focus on complete implementation quality, patch correctness, tests, and production readiness.\n\nassistant: Diagnosis:\n- Root cause: the failure around idempotent retry design is caused by missing validation, weak edge-case handling, or unsafe lifecycle behavior in the current implementation.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```go\npackage service\n\nimport \"fmt\"\n\nfunc NormalizePayload(payload map[string]any) map[string]any {\n\tout := make(map[string]any)\n\tfor k, v := range payload {\n\t\tif v == nil {\n\t\t\tcontinue\n\t\t}\n\t\tout[k] = v\n\t}\n\treturn out\n}\n\nfunc Handle(payload map[string]any) (map[string]any, error) {\n\tclean := NormalizePayload(payload)\n\tif _, ok := clean[\"id\"]; !ok {\n\t\treturn nil, fmt.Errorf(\"missing id\")\n\t}\n\treturn map[string]any{\"ok\": true, \"data\": clean}, nil\n}\n```\n\nTests:\n```go\npackage service\n\nimport \"testing\"\n\nfunc TestHandle(t *testing.T) {\n\tgot, err := Handle(map[string]any{\"id\": 7, \"name\": \"ok\", \"unused\": nil})\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tif got[\"ok\"] != true {\n\t\tt.Fatalf(\"expected ok=true\")\n\t}\n\tif _, err := Handle(map[string]any{\"name\": \"x\"}); err == nil {\n\t\tt.Fatalf(\"expected missing id error\")\n\t}\n}\n```\n\nVerification:\n- `go test ./...`\n- `go vet ./...`\n\nEngineering notes:\n- Language: Go\n- Framework/tooling: sqlc\n- Stack context: GitHub Actions, Docker Compose, Kubernetes, Terraform\n- Domain: document processing API\n- Task type: bug_fix\n- Difficulty: medium\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"} {"text": "Refactor to typed, mostly-immutable Python and add minimal tests.\n\n```python\nclass C35646:\n def __init__(self, values): self.values=list(values)\n def mean(self): return sum(self.values)/len(self.values)\n```\nReturn `m02742.py` and `test_m02742.py`.\n\n```python\n# m02742.py\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom typing import Iterable, Tuple\n\n@dataclass(frozen=True)\nclass C35646:\n values: Tuple[float, ...]\n\n @staticmethod\n def create(values: Iterable[float]) -> \"C35646\":\n vals = tuple(float(v) for v in values)\n if not vals: raise ValueError(\"empty\")\n return C35646(vals)\n\n def mean(self) -> float:\n return sum(self.values)/len(self.values)\n```\n\n```python\n# test_m02742.py\nimport pytest\nfrom m02742 import C35646\n\ndef test_mean():\n assert C35646.create([1,2,3]).mean() == 2.0\ndef test_empty():\n with pytest.raises(ValueError):\n C35646.create([])\n```", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Build an elite-grade solution in the domain of compilers for scenario: feature flagging.\nPrimary language: go.\nDifficulty: medium.\nConstraints: document performance characteristics, provide rollout and rollback guidance, make the interface contract explicit, include invariants and failure modes, design for backward compatibility and migrations.\nComponent: component_sjrgfmi.\nAssume 50k RPS and p99 < 250ms.\nTask: Implement a concurrency primitive or subsystem (lock-free queue, thread pool, async runtime component). Explain memory ordering and correctness arguments; include stress tests.\n\nOutput: elite-grade engineering answer with contracts, edge cases, and verification.\nOutput: correctness-focused concurrency primitive + stress tests.\n\n**Primitive**\n- Bounded MPMC queue with backpressure (blocking push/pop) OR lock-free SPSC ring buffer.\n\n**Correctness notes**\n- For lock-free: use acquire/release semantics on head/tail indices.\n- Avoid ABA by monotonic counters; ring index = counter % capacity.\n\n**Stress tests**\n- Multi-thread producers/consumers; assert item multiset preserved.\n- Use time-bounded randomized schedules; detect deadlocks.\n\n\nChecks: boundary validation and deterministic behavior verified.", "source": "WithinUsAI/Elite_GOD_Coder_100k"} {"text": "Build an elite-grade solution in the domain of sre/observability for scenario: feature flagging.\nPrimary language: rust.\nDifficulty: hard.\nConstraints: include tests or verification strategy, avoid undefined behavior and data races, provide rollout and rollback guidance, include invariants and failure modes.\nComponent: component_zcfjltj.\nAssume partial network partitions occur weekly.\nTask: Implement or outline a storage/indexing subsystem (LSM/B-Tree, WAL, snapshots). Include transaction/consistency considerations and benchmark plan.\n\nOutput: production blueprint plus correctness arguments and test strategy.\nOutput: storage design + WAL + compaction + benchmarks.\n\n**Design**\n- WAL (append-only) for durability; fsync policy configurable.\n- Memtable (in-memory) → flush to immutable SSTables.\n- LSM compaction tiers; bloom filters per SSTable for point-lookups.\n- Manifest tracks SSTable set; atomic pointer swap on updates.\n\n**Correctness**\n- Crash recovery: replay WAL to rebuild memtable; manifest ensures last consistent set.\n- Reads: merge memtable + SSTables newest→oldest; tombstones override older values.\n\n**Bench plan**\n- Workloads: write-heavy, read-heavy, mixed; measure p50/p95 latency and write amplification.\n- Track compaction debt and space amplification.\n\n**Test plan**\n- Fuzz crash points: kill after WAL append / after manifest update; verify invariants on restart.\n\n\nHard checks: failure injection tests and performance regressions gated.", "source": "WithinUsAI/Elite_GOD_Coder_100k"} {"text": "Build an elite-grade solution in the domain of security engineering (defensive) for scenario: edge sync.\nPrimary language: go.\nDifficulty: hard.\nConstraints: assume untrusted inputs; validate and sanitize, document performance characteristics, avoid undefined behavior and data races, design for backward compatibility and migrations.\nComponent: component_qehdmrf.\nAssume 50k RPS and p99 < 250ms.\nTask: Write a precise interface contract, list invariants, and provide a lightweight formal/spec-style description (pseudo-TLA+/state machine) plus reference implementation skeleton and tests.\n\nOutput: production blueprint plus correctness arguments and test strategy.\nOutput: contract + invariants + spec + reference skeleton.\n\n**Interface contract**\n- Commands: `Put(key, value, expected_version?)`, `Get(key)`, `Delete(key, expected_version?)`\n- Responses: `Ok(version, value?)`, `NotFound`, `Conflict(current_version)`, `InvalidInput`\n- Idempotency: client supplies `request_id`; server must de-duplicate per (tenant_id, request_id).\n\n**Invariants**\n1. Monotonic version per key (strictly increases on successful writes).\n2. Reads return latest committed value for a given consistency level.\n3. Exactly-once effect for a given `request_id` (at-most-once execution + replay response).\n4. Tenant isolation: keys are scoped by tenant_id.\n\n**State machine (pseudo)**\nState:\n- store: map[(tenant,key)] -> (version:int, value:bytes|tombstone)\n- seen: map[(tenant,request_id)] -> response\nTransition Put:\n- if request_id in seen: return seen[...]\n- validate input; if expected_version set and != current version -> Conflict\n- version' = version + 1; store[...] := (version', value); seen[...] := Ok(version', value)\n\n**Reference skeleton (Python)**\n```python\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom typing import Dict, Optional, Tuple\n\nclass Conflict(Exception): pass\nclass InvalidInput(ValueError): pass\n\n@dataclass(frozen=True, slots=True)\nclass Value:\n version: int\n data: Optional[bytes] # None == tombstone\n\n@dataclass(frozen=True, slots=True)\nclass Reply:\n kind: str\n version: Optional[int] = None\n data: Optional[bytes] = None\n\nclass KV:\n def __init__(self) -> None:\n self._store: Dict[Tuple[str,str], Value] = {}\n self._seen: Dict[Tuple[str,str], Reply] = {}\n\n def put(self, tenant: str, request_id: str, key: str, data: bytes, expected_version: Optional[int]=None) -> Reply:\n if not tenant or not request_id or not key:\n raise InvalidInput(\"tenant/request_id/key required\")\n de = self._seen.get((tenant, request_id))\n if de: \n return de\n cur = self._store.get((tenant, key), Value(0, None))\n if expected_version is not None and expected_version != cur.version:\n r = Reply(\"conflict\", version=cur.version)\n self._seen[(tenant, request_id)] = r\n return r\n nxt = Value(cur.version + 1, data)\n self._store[(tenant, key)] = nxt\n r = Reply(\"ok\", version=nxt.version)\n self._seen[(tenant, request_id)] = r\n return r\n```\n\n**Tests**\n- Determinism: same request_id → same reply.\n- Conflict detection and version monotonicity.\n\n\nHard checks: failure injection tests and performance regressions gated.", "source": "WithinUsAI/Elite_GOD_Coder_100k"} {"text": "You are Royal Ghost Coder, an expert offline software engineer and code-evolution agent. You produce production-quality code, minimal diffs, and tests. Safety: refuse or redirect requests that enable malware, exploitation, credential theft, or unauthorized access.\n\nTask: Fix a bug and add tests.\n\nFile: qip_qmd0pr7.py\n```python\ndef fvei5k_(n: int) -> int:\n \"\"\"Sum 1..n inclusive.\"\"\"\n if n < 0:\n raise ValueError(\"n must be non-negative\")\n total = 0\n for k in range(n): # BUG: should include n\n total += k\n return total\n```\n\nReturn unified diffs for qip_qmd0pr7.py and test_qip_qmd0pr7.py (pytest).\n\n*** Begin Patch\n*** Update File: qip_qmd0pr7.py\n@@\n def fvei5k_(n: int) -> int:\n@@\n total = 0\n- for k in range(n): # BUG: should include n\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_qip_qmd0pr7.py\n+import pytest\n+from qip_qmd0pr7 import fvei5k_\n+\n+def test_zero():\n+ assert fvei5k_(0) == 0\n+\n+def test_one():\n+ assert fvei5k_(1) == 1\n+\n+def test_small():\n+ assert fvei5k_(7) == 28\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ fvei5k_(-1)\n+\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Build a data pipeline for a social media product around background jobs.\nTarget platform: data (SQL + Python).\nRequirements: schema, ingestion, validation, backfills, and tests.\nConstraints: must include tests, must be secure-by-default, must be easy to extend.\nDifficulty: hard. Assume untrusted input; validate everything.\n\nOutput: design + implementation guidance suitable for shipping.\nDeliverable: schema + ingestion + validation + backfill strategy.\n\n**Schema (example)**\n- events(event_id TEXT PK, tenant_id TEXT, ts TIMESTAMP, type TEXT, payload JSONB)\n\n**Ingestion**\n- Write to raw table first; validate; then materialize to curated tables.\n- Idempotency by event_id; enforce uniqueness.\n\n**Validation**\n- Reject missing tenant_id/type/ts.\n- Quarantine bad records with reason.\n\n**Backfills**\n- Re-run deterministic transforms from raw → curated.\n- Version transformations; store transform_version with outputs.\n\n**Tests**\n- Unit tests for validators and transforms.\n- Integration test: sample raw batch produces expected curated rows.\n\n\nHard-mode checks: concurrency safety, idempotency, and rollback validated; add chaos tests where feasible.", "source": "WithinUsAI/GOD_Coder_100k"} {"text": "Refactor a Python module used for ETL pipelines into a clean, extensible design.\nRequirements: outline the new architecture briefly, then provide the refactored code and tests.\nConstraints: stdlib-only, must handle Windows paths safely.\nDifficulty: easy. Ensure the API is testable via dependency injection.\n\nDeliverable: corrected code and verification tests.\nArchitecture:\n- Public facade class coordinating concerns (parsing, validation, persistence)\n- Small pure functions for testability\n- No global state; dependency injection for filesystem I/O\n\n```python\nfrom __future__ import annotations\nfrom dataclasses import dataclass\nfrom pathlib import Path\nfrom typing import Protocol, Iterable\nimport json\n\nclass Store(Protocol):\n def write_text(self, path: Path, data: str) -> None: ...\n\nclass FSStore:\n def write_text(self, path: Path, data: str) -> None:\n path.parent.mkdir(parents=True, exist_ok=True)\n path.write_text(data, encoding=\"utf-8\")\n\n@dataclass(frozen=True, slots=True)\nclass Item:\n name: str\n qty: int\n\ndef parse_items(lines: Iterable[str]) -> list[Item]:\n out: list[Item] = []\n for i, line in enumerate(lines, 1):\n s = line.strip()\n if not s:\n continue\n obj = json.loads(s)\n if not isinstance(obj, dict):\n raise ValueError(f\"line {i}: expected object\")\n name = obj.get(\"name\")\n qty = obj.get(\"qty\")\n if not isinstance(name, str) or not name:\n raise ValueError(f\"line {i}: name must be str\")\n if not isinstance(qty, int) or qty < 0:\n raise ValueError(f\"line {i}: qty must be non-negative int\")\n out.append(Item(name, qty))\n return out\n\nclass InventoryWriter:\n def __init__(self, base_dir: Path, store: Store | None = None) -> None:\n self._base = base_dir\n self._store: Store = store or FSStore()\n\n def write(self, rel_path: str, items: list[Item]) -> Path:\n dst = (self._base / rel_path).resolve()\n base = self._base.resolve()\n if dst != base and base not in dst.parents:\n raise ValueError(\"unsafe path traversal\")\n payload = json.dumps([item.__dict__ for item in items], ensure_ascii=False)\n self._store.write_text(dst, payload)\n return dst\n```\n\n```python\nimport json\nfrom pathlib import Path\nimport pytest\nfrom module_under_test import InventoryWriter, parse_items\n\ndef test_parse_items_valid():\n lines = [json.dumps({\"name\":\"x\",\"qty\":1})]\n assert parse_items(lines)[0].name == \"x\"\n\ndef test_writer_blocks_traversal(tmp_path: Path):\n w = InventoryWriter(tmp_path)\n with pytest.raises(ValueError):\n w.write(\"../evil.json\", [])\n```", "source": "WithinUsAI/python_GOD_coder_100k"} {"text": "Fix the bug and add pytest tests.\n\n```python\ndef f79427(n: int) -> int:\n # sum 1..n inclusive\n if n < 0: raise ValueError\n total = 0\n for k in range(n): # BUG\n total += k\n return total\n```\nReturn unified diffs for `m97061.py` and `test_m97061.py`.\n\n*** Begin Patch\n*** Update File: m97061.py\n@@\n def f79427(n: int) -> int:\n@@\n- for k in range(n): # BUG\n- total += k\n+ for k in range(1, n + 1):\n+ total += k\n return total\n*** End Patch\n\n*** Begin Patch\n*** Add File: test_m97061.py\n+import pytest\n+from m97061 import f79427\n+\n+def test_small():\n+ assert f79427(7) == 28\n+\n+def test_zero():\n+ assert f79427(0) == 0\n+\n+def test_negative():\n+ with pytest.raises(ValueError):\n+ f79427(-1)\n*** End Patch", "source": "WithinUsAI/Royal_Ghost_Coder_501k"} {"text": "Task type: compiler_frontend\nScenario: document indexing pipeline\nDomain focus: zero-downtime migrations\nPrimary language: go\nDifficulty: expert+\nScale/SLO: 100k RPS peak\nComponent: component_qrpnnllw\nConstraints: include verification strategy, include backward compatibility and migration plan, avoid data races and undefined behavior, include test vectors and fuzz strategy, include deterministic replay plan\nAssume crash-only processes; recovery must be deterministic.\nDeliverable: Design a DSL language frontend: lexer/parser, AST, type checking, error reporting, and tests.\n\nOutput: rigorous design + invariants + verification plan + implementation sketch.\n**Contract**\n- Inputs validated at the boundary; explicit error taxonomy.\n- Idempotency for side effects via request_id; deterministic replay.\n- Backward compatibility: additive changes by default; versioned breaking changes.\n**Invariants**\n- Isolation: tenant boundary enforced; no cross-tenant reads/writes.\n- Safety: state transitions preserve invariants; no partial commit leaks.\n- Liveness: under bounded faults and stable network, progress occurs.\n**Failure modes & recovery**\n- Data corruption: checksums + scrubber; quarantine and rebuild from replicas/snapshots.\n- Duplicate requests: de-duplicate by (tenant, request_id) returning cached response.\n- Network partition: minority cannot commit; clients receive retriable errors.\n**Security posture (defensive)**\n- Threat model: auth/authz, injection, replay/abuse, supply chain.\n- Least privilege; secrets in managed store; audit logs for sensitive ops.\n- Input normalization, parameterized queries, path traversal protections.\n**Verification strategy**\n- Canary + shadow traffic; invariants checked in production via assertions/metrics.\n- Deterministic simulation with fault injection (crash/partition/latency).\n- Fuzzing of parsers/framers/validators with corpus seeds.\n\n**Snippet**\n```text\nImplementation sketch: factor pure state-machine core; adapters for I/O; add deterministic replay log.\n```\nExpert+ checks: mechanized invariants (or exhaustive model checking), adversarial fuzzing, and multi-region failure drills.", "source": "WithinUsAI/Omega_Genesis_Coder_100k"} {"text": "Design a production system for fintech supporting audit logs.\nTarget platform: backend (Go).\nRequirements: APIs, data model, scaling strategy, failure modes, and security.\nConstraints: must avoid global state, must include documentation/comments, must include tests.\nDifficulty: easy. Assume 10k RPS peak traffic.\n\nOutput: actionable implementation and verification artifacts.\nDeliverable: system design with APIs, data model, and operational plan.\n\n**High-level architecture**\n- Edge: API Gateway + WAF\n- Core service: stateless app pods behind L7 LB\n- Data: Postgres (primary), Redis (cache + rate limit tokens), Object storage (uploads if needed)\n- Async: message queue (e.g., SQS/Rabbit) + worker pool for background jobs\n- Observability: structured logs + metrics + tracing\n\n**APIs (example)**\n- `POST /v1/{resource}` create (idempotent via `Idempotency-Key`)\n- `GET /v1/{resource}/{id}` read\n- `POST /v1/{resource}/{id}:action` command endpoint when side effects exist\n\n**Data model (Postgres)**\n- `resources(id UUID PK, tenant_id UUID, status TEXT, payload JSONB, created_at, updated_at)`\n- Unique constraint for idempotency: `(tenant_id, idempotency_key)` in a separate table:\n - `idempotency(tenant_id, key TEXT, request_hash TEXT, response JSONB, created_at, PRIMARY KEY(tenant_id,key))`\n\n**Scaling**\n- App layer scales horizontally; keep sessions out of process.\n- Cache reads in Redis; write-through invalidation on mutations.\n- Use connection pooling; consider read replicas for heavy reads.\n\n**Failure modes**\n- Retries: only for safe/ idempotent operations; exponential backoff + jitter.\n- Partial failures: background jobs must be idempotent; use a de-dup key.\n\n**Security**\n- AuthN: JWT/OIDC; AuthZ: RBAC/ABAC with tenant isolation\n- Validate all inputs; enforce per-tenant quotas/rate limits.\n\n**Rollout**\n- Dark launch + feature flags; canary; rapid rollback by toggling flags.\n\n\nChecks: input validation, tests, and safe defaults included.", "source": "WithinUsAI/GOD_Coder_100k"} {"text": "system: You are a production-grade software engineer. Return a correct, secure, complete, test-backed solution with concise reasoning and no placeholders.\n\nuser: Repository domain: data pipeline\nPrimary language: C#\nFramework/tooling: xUnit\nReported problem: invalid rollback sequence\nTask type: test_repair\nDifficulty: hard\n\nProduce a complete professional engineering response:\n1. Diagnose the root cause.\n2. Provide the corrected implementation or patch.\n3. Add tests.\n4. Add verification commands.\n5. Note edge cases and any migration or rollback risk.\n\nRepository sketch:\nrepo/\n src/App/Program.cs\n src/App/Service.cs\n tests/App.Tests/ServiceTests.cs\n App.sln\n\nQuality target:\n- Minimal diff unless redesign is clearly required\n- Production-ready code\n- No placeholders\n- Secure defaults\n- Clear acceptance of failure cases\n\nFocus: Focus on complete implementation quality, patch correctness, tests, and production readiness.\n\nassistant: Diagnosis:\n- Root cause: the failure around invalid rollback sequence is caused by missing validation, weak edge-case handling, or unsafe lifecycle behavior in the current implementation.\n- Patch strategy: keep the diff focused, harden inputs, preserve compatibility where possible, and add tests that reproduce the real failure mode.\n- Result: the updated implementation improves correctness first, then maintainability and operational safety.\n\nImplementation:\n```csharp\nusing System;\nusing System.Collections.Generic;\n\npublic static class RequestHandler\n{\n public static Dictionary HandleRequest(Dictionary payload)\n {\n var clean = new Dictionary();\n foreach (var entry in payload)\n {\n if (entry.Value != null)\n clean[entry.Key.Trim()] = entry.Value;\n }\n if (!clean.ContainsKey(\"id\"))\n throw new ArgumentException(\"missing id\");\n return new Dictionary\n {\n [\"ok\"] = true,\n [\"data\"] = clean\n };\n }\n}\n```\n\nTests:\n```csharp\nusing System;\nusing System.Collections.Generic;\nusing Xunit;\n\npublic class RequestHandlerTests\n{\n [Fact]\n public void RequiresId()\n {\n Assert.Throws(() => RequestHandler.HandleRequest(new Dictionary { [\"name\"] = \"x\" }));\n }\n}\n```\n\nVerification:\n- `dotnet test`\n- `dotnet build`\n\nEngineering notes:\n- Language: C#\n- Framework/tooling: xUnit\n- Stack context: FastAPI, PostgreSQL, Redis, Celery, pytest, Docker\n- Domain: data pipeline\n- Task type: test_repair\n- Difficulty: hard\n- Security: prefer validation, safe defaults, and explicit failure handling.\n- Compatibility: keep the patch backward compatible unless the problem explicitly requires a migration.\n- Rollout: deploy behind normal verification gates and watch logs, metrics, and regression tests after release.", "source": "WithinUsAI/GOD_Coder_Complete_DataSet"}