← Complete program

Chapter 17 · Course 3 c17-m03

What if a message changes shape?

Your goal Validate JSON stream changes and preserve incompatible messages for investigation without losing recognized commands.

The lesson, the vocabulary, the worked example and the mission are separate blocks. You can follow them in order or return to the one you need.

Video explanation

This English explanation has English subtitles. Its examples may use a separate practice dataset; use the data stated in the written mission for your answers.

01

Story · optional context

The story so far

You are Aster Motors' new data recruit. Luca was hurt when a car resembling Noctis 01 crashed; the prototype is missing and Voss is trying to blame you. Mara Sol and Imani found two distinct commands, OPEN-17 and OPEN-18, under the technical identity SUPPLIER-SVC. The stream is reread after a stop, but one producer added a field to its messages. Another test even replaced command_id with operation_id. If the reader ignores that difference, it may silently lose a command.

This lesson stands alone. JSON writes objects with named fields. A schema describes expected fields, their types, and which are required. The producer writes messages; the consumer reads them. You will compare three versions, accept an optional field without losing OPEN-18, and isolate an incompatible change instead of guessing or deleting it. SUPPLIER-SVC is an identity label, never a real secret key.

02

Before the lesson

Purpose of this course

Validate JSON stream changes and preserve incompatible messages for investigation without losing recognized commands.

Topics covered

Read a JSON object and identify required and optional fields.; Explain why adding a field can be compatible while renaming a required field can break a reader.; Check version and types before using a command.; Quarantine an unrecognized message while preserving its raw form.

What you will learn

  • Read a JSON object and identify required and optional fields.
  • Explain why adding a field can be compatible while renaming a required field can break a reader.
  • Check version and types before using a command.
  • Quarantine an unrecognized message while preserving its raw form.

PART 1 · THE LESSON

Understand step by step

1

Lesson · explanation

A command can disappear inside a new envelope

You are Aster Motors' new data recruit. Luca was hurt in a crash involving a car resembling Noctis 01, the prototype is missing, and Voss is trying to blame you. Mara and Imani found two distinct commands, OPEN-17 and OPEN-18, in a stream carrying the technical identity SUPPLIER-SVC. After a stop, the stream is reread and a producer has changed some message shapes. Voss claims OPEN-18 disappeared.

A producer writes messages; a consumer reads them and decides what to do. Imagine one person filling forms and another filing them. If the first adds a box or renames a required box without warning, the second may misread the form. In an investigation, a silently ignored command could make a requested action look as though it never existed.

JSON is a way to write an object as text with named fields and values. For example, {"command_id":"OPEN-17"} says that command_id contains the text OPEN-17. Braces surround the object; quotation marks surround field names and text values. A number such as schema_version: 1 is an integer, whereas "1" would be text. This type distinction matters.

Your goal is to read three message shapes, accept the versions understood by the practice reader, and set aside the one it cannot understand. You use no secret key or real stream. SUPPLIER-SVC is only a technical identity label in this copy. The countdown belongs to the story; the exercise has no timer.

Pause and think

Why can changing a field name trouble the message reader?

See the explanation

The reader looks for the name specified by its contract and may no longer find the command under a new name.

2

Lesson · explanation

The schema is a reading contract

A schema describes a message's expected shape: which fields must exist and what type of value each holds. Our practice contract requires four fields. schema_version must be an integer. event_id, command_id, and credential must be strings. A command can be used only when the reader recognizes its version and these required fields are present with the right types.

The copy's v1 message contains schema_version=1, event_id=E1, command_id=OPEN-17, and credential=SUPPLIER-SVC. All four boxes are filled as expected. Here credential is an alias for a technical identity, not a secret value. Copying a real private key into logs or an exercise would be unsafe. We observe only a fictional label.

Picture a library form requiring a numeric form number, a text book title, and a text borrower name. Without the number, it cannot be tracked reliably. Writing 'one' in a box expecting an integer may cause a program to reject it. Likewise, a JSON value can be present but of the wrong type and still break our contract.

A required field differs from an optional field. The required one must exist for the consumer to know what command it is handling. An optional one may supply extra detail that the reader is allowed to ignore. Our schema also allows additional properties, but that does not mean it automatically understands future versions or field renames.

Pause and think

Which four fields are required, and what type is schema_version?

See the explanation

schema_version is an integer; event_id, command_id, and credential are strings.

3

Lesson · explanation

An extra box can remain compatible

The v2 message has event_id=E2 and command_id=OPEN-18. It retains schema_version=2 and credential=SUPPLIER-SVC, then adds device=KIOSK-2. In our contract, device is optional and must be a string when present. The practice reader explicitly accepts versions 1 and 2. It can therefore read OPEN-18 rather than losing that command.

