← Complete program

Chapter 18 · Course 3 c18-m03

How do we recover an interrupted calculation?

Your goal Restore the memory and reading position of an interrupted calculation, then check that recovery gives the same result.

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 the missing Noctis 01 prototype crashed, and Voss wants to blame you. Imani found that OPEN-18 arrived after the crash but carries an earlier event time. Mara prepared a window that preserves late arrivals. As the team is about to publish the corrected timeline, the command-counting program stops. Voss claims the second result is lost and restarting will duplicate everything.

This lesson stands alone. A streaming program reads one message after another and may keep a small memory called state. Here it records which commands have already been seen for technical identity SUPPLIER-SVC. A checkpoint saves that state together with a matching reading position. You will restore a fictional copy after a failure and compare it with a run without failure. The local simulation does not prove transactional behavior in a live system.

02

Before the lesson

Purpose of this course

Restore the memory and reading position of an interrupted calculation, then check that recovery gives the same result.

Topics covered

Describe keyed state and separate the key from the person who used the account.; Explain the contents of a checkpoint and a source reading position.; Replay after a failure without applying the same business command twice.; Compare uninterrupted and restored output, then state the simulator's limit.

What you will learn

  • Describe keyed state and separate the key from the person who used the account.
  • Explain the contents of a checkpoint and a source reading position.
  • Replay after a failure without applying the same business command twice.
  • Compare uninterrupted and restored output, then state the simulator's limit.

PART 1 · THE LESSON

Understand step by step

1

Lesson · explanation

When the screen goes dark, the investigation must not vanish

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 wants to blame you. Imani found that OPEN-18, received after the crash signal, carries an earlier event time. Mara is preparing a timeline that retains late messages. Just before publication, the command-counting program stops and its screen goes dark.

Voss says the second result is lost and a restart will repeat every command. Mara gives you a sealed copy of the calculation's state and three retained messages. Your task is to reconstruct what the program knows, where it resumes reading, and what local output it produces. The suspense is fictional. You restart no real system, and the exercise has no timer.

A streaming program reads messages one after another. To decide whether a command was already counted, it may retain a small memory called state. Picture a librarian noting which order slips were fulfilled. If a photocopy arrives, the librarian checks the list before handing out another book. Lose the list in a crash, and a copy can appear new.

The goal is to restore that memory alongside the reading position, then compare a restarted run with an uninterrupted run. We also show what the simulation cannot establish: publishing a report to an outside service needs its own protection. SUPPLIER-SVC remains a technical label and does not reveal who used the account.

Pause and think

Why is rereading messages alone insufficient after a failure?

See the explanation

The program also needs its memory of commands already counted, or a repeat may cause another effect.

2

Lesson · explanation

Keyed state holds separate memories

In the fictional copy, position 40 has E1/OPEN-17, position 41 repeats E1/OPEN-17, and position 42 has E2/OPEN-18. All carry key SUPPLIER-SVC. Under that key the program keeps a set of already applied command_id values. After position 40, the set is {OPEN-17}. It is not a list of every message. It remembers the local effects already recognized.

A key groups related messages. Imagine lockers labeled with service names. SUPPLIER-SVC slips go in one locker; another service would have another locker and set. A repeated slip is checked against the right memory. The key must remain stable so a repeat reaches the group where its original command was recorded.

If OPEN-17 appeared under SUPPLIER-SVC one day and an unrelated key the next, two separate sets could both believe it new. The key choice and business command identifier must fit the intended deduplication rule. In this exercise all three messages keep the same key, so the program can recognize position 41 as an old command.

SUPPLIER-SVC names a technical identity, not a person. Software may use it, and several humans may have access to its key. Keyed state helps calculation but cannot turn a service label into evidence about a human. Even after OPEN-18 survives restoration, Imani must still check access records and the gate clock.

Pause and think

What set is stored under SUPPLIER-SVC after position 40?

See the explanation

{OPEN-17}, because the first command was recognized once.

3

Lesson · explanation

An offset marks where reading resumes

An offset is a position number inside one stream partition. Our simplified copy shows positions 40, 41, and 42. 'Next position 41' means the reader finished 40 and must begin with 41. It does not say 41 was already processed. After reading 41, the next position becomes 42. After 42, it becomes 43.

