Can Marshal.from_string verify recovered OCaml backup values?
0 reputation · 27 Oct 2021, 21:46 UTC
The goal is to decide whether Marshal.from_string can be trusted to validate values restored from a backup before the application consumes them.
OCaml's Marshal module writes no static type information into the byte stream. Marshal.from_string therefore returns a value whose type is supplied by the caller, commonly through a type witness and Obj.magic, while the runtime performs no check. A changed variant constructor or record layout can produce silently wrong values instead of an exception.
The format also embeds a magic number tied to the compiler version and word size, so bytes written under one release or architecture may not load under another. Malformed input can raise an exception, but semantically plausible corruption is not detected without an external digest.
Assuming recovery happens on the same OCaml major version and word size, what verification strategy makes the type mismatch visible? Should the backup store a digest alongside the marshalled bytes, and should the reader compare a stored schema version before deserialising?