Imagine a delivery form retaining all its usual boxes and adding an optional 'parcel color' box. The person reading it can still find the address even if they ignore color. This is compatible for that particular reader. If the optional box held a number when its contract required text, our type check would reject it.

Compatibility depends on the message-reader pair, not only on the JSON's appearance. An older reader hardcoded to accept strictly schema_version=1 would reject v2 even if its only new field were harmless. Our reader knows versions 1 and 2. Saying 'adding a field is always safe' is therefore false; check accepted versions and actual code behavior.

In the mission, Voss shows a table where OPEN-18 seems missing after the update. Test the v2 copy: required fields remain, their types fit, and device is permitted. This supports the conclusion that the practice reader accepts E2/OPEN-18. It does not prove every deployed consumer elsewhere would accept the same evolution.

Pause and think

Why does this reader accept v2 E2/OPEN-18?

See the explanation

It retains required fields, device is optional text, and the reader explicitly supports version 2.

4

Lesson · explanation

Renaming a required box breaks the old contract

The fictional third message declares version 3, has event_id=E4, and replaces command_id with operation_id holding OPEN-19. The practice reader supports only versions 1 and 2. It also looks for the required name command_id, absent here. Although OPEN-19 looks like a command, no approved migration tells this reader that operation_id means exactly the same thing.

Imagine a library form replacing 'requested book' with 'operation' without explanation. The clerk cannot know whether operation names a book, a delivery code, or something else. Guessing might supply the wrong book. Here inventing a default command_id or automatically copying operation_id into it would be an unauthorized decision.

The version number 3 alone does not fix the problem. It signals a shape change but does not teach an old reader what the new field means. A real migration needs producers and consumers to agree on field meaning, supported versions, and tests. Old and new formats can coexist during a transition only if the reader was prepared to interpret both correctly.

Do not say E4 proves an OPEN-19 opening. It proves a text message carrying operation_id=OPEN-19 was received in this copy. That message does not meet the current processing contract. The distinction protects the case: preserve E4, but do not apply a command the reader has no authority to infer.

Pause and think

Which two problems stop this reader from accepting E4?

See the explanation

Version 3 is unsupported, and the required command_id field is missing.

5

Lesson · explanation

Validate before using a command

The small program first reads each text with json.loads, turning JSON into an object Python can inspect. It then checks that schema_version is an integer, that it equals 1 or 2, and that event_id, command_id, and credential are strings. If device exists, it checks that this optional field is a string too. Only after these checks does it add command_id to accepted commands.

The condition type(message.get('schema_version')) is int distinguishes an integer from text in this program. A version written as "2", with quotation marks, is rejected. An absent value fails as well. This is not punishment: the reader must not pretend to understand a message that does not follow its agreed shape.

Picture a sorting gate with four questions: 'known version? numeric version? essential boxes present? correct value types?' A form enters the command queue only when the answers fit. A rejected form is not destroyed; it goes to a review tray. This image separates validation from execution. The example code classifies text; it activates no lock.

Simply counting fields is insufficient. An object could have four fields but lack command_id, or write schema_version as text. Inspect names, types, and version. The same applies to device: optional does not mean any value is valid when the field is supplied.

Pause and think

Does the reader accept schema_version written as text "2"?

See the explanation

No. This program requires an integer rather than a string.

6

Lesson · explanation

Quarantine preserves inspectable evidence

When a message fails the contract, quarantine keeps it separately with a rejection reason. For E4, record 'unsupported version 3' and 'missing command_id.' Also retain the raw form, not just E4's name. The original text lets Imani later check whether the producer truly sent operation_id and which value it held.

Quarantine resembles a museum box of unidentified objects. Staff neither display them under invented labels nor throw them away. They keep provenance, condition, and the question to resolve. Silently deleting E4 would make it look as if only two messages existed. Accepting it by guessing OPEN-19 would make it look as if the contract had been followed. Both shortcuts distort facts.

The demonstration program prints accepted ['OPEN-17', 'OPEN-18'] and quarantined ['E4']. Its displayed quarantine list contains only an ID, but the investigation requires more: preserve raw text and reason in suitable storage. A short screen output must not be confused with a complete evidence archive.

Imani also asks for counts: three raw messages, two accepted messages, and one set aside. These totals expose silent loss. If the reader reported only two accepted commands without mentioning the third message, Mara might think nothing else arrived. Visibility of refusals is part of safe evolution.

Pause and think

Why preserve E4's raw text and rejection reason instead of deleting it?

See the explanation

