Repository navigation
Description
Background and Motivation
Recently I was trying to fix something in ReferenceResolver.AddReference that at first seemed to be a bug but in reality its just its behaviour. I wanted to add external reference to ReferenceResolver and not rely on passed value (unless external reference got deleted or otherwise expired), however internals of serializer ignores external reference if theres no $ref property after $id and rely on newly created value. To fix this i propose:
Proposed API
namespace System.Text.Json.Serialization
{
public abstract class ReferenceResolver {
+ public virtual object? TryGetExternalReference(string reference)=>null;
}Usage Examples
This new API internally should be called before creating new value for AddReference and if return null should proceed like usual. ResolveReference should take care of $ref and as such further calls to TryGetExternalReference should be unecessary
Alternative Designs
Write custom converter that will catch ALL reference objects and change behaviour around ReferenceResolver on read (CanWrite can be false). Currently this is awful though since theres no way to extend existing converters or call default behaviour in custom converters when references got deleted or expired as far as i know (at which point custom converter isnt needed). If either was available such alternative would be viable. However theres one more thing that makes me leery with this approach: ensuring this special converter remains last. This might be problematic in more dynamic setup which might be the case for me
Theoretically AddReference could be slighty modified (return object? instead of void or add out/ref parameter) to accomodate such feature but due to back compat i assume its off table
Another alternative would be calling ResolveReference before creating and checking if returns null but this might make breaking change although i feel like in almost all cases it wont since it will be first call before AddReference it will return null anyway. If this turns out to be breaking then this could be hidden behind an option in JsonSerializerOptions with a name like ReuseExternalObjects
Last alternative would be to add ref modifier to value in AddReference not sure if this count as breaking change or not
Risks
Only slight performance hit of calling TryGetExternalReference (by default returns only null and does nothing else) and processing if per $id. Actually, those who would rely on such feature might see slight performance win since it will avoid creating new object. There should be no breaking change thanks to virtual modifier and returning null by default that causes serializer to behave like in the past
Activity
layomia commentedon Sep 13, 2020
Can you share some real-world scenario where this behavior is useful? If you already have existing instances, is the idea that you are using the deserializer to "hydrate"/set additional properties on the instances? Besides performance, what is the implication of getting new instances over using existing ones?
cc @jozkee
BreyerW commentedon Sep 13, 2020
@layomia Undo/Redo system based on deltas rather than whole serialized objects to reduce memory pressure and reduce wasted disk space when project gets saved. Also it can be potentially used to allow future
PopulateObjectto work without replacing arrays when preserved reference is desired which is regular pain point ofJson.Netif you ever come to implement this feature (although thats merely a prediction on my part)PopulateObjectalso could serve my purpose but ideally it should be able to deal with arrays otherwise i dont think it will beat my proposal which also will be much smaller change. Also it wont be as clean since some objects may get deleted and resurrected during program lifetime (its Undo/Redo after all) and herePopulateObjectgets a little messy. With my proposal i simply returnnullinTryGetExternalReferenceand get fresh object when redoing.So yes you are very close with hydrate but in my case its updating existing objects with deltas. With current behaviour i get completely new object which is not what i want (and simply swapping references would be huge PITA since references to single object are already all over the place, unless theres a way to get to the 'root' reference of 'local' reference but swapping references themselves with
refwork only locally)i think you accidentally wrote it backward? Otherwise i trust previous explanation is sufficient. If not ping me.
BreyerW commentedon Sep 17, 2020
@layomia @jozkee
Extra scenarios that i realised could be supported with this:
any cross reference eg file x file, file x database, memory x file, memory x file x database and any other combination that you can think of.
or in other words support for sort of "foreign key" if ur familiar with database terminology
poor man's PopulateObject (poor man's because it will work only with ref preserve enabled and complete json unless custom converter that can deal with incomplete json is provided, on the other hand implementation is super easy since everything is in place already)
recently i realized my workaround with writing custom converter with read reimplemented that catches all objects scales really weakly the more you have special types like dictionaries, lists etc. Since i have to implement custom read for each of these special types from scratch making it untenable in the long run. With this proposal i could avoid all that hassle and reimplement only what i really need
also current workaround prevents me from taking advantage of future code-gen version because i have to call reflection in custom read to populate external object defeating the purpose of gode-gen unless i copy your code-gen infrastructure and tweak it to my needs which i think is really bad thing
Closing if i wrote this proposal again i would advocate for option in
JsonSerializerSettingsthat enablesResolveReferenceto be called beforeAddReference. This way theres no new API surface onReferenceResolverand option that hides extra call toResolveReferenceby default will prevent breaking change. This is how i deal currently in Json.Net and i can provide snippets if you want but currently im writing on phonelayomia commentedon Sep 18, 2020
Thanks for the response @BreyerW.
Yes, there is some overlap with this design and "populate object"-related features. #29538 / #30258. We'll be sure to account for this in the design of each feature.
Yes I was also thinking along these lines. Just thinking about how relevant relevant state can be passed to the custom resolver to help it fetch the external references.
Code snippets would be great here. Curious how this custom configuration is done.
BreyerW commentedon Sep 18, 2020
@layomia Here you go:
Before we start small caveat: in my project JsonSerializer settings are invariant except custom converters collection so i opted to NOT support any setting in custom converters to simplify maintenance. As such they are barebone with added support for reference preserving and thats it. Lets go.
With this i can deal with
System.Arrayand any well behavingIList(likeList<T>)at first glance placement of
ReferenceResolveandAddReferencemight seems peculiar but notice that its basicallyReferenceResolve-> create object if null (cant useContractResolver.Createbecause it wont create properly sizedSystem.Array) otherwise reuse external object ->AddReference-> populate resulting objectI had to override write because Json.Net serializes byte array as base64 encoding and didnt bother writing separate path for that in custom Read since write was straightforward. Maybe later.
Next would be Dictionaries:
here placement of
ReferenceResolverandAddReferenceis more obvious and just like i imagine it to be implemented inSystem.Text.Json. Write is overridden only because Json.Net cant deal with dicts more complex thanDictionary<string,>out of box.And the heart of it all:
Here we catch all reference types and modify reference resolving behaviour. Process is identical to dictionaries and almost identical to arrays but thats only because
ContractResolvercant deal withSystem.ArrayproperlyLast notes:
since
ReferenceResolverspits and acceptstringyou can pass anything and format it however you want. Eg prepend prefix like "sql:unique-indentifier-of sql-query", "file:path-to-file" or use GUIDs for absolutely everything (my current approach).here is my custom resolver: (a bit dirty but works)
Extension.objectToIdMappingcontains all alive references with associated GUIDs. Currently its simpleDictionarybut thinking about going back toConditionalWeakTableas Dictionary require careful disposing of everything when deleted (basically reference counting problem).Hope it helps understanding. If u got questions ping me as usual ;)
BreyerW commentedon Oct 6, 2020
@steveharter @layomia @jozkee
I have noticed this comment that you plan on tweaking
ReferenceResolver. #40099 (comment)Can i hope that you take my proposal under consideration when you actually get to it? I believe my proposal is relatively simple to implement
jozkee commentedon Jan 19, 2021
@BreyerW Can you provide a sample class that implements
ReferenceResolverand also implementsTryGetExternalReference?The reason I am asking for it is that I don't really comprehend this statement:
I was sketching an scenario where I had an external reference already added to my
ReferenceResolverand then callDeserialize, and it does deserialize it correctly when it steps into the corresponding$refJSON property.How do you pretend to use your resolver? Are you still using the resolver as a persistent bag of references across multiple serialization calls? If yes, above scenario should also work for your use case.
Here's the full code as well https://dotnetfiddle.net/tTBVdO.
BreyerW commentedon Jan 20, 2021
@jozkee i fiddled with your example and it will NOT work under scenario that i must support: when there is reference in json but external reference does not exist (just comment out
AddReferenceand you will see what i mean). Remember we are talking about Undo/Redo system meaning object/s may get created/destroyed and even "resurrected".I suppose i could inject extra info into
$refmetadata and use that info to create factory atResolveReferencebut this prevents me from usingSystem.Text.Jsonfactory infrastructure (and future AOT feature most likely) meaning extra burden on me to keep parity with factory behaviour inside json library (eg respecting constructor attributes) or making clean break and documenting it neither being perfect.Also it violates responsibility separation principle (because extra data on
$refwould be similar or even identical to$typemetadata)Regarding the confusing part:
It is possible that single file might contain only
$idmetadata and no$ref. In such scenario serializer creates internally an object and moves on without ever asking for external reference. Workaround i can imagine is pretending that reference was already added even if it wasnt, forcing serializer to always spit$refinstead of$id. But i need to spit$idat least once per object in order to preserve data and populate that data onto existing object (unless it does not exist in which case create new object and populate that new object). Spitting$refpreserves only reference but no data. And more importantly i always hit brick wall that i mentioned at the begining.And yes i still use it as sort of persistent bag of references across multi serializations - with caveat that i remove references when object gets destroyed externally to prevent infinite grow (teoretically can still happen but in reality chances are next to 0). I did post almost all code snippets already in ealier comments
Last but not least I would abandon idea of
TryGetExternalReferenceand instead reuseResolveReference(by calling before firstAddReference) guarded by new option maybe likeJsonSerializerOptions.AllowExternalReferencesor somesuch for backward-compatibility. This idea came to me after i created this proposal and thats why it isnt in opening post. I believe @layomia also agrees on this particular point. That being said i dont think about it too strongly. If you think separation with added benefit of no new option is better then so be it.BreyerW commentedon Jan 21, 2021
@jozkee sorry for calling out again but i made another dive into my source code to make sure i didnt forgot anything important and i must say after that, that i messed up my explanation but dont want to delete previous post stuff since there might still be something worth reading. Sorry. Here is real reason behind this proposal:
this dive reminded me that
$idscenario is even more important than$refdespite being considerably less abundant because thats where all the data is. And$idduring deserialization does not fire offResolveReference, making it impossible forReferenceResolverto use external reference when that reference is still alive. I made example off your fiddle and pasted it below to show that reference equality is false after deserialization when using$idin json. AlsoResolveReferencedoes not fire off (i addedConsole.WriteLinehere)BreyerW commentedon Jan 23, 2021
@jozkee I decided to make certain that this request will solve my problem by forking Json.Net (not
STJbecause it still lacks some features like polymorphims & full support for private members) and sprinklingResolveReferencein strategic places. And it indeed allowed me to remove customReferenceConverterwhich was biggest offender in my eyes since it was unamaintanable in long run and broke AOT scenario. I checked inside my code if references are equal before and after deserialize with$idinside and they are.I would have liked to show neat diff of Json.Net but unfortunetly before forking i used nuget version and didnt thought to commit Json.Net without changes. What i did basically is placing this snippet
existingValue =(id is not null? Serializer?.ReferenceResolver?.ResolveReference(new object(), id) : null) ?? existingValue;in 3 places with slight variance to conform to correct types egobject,IList,IDictionary(should have placed in 5-6 but didnt care fordynamicorISerializablesupport so i omitted them). All of them happened inJsonSerializerInternalReader.csfileSince its just 3 places i will just tell you where i made these changes instead of linking "broken" commit (there is more code than necessary to provide better context as to where aforementioned snippet landed):
line: 476line: ~523-526line: ~846-849If you still want link to commit i can provide it, my project is public so its not a problem.
As for
$refwhen reference is dead i can workaround it outside serializer itself but$idwith alive reference ("dead"$iddoes not exist in my codebase unlike$ref) right now is impossible (or at least i couldnt think of one since serializer seems to always create new object internally when encountering$idand theres no way to override it)Alternative would be to implement
PopulateObjectbut so far cant use it withJson.Netsince it refuses to work with arrays and problem with$idnot using external references still persist. And i believe this alternative is potentially much larger change than this proposal.Sorry for triple post but what i wrote rn seems to be worth a post on its own
BreyerW commentedon Apr 21, 2021
@layomia in light of your recent comment in other issue i would like to mention use cases in a bit more broad stroke: its games and editors like Unity3d. There is even sort of "prior art" namely
Cerasserializer which support what i want via interfaceIExternalObject(which is not viable for me but i digress). You can even find example based on game related issue here https://github.com/rikimaru0345/Ceras/blob/master/src/Tutorial/Tutorial.cs - do ctrl + f write 'IExternalObject' and it should show up.Unity3d-like editors often serialize current object and compare result to discover automatically changes in objects compared to previous frame. Of course what i request isnt strictly necessary for that but can have considerable memory AND perf wins simply because
$idwith data for object appears only once no matter how much i fracture the serialization step (which could be used for multithreading state change discovery).It has snowballing effect for my particular use case: single set of data means smaller serialization results (because references in other places are turned into guids which has fixed length even when reference is serialized in completely different call) that in turn means less work for state discovery and invariant amount of data sets means i can fracture serialization step into smaller serialization steps paying price of extra calls instead of single one but i get considerably smaller memory peak usage since previous work can be discarded or reused immediately and can get back lost perf by multithreading state discovery.
Well actually all that can still be achieved without my request but such data is unusable for deserialization. And thats where shit hits the fan because i reuse data from state discovery for Undo/Redo where deserialization support is absolutely necessary
As for
PopulateObjectim worried it wont work well because only root object will get reused and all$refbut any subsequent$iddeep in JSON structure will probably break my use case unless you will provide an overload that will override default behaviour around$id(that is always create new object when i need it to first try find external reference then create new obj if not exist). If im wrong or such overload will be possible then remaining concern is if it will work with plain arrays which is recurring annoyance with json.net that was never fixed despite all these years of it existing in json.netOther than that it is admittedly niche but can be used for optimization trade-offs (eg. memory peak vs perf) in any application that does heavy serialization though that requires a bit of creativity (like mentioned splitting of large payload into smaller chunks that can be discarded or reused quickly and optionally multithreaded while still preserving references - though that apply only to deserialization part since serialization can already achieve that)
layomia commentedon Apr 26, 2021
@BreyerW - thanks for all the insight you've shared. Are you able to prototype the desired semantics in a fork of this repo (dotnet/runtime) and share it with me? I believe the proposed behavior of a new option (e.g.
JsonSerializerOptions.ResolveNewReferences) making the serializer callResolveReferencefirst before creating a new instance is valid. Having a PoC showing that the feature will actually work for your scenarios will help move it along. I believe this is where the major changes to fetch an existing reference before creating a new one need to be made:runtime/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializer.Read.HandleMetadata.cs
Line 260 in c0d5122
BreyerW commentedon Apr 27, 2021
@layomia sure thing and already done + sample test ;)
changes are really simple
this snippet i placed above
AddReferencein 2 places exactly where you predicted and that was enough to enable what i wanted. Current version changes order of things a little bit in order to get best perfbut places restriction on
converter.CreateInstanceForReferenceResolverandreader.GetStringthat it wont forward reader (or at least the moves wont clash). If that is not acceptable i provided alternative implementation that preserves old order in commented part of snippet.sample test:
i added some comments in sample test that may or may not be of interest to you
link to fork with updated code: https://github.com/BreyerW/runtime made from main from yesterday (which is net 6 preview 4 or preview 5 i believe?) however my build script blew up after doing 99% work and had to manually fix last 1% resulting in this fork not being exact copy when it comes to dependency tree so i suggest extra caution when getting my copy
Let me know if this sample test is too simple i can add some extra scenarios though im a little busy today and tomorrow.
EDIT also a bit of bikeshedding ;) i think
ResolveNewReferencesdoesnt tell much about its purpose so i propse something closer toTryResolveExternalReferences. Try part suggest that it can gracefully fail (just like all Try patterns) and it is about external references. AlternativelyCallResolveBeforeAddReference. Self documenting but a bit mouthy at the same time. However since its just bikeshedding i leftResolveNewReferencesfor noweiriktsarpalis commentedon Oct 25, 2021
The semantics of
$idare meant to indicate "populate with instance produced by the deserializer and associate with specified identifier for future use". I'll say that adding a method specifically intended to override that behavior does strike me as a little bit odd.It leaves at least one open question regarding the implementation: would the deserializer be skipping the nested JSON content of such an
$idobject or would it deserialize onto the externally fed instance? I suspect it would need to be the former, given that yourReferenceResolveris now effectively a singleton: any deserialization would be mutating state attached to yourJsonSerializerOptionsinstance. It is also not clear to me how this feature would interact with polymorphic deserialization (currently planned in #30083).I think @jozkee already alluded to this in his previous remarks, but wouldn't it make sense to employ a schema where externally fed nodes are always serialized and deserialized as
$refnodes? This would involve making a call as to whether a reference needs to be fed externally on serialization, via a customReferenceResolver.GetReferenceimplementation.BreyerW commentedon Oct 25, 2021
@eiriktsarpalis actually it is the latter. Override of behaviour cant be piecemeal so any nested json contents will try find external reference first and deserialize onto that (almost like PopulateObject except it works with any depth unlike newtonsoft which works only on rootobject and creates new instances for anything below that if memory serves right ) if not found then what happens is up to you can throw or return null to indicate that blank slate should be created and deserialized onto that then insert that object to parent object
Also note above you is link to my working fork with extra comments in code
EDIT and no cant use
$refeverywhere bc data must be stored somewhere and deserialized unless i employ 2 schemas: one with data AND skipped (or written as null to ensure graph is invalidated before relinking step) any reference objects that arent root objects since that would be wasteful (i want to do disjoint serialization to reduce max memory used and possibly parallelize) and serialize whole graph again with disabled data and only$refwritten so that graph can be correctly relinked again.That being said i will definitely need PopulateObject for alternative approach and not sure if
System.Text.Jsonconverters support rerouting to other converters since i will need root converter for all reference types in first step that will detect if given object should be skipped or written and if written reroute to actual convertereiriktsarpalis commentedon Oct 25, 2021
That's what I don't like. For your use case you'd need a reference handler storing mutable deserialization state that spans multiple operations, effectively tying it to the
JsonSerializerOptionsinstance.JsonSerializerOptionsis designed to be used as a singleton instance (apart from being a configuration object it also encapsulates all converter caches, which are expensive to recalculate) and as such it is meant to stay immutable, referentially transparent and thread safe after it has been configured. I would say that the use case is clearly outside of the design parameters of bothReferenceResolverandJsonSerializerOptionsand therefore I don't think it should be supported.That's certainly something we're considering for a future release, I would recommend contributing to the conversation in #29538.