Picture a book after you finish page 40. A bookmark at 41 says which page to read next. If you move it to 43 before reading 41 and 42, you miss two pages. If you restart at 40 without your memory of finished tasks, you might repeat work. Bookmark and task list must describe the same moment.

In a real stream, each partition has its own offsets. Position 41 in one partition is not automatically the same message as position 41 in another. This lab shows one simple sequence to teach recovery. Do not assume an offset alone globally identifies an event or determines the real order of all actions. It marks a reading position within its partition.

A mistake would be calling 41 'the total number of commands.' It is a position, while {OPEN-17} describes commands already recognized. Both pieces are needed. The number says which messages to read; the set says whether their command_id should create a new local effect.

Pause and think

If a checkpoint says next position 41, has position 41 already been processed?

See the explanation

No. It is the next position to read after position 40.

4

Lesson · explanation

A checkpoint links memory and bookmark

A checkpoint is a consistent saved copy of what is needed for recovery. Here it contains SUPPLIER-SVC → {OPEN-17} and next position 41. Both pieces describe the same point: OPEN-17 was recorded after reading 40, and reading must continue at 41. Mara can give this copy to the program after the stop.

Saving position 41 without the set would forget that OPEN-17 was already applied. Its repeat at 41 might act again. Saving the set but restoring a position too far ahead, such as 43, would skip E2/OPEN-18. The consistent link between state and position protects the calculation from some losses and repeats.

Imagine saving a game. Save both the items collected and the character's location. Yesterday's items with tomorrow's position might skip a task. Yesterday's position with an empty item list might count a reward twice. The image helps show why both pieces belong to one saved moment.

A real engine may coordinate checkpoints across many operators and partitions. Check that a checkpoint completed and can truly be restored; an announced but incomplete file is not enough. Our copy is deliberately small and already consistent. It teaches the reasoning but cannot prove every production system will save successfully.

Pause and think

Which two parts of the practice checkpoint must be restored together?

See the explanation

SUPPLIER-SVC state containing OPEN-17 and next reading position 41.

5

Lesson · explanation

Replay 41, then read the genuine second command

After restoration, the program reads position 41. It again contains E1/OPEN-17. The SUPPLIER-SVC set already contains OPEN-17, so the program adds nothing to its local action list. It advances next position to 42. Rereading a retained message need not repeat its effect when restored state and command IDs work together.

Position 42 contains E2/OPEN-18. OPEN-18 is absent from {OPEN-17}. The program adds it, and the action list becomes [OPEN-17, OPEN-18]. After this message, next position is 43. Voss was wrong to say the second result must disappear: in this simulation, recovery sees the distinct second command.

Imagine two library slips in one locker. Slip 17 returns as a photocopy, and its 'fulfilled' stamp prevents another book. Slip 18 arrives without a stamp and gets its book. Ignoring every later slip for fear of repeats would lose 18. Fulfilling every paper without checking state would give another book for 17.

Positions 41 and 42 are retained inputs, not proof that physical gates moved. The script adds command names to a Python list. It contacts neither a gate nor a real stream. It shows local logic distinguishing the OPEN-17 replay from the new OPEN-18 command under stated conditions.

Pause and think

What happens when restored reading handles 41 and then 42?

See the explanation

41 adds nothing; 42 adds OPEN-18. The local list is [OPEN-17, OPEN-18], and next position is 43.

6

Lesson · explanation

Compare against the uninterrupted run

An uninterrupted run starts with empty state at position 40. It reads OPEN-17 and records it. At 41, the repeat adds nothing. At 42, OPEN-18 is added. Local output is [OPEN-17, OPEN-18] and next position 43. These values are a baseline for recovery, like an answer you can work out on paper.

The restored run begins at its saved point: state {OPEN-17}, next position 41, and a local list already containing OPEN-17. It skips the repeat's effect, adds OPEN-18, and finishes at the same point. The script prints same_result True because the two local lists match. With identical data, rules, and consistent starting state, this example gives a deterministic result.

Comparing only list lengths would be weak: two different command lists can each have length two. Compare values and, if order matters to the calculation, their order. Here both sequences are exactly OPEN-17 followed by OPEN-18. Also verify position 43 to know where reading continues. This makes Mara's answer repeatable.

The code uses deepcopy so restored state is separate from the reference. Without separation, modifying a shared set could change the baseline during the test and mislead the comparison. The lab covers only one tiny partition and fixed rules. A real restart test should vary failures, inputs, and destinations.

Pause and think

Which local output do the uninterrupted and restored runs share?

See the explanation

[OPEN-17, OPEN-18], with next position 43 in both.

7

Lesson · explanation

Outside publication needs separate protection

Engine state and the Python list live inside our simulation. A report already sent to a database or outside service is not automatically rolled back when the engine restores an older checkpoint. If a failure happens after sending but before checkpoint confirmation, recovery may send the same result again. Internal calculation can be correct while external publication is duplicated.

Imagine mailing a letter and losing your notebook before writing 'sent.' At restart, the notebook still says 'to send,' and you may post another copy. One possible protection gives the report a stable identifier and asks the receiver to reject a second write with that ID. Another coordinates a transaction when the destination supports one. The right choice depends on the real system.

That is why 'same list after recovery' does not automatically mean 'exactly one published report.' Mara must test a real stop and restart with the final destination before promising that guarantee. She must also observe whether the checkpoint actually completed. This lesson builds no end-to-end transaction; it identifies the risk and the necessary check.

The case timeline has other limits too. Even if OPEN-18 survives this simulation, the gate controller's time still needs independent verification. SUPPLIER-SVC does not reveal the human behind the account. Fixing calculation recovery does not automatically settle human attribution or clock accuracy.

Pause and think

Why does same_result True not prove an outside report was published only once?

See the explanation

A result already sent outside may be sent again after a failure unless the destination protects against duplicates.

8

Lesson · explanation

Write Mara's answer before the new chart

Begin your note with the sealed checkpoint: state under SUPPLIER-SVC contains {OPEN-17} and next position is 41. Explain that offset 40 was already accounted for. Then describe each remaining message: at 41, E1/OPEN-17 is a repeat with no new local effect; at 42, E2/OPEN-18 is a different command to add. Reading continues at 43.

Compare restored [OPEN-17, OPEN-18] with the identical uninterrupted list. This answers Voss for the fictional copy: the second result is not lost and OPEN-17 is not locally doubled. Keep raw messages and checkpoint version so Imani can repeat the demonstration. Do not present a local example as a measurement of the real gate system.

Add one concrete warning: if an outside report was published before a failure but the checkpoint was unconfirmed, replay may publish it again. Suggest a stable identifier and a restart test against the real destination, or a suitable transactional approach. That shows you distinguish the calculation's memory from an effect outside it.

The chapter's final lesson brings event time, windows, state, and checkpoints into a Flink lab. For now, make recovery checkable without erasing the second command or promising protection the simulator has not shown. The story presses the team, but an honest timeline must rest on results others can verify.

Pause and think

What limit should accompany the two recovered commands?

See the explanation

Their local result does not prove an outside destination is free of duplicates; test and protect it separately.

Visual guide

The calculation's recovery point

  1. 1Position 40: OPEN-17 → state {OPEN-17}
  2. 2Checkpoint: state {OPEN-17}, next position 41
  3. 3Failure then restore: 41 repeated, 42 OPEN-18
  4. 4Uninterrupted result = restored result: two commands

A checkpoint must cover state and stream progress; external outputs need their own check.

Code · read each line

Simulate a checkpoint and restoration

from copy import deepcopy
events = [
    {"offset": 40, "id": "E1", "command": "OPEN-17", "key": "SUPPLIER-SVC"},
    {"offset": 41, "id": "E1", "command": "OPEN-17", "key": "SUPPLIER-SVC"},
    {"offset": 42, "id": "E2", "command": "OPEN-18", "key": "SUPPLIER-SVC"},
]
def run(state, next_offset, actions):
    for event in events:
        if event["offset"] < next_offset:
            continue
        seen = state.setdefault(event["key"], set())
        if event["command"] not in seen:
            seen.add(event["command"])
            actions.append(event["command"])
        next_offset = event["offset"] + 1
    return state, next_offset, actions
unbroken = run({}, 40, [])
snapshot = {"SUPPLIER-SVC": {"OPEN-17"}}, 41, ["OPEN-17"]
restored = run(deepcopy(snapshot[0]), snapshot[1], snapshot[2].copy())
print("unbroken", unbroken[2])
print("restored", restored[2])
print("same_result", unbroken[2] == restored[2])
print("next_offset", restored[1])

The copy restarts with state after OPEN-17 and position 41. Both runs produce the same two commands and finish at position 43.

PART 2 · WATCH IT WORK

A complete worked example

Follow each step, then the result

Worked example: failure after OPEN-17

E1 was applied at position 40. The checkpoint records {OPEN-17} and 41. The reader restarts before the repeat at 41 and E2 at 42.

  1. Restore both {OPEN-17} and next position 41.
  2. Read 41: OPEN-17 is already in the set, so there is no new local effect.
  3. Read 42: OPEN-18 is new; add it and advance to 43.
  4. Compare [OPEN-17, OPEN-18] with the uninterrupted run and check the external destination separately.
What this shows

Correct recovery needs a consistent point linking memory and reading; final publication must also handle replay.

How this helps with your mission

For the mission, restore SUPPLIER-SVC → {OPEN-17} together with next position 41. Read 41 without reapplying OPEN-17; read 42 and add OPEN-18; next position is 43. Compare [OPEN-17, OPEN-18] with the identical uninterrupted simulation. Explain that a report sent to an outside destination can be republished after failure unless its write is idempotent or transactional, and that SUPPLIER-SVC identifies no person.

PART 3 · YOUR TURN

Use the lesson to solve the mission

Story scene · practical task

Mission: the calculation goes dark

Imani's screen turns black just after the first record. Voss demands that the old graph be frozen. Mara hands you the sealed checkpoint and retained messages: reconstruct what the program should do at restart before the new timeline is published. The urgency belongs to the story; the exercise has no timer.

Your task

  1. Write the SUPPLIER-SVC state and next position in the checkpoint.
  2. Process positions 41 and 42 after restoration.
  3. Compare local actions to the uninterrupted run and give the next position.
  4. Explain an external publication failure that the simulator cannot solve.

How to know you have succeeded

  • State {OPEN-17}, next position 41.
  • Repeat at 41 has no effect; E2 at 42 adds OPEN-18.
  • Both runs have two commands; next position 43.
  • External output requires idempotence or a transaction and a restart test.
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. What does the exercise checkpoint contain after position 40 was read?
2. After restoration, position 41 again contains E1/OPEN-17. What is its local effect?
3. Position 42 contains E2/OPEN-18. What local output and next position result after reading it?
4. What does comparing uninterrupted and restored runs show in this simulator?
5. Why does `same_result True` not guarantee an outside report was published exactly once?
See the worked answer
  1. The checkpoint holds SUPPLIER-SVC → {OPEN-17} and next position 41.
  2. At 41, OPEN-17 is already in state: no new effect. At 42, OPEN-18 is new and is added.
  3. Both uninterrupted and restored local actions are [OPEN-17, OPEN-18]. Reading continues at 43.
  4. If the report was sent before the failure but the checkpoint was not confirmed, replay could send it again. Give the report a stable identifier and test the real receiver.

You can recover an interrupted calculation. The chapter's final lesson brings event time, windows, state, and checkpoints into a Flink laboratory.

Before you leave

Remember this

  • State is memory retained between messages; keyed state holds a separate set for SUPPLIER-SVC.
  • An offset is a position within a partition; 41 is the next line after 40 in this copy.
  • The consistent checkpoint contains {OPEN-17} under SUPPLIER-SVC and next position 41.
  • After recovery, 41 repeats OPEN-17 without a local effect; 42 adds OPEN-18 and reading advances to 43.
  • Restored and uninterrupted runs locally produce [OPEN-17, OPEN-18].
  • Outside publication needs its own duplicate protection and restart test; the simulation cannot prove that guarantee.
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.

State
Memory retained by a program between messages.
Key
Value chosen to group related messages, here SUPPLIER-SVC.
Keyed state
Separate memory for each key value; another account would have its own set.
Checkpoint
A consistent copy of state and source positions needed to restart.
Offset
A message's position number within a stream partition.
Restoration
Restarting a computation from a checkpoint after failure.
Deterministic result
The same result for the same inputs, rules, and initial state.
External effect
An action outside the computation, such as publishing a report, which needs its own duplicate protection.

Official references