Fix the task loader that replaced pickle

Review the AI's codeEasy10 min

Your task

A worker reads task definitions that an upstream service caches in Redis. The first version called pickle.loads on those bytes, which runs code while it loads. Now the cache holds plain text that the worker parses against a fixed schema.

An assistant wrote load_task_definition(raw_blob, allowed_task_types). It is in the editor. It has a bug. Find it and fix it.

Input and output:

  • raw_blob: the cached text, key=value pairs separated by ;. For example type=email_send;retries=3;payload=abc.
  • allowed_task_types: the task types this worker may run.
  • Return "ok:<type>:<retries>", or one of "reject:format", "reject:field" and "reject:type".

Rules the tests check:

  • An empty raw_blob returns "reject:format".
  • Split on ;. Split each pair at its first = into a key and a value. Read the pairs left to right and stop at the first problem:
    • no =, or an empty key: "reject:format"
    • a key other than type, retries or payload: "reject:field"
    • a key seen before: "reject:field"
  • Then, in this order:
    1. type or retries is missing: "reject:field".
    2. type is not exactly one of allowed_task_types: "reject:type".
    3. retries is not 1 to 3 digits (0 to 9), or its value is above 10: "reject:field".
  • payload is optional and its value can be anything.
  • Otherwise return "ok:", the type, ":", and retries as a plain integer. Leading zeros go away: 007 becomes 7.

Examples:

  • load_task_definition("type=email_send;retries=3;payload=abc", ["email_send", "report_build"]) returns "ok:email_send:3".
  • load_task_definition("type=shell_exec;retries=1", ["email_send"]) returns "reject:type".
  • load_task_definition("__reduce__=os.system", ["email_send"]) returns "reject:field": __reduce__ is not a key the schema knows.

Then, in a sentence or two: how would you catch this kind of bug in review?

Examples

load_task_definition(raw_blob: str, allowed_task_types: list[str]) -> str
Example 1
Inputload_task_definition("type=email_send;retries=3;payload=abc", ["email_send", "report_build"])
Output"ok:email_send:3"
Example 2
Inputload_task_definition("type=shell_exec;retries=1", ["email_send"])
Output"reject:type"
Example 3
Inputload_task_definition("__reduce__=os.system", ["email_send"])
Output"reject:field"