Skip to content

Commit d36d5bf

Browse files
authored
Merge pull request #56 from bluedynamics/fix/reduce-build-newobj
fix: REDUCE-created instances re-encode with REDUCE (#32)
2 parents 7f5cbc5 + 7aecfc0 commit d36d5bf

10 files changed

Lines changed: 395 additions & 22 deletions

File tree

‎CHANGES.md‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,17 @@
22

33
## unreleased
44

5+
- Instances that a pickler wrote as `REDUCE(cls, ()) + BUILD` (a `__reduce__`
6+
returning the class with empty arguments, for example `OrderedDict`
7+
subclasses with a `__dict__`) re-encode as `REDUCE` again, so `__init__`
8+
runs on unpickling as it did for the original pickle; they used to come
9+
back as `NEWOBJ`. The JSON carries `"@newobj": false` next to `@cls`/`@s`
10+
for such instances; absent means `NEWOBJ`, so stored data is unaffected.
11+
The Python-dict readers now recognise instance dicts of five keys
12+
(`@cls`, `@s`, `@newobj`, `@items`, `@appends`), and every reader rejects
13+
`@newobj`, `@items` or `@appends` on a bare class reference without `@s`
14+
(the JSON reader used to drop them silently) [#32]
15+
516
- Docs: journal entry 22 explains the PGO slowdown of the PG JSON path
617
(the profile-guided build put the end-of-slice check on the pointer step of
718
the string loop) and the performance page is re-measured with the fixed

‎docs/.vale/styles/config/vocabularies/Project/accept.txt‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -144,7 +144,7 @@ special_types
144144
wide_dict
145145
[Bb]ackend[s]?
146146
[Aa]uto(detect(ed|s|ion)?|discover(ed|s|y)|creat(ed|es))
147-
unpickle(s|d)?
147+
unpickl(e|es|ed|ing)
148148
mimalloc
149149
glibc
150150
pymalloc

‎docs/sources/reference/json-format.md‎

Lines changed: 25 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -215,6 +215,28 @@ ZODB record.
215215
}
216216
```
217217

218+
### `@newobj` -- Construction Kind
219+
220+
Written as `false`, next to `@cls`/`@s`, when the pickle created the instance
221+
by calling the callable named by `@cls`, usually the class (`REDUCE` with
222+
empty arguments, the shape of a `__reduce__` that returns `(cls, (), state)`,
223+
for example `OrderedDict` subclasses with a `__dict__`). Absent means the
224+
instance was created with `NEWOBJ` (`cls.__new__(cls)`), the common case. The
225+
encoders emit the same opcode again, so `__init__` runs on unpickling exactly
226+
when it did for the original pickle. Note the opposite default of the
227+
`newobj` key inside `@reduce` below: there, absent means `REDUCE`; each
228+
default is the common case of its form. `@newobj`, like `@items` and
229+
`@appends`, is only valid next to `@s`; readers reject it on a bare class
230+
reference.
231+
232+
```json
233+
{
234+
"@cls": ["myapp.models", "Registry"],
235+
"@s": {"entries": 3},
236+
"@newobj": false
237+
}
238+
```
239+
218240
### `@ref` -- Persistent Reference
219241

220242
ZODB persistent object reference, using hex OID format (16 hex digits,
@@ -290,7 +312,7 @@ a state that is exactly `{"@args": ..., "@state": ...}` is always read as
290312
constructor arguments plus state. A `@reduce` with both `newobj` and `state`
291313
is written only when the class itself is not a global (`NEWOBJ` on a class
292314
pickled by value, then `BUILD`); for a global class the `@cls`/`@s` form above
293-
is used. Readers accept both.
315+
is used, with `@newobj` marking the `REDUCE` kind. Readers accept both.
294316

295317
### `@ns` -- String with NUL bytes (PostgreSQL storage)
296318

@@ -350,8 +372,8 @@ order:
350372

351373
**Multi-key markers:**
352374

353-
`@cls` + `@s` (instance with BTree detection), `@dt` + `@tz`
354-
(timezone-aware datetime)
375+
`@cls` + `@s` (instance with BTree detection; `@items`, `@appends` and
376+
`@newobj` ride along), `@dt` + `@tz` (timezone-aware datetime)
355377

356378
**Fallback:** Plain JSON object becomes a Python dict.
357379

‎src/decode.rs‎

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -679,6 +679,7 @@ impl<'a> Decoder<'a> {
679679
state: Box::new(state),
680680
dict_items: None,
681681
list_items: None,
682+
newobj: true,
682683
})), build_depth);
683684
}
684685
PickleValue::Instance(inst) => {
@@ -689,6 +690,7 @@ impl<'a> Decoder<'a> {
689690
state: Box::new(state),
690691
dict_items: inst.dict_items,
691692
list_items: inst.list_items,
693+
newobj: inst.newobj,
692694
})), build_depth);
693695
}
694696
PickleValue::Reduce {
@@ -711,6 +713,7 @@ impl<'a> Decoder<'a> {
711713
state: Box::new(state),
712714
dict_items,
713715
list_items,
716+
newobj,
714717
})), build_depth);
715718
} else if newobj {
716719
// NEWOBJ with constructor args: the stored shape keeps
@@ -725,6 +728,7 @@ impl<'a> Decoder<'a> {
725728
])),
726729
dict_items,
727730
list_items,
731+
newobj: true,
728732
})), Self::nest(build_depth)?);
729733
} else {
730734
// REDUCE with args then BUILD: re-emitting as NEWOBJ would
@@ -766,6 +770,7 @@ impl<'a> Decoder<'a> {
766770
])),
767771
dict_items: None,
768772
list_items: None,
773+
newobj: true,
769774
})), Self::nest(build_depth)?);
770775
}
771776
}
@@ -1434,6 +1439,7 @@ mod tests {
14341439
)])),
14351440
dict_items: None,
14361441
list_items: None,
1442+
newobj: true,
14371443
}));
14381444

14391445
// First element: the Instance from BUILD (stack top)
@@ -1773,6 +1779,37 @@ mod tests {
17731779
}
17741780
}
17751781

1782+
#[test]
1783+
fn test_reduce_empty_args_build_keeps_reduce_kind() {
1784+
// GLOBAL m.C, EMPTY_TUPLE, REDUCE, {"x": 1}, BUILD: a __reduce__ returning (cls, (), state)
1785+
let data = b"\x80\x03cm\nC\n)R}X\x01\x00\x00\x00xK\x01sb.";
1786+
match decode_pickle(data).unwrap() {
1787+
PickleValue::Instance(inst) => {
1788+
assert_eq!(inst.module, "m");
1789+
assert!(!inst.newobj, "REDUCE-created instance must not be marked newobj");
1790+
}
1791+
other => panic!("expected Instance, got {other:?}"),
1792+
}
1793+
// NEWOBJ stays newobj
1794+
let data = b"\x80\x03cm\nC\n)\x81}X\x01\x00\x00\x00xK\x01sb.";
1795+
match decode_pickle(data).unwrap() {
1796+
PickleValue::Instance(inst) => assert!(inst.newobj),
1797+
other => panic!("expected Instance, got {other:?}"),
1798+
}
1799+
// a second BUILD keeps the kind
1800+
let data = b"\x80\x03cm\nC\n)R}X\x01\x00\x00\x00xK\x01sb}X\x01\x00\x00\x00yK\x02sb.";
1801+
match decode_pickle(data).unwrap() {
1802+
PickleValue::Instance(inst) => {
1803+
assert!(!inst.newobj);
1804+
assert_eq!(
1805+
*inst.state,
1806+
PickleValue::Dict(vec![(PickleValue::String("y".into()), PickleValue::Int(2))])
1807+
);
1808+
}
1809+
other => panic!("expected Instance, got {other:?}"),
1810+
}
1811+
}
1812+
17761813
#[test]
17771814
fn test_newobj_without_build_is_flagged() {
17781815
let data: &[u8] = &[0x80, 0x03, b'c', b'm', b'\n', b'C', b'\n', 0x8c, 0x01, b'a', 0x85, 0x81, b'.'];

‎src/encode.rs‎

Lines changed: 39 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -339,17 +339,18 @@ impl Encoder {
339339
self.write_u8(b'\n');
340340
}
341341
PickleValue::Instance(inst) => {
342-
let InstanceData { module, name, state, dict_items, list_items } = inst.as_ref();
342+
let InstanceData { module, name, state, dict_items, list_items, newobj } = inst.as_ref();
343343
if module.is_empty() && name.is_empty() {
344344
return self.encode_anonymous_instance(state, depth);
345345
}
346-
// Emit as: GLOBAL module\nname\n args NEWOBJ [items] state BUILD, where args is
347-
// EMPTY_TUPLE unless the state carries constructor args (@args/@state, #12).
346+
// Emit as: GLOBAL module\nname\n args NEWOBJ|REDUCE [items] state BUILD, where args
347+
// is EMPTY_TUPLE unless the state carries constructor args (@args/@state, #12)
348+
// and the opcode follows the construction kind (#32).
348349
let (args, state) = match newobj_args_state(state) {
349350
Some((args, inner)) => (Some(args), inner),
350351
None => (None, state.as_ref()),
351352
};
352-
self.buf.reserve(5 + module.len() + name.len()); // GLOBAL+mod+\n+name+\n+EMPTY_TUPLE+NEWOBJ
353+
self.buf.reserve(5 + module.len() + name.len()); // GLOBAL+mod+\n+name+\n+EMPTY_TUPLE+opcode
353354
self.write_u8(GLOBAL);
354355
self.write_bytes(module.as_bytes());
355356
self.write_u8(b'\n');
@@ -359,7 +360,7 @@ impl Encoder {
359360
Some(args) => self.encode_value(args, depth + 1)?,
360361
None => self.write_u8(EMPTY_TUPLE),
361362
}
362-
self.write_u8(NEWOBJ);
363+
self.write_u8(if *newobj { NEWOBJ } else { REDUCE });
363364
// Dict/list subclass items go before the state, in the order CPython's
364365
// save_reduce writes them: APPENDS, then SETITEMS, then BUILD.
365366
if let Some(items) = list_items {
@@ -586,6 +587,7 @@ mod tests {
586587
)])),
587588
dict_items: Some(Box::new(vec![(PickleValue::String("k".into()), PickleValue::Int(2))])),
588589
list_items: None,
590+
newobj: true,
589591
}));
590592
let bytes = encode_pickle(&val).unwrap();
591593
// CPython's save_reduce: NEWOBJ, then the items (MARK ... SETITEMS), then state + BUILD.
@@ -609,6 +611,7 @@ mod tests {
609611
state: Box::new(PickleValue::Dict(vec![])),
610612
dict_items: Some(Box::new(vec![(PickleValue::Int(1), PickleValue::Int(2))])),
611613
list_items: Some(Box::new(vec![PickleValue::Int(3)])),
614+
newobj: true,
612615
}));
613616
let bytes = encode_pickle(&val).unwrap();
614617
let newobj = bytes.iter().position(|&b| b == NEWOBJ).unwrap();
@@ -620,6 +623,36 @@ mod tests {
620623
assert_eq!(decode_pickle(&bytes).unwrap(), val);
621624
}
622625

626+
#[test]
627+
fn test_reduce_kind_instance_emits_reduce() {
628+
let val = PickleValue::Instance(Box::new(InstanceData {
629+
module: "m".into(),
630+
name: "C".into(),
631+
state: Box::new(PickleValue::Dict(vec![])),
632+
dict_items: None,
633+
list_items: None,
634+
newobj: false,
635+
}));
636+
let bytes = encode_pickle(&val).unwrap();
637+
assert!(bytes.contains(&REDUCE) && !bytes.contains(&NEWOBJ));
638+
// with the @args/@state shape: GLOBAL args REDUCE state BUILD
639+
let val = PickleValue::Instance(Box::new(InstanceData {
640+
module: "m".into(),
641+
name: "C".into(),
642+
state: Box::new(PickleValue::Dict(vec![
643+
(PickleValue::String("@args".into()), PickleValue::Tuple(vec![PickleValue::Int(1)])),
644+
(PickleValue::String("@state".into()), PickleValue::Dict(vec![])),
645+
])),
646+
dict_items: None,
647+
list_items: None,
648+
newobj: false,
649+
}));
650+
let bytes = encode_pickle(&val).unwrap();
651+
let r = bytes.iter().position(|&b| b == REDUCE).unwrap();
652+
let b = bytes.iter().position(|&b| b == BUILD).unwrap();
653+
assert!(r < b && !bytes.contains(&NEWOBJ));
654+
}
655+
623656
fn reduce(newobj: bool, state: Option<PickleValue>) -> PickleValue {
624657
PickleValue::Reduce {
625658
callable: Box::new(PickleValue::Global { module: "m".into(), name: "C".into() }),
@@ -659,6 +692,7 @@ mod tests {
659692
])),
660693
dict_items: None,
661694
list_items: None,
695+
newobj: true,
662696
}));
663697
let bytes = encode_pickle(&val).unwrap();
664698
let newobj = bytes.iter().position(|&b| b == NEWOBJ).unwrap();

0 commit comments

Comments
 (0)