harbor run -t openthoughts/tasktrove-exp-rpt-curriculum-hard-curriculum-hard-0152harbor download openthoughts/tasktrove-exp-rpt-curriculum-hard-curriculum-hard-0152Harder task: robust, high-performance S3-backed data store with concurrency considerations
Goal
- Implement a Python module at /app/s3data.py (or /app/s3data/ as a package) that provides a minimal but production-friendly S3-based data store, compatible with the tests, but designed for high concurrency, large payloads, and edge cases.
What to implement
- A single class named S3Data with the exact public interface below, plus internal design choices that improve robustness and performance without altering the required signatures.
Required interface (signatures you must implement)
- class S3Data:
- __init__(self, aws_access_key_id: str, aws_secret_access_key: str, bucket: str, region_name: Optional[str] = None)
- put(self, key: str, data: dict) -> None
- get(self, key: str) -> dict
- delete(self, key: str) -> None
Behavior and details (beyond the original task to increase difficulty)
- Initialization
- Create a boto3 S3 client using the provided credentials and optional region_name.
- Do not perform any network I/O in __init__; defer to method calls.
- Create a botocore.config.Config (or equivalent) with sensible defaults to optimize performance under concurrency and occasional timeouts:
- connect_timeout: small, e.g., 2 seconds
- read_timeout: modest, e.g., 5–10 seconds
- retries: a small, bounded number of retries (do not mask ClientError)
- max_pool_connections: tuned for concurrency (e.g., 50)
- Ensure the client is stored per-instance and is thread-safe for concurrent calls. If appropriate, document the thread-safety assumption and protect non-thread-safe internals with a lightweight lock.
- put(key, data)
- Serialize the data dictionary to JSON with Unicode support (ensure_ascii=False) and encode to UTF-8.
- Upload to the configured bucket under the exact key.
- Overwrite any existing object at that key.
- Use Content-Type: application/json (recommended).
- For large data, use an approach suitable for streaming or chunked upload to minimize peak memory usage while still delivering a correct result (e.g., use upload_fileobj with a BytesIO stream). The implementation must not require loading an entire huge payload into memory twice.
- Do not suppress exceptions; propagate any ClientError or related errors (including credential or bucket errors).
- If data is not JSON-serializable, raise a clear TypeError with an explanatory message.
- get(key)
- Retrieve the object at the given key from the configured bucket.
- If the object exists, read its body, parse the JSON, and return the resulting Python dict.
- If the key does not exist in a valid bucket (NoSuchKey or NoSuchKey-equivalent error), return {} (empty dict). A falsy value is acceptable as a test hint, but return a dict as specified.
- If the bucket is invalid or credentials are invalid, propagate the botocore.exceptions.ClientError (do not swallow).
- If the object contains invalid JSON, propagate the JSON decode error (do not swallow) to surface the problem.
- delete(key)
- Delete the object at the given key from the bucket.
- Do not raise an error if the key does not exist (S3 delete is idempotent).
- Propagate any ClientError for invalid bucket or credentials.
Error handling guidance
- Let botocore.exceptions.ClientError propagate for invalid credentials and invalid bucket cases.
- For a missing key in a valid bucket, catch the appropriate error(s) (e.g., NoSuchKey) and return {} from get(key).
- Do not modify or bypass the tests’ expectations about exceptions; only swallow NoSuchKey when getting a non-existent key.
- All behavior should be deterministic and well-documented in code (docstrings) to aid future maintenance and testing.
Data format
- Use JSON for the stored data. Expect and return dicts in Python (e.g., {"test": "flag", "version": 1}) when retrieving.
- Ensure proper handling of Unicode characters in both directions (encoding and decoding).
Notes and constraints
- The tests rely on AWS credentials provided via environment variables:
- AWS_ACCESS_KEY_ID
- AWS_SECRET_ACCESS_KEY
- S3DATA_BUCKET
- The implementation must be compatible with those tests, including tests that verify proper ClientError codes for invalid access, invalid secret, and invalid bucket.
- Do not modify the public interface beyond the exact signatures specified above.
- Do not perform any network I/O in __init__; only instantiate and configure the client.
- Code should be robust under concurrent usage from multiple threads.
- Path: /app/s3data.py (or /app/s3data/__init__.py if you prefer packaging). If you choose the package form, ensure the tests can import S3Data from the same place as the flat module.
Optional but encouraged design choices (internal, not required by signature)
- Use a simple, well-documented design pattern (e.g., Repository/Adapter pattern) to separate the AWS I/O from data handling logic.
- Implement a minimal internal concurrency guard (e.g., a per-instance threading.RLock) to ensure thread-safety without sacrificing performance in typical workloads.
- Provide clear, concise logging or debug statements (optional) behind a debug flag to aid troubleshooting without affecting test output.
Example usage (conceptual)
- s3 = S3Data(os.environ["AWS_ACCESS_KEY_ID"], os.environ["AWS_SECRET_ACCESS_KEY"], os.environ["S3DATA_BUCKET"], region_name="us-west-2")
- s3.put("user/1234/profile", {"name": "Alice", "age": 30, "languages": ["en","ja"]})
- data = s3.get("user/1234/profile")
- s3.delete("user/1234/profile")
Implementation goes in: /app/s3data.py