Chapter 11 · Course 1 c11-m01
When should you mark a step complete?
Your goal Decide when to confirm a batch and record its checkpoint in agreement with rows actually stored.
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.
Story · optional context
The story so far
You are Aster Motors’ new data recruit. After the crash that hurt Luca, Noctis 01 vanished and an authorization in your name was used to accuse you. Mara Sol recovered the vendor page with TRANSFER-7. Yet a published report shows that event twice in different forms. Imani notices a loading program restarted overnight: it had written rows, but its recovery notebook did not clearly say whether that batch was finished. You must reconstruct what needed confirmation before moving on.
This lesson stands alone. A pipeline is a sequence receiving, checking and storing events. A batch is a small group processed together; a checkpoint is like a bookmark showing where to resume after a stop. In this exercise, the confirmed count is called an offset: 0 at first, 2 after two checked events, 3 after the third. You will commit rows and bookmark together in a local transaction without access to the real system.
Before the lesson
Purpose of this course
Decide when to confirm a batch and record its checkpoint in agreement with rows actually stored.
Topics covered
Tell a batch, a read position and a confirmed position apart.; Explain why a bookmark advanced too early can lose events.; Put rows and checkpoint in one transaction when they share a database.; Predict state after a stop before or after COMMIT, then see the risk of separate confirmation.
What you will learn
- Tell a batch, a read position and a confirmed position apart.
- Explain why a bookmark advanced too early can lose events.
- Put rows and checkpoint in one transaction when they share a database.
- Predict state after a stop before or after
COMMIT, then see the risk of separate confirmation.
PART 1 · THE LESSON
Understand step by step
Lesson · explanation
A batch is a small packet of events handled together
The earlier pipeline read three events: E7, TRANSFER-7, and E9. Now they arrive in two batches. B1 contains E7 and TRANSFER-7; B2 contains E9. A batch is simply a packet that a program handles as one step. Grouping events helps a program resume after a stop: it must know which packet was really finished and which still needs work.
Imagine a delivery with two boxes. The first contains two books and the second contains one. You can open, check, and shelve each box before starting the next. If work stops after the first, you need to know whether its books reached the shelves. Seeing their covers on a desk is different from finding them in the completed inventory.
In this exercise the checkpoint starts at 0 and counts confirmed events. After B1 it should be 2 because two events have been stored and checked; after B2 it should be 3. Other systems may number positions differently. Write the convention before comparing numbers. Here 0, 2, and 3 mean confirmed-event counts for this story.
Voss says “processed” means “shown once on screen.” That rule cannot protect against a stop: a program may print an event name and fail before keeping its row. For Mara and Imani, a finished batch needs checked rows and a checkpoint describing that same completed state. An appearance on a screen is only an observation of a moment.
Pause and think
What is in B1 and B2, and what does this exercise's checkpoint count?
See the explanation
B1 has E7 and TRANSFER-7, B2 has E9, and the checkpoint counts confirmed events.
Lesson · explanation
A confirmed offset is an honest bookmark
An offset, or checkpoint, tells a program where to resume. Picture a bookmark in a novel: do not place it on page 20 after reading only to page 18, or you will skip two pages next time. Confirming offset 2 before E7 and TRANSFER-7 are stored creates a similar danger. A restart may begin with B2 and never load the missing B1 events.
The position read and the position confirmed can differ. A program may have read B1 from a file and printed both names. Until their rows are checked and committed, the confirmed position remains 0. Once the group is safely completed, it becomes 2. Naming these positions separately prevents a reading attempt from being mistaken for finished work.
The same rule applies to B2. After B1 commits, the checkpoint is 2 and E9 is next. Once E9 is stored and confirmed, it becomes 3. A notebook saying 3 while the database has only E7 and TRANSFER-7 would misstate progress. Check the stored IDs and the checkpoint together rather than trusting either number alone.
Always write what the offset means: here it is the number of confirmed events. Another system might use the last message ID or the number of the next message. Two matching numbers can describe different things if their conventions differ. The bookmark's definition belongs in the report, especially when Imani compares the vendor's notebook with database rows.
Pause and think
Why must the program wait before confirming offset 2 for B1?
See the explanation
If it confirms 2 before storing B1, a restart may skip E7 and TRANSFER-7 entirely.
Lesson · explanation
A transaction keeps related actions in one envelope
When rows and checkpoint live in the same database, a transaction can group them. BEGIN opens the group. The program writes E7 and TRANSFER-7, checks that both IDs are present, updates the checkpoint to 2, and then uses COMMIT to accept the group. We want all those changes to count together, rather than keeping only part of the handoff.
Imagine giving Imani a sealed envelope with two event cards and a note saying “two confirmed.” Before sealing it, you may still correct the packet. Once sealed, the cards and note travel together. A database transaction is such an envelope for data held in one database. It keeps the checkpoint from describing a different committed state than the rows.
The code example uses an in-memory SQLite database to demonstrate the boundary. executemany inserts two IDs; SELECT COUNT(*) checks the rows; an UPDATE sets the checkpoint to 2. The final output shows 2 and 2. One number counts stored rows and the other counts confirmed events. Their agreement is a useful check, even though the numbers describe different things.
If a check fails before COMMIT, ROLLBACK undoes this transaction. In the exercise's initial 0/0 state, that leaves zero committed B1 rows and checkpoint 0. B1 can be tried again. An in-memory database disappears when its process ends; a real restart demonstration needs persistent storage. The transaction lesson concerns which changes become committed together.
Pause and think
Which B1 actions belong in one transaction?
See the explanation
Write E7 and TRANSFER-7, check their rows and IDs, set the checkpoint to 2, and commit the group.
Lesson · explanation
A stop before COMMIT leaves no half-confirmed batch
Suppose the program starts the transaction and inserts E7 and TRANSFER-7, then stops before COMMIT. In the model where rows and checkpoint share one transaction, the unfinished group is rolled back. Its committed state remains what it was before B1: zero B1 rows and confirmed offset 0. On a persistent version of this setup, the restart must try B1 again.
Think of a letter saved as a draft but never sent. Two sentences may be visible on your screen, yet the recipient has received nothing. COMMIT is like sending the complete envelope: it marks the group as accepted. Seeing inserted rows within a still-open transaction is not proof that those rows will survive a stop.
A stop before BEGIN also leaves 0/0. A stop after the inserts but before updating the checkpoint leaves 0/0 in this transaction model because all pending changes are abandoned together. You need not memorize every instant. Remember the boundary: before COMMIT, the batch has not been confirmed. If a check detects a mismatch, use ROLLBACK rather than advancing the marker.
Draw a line labeled COMMIT for Imani. On its left are attempted actions that may have printed names, but a stop leaves the previous committed state. On its right, the whole group has been accepted. A screen display could happen on either side, which is why Voss's definition of “processed” cannot tell the team whether B1 was safely completed.
Pause and think
If B1 stops just before COMMIT in the shared transaction, what committed state remains?
See the explanation
The previous 0/0 state remains; B1 must be retried.
Lesson · explanation
After COMMIT, rows and checkpoint agree
If B1's COMMIT succeeds, the two event rows and confirmed offset 2 belong to the accepted state. A restart against a persistent database should begin with B2, containing E9. After B2 is checked and committed in the same fashion, there are three events and offset 3. The expected sequence is 0 rows/0 confirmed, then 2/2, then 3/3.
Imagine sealing and filing the first box's envelope before the lights go out. When you return, the filed envelope contains its two cards and the “two confirmed” note. You can move to the second box instead of redoing the first. This reasoning depends on rows and checkpoint sharing the same committed database state. The small in-memory script demonstrates the actions but does not survive its own process ending.
A COMMIT does not prove the events themselves are authentic. If TRANSFER-7 was wrong in the incoming copy, it can be consistently committed as wrong data. Technical agreement between rows and checkpoint is necessary for correct resumption; checking original pages and who created them is another task. Do not use a successful database operation as a verdict about the accident.
When Mara asks for the state after each batch, say what each number counts. After B1: two stored event IDs and checkpoint 2. After B2: three stored event IDs and checkpoint 3. This lets Imani check that the report has not silently skipped the transfer page. It also gives the next worker a precise point from which to resume.
Pause and think
What state follows B1's commit and then B2's commit?
See the explanation
After B1, 2 rows and offset 2; after B2, 3 rows and offset 3 under this exercise's convention.
Lesson · explanation
An external notebook left behind can cause replay
The vendor may store events in one database but keep the checkpoint in a separate notebook. Imagine B1 becomes committed in the database, then the program stops before writing “2 confirmed” in that notebook. The external checkpoint still says 0. At restart the reader believes it must begin again and reads E7 and TRANSFER-7 a second time. This mismatch creates a risk of repeated presentation.
Think of someone shelving two books but forgetting to tick them off a paper list. A replacement sees an empty list and handles the same titles again. The books were handled once; the list was simply behind. Disagreement between two storage places can therefore explain a replay without showing who caused the stop or whether anyone acted dishonestly.
If rows and checkpoint cannot share a transaction, the program must be ready to see a batch already written. It needs to recognize stored event IDs and avoid publishing a second row for the same event while retaining a record of the replay. That property is called idempotence and comes in the next lesson. For now, remember that an external offset 0 does not guarantee an empty events database.
Make a two-column comparison before accusing anyone. In one column record the database's event IDs, row count, and known commit moment. In the other record the external notebook's last confirmed count and time. If the database shows B1 but the notebook says 0, write “mismatch to investigate,” not “new transfer.” Ask for restart logs and the report's publication rule. Two appearances of TRANSFER-7 may support a technical replay hypothesis, not a conclusion about a person.
Pause and think
What may happen if B1 is stored but an external checkpoint still says 0?
See the explanation
Restart may reread B1 and present E7 and TRANSFER-7 again; existing IDs must be checked before republishing.
Visual guide
B1 inside one transaction
- 1Start: 0 rows, confirmed offset 0
- 2Insert E7 + TRANSFER-7 and verify 2 rows
- 3
COMMIT: 2 rows and offset 2 together
A stop before COMMIT leaves 0 and 0; afterward 2 and 2. Separate confirmation may create a mismatch.
Code · read each line
Mark B1 complete only after checking
import sqlite3
db = sqlite3.connect(':memory:')
db.execute('CREATE TABLE events (event_id TEXT)')
db.execute('CREATE TABLE checkpoints (name TEXT PRIMARY KEY, confirmed_count INTEGER NOT NULL)')
db.execute("INSERT INTO checkpoints VALUES ('vendor', 0)")
db.commit()
batch = ['E7', 'TRANSFER-7']
try:
db.execute('BEGIN')
db.executemany('INSERT INTO events VALUES (?)', [(event_id,) for event_id in batch])
stored = db.execute('SELECT COUNT(*) FROM events').fetchone()[0]
if stored != len(batch):
raise ValueError('batch count mismatch')
db.execute("UPDATE checkpoints SET confirmed_count = ? WHERE name = 'vendor'", (2,))
db.commit()
except Exception:
db.rollback()
raise
print(db.execute('SELECT COUNT(*) FROM events').fetchone()[0])
print(db.execute("SELECT confirmed_count FROM checkpoints WHERE name = 'vendor'").fetchone()[0])
db.close()The in-memory database holds rows and checkpoint. The script inserts B1, checks two rows, advances the count to 2 and commits one transaction. It prints 2 and 2. An error within that group causes ROLLBACK.
PART 2 · WATCH IT WORK
A complete worked example
Follow each step, then the result
Worked example: three possible stopping times
B1 contains E7 and TRANSFER-7. Initially the database has no rows and confirmed count is 0.
- If the program stops before
BEGIN, nothing changes: 0 rows and offset 0. The next run handles B1. - If it stops after inserting both rows but before
COMMITin the same transaction, that group is canceled: on restart, 0 rows and offset 0. - If it stops after
COMMIT, both rows and offset 2 were confirmed together. The restart begins with B2 and E9. - If an outside system holds the offset, it could remain 0 although rows already exist. This mismatch signals a replay risk to handle explicitly.
Confirmed position must describe the same state as durable data. Separation of the two requires a replay strategy.
How this helps with your missionThe worked example compares three stopping moments around B1: before BEGIN, before COMMIT, and after COMMIT. In the mission, use that boundary for E7 and TRANSFER-7. Before the shared transaction is committed, its accepted state is 0 rows/offset 0; afterward it is 2/2. B2 then adds E9 and reaches 3/3. Finally explain why a separate checkpoint still at 0 could replay B1 even if its rows were committed elsewhere. That possibility guides investigation without proving who caused the restart.
PART 3 · YOUR TURN
Use the lesson to solve the mission
Story scene · practical task
Mission: the midnight restart
In the story, a vendor service stopped just after writing B1. Imani has E7 and two forms of TRANSFER-7. Mara gives you a simulation: B1 has E7 and TRANSFER-7, B2 has E9, and confirmed count starts at 0. The practice database can hold rows and checkpoint in one transaction. Voss claims “processed” means “shown once on screen”; explain a more precise rule.
Your task
- Give the confirmed count after B1 and after B2 once each is truly checked.
- Describe the correct order of actions inside B1’s transaction.
- Give expected state if the program stops before or after B1’s
COMMIT. - Explain what can happen if the database keeps B1 while an external notebook still says 0.
How to know you have succeeded
- After B1, this exercise’s offset is 2; after B2, 3.
- Insert, check both rows, update checkpoint and
COMMITbelong to one group. - Before commit: 0 rows and 0 confirmed; afterward: 2 rows and 2 confirmed.
- A notebook at 0 may replay B1; existing events must be recognized before republishing.
Try code or SQL and keep a local draft. The mission questions are checked separately below.
See the worked answer
- B1 confirms two events, moving offset from 0 to 2. B2 adds E9, moving it to 3 after verification and commit.
- Open with
BEGIN, write E7 and TRANSFER-7, check both rows and IDs, set checkpoint to 2, thenCOMMIT. On failure,ROLLBACK. - In one transaction, a stop before
COMMITcancels rows and checkpoint: 0/0. AfterCOMMIT, both remain: 2/2. A screen display may have happened at another moment; it does not prove durability. - If the outside checkpoint remains 0 while B1 is durable, restart reads E7 and TRANSFER-7 again. That may explain a repetition but not who caused it; next lesson will make replay safe.
You know when to confirm a batch. Next you will allow a necessary replay without making a second row for the same event.
Before you leave
Remember this
- A batch is a packet of events: B1 has two and B2 has one.
- This exercise's offset counts confirmed events, not names merely read or printed.
- A transaction can group rows, checks, and checkpoint when they share one database.
- Before
COMMIT, a stop leaves the previous 0/0 state in this model; after B1 commits, it is 2/2. - After B2 is confirmed, expect three rows and offset 3.
- An external checkpoint still at 0 can replay B1; a later design must recognize already stored events.
Continue with the integrated lessons
After the lesson and its mission, work through the additional lessons below in order. Each workshop supplies its own fictional data: do not merge identifiers or times from separate exercises into the story timeline.
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.
- Batch
- A small group of events processed as one step, here E7 and TRANSFER-7.
- Offset
- A position in an event sequence; here the number of confirmed events.
- Checkpoint
- A saved value telling a program where to restart after a stop.
- Transaction
- A group of writes kept together by
COMMITor canceled byROLLBACK. - COMMIT
- Durable confirmation of a transaction’s writes.
- ROLLBACK
- Cancellation of writes in a still-open transaction.
- Verification
- Checking an expected result before declaring work complete.
Approfondissements de ce cours
Télécharger le jeu de données de cet atelier. Sa préparation sur une base de test isolée est confiée à la personne qui administre l’atelier ; les lectures utilisent ensuite le compte et les paramètres qu’elle fournit.
Attribuer un lot et comprendre les verrous de table
La concurrence désigne l’activité de plusieurs sessions sur les mêmes données. Un verrou limite certaines opérations concurrentes sur une table, un enregistrement ou un intervalle d’index selon le moteur. Restreindre le plus petit périmètre utile améliore souvent la concurrence, mais dépend des requêtes et de leur plan. La description du PDF concernait MySQL5.5 ; il faut vérifier les règles du moteur actuel.
Le cas Client/Adoption devient Consommateur/Affectation : une équipe consomme une livraison, sa réservation a une date, une exécution facultative, un coût et un état terminé. Une contrainte unique sur livraison_id empêche deux affectations du même objet selon ce contrat ; la clé composée (consommateur_id,livraison_id) illustre l’identité d’association même si l’unicité livraison pourrait déjà servir de clé. Le choix doit suivre la règle métier plutôt qu’être copié mécaniquement.
Des coordonnées peuvent comporter nom, contact, adresse, code postal, ville, pays et email ; un code postal est du texte même s’il semble numérique. Un email binaire unique distingue exactement des octets, ce qui n’est pas forcément la règle d’identité souhaitée d’un contact. La source le choisit ainsi ; dans un projet, définir normalisation, collation, confidentialité et traitement des absences. Un TINYINT(1) n’impose pas à lui seul un domaine booléen : CHECK ou un modèle approprié doit en donner les valeurs.
LOCK TABLES table READ, autre_table AS alias WRITE acquiert des verrous explicites de table. READ autorise les lectures compatibles et bloque les écritures concurrentes ; WRITE limite beaucoup plus fortement les accès des autres sessions. Les détails diffèrent du verrouillage de lignes InnoDB et des lectures MVCC. UNLOCK TABLES libère les verrous explicites de table de la session, pas une table choisie arbitrairement dans une liste.
La session qui a pris LOCK TABLES doit utiliser les tables et alias verrouillés. Verrouiller une table sous son nom n’autorise pas automatiquement une occurrence sous un nouvel alias. Si une requête doit employer deux occurrences, les noms ou alias nécessaires doivent figurer dans le même LOCK TABLES. Une occurrence verrouillée READ ne peut pas être modifiée par cette session.
Un nouveau LOCK TABLES remplace les verrous explicites précédents de cette session ; il ne les additionne pas. L’exemple qui verrouille d’abord affectation puis format_ref et son alias laisse donc seulement les derniers verrous. Accéder ensuite à affectation peut être refusé comme table non verrouillée. Les erreurs de nom ou d’alias se distinguent d’une attente causée par une autre connexion.
Dans un essai à deux sessions, une lecture sur une table verrouillée READ peut réussir tandis qu’un UPDATE attend ; une table verrouillée WRITE bloque les opérations incompatibles de l’autre session jusqu’à libération. Tester aussi les demandes de verrous de l’autre session permet de constater les compatibilités. Les délais doivent rester bornés, les transactions terminées et les verrous libérés à la fin de l’atelier.
LOCK/UNLOCK TABLES interagissent avec les transactions et START TRANSACTION peut libérer des verrous de table. Pour un usage InnoDB qui les nécessite, la séquence documentée et les validations implicites doivent être comprises ; le livre montre autocommit0, prise de verrous avant les changements, COMMIT ou ROLLBACK, puis UNLOCK. Les verrous de lignes transactionnels sont souvent plus adaptés à une réservation ciblée.
Exemple appliqué aux données
CREATE TABLE consommateur (consommateur_id SMALLINT UNSIGNED PRIMARY KEY,nom VARCHAR(100) NOT NULL,contact VARCHAR(60),adresse VARCHAR(200),code_postal VARCHAR(12),ville VARCHAR(60),pays VARCHAR(60),email VARBINARY(200) UNIQUE) ENGINE=InnoDB;
CREATE TABLE affectation (consommateur_id SMALLINT UNSIGNED NOT NULL,livraison_id BIGINT UNSIGNED NOT NULL,date_reservation DATE NOT NULL,date_execution DATE,cout DECIMAL(7,2) NOT NULL,termine TINYINT NOT NULL DEFAULT 0 CHECK(termine IN(0,1)),PRIMARY KEY(consommateur_id,livraison_id),UNIQUE(livraison_id),FOREIGN KEY(consommateur_id) REFERENCES consommateur(consommateur_id),FOREIGN KEY(livraison_id) REFERENCES livraison(livraison_id)) ENGINE=InnoDB;
INSERT INTO consommateur(consommateur_id,nom,email) VALUES(1,'Équipe ventes','ventes@example.invalid'),(2,'Équipe qualité','qualite@example.invalid');
LOCK TABLES format_ref READ,profil_flux AS p READ;
SELECT libelle FROM format_ref ORDER BY format_id;
SELECT nom FROM profil_flux AS p ORDER BY profil_id;
UNLOCK TABLES;
Sur base de test autorisée ; les essais de concurrence demandent plusieurs connexions distinctes.
À toi de jouer
Pourquoi un alias non déclaré dans LOCK TABLES peut-il provoquer une erreur dans la session qui possède le verrou ?
Voir la correction expliquée
Les verrous explicites sont associés aux occurrences déclarées. Une table sous un autre alias n’est pas automatiquement couverte ; il faut déclarer les occurrences nécessaires dans la prise de verrous.
Références : LOCK TABLES.
Adapté de Administrez vos bases de données avec MySQL, Chantal Gribaumont (Taguan), pages 233–242. Consulter le PDF source et ses illustrations · Provenance. Licence Creative Commons 6 2.0 (libellé exact de la couverture ; modalités précises non résolues)
Protéger une lecture destinée à une écriture
Les écritures InnoDB acquièrent des verrous sur les enregistrements et accès d’index concernés. UPDATE et DELETE n’ont pas besoin d’une commande LOCK explicite pour cela ; INSERT protège aussi la nouvelle ligne. La portée exacte ne se déduit pas seulement des lignes du résultat : elle dépend des index parcourus, du prédicat et de l’isolation.
Une lecture simple peut être une lecture cohérente par MVCC sans verrou partagé explicite. SELECT ... FOR SHARE est la forme actuelle pour une lecture verrouillante partagée ; LOCK IN SHARE MODE est la forme historique à reconnaître. SELECT ... FOR UPDATE demande des verrous adaptés à une modification ultérieure. Les verrous sont utiles dans une transaction conservée ouverte jusqu’au COMMIT ou ROLLBACK.
Deux verrous partagés compatibles peuvent coexister, mais un verrou exclusif empêche les demandes partagées ou exclusives incompatibles d’autres transactions. La source disait parfois qu’un verrou exclusif interdit toute lecture : c’est faux pour une lecture cohérente MVCC qui peut lire une ancienne version. Ne confonds donc pas « lire le résultat courant sous verrou » et « lire une version cohérente ».
L’image de la photographie aide à expliquer la visibilité, mais une transaction ne copie pas nécessairement toutes les tables lors de START TRANSACTION. Sous REPEATABLE READ, une lecture cohérente établit normalement sa vue selon les règles d’InnoDB. Une lecture verrouillante ou une écriture ne doit pas être décrite comme actualisant automatiquement toute la photographie pour les futures lectures ordinaires.
Essais à deux connexions : A modifie une ligne sans valider ; B peut faire une lecture simple d’une version visible mais une écriture ou une lecture verrouillante incompatible attend. Après libération par A, B peut poursuivre sur la valeur courante appropriée. Une insertion non validée peut aussi bloquer une recherche verrouillante qui concerne son intervalle, alors qu’une recherche sur une zone indépendante peut continuer.
Autre essai : A prend FOR SHARE sur plusieurs lignes ; B peut prendre un verrou partagé compatible mais attend pour une modification. Avec FOR UPDATE dans A, les lectures verrouillantes de B deviennent incompatibles, tandis qu’un SELECT cohérent peut rester possible. Ces distinctions expliquent les exemples de lecture, suppression, modification et insertion du PDF sans assimiler toutes les opérations à un verrou de table WRITE.
Les index limitent souvent le parcours et donc les verrous utiles. Un filtre sur une colonne non indexée peut scanner et verrouiller beaucoup plus de lignes que prévu, tandis qu’un filtre de clé précise permet un accès ciblé. Un autre index peut retrouver la même ligne et rencontrer le même conflit : il ne faut pas utiliser le même nom d’index pour être en concurrence. Les comportements varient avec le plan et le niveau d’isolation.
Un fantôme est une nouvelle ligne répondant à un prédicat entre deux observations. InnoDB peut utiliser des verrous d’enregistrement, de gap et next-key, combinant enregistrement et intervalle, pour empêcher certaines insertions concurrentes en REPEATABLE READ. La plage protégée ne se résume pas toujours à « après la dernière ligne » ; il faut comprendre les intervalles d’index et la recherche. Une égalité sur une clé unique existante peut ne verrouiller que l’enregistrement ; une clé absente ou un prédicat de plage demande une autre analyse.
L’atelier doit contrôler les délais et traiter les erreurs d’attente ou de deadlock. Une libération de jalon n’est pas une garantie que tous les verrous associés ont disparu ; termine explicitement la transaction selon le scénario. Des opérations ciblées et brèves réduisent le risque de bloquer inutilement les autres traitements.
Exemple appliqué aux données
START TRANSACTION;
SELECT livraison_id,nom FROM livraison WHERE livraison_id=1 FOR UPDATE;
-- Dans une autre connexion, essayer lecture simple puis FOR SHARE avec délai borné.
-- Revenir ici pour terminer la transaction :
ROLLBACK;
Sur base de test autorisée ; les essais de concurrence demandent plusieurs connexions distinctes.
À toi de jouer
Un SELECT simple doit-il toujours attendre lorsqu’une autre transaction possède un verrou exclusif sur cette ligne ?
Voir la correction expliquée
Non. Une lecture cohérente MVCC peut lire une version visible sans prendre ce verrou incompatible. Une lecture verrouillante et une écriture suivent d’autres règles.
Références : Lectures verrouillantes · Verrous InnoDB · Next-key.
Adapté de Administrez vos bases de données avec MySQL, Chantal Gribaumont (Taguan), pages 242–250. Consulter le PDF source et ses illustrations · Provenance. Licence Creative Commons 6 2.0 (libellé exact de la couverture ; modalités précises non résolues)
Suivre une connexion TCP sans confondre réception et traitement
TCP fournit aux applications un flux d’octets ordonné et fiable tant que la connexion peut progresser. Il numérote les octets, acquitte les données et retransmet selon ses mécanismes lorsqu’une perte est détectée ou supposée. Les acquittements peuvent être cumulatifs : ils ne signifient pas un paquet d’acquittement distinct pour chaque paquet envoyé. TCP peut finalement signaler une erreur ; il ne garantit pas qu’un service continue à fonctionner indéfiniment.
L’établissement ordinaire utilise SYN, SYN+ACK puis ACK : le client et le serveur synchronisent leurs numéros de séquence et confirment les états nécessaires. C’est une connexion TCP bidirectionnelle, avec un flux et un espace de séquence par sens, pas deux connexions indépendantes au sens de deux sockets séparées à établir. Les flags sont des bits de contrôle dans l’en-tête. Des options et extensions peuvent modifier les détails, notamment la présence de données tôt dans certains échanges ; le schéma simple ne décrit pas tous les cas.
Une fois la connexion établie, les segments peuvent porter des données, des acquittements et d’autres informations de contrôle. La taille d’un appel send n’est pas une frontière de message reçue ; le destinataire peut lire le flux en plusieurs fois ou regrouper des données. Un protocole de livraison doit donc prévoir délimitation, longueur ou format permettant la reconstitution. Le flag ACK ne prouve pas que l’application a validé le lot ou l’a écrit durablement.
FIN indique la fin d’envoi d’un sens du flux, pas nécessairement la fermeture simultanée des deux sens. Le pair acquitte et peut encore envoyer ses données avant son propre FIN. Les FIN et ACK peuvent être combinés ou séparés ; la séquence de trois segments présentée dans le livre est un exemple, pas une obligation. Des états tels que TIME_WAIT persistent après l’échange final pour traiter des segments anciens et la retransmission éventuelle de la fin.
Un segment TCP possède notamment ports, numéros de séquence et d’acquittement, longueur d’en-tête, flags, fenêtre et checksum. L’en-tête minimal fait vingt octets et les options peuvent l’allonger. Le checksum n’est pas le CRC Ethernet. Parmi les flags historiques : SYN pour synchroniser, ACK pour valider le champ d’acquittement, FIN pour terminer un sens, RST pour réinitialiser une connexion. Les mécanismes de congestion ont aussi leurs bits ; le protocole actuel ne se limite pas aux six flags décrits dans le PDF.
RST peut signaler un segment sans connexion correspondante ou un refus dans certaines situations, notamment une tentative vers un port fermé. Un pare-feu peut aussi filtrer ou rejeter : absence de RST n’est pas une preuve de port ouvert. Une « incohérence » ne provoque pas systématiquement une réinitialisation ; la pile vérifie les segments selon ses règles. PSH concerne la remise de données et URG signale l’interprétation du pointeur urgent : aucun des deux n’est une garantie de priorité réseau générale.
Pour un pipeline reprenable, distinguer trois confirmations : TCP a reçu des octets ; le protocole applicatif a répondu ; la transaction ou le lot est enregistré durablement et identifié. Une coupure après l’écriture mais avant la réponse peut laisser le client incertain. C’est le contrat d’idempotence et de reprise étudié dans ce chapitre qui résout le risque de duplication, et non le seul choix de TCP.
À toi de jouer
Le client a envoyé tout un fichier sur TCP puis perd la connexion avant la réponse métier. Peut-il affirmer que le fichier n’a pas été enregistré ?
Voir la correction expliquée
Non : le serveur peut l’avoir enregistré avant la coupure. Rechercher le résultat par identifiant de lot ou reprendre selon un contrat idempotent ; ne pas assimiler silence de la réponse à absence d’effet.
Références : RFC 9293 — TCP actuel · Python — sockets et gestion du flux.
Adapté de Apprenez le fonctionnement des réseaux TCP/IP, Romain Guichard (Caelifer), elalitte, pages 151–155. Consulter le PDF source et ses illustrations · Provenance. Licence Creative Commons 6 2.0 (mention extraite de la couverture ; variante non identifiée)