Skip to content

Commit f704bd1

Browse files
fix: read a version 1 checkpoint, which held text content
1 parent 100721d commit f704bd1

3 files changed

Lines changed: 58 additions & 20 deletions

File tree

‎syft/sync/checkpoints/checkpoint.py‎

Lines changed: 30 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -11,8 +11,9 @@
1111
- After N incremental checkpoints: compact into single full Checkpoint
1212
"""
1313

14+
import json
1415
from pathlib import Path
15-
from typing import TYPE_CHECKING, Dict, List
16+
from typing import TYPE_CHECKING, Any, Dict, List
1617

1718
from pydantic import BaseModel, ConfigDict, Field
1819

@@ -29,23 +30,36 @@
2930

3031
CHECKPOINT_FILENAME_PREFIX = "checkpoint"
3132
INCREMENTAL_CHECKPOINT_PREFIX = "incremental_checkpoint"
32-
CHECKPOINT_VERSION = 1
33+
# Version 2 stores file content as base64 bytes; version 1 stored it as text.
34+
CHECKPOINT_VERSION = 2
35+
# An incremental checkpoint holds events, whose format did not change.
36+
INCREMENTAL_CHECKPOINT_VERSION = 1
3337

3438

35-
def _check_version(version: int, kind: str) -> None:
39+
def _check_version(version: int, latest: int, kind: str) -> None:
3640
"""Refuse a checkpoint from a later client."""
3741

3842
# A later client can change what a field holds while the object still parses.
3943
# The restore would then be wrong and silent. Every caller falls back to a
4044
# download of all events, so a refusal costs one slow cold start.
4145

42-
if version > CHECKPOINT_VERSION:
46+
if version > latest:
4347
raise ValueError(
4448
f"This {kind} has version {version}, and this client reads up to "
45-
f"version {CHECKPOINT_VERSION}."
49+
f"version {latest}."
4650
)
4751

4852

53+
def _upgrade_text_content(checkpoint: dict[str, Any]) -> dict[str, Any]:
54+
"""A version 1 checkpoint as the current version: its text content as
55+
UTF-8 bytes. Version 1 held only text, so this gives the exact bytes."""
56+
files = [
57+
{**file, "content": file["content"].encode("utf-8")}
58+
for file in checkpoint["files"]
59+
]
60+
return {**checkpoint, "version": CHECKPOINT_VERSION, "files": files}
61+
62+
4963
# Default compacting threshold: merge after this many incremental checkpoints
5064
DEFAULT_COMPACTING_THRESHOLD = 4
5165

@@ -175,11 +189,14 @@ def as_compressed_data(self) -> bytes:
175189

176190
@classmethod
177191
def from_compressed_data(cls, data: bytes) -> "Checkpoint":
178-
"""Load checkpoint from compressed data."""
192+
"""Load checkpoint from compressed data. A version 1 checkpoint, which
193+
held text content, loads as the current version."""
179194
uncompressed_data = uncompress_data(data)
180-
checkpoint = cls.model_validate_json(uncompressed_data)
181-
_check_version(checkpoint.version, "checkpoint")
182-
return checkpoint
195+
checkpoint = json.loads(uncompressed_data)
196+
_check_version(checkpoint["version"], CHECKPOINT_VERSION, "checkpoint")
197+
if checkpoint["version"] <= 1:
198+
return cls.model_validate(_upgrade_text_content(checkpoint))
199+
return cls.model_validate_json(uncompressed_data)
183200

184201

185202
class IncrementalCheckpoint(BaseModel):
@@ -196,7 +213,7 @@ class IncrementalCheckpoint(BaseModel):
196213
- After compacting: single full Checkpoint with merged state
197214
"""
198215

199-
version: int = CHECKPOINT_VERSION
216+
version: int = INCREMENTAL_CHECKPOINT_VERSION
200217
timestamp: float = Field(default_factory=create_event_timestamp)
201218
email: str
202219
sequence_number: int # 1, 2, 3, ... (which checkpoint this is)
@@ -236,7 +253,9 @@ def from_compressed_data(cls, data: bytes) -> "IncrementalCheckpoint":
236253
"""Load from compressed data."""
237254
uncompressed_data = uncompress_data(data)
238255
checkpoint = cls.model_validate_json(uncompressed_data)
239-
_check_version(checkpoint.version, "incremental checkpoint")
256+
_check_version(
257+
checkpoint.version, INCREMENTAL_CHECKPOINT_VERSION, "incremental checkpoint"
258+
)
240259
return checkpoint
241260

