TASK
Implementation
Production systems must handle malformed input gracefully. Your node should validate that incoming messages have the required structure before processing.
Required validations:
- Message must be valid JSON
- Message must have
src,dest, andbodyfields - Body must have a
typefield - For requests expecting responses, body should have a
msg_id
If validation fails, log an error to stderr but do not crash. This defensive programming prevents a single bad message from taking down your node.
Sample Test Cases
Handle valid messageTimeout: 5000ms
Input
{
"src": "c0",
"dest": "n1",
"body": {
"type": "init",
"msg_id": 1,
"node_id": "n1",
"node_ids": [
"n1"
]
}
}Expected Output
{"src": "n1", "dest": "c0", "body": {"type": "init_ok", "in_reply_to": 1, "msg_id": 0}}
Hints
Hint 1▾
Check that required fields are present
Hint 2▾
Handle malformed JSON gracefully
Hint 3▾
Log validation errors to stderr
OVERVIEW
Theoretical Hub
Defensive Programming
In distributed systems, you cannot trust the network or other nodes. Messages may be corrupted, truncated, or malformed. Your node must validate inputs and fail gracefully.
Why Validation Matters
Consider what happens without validation:
- Crashes - accessing missing fields throws exceptions
- Security vulnerabilities - malformed input could be exploited
- Cascading failures - one bad message takes down the node
Validation Strategy
A good validation strategy checks inputs at the boundary of your system:
def validate_message(msg):
# Check structure
if not isinstance(msg, dict):
return False, "Message must be an object"
# Check required fields
for field in ["src", "dest", "body"]:
if field not in msg:
return False, f"Missing field: {field}"
# Check body structure
if "type" not in msg["body"]:
return False, "Body missing type field"
return True, None
Error Semantics
Maelstrom defines error responses with type error and error codes:
{
"type": "error",
"in_reply_to": 1,
"code": 10,
"text": "Node not initialized"
}
Common error codes:
0- timeout1- node not found10- not supported11- temporarily unavailable12- malformed request
Key Concepts
validationerror handlingdefensive programming
main.py
python
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
#!/usr/bin/env python3
import sys
import json
class Node:
def __init__(self):
self.node_id = None
self.node_ids = []
self.next_msg_id = 0
def send(self, dest, body):
body["msg_id"] = self.next_msg_id
self.next_msg_id += 1
message = {"src": self.node_id, "dest": dest, "body": body}
print(json.dumps(message), flush=True)
def reply(self, request, body):
body["in_reply_to"] = request["body"]["msg_id"]
self.send(request["src"], body)
def validate_message(self, message):
# TODO: Validate message structure
# Return True if valid, False otherwise
# Log errors to stderr
pass
def main():
node = Node()
for line in sys.stdin:
try:
message = json.loads(line)
except json.JSONDecodeError as e:
print(f"Invalid JSON: {e}", file=sys.stderr)
continue
# TODO: Validate message before processing
body = message["body"]
msg_type = body["type"]