They let the team inspect the format change and prevent silent loss of evidence.

7

Lesson · explanation

Evolve producer and consumer together

The producer writes messages; the consumer interprets them. If the producer alone changes command_id to operation_id, the old consumer cannot find the request. A safe update starts with an explicit contract: what the new field means, which versions are supported, and whether old messages remain readable. Both teams need these answers.

One possible sequence is to prepare a reader that understands old and new shapes, with tests for both, before the producer starts writing only the new shape. This sequence is not automatic: it needs approved decisions and restart tests. A new version number without a corresponding reader is insufficient.

Picture a school renaming a box on its forms. Before giving out new forms, it tells clerks where to find the information and tests old and new examples. Otherwise a request may sit in a drawer unnoticed. The same risk exists after a stream restart: messages of several ages may arrive together.

Useful tests include a valid v1, a v2 with device, a v2 where device has the wrong type, and a v3 with the rename. Write expected results before release: accept the first two and isolate the last two under the current contract. If a future migration approves v3, change expectations explicitly rather than changing interpretation silently.

Pause and think

Why update the reader before a producer writes only operation_id?

See the explanation

So it can read the new shape under an approved contract instead of silently losing commands.

8

Lesson · explanation

Give Mara a useful, limited conclusion

The mission begins with four required fields: integer schema_version, plus string event_id, command_id, and credential. V1 E1 has them, so OPEN-17 is accepted. V2 E2 keeps them and adds optional string device=KIOSK-2, so this reader accepts OPEN-18. E4 declares v3 and replaces the command field with operation_id, so it goes to quarantine.

A good note to Mara separates outputs from evidence: two recognized commands, OPEN-17 and OPEN-18; one rejected event, E4; three raw messages still traceable. Give E4's reasons: unsupported version and absent command_id. Claim neither that OPEN-19 is a validated action nor that E4 never existed. This prevents silent loss.

SUPPLIER-SVC is the technical identity written in the messages, not a known person. Even device=KIOSK-2 cannot prove who stood at the kiosk; the value could be mistaken or forged. This lesson checks data shape, not command authorship. Imani would need access records and independent sources to attribute an action.

The next lesson simulates a producer and consumer stop and restart. Incompatible messages and recognized commands must remain visible during that check. For now, your achievement is precise: explain why OPEN-18 does not vanish in this practice reader and why E4 waits for a verified migration rather than being guessed or deleted.

Pause and think

Which commands are accepted and which event is quarantined here?

See the explanation

OPEN-17 and OPEN-18 are accepted; E4 is quarantined with a rejection reason.

Visual guide

Three contract versions

  1. 1v1: required fields → OPEN-17 accepted
  2. 2v2: same fields + optional device → OPEN-18 accepted
  3. 3v3: command_id renamed → E4 quarantined

An optional field may be tolerated; removing a required field needs a planned migration.

Code · read each line

Read and isolate three messages

import json

raw_messages = [
    '{"schema_version":1,"event_id":"E1","command_id":"OPEN-17","credential":"SUPPLIER-SVC"}',
    '{"schema_version":2,"event_id":"E2","command_id":"OPEN-18","credential":"SUPPLIER-SVC","device":"KIOSK-2"}',
    '{"schema_version":3,"event_id":"E4","operation_id":"OPEN-19","credential":"SUPPLIER-SVC"}',
]
accepted, quarantined = [], []
for raw in raw_messages:
    message = json.loads(raw)
    valid = (
        type(message.get("schema_version")) is int
        and message["schema_version"] in (1, 2)
        and all(type(message.get(field)) is str
                for field in ("event_id", "command_id", "credential"))
        and ("device" not in message or type(message["device"]) is str)
    )
    if not valid:
        quarantined.append(message.get("event_id", "UNKNOWN"))
        continue
    accepted.append(message["command_id"])
print("accepted", accepted)
print("quarantined", quarantined)

Standalone Python reads three JSON strings. It accepts OPEN-17 and OPEN-18 because version and required fields fit, and quarantines E4 because v3 is unsupported and command_id is missing. It contacts no real stream.

Configuration · read the values

Practice JSON Schema

{
  "type": "object",
  "properties": {
    "schema_version": {
      "type": "integer",
      "enum": [
        1,
        2
      ]
    },
    "event_id": {
      "type": "string"
    },
    "command_id": {
      "type": "string"
    },
    "credential": {
      "type": "string"
    },
    "device": {
      "type": "string"
    }
  },
  "required": [
    "schema_version",
    "event_id",
    "command_id",
    "credential"
  ],
  "additionalProperties": true
}