242261

‎tests/unit/test_checkpoint_version.py‎

Lines changed: 26 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -10,16 +10,20 @@
1010
cold start and nothing else.
1111
"""
1212

13+
import json
14+
1315
import pytest
1416
from syft.sync.checkpoints.checkpoint import (
1517
CHECKPOINT_VERSION,
18+
INCREMENTAL_CHECKPOINT_VERSION,
1619
Checkpoint,
1720
IncrementalCheckpoint,
1821
)
1922
from syft.sync.checkpoints.rolling_state import (
2023
ROLLING_STATE_VERSION,
2124
RollingState,
2225
)
26+
from syft.sync.utils.syftbox_utils import compress_data
2327

2428
EMAIL = "alice@example.com"
2529

@@ -45,7 +49,7 @@ def test_an_incremental_checkpoint_round_trips():
4549
loaded = IncrementalCheckpoint.from_compressed_data(
4650
_incremental().as_compressed_data()
4751
)
48-
assert loaded.version == CHECKPOINT_VERSION
52+
assert loaded.version == INCREMENTAL_CHECKPOINT_VERSION
4953

5054

5155
def test_a_rolling_state_round_trips():
@@ -60,8 +64,9 @@ def test_a_later_checkpoint_is_refused():
6064

6165

6266
def test_a_later_incremental_checkpoint_is_refused():
63-
data = _incremental(version=CHECKPOINT_VERSION + 1).as_compressed_data()
64-
with pytest.raises(ValueError, match=str(CHECKPOINT_VERSION + 1)):
67+
later_version = INCREMENTAL_CHECKPOINT_VERSION + 1
68+
data = _incremental(version=later_version).as_compressed_data()
69+
with pytest.raises(ValueError, match=str(later_version)):
6570
IncrementalCheckpoint.from_compressed_data(data)
6671

6772

@@ -71,7 +76,21 @@ def test_a_later_rolling_state_is_refused():
7176
RollingState.from_compressed_data(data)
7277

7378

74-
def test_an_earlier_version_still_loads():
75-
# Version 0 predates the field. Those objects are the shape this client reads.
76-
data = _checkpoint(version=0).as_compressed_data()
77-
assert Checkpoint.from_compressed_data(data).version == 0
79+
def test_a_version_1_checkpoint_loads_its_text_content():
80+
# Version 1 stored content as text. "true" is valid base64 too, so a base64
81+
# read would give other bytes without an error.
82+
version_1 = {
83+
"version": 1,
84+
"timestamp": 1.0,
85+
"email": EMAIL,
86+
"last_event_timestamp": 1.0,
87+
"files": [{"path": "public/a.txt", "hash": "abc", "content": "true"}],
88+
}
89+
data = compress_data(json.dumps(version_1).encode("utf-8"))
90+
91+
loaded = Checkpoint.from_compressed_data(data)
92+
93+
assert loaded.version == CHECKPOINT_VERSION
94+
assert loaded.files[0].content == b"true"
95+
reloaded = Checkpoint.from_compressed_data(loaded.as_compressed_data())
96+
assert reloaded.files[0].content == b"true"

‎tests/unit/test_versioned_folder_adopt.py‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -185,13 +185,13 @@ def _checkpoints_folder_names(cached_client) -> list[str]:
185185

186186
def test_an_adopted_folder_serves_a_checkpoint_from_an_earlier_client():
187187
# Version 0 predates the field, which is the shape an earlier client wrote.
188-
# The rename finds the folder and the file still loads.
188+
# The rename finds the folder and the file still loads, as the current version.
189189
router, cached_client, older_name = _checkpoints_owner_with_version(0)
190190

191191
checkpoint = router.get_latest_checkpoint()
192192

193193
assert checkpoint is not None, "the adopted folder must still serve its files"
194-
assert checkpoint.version == 0
194+
assert checkpoint.version == CHECKPOINT_VERSION
195195
assert _checkpoints_folder_names(cached_client) == [
196196
router.connections.owner_store_con._get_checkpoints_folder_name()
197197
], "the read must go through the adopt, which renames the folder"

0 commit comments

Comments
 (0)