Repository navigation
Description
Summary of the proposal:
-
Remove the default value for
-Depth- The hard-coded internal limit of
100, which when exceeded, reports an error, is sufficient to prevent "runaway" JSON strings stemming from object trees with cyclic dependencies. - Typical input objects will then be fully serialized by default, which is typically the intent.
- The hard-coded internal limit of
-
Use
-Depthsolely at the user's discretion in order to:- Intentionally truncate the input object tree at the specified depth.
- On rare occasions, allow serialization of object trees that are deeper than
100levels (this could also be a solution to In ConvertTo-Json the max allowed depth is 100. However, we should add code to dynamically check if we are running out of stack, and serialize objects with bigger depths. #3181).
Motivation
-Depth defaulting to 2 in ConvertTo-Json has caused much confusion and frustration over the years; iRon7 has recently tried to create a "canonical" post on SO, which also shows how frequently the issue is arising.
Currently, an input object tree that exceeds the (default) depth doesn't cause an error, but results in near-useless .psobject.ToString() serialization of property values that exceed the depth (see #8381 for a proposal to visualize the cut-off differently).
In combination with the low default -Depth value of 2, that makes for frequent user frustration, because the behavior frequently amounts to quiet de-facto failure that may not be discovered until later.
The seemingly arbitrary and quiet truncation is surprising to most users, and having to account for it in every ConvertTo-Json call is an unnecessary burden.
Backward-compatibility impact
The only way in which I think existing code could be impacted is in that payloads generated with ConvertTo-Json could now increase in depth (and size), if users previously relied on the implicit cut-off at depth 2 - that strikes me as a Bucket 3: Unlikely Grey Area change.
Activity
iSazonov commentedon Dec 4, 2018
/cc Mark Kraus (@markekraus)
iRon7 commentedon Dec 4, 2018
Michael Klement (@mklement0), thank for picking this up.
It is not completely clear to me what happens with the circular references.
If you leave them intact up till the hard-coded internal limit of 100, then your Backward-compatibility impact might be even higher than expected: Take for example:
get-service | Where-Object {$_.DisplayName -match 'tcp/ip*'} | ConvertTo-Json -Depth 10where it just concerns a single object (and not even all services) with a depth of 10. Knowing that a depth of 10 for this command takes already several seconds and produces a file of 22Mb (and for-Depth 12; 40sec/ 160Mb).At the other hand, if you cut them off at the point where the circular reference is detected, users might lose circular properties (e.g.
$Object.parent.parent.parent.parent). Which might be a downwards compatibility concern too if the property is within the originally used depth (2).Maybe an new (user) parameter something like:
-RecurringDepth = 2(default: 2), in addition to your purpose might help. In this idea, the-RecurringDepthwill cut off only recurring references at the given depth (or below).But would also understand if additional parameters are generally unwanted.
SteveL-MSFT commentedon Dec 4, 2018
iRon7 I don't know the history of
-Depth 2, but I also suspect it has to do with recursion where .NET objects reference other instances. The obvious case as you noted is with services which haveDependentServicesandServicesDependedOncreating circular references. A-RecurringDepthparameter seems like a reasonable solution along with a warning if the depth gets hit. New parameters are fine as long as they make sense and generally help avoid a breaking change.mklement0 commentedon Dec 4, 2018
iRon7:
I see the problem with the depth of
100, but my guess is that it's fine to lower this to a more reasonable number that covers the majority of use cases while preventing infinite recursion.(Again, only people with excessively deep trees who rely on default truncation at depth 2 would be affected, which doesn't strike me as likely.)
As for circular references and the default value preventing "runaway" strings when serializing arbitrary .NET types:
It doesn't really make sense to use
ConvertTo-Jsonfor that - useExport-CliXmlinstead.So I'm not sure that
-RecurringDepthis needed, but, as Steve Lee (@SteveL-MSFT) says, adding parameters is an option.However, the gist of my proposal is to bring sane default behavior to
ConvertTo-Json, and that won't be possible without what is technically a breaking change - fingers crossed for bucket 3, though.The typical use case is to use custom-made data-transfer objects ("property bags"; hashtables or custom objects) that you want serialized in full - the internal hard limit is there as a safety belt.
Cutting off the input object tree at a given depth should always be an explicit decision, not quietly applied default behavior that may initially even go unnoticed.
That concerns about incautious, atypical use dictate default behavior that:
-Depth 100, which shouldn't be necessary)has led to longstanding frustration with the cmdlet.
SteveL-MSFT commentedon Dec 5, 2018
Michael Klement (@mklement0) assuming your assertion on use case is correct, it would be possible to treat PSCustomObject and HashTables differently from other .NET types, but then we have asymmetric behavior and could be confusing to some users.
It would be great if someone could script out some tests to see if other types besides Service has circular references. If that is the case, it may make more sense to special case that one (maybe output a warning) and increase the depth by default.
mklement0 commentedon Dec 6, 2018
Steve Lee (@SteveL-MSFT):
As for what use cases are typical:
My observations are based on what I came across on Stack Overflow and what makes sense to me, but you could use your Twitter clout to solicit feedback from a wider audience.
On a similar note, iRon7: If you support this proposal at least in essence, please update your SO self-answer to point to my answer, which promotes this proposal. With the current vote tally, users are likely to focus on your justification of the status quo.
mklement0 commentedon Dec 6, 2018
As for treating
[hashtable]and[pscustomobject]instances differently:Yes, that could be confusing, so we should avoid it. That said, if too much legacy code turns out to rely on the implicit
-Depth 2truncation, it may be an option, though.Given that it generally makes no sense to blindly use
ConvertTo-Jsonwith arbitrary .NET types, I wouldn't be too concerned about that - except with respect to legacy code in order to assess whether the-Depth 2should be retained selectively for non-hashtable-non-custom-object instances.Here are the ca. 20,000 hits for PowerShell code that calls
ConvertTo-Jsonon GitHub:https://github.com/search?p=5&q=language%3Apowershell+ConvertTo-Json&type=Code
markekraus commentedon Dec 7, 2018
I have long suspected the default Depth was too low. That was until I experimented with setting the Depth to 100 in
$PSDefaultParameterValues. The result was a marked increase in execution times for bunch of automation I was responsible for. In some cases, the scripts would execute indefinitely. Large numbers of deep and wide (and sometimes infinitely deep) objects can account for that. Changing this could result in user complaints that scripts are taking longer after upgrading to a pwsh version where the depth was set too high. In some cases, they may even have scripts that never finish executing.While I definitely feel the pain of the default depth being low and silently truncating, I disagree with the assertion that this would not be an impactful change.
I think the default behavior from the beginning should have been to error instead of silently truncate. I agree that 2 is too low. I disagree that increasing the default to 100 is a good idea.
As was discussed in another issue or PR, there are 2 concepts at play here: depth and action when that depth is reached. I think for most uses, slightly increasing the default depth and changing the default behavior to error would be sufficient is solving the majority of pain points. This would need to come with the ability to truncate as an option, as without it infinitely deep objects could never be serialized.
I believe that the assertion that users rarely serialize arbitrary .NET types is false. I have seen plenty of logging that lazily throws any and all objects through
ConvertTo-Json -Compress. I would caution that this assertion be investigated thoroughly before any decisions are made.mklement0 commentedon Dec 10, 2018
Yeah, looking at some of the code here on GitHub seems to confirm the unfortunate reality of lazy
ConvertTo-Jsonuse being not uncommon.In light of this, Steve Lee (@SteveL-MSFT)'s suggestion is well worth considering; to flesh it out some more:
If an input object is a deliberately constructed DTO (property bag), do not apply the default depth (let the internal max. depth prevent infinite recursion); specifically, this applies to:
[pscustomobject]instances whose.pstypenamesarray contains onlySystem.Management.Automation.PSCustomObjectandSystem.Object(to rule out arbitrary deserialized .NET types)classconstruct.[string],[bool],[int], ...)1- that is, serialize only the immediate properties of such a type, and represent nested objects as they.ToString()values.[pscustomobject]instances (ultimately) containing properties that have scalar JSON representations - i.e., deliberately constructed as DTOs.@{ foo = Get-Item / } | ConvertTo-Json)With any other input, retain the current behavior.
This would alleviate the pain based on straightforward exception rules (the inevitable price to pay for remaining mostly backward-compatible):
Lazy piping of arbitrary .NET types to
ConvertTo-Jsonwould work as before.Deliberately constructed DTOs would no longer be subject to the quiet truncation at depth 2.
markekraus commentedon Dec 10, 2018
Michael Klement (@mklement0) How would you handle mixed scenarios? For example, depth 1-5 is occupied by property bags, 6 has a .NET Type but 8-11 are property bags again (possible due to ETS)?
mklement0 commentedon Dec 10, 2018
Mark Kraus (@markekraus): What I'm proposing amounts to 3 distinct scenarios:
If
-Depthis present, the behavior will be as it is now, irrespective of the type of input object (quiet truncation at specified depth).-Depth#8199, it should be possible to use-Depthas an opt-in to depths greater than the internal max. depth of100.Otherwise, in the absence of
-Depth:If an object is a DTO, as described above:
-Depthvalue is implied; only the internal max. depth is in effect (which can be increased with an explicit-Depthargument).1is applied (note that if it weren't for backward compatibility, it might be better to use0, i.e., to only include the immediate properties).If an object is of any other type, the behavior will be as it is now (default depth
2).To put it differently: in the absence of
-Depth, it is the root of a given input object's tree that selects one of two fundamental behaviors:Note that I've updated the definition of DTO in the previous comment to include classes created with PowerShell's
classconstruct.As for the presence of ETS properties: only the base object's type should govern the behavior.
markekraus commentedon Dec 10, 2018
I think that proposal of silent asymmetrical behavior will cause more problems than it will solve.
I really do think there is no decent solution to this that does not involve both a depth parameter and an action to be taken at that depth. I also agree that the default depth could be increased.
mklement0 commentedon Dec 11, 2018
Mark Kraus (@markekraus):
Given that lazy to-JSON conversion isn't uncommon, that's not really an option, if you want to avoid "marked increase in execution times", as you've stated.
Attempting a lukewarm compromise along the lines of increasing the default depth to say,
4, is not worth the effort, in my estimation: it can still substantially increase the runtime/memory requirements of lazy conversions while still running the risk of unexpected silent truncation for purposefully constructed DTOs.Let's start with the problems that it does solve or avoids:
Deliberately constructed DTOs will serialize as expected - with no depth restriction other than the "safety belt" of
100levels (which you'll be able to override with-Depth).This will remove the major pain point of the current behavior.
Backward-compatibility:
-Depthwill continue to work as-is.-Depthwill continue to work as-is.2, which strikes me as unlikely.Which problems do you think it will cause?
25 remaining items
SteveL-MSFT commentedon Aug 5, 2020
@PowerShell/powershell-committee for review, the basic problem is that the default
-depth 2value can end up with "data truncation" where the user is not aware they no longer have full fidelity of the original object. For 7.1, I suggest we add a warning message when the depth is hit. The DTO vs .NET object serialization I think needs more discussion. The asymmetric behavior, by default, may be confusing vs introducing a new switch/parameter to make it opt-in.SteveL-MSFT commentedon Aug 5, 2020
@PowerShell/powershell-committee discussed this, we agreed for 7.1, we should emit a warning message when the depth is hit to inform the user that the object has been truncated.
For additional enhancements, we should explore those as part of Ilya (@iSazonov) changes to move to .NET JSON APIs as an experimental feature.
mklement0 commentedon Aug 12, 2020
Steve Lee (@SteveL-MSFT)
Let me point out again that the same asymmetry (DTOs serialized with full depth, others cut off at a given depth) is built into PowerShell's serialization infrastructure.
The asymmetry makes sense: limiting the depth is only necessary to prevent "runaway serialization" with non-DTOs.
I've never heard anyone complain about it in the context of serialization, and I suspect the average PowerShell user is unaware of it - despite the fact that loss of information is commonplace (though typically doesn't matter in practice), and the depth (
1) is not configurable.The asymmetry equally makes sense for
ConvertTo-Json, and is even more innocuous there:A deliberately constructed DTO as input you'd by definition want to serialize completely, whatever its depth. This is the primary use case for
ConvertTo-Json.Using
ConvertTo-Jsonwith arbitrary .NET types such asSystem.IO.FileInfois virtually pointless anyway, but should you attempt it, the depth limit would save you from "runaway serialization" (a warning could be issued).heilkn commentedon Aug 14, 2020
Hello,
I would also like to up-vote this issue. Please remove this unexpected behavior. Day to day it costs developers several hours or days to find out the reason for the bugs caused by this.
I would have even preferred my program to die with an error instead of silently messing with the data structure.
Kind regards
Konstantin
0009-0009-1013-986X commentedon Mar 11, 2024
#13692 (comment) doesn't address this. As https://stackoverflow.com/questions/53583677/unexpected-convertto-json-results-answer-it-has-a-default-depth-of-2#comment94031210_53583678 explains:
Why should I need to know the depth of the JSON object to be returned before its returned? What if the JSON is of afore-unknown depth? Must I constantly recall it, increasing the depth parameter until I've no error any more? That seems absurd considering the amount of data that might require requesting for large datasets.
iRon7 commentedon Mar 12, 2024
@RokeJulianLockhart,
The point is that you start of with a PowerShell object (which is based on .Net objects) that in fact does support circular references. As pointed out in the Unexpected ConvertTo-Json results? Answer: it has a default -Depth of 2 example, a property might reference the parent or a grand parent higher up. This might create a circular reference that might go forever:
But it might also (dynamically) end somewhere very deep (if I add e.g. a failsafe myself in the concerned object):
There is indeed no easy way to tell upfront where it ends because:
In other words, "writing a serializer that does not support circular dependencies" is to my opinion not a matter of choice for circular (PowerShell/.Net) objects, the issue is that serializers (by design) lack the possibility to define a circular reference for these type of objects.