The schema declares four required fields and types, permits v1 and v2, and makes device optional. additionalProperties=true allows other fields, but consumer code still needs tests. The schema does not validate anything by itself until a tool uses it.

PART 2 · WATCH IT WORK

A complete worked example

Follow each step, then the result

Worked example: the device field

E2/OPEN-18 arrives as v2 with an extra device field; E4 arrives as v3 with operation_id replacing command_id.

  1. Check that v2 keeps schema_version, event_id, command_id, and credential with the correct types.
  2. device is optional in our practice contract, so accept OPEN-18.
  3. For v3 look for command_id: it is absent. Do not infer its meaning from operation_id without an approved migration.
  4. Keep raw E4 and note 'unsupported version / missing command_id.'
What this shows

Safe evolution comes from a producer–consumer agreement and tests, not a version number alone.

How this helps with your mission

For the mission, name required fields and types, then inspect the three raw messages. Accept v1 E1/OPEN-17 and v2 E2/OPEN-18 because optional device=KIOSK-2 is a string and this reader supports v2. Quarantine E4: v3 is unsupported and command_id was replaced by operation_id. Keep raw E4 with both reasons. Report three messages, two accepted, and one rejected without treating SUPPLIER-SVC as a human identity.

PART 3 · YOUR TURN

Use the lesson to solve the mission

Story scene · practical task

Mission: the command the reader can no longer see

Voss shows a table where OPEN-18 appears to disappear after a producer update. Mara suspects a JSON contract break; Imani refuses to have unknown messages erased. Explain what the reader accepts and quarantines before the fictional meeting. The countdown belongs to the plot; the exercise has no timer.

Your task

  1. Name the required fields and types.
  2. Explain why the v2 message containing device remains readable to this practice reader.
  3. Explain the v3 problem and safe handling.
  4. List accepted commands and quarantined event IDs.

How to know you have succeeded

  • schema_version integer; event_id, command_id, credential strings.
  • v2 retains required fields, device is optional, and this reader supports v2.
  • v3 renames command_id; keep raw E4 in quarantine.
  • OPEN-17 and OPEN-18 accepted; E4 rejected without silent loss.
Open this mission in the browser workspace

Try code or SQL and keep a local draft. The mission questions are checked separately below.

Check the facts in your mission

Answer each factual question, then write your report in your own words. The program checks the choices; compare the report with the worked answer below.

1. Which set correctly describes the practice reader's required fields?
2. Why does the practice reader accept v2 E2/OPEN-18 with `device=KIOSK-2`?
3. E4 declares v3 and carries `operation_id=OPEN-19` instead of `command_id`. What should this practice reader do?
4. For the three messages E1/v1, E2/v2, and E4/v3, which lists does the simulation print?
5. Which conclusion respects the limits of `credential=SUPPLIER-SVC` and `device=KIOSK-2`?
See the worked answer
  1. The schema requires integer schema_version and string event_id, command_id, and credential. It allows v1 and v2.
  2. E2 keeps all four required fields and adds device=KIOSK-2. This practice reader can ignore or use that field while preserving OPEN-18.
  3. E4 declares v3 and replaces command_id with operation_id. Version and field do not match the contract; isolate the message and reason instead of inventing a command.
  4. The program prints accepted ['OPEN-17','OPEN-18'] and quarantined ['E4']. All three raw messages remain traceable; SUPPLIER-SVC still does not identify a human.

You can evolve messages without losing the second command. The final lesson will simulate a producer and consumer stop and restart, checking explicitly for loss and repeated effects.

Before you leave

Remember this

  • JSON represents objects with named fields; a schema fixes names, types, and requirements.
  • The contract requires integer schema_version and string event_id, command_id, credential; this reader supports v1 and v2.
  • E2 keeps required fields and adds optional string device=KIOSK-2, so OPEN-18 remains readable.
  • V3 E4 replaces command_id with operation_id; without an approved migration, do not guess OPEN-19.
  • The simulation accepts OPEN-17 and OPEN-18, quarantining E4 while preserving its raw text and reason.
  • A SUPPLIER-SVC or KIOSK-2 label does not prove a person's identity.
A–Z

Part of the lesson · keep nearby

New words, explained

These are the names of ideas used in the lesson above. Return here whenever a word feels unfamiliar.

JSON
A text format representing objects with field names and values.
Schema
A contract describing expected message fields and types.
Producer
A program writing messages into a stream.
Consumer
A program reading messages and acting on their contents.
Required field
A field that must be present and correctly typed to use the message.
Optional field
Extra information a reader may ignore when the contract permits it.
Compatibility
Whether a new message shape and an existing reader can work together.
Quarantine
Separate preservation of a rejected message with its reason.

Official references