hocon-parser 1.14.2__tar.gz → 1.14.3__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (90) hide show
  1. {hocon_parser-1.14.2 → hocon_parser-1.14.3}/.github/workflows/lint.yml +2 -2
  2. {hocon_parser-1.14.2 → hocon_parser-1.14.3}/.github/workflows/test.yml +2 -2
  3. {hocon_parser-1.14.2 → hocon_parser-1.14.3}/CHANGELOG.md +35 -0
  4. {hocon_parser-1.14.2 → hocon_parser-1.14.3}/Makefile +7 -2
  5. {hocon_parser-1.14.2 → hocon_parser-1.14.3}/PKG-INFO +1 -1
  6. {hocon_parser-1.14.2 → hocon_parser-1.14.3}/pyproject.toml +1 -1
  7. {hocon_parser-1.14.2 → hocon_parser-1.14.3}/src/hocon/_internal/resolver/substitution_resolver.py +235 -20
  8. hocon_parser-1.14.3/tests/test_optional_cycle_reentry.py +389 -0
  9. {hocon_parser-1.14.2 → hocon_parser-1.14.3}/.github/workflows/release.yml +0 -0
  10. {hocon_parser-1.14.2 → hocon_parser-1.14.3}/.gitignore +0 -0
  11. {hocon_parser-1.14.2 → hocon_parser-1.14.3}/CONTRIBUTING.md +0 -0
  12. {hocon_parser-1.14.2 → hocon_parser-1.14.3}/LICENSE +0 -0
  13. {hocon_parser-1.14.2 → hocon_parser-1.14.3}/README.ja.md +0 -0
  14. {hocon_parser-1.14.2 → hocon_parser-1.14.3}/README.md +0 -0
  15. {hocon_parser-1.14.2 → hocon_parser-1.14.3}/SECURITY.md +0 -0
  16. {hocon_parser-1.14.2 → hocon_parser-1.14.3}/benchmarks/bench.py +0 -0
  17. {hocon_parser-1.14.2 → hocon_parser-1.14.3}/docs/spec-compliance.md +0 -0
  18. {hocon_parser-1.14.2 → hocon_parser-1.14.3}/src/hocon/__init__.py +0 -0
  19. {hocon_parser-1.14.2 → hocon_parser-1.14.3}/src/hocon/_internal/__init__.py +0 -0
  20. {hocon_parser-1.14.2 → hocon_parser-1.14.3}/src/hocon/_internal/depth.py +0 -0
  21. {hocon_parser-1.14.2 → hocon_parser-1.14.3}/src/hocon/_internal/int64.py +0 -0
  22. {hocon_parser-1.14.2 → hocon_parser-1.14.3}/src/hocon/_internal/lexer/__init__.py +0 -0
  23. {hocon_parser-1.14.2 → hocon_parser-1.14.3}/src/hocon/_internal/lexer/lexer.py +0 -0
  24. {hocon_parser-1.14.2 → hocon_parser-1.14.3}/src/hocon/_internal/lexer/token.py +0 -0
  25. {hocon_parser-1.14.2 → hocon_parser-1.14.3}/src/hocon/_internal/os_text.py +0 -0
  26. {hocon_parser-1.14.2 → hocon_parser-1.14.3}/src/hocon/_internal/parser/__init__.py +0 -0
  27. {hocon_parser-1.14.2 → hocon_parser-1.14.3}/src/hocon/_internal/parser/ast.py +0 -0
  28. {hocon_parser-1.14.2 → hocon_parser-1.14.3}/src/hocon/_internal/parser/parser.py +0 -0
  29. {hocon_parser-1.14.2 → hocon_parser-1.14.3}/src/hocon/_internal/properties/__init__.py +0 -0
  30. {hocon_parser-1.14.2 → hocon_parser-1.14.3}/src/hocon/_internal/properties/properties.py +0 -0
  31. {hocon_parser-1.14.2 → hocon_parser-1.14.3}/src/hocon/_internal/resolver/__init__.py +0 -0
  32. {hocon_parser-1.14.2 → hocon_parser-1.14.3}/src/hocon/_internal/resolver/fold_self_ref.py +0 -0
  33. {hocon_parser-1.14.2 → hocon_parser-1.14.3}/src/hocon/_internal/resolver/include_loader.py +0 -0
  34. {hocon_parser-1.14.2 → hocon_parser-1.14.3}/src/hocon/_internal/resolver/resolver.py +0 -0
  35. {hocon_parser-1.14.2 → hocon_parser-1.14.3}/src/hocon/_internal/resolver/structure_builder.py +0 -0
  36. {hocon_parser-1.14.2 → hocon_parser-1.14.3}/src/hocon/_internal/resolver/types.py +0 -0
  37. {hocon_parser-1.14.2 → hocon_parser-1.14.3}/src/hocon/_internal/resolver/utils.py +0 -0
  38. {hocon_parser-1.14.2 → hocon_parser-1.14.3}/src/hocon/_internal/text.py +0 -0
  39. {hocon_parser-1.14.2 → hocon_parser-1.14.3}/src/hocon/adapters/__init__.py +0 -0
  40. {hocon_parser-1.14.2 → hocon_parser-1.14.3}/src/hocon/adapters/_tree.py +0 -0
  41. {hocon_parser-1.14.2 → hocon_parser-1.14.3}/src/hocon/adapters/env.py +0 -0
  42. {hocon_parser-1.14.2 → hocon_parser-1.14.3}/src/hocon/adapters/json5.py +0 -0
  43. {hocon_parser-1.14.2 → hocon_parser-1.14.3}/src/hocon/adapters/jsonc.py +0 -0
  44. {hocon_parser-1.14.2 → hocon_parser-1.14.3}/src/hocon/adapters/properties.py +0 -0
  45. {hocon_parser-1.14.2 → hocon_parser-1.14.3}/src/hocon/adapters/toml.py +0 -0
  46. {hocon_parser-1.14.2 → hocon_parser-1.14.3}/src/hocon/adapters/yaml.py +0 -0
  47. {hocon_parser-1.14.2 → hocon_parser-1.14.3}/src/hocon/coerce.py +0 -0
  48. {hocon_parser-1.14.2 → hocon_parser-1.14.3}/src/hocon/config.py +0 -0
  49. {hocon_parser-1.14.2 → hocon_parser-1.14.3}/src/hocon/decode.py +0 -0
  50. {hocon_parser-1.14.2 → hocon_parser-1.14.3}/src/hocon/errors.py +0 -0
  51. {hocon_parser-1.14.2 → hocon_parser-1.14.3}/src/hocon/markers.py +0 -0
  52. {hocon_parser-1.14.2 → hocon_parser-1.14.3}/src/hocon/numeric_array.py +0 -0
  53. {hocon_parser-1.14.2 → hocon_parser-1.14.3}/src/hocon/parse.py +0 -0
  54. {hocon_parser-1.14.2 → hocon_parser-1.14.3}/src/hocon/py.typed +0 -0
  55. {hocon_parser-1.14.2 → hocon_parser-1.14.3}/src/hocon/render_hocon.py +0 -0
  56. {hocon_parser-1.14.2 → hocon_parser-1.14.3}/src/hocon/value.py +0 -0
  57. {hocon_parser-1.14.2 → hocon_parser-1.14.3}/src/hocon/value_factory.py +0 -0
  58. {hocon_parser-1.14.2 → hocon_parser-1.14.3}/tests/conformance/test_conformance.py +0 -0
  59. {hocon_parser-1.14.2 → hocon_parser-1.14.3}/tests/conformance/test_error_fixtures.py +0 -0
  60. {hocon_parser-1.14.2 → hocon_parser-1.14.3}/tests/test_adapter_json5.py +0 -0
  61. {hocon_parser-1.14.2 → hocon_parser-1.14.3}/tests/test_adapters.py +0 -0
  62. {hocon_parser-1.14.2 → hocon_parser-1.14.3}/tests/test_config_decode.py +0 -0
  63. {hocon_parser-1.14.2 → hocon_parser-1.14.3}/tests/test_config_mapping.py +0 -0
  64. {hocon_parser-1.14.2 → hocon_parser-1.14.3}/tests/test_decode_unit_markers.py +0 -0
  65. {hocon_parser-1.14.2 → hocon_parser-1.14.3}/tests/test_deferred_resolution_fixtures.py +0 -0
  66. {hocon_parser-1.14.2 → hocon_parser-1.14.3}/tests/test_docs.py +0 -0
  67. {hocon_parser-1.14.2 → hocon_parser-1.14.3}/tests/test_e18_emitter_roundtrip.py +0 -0
  68. {hocon_parser-1.14.2 → hocon_parser-1.14.3}/tests/test_e19_float_overflow.py +0 -0
  69. {hocon_parser-1.14.2 → hocon_parser-1.14.3}/tests/test_e8_plus_reserved.py +0 -0
  70. {hocon_parser-1.14.2 → hocon_parser-1.14.3}/tests/test_env_undecodable.py +0 -0
  71. {hocon_parser-1.14.2 → hocon_parser-1.14.3}/tests/test_format_ingestion.py +0 -0
  72. {hocon_parser-1.14.2 → hocon_parser-1.14.3}/tests/test_hocon_json_adapter.py +0 -0
  73. {hocon_parser-1.14.2 → hocon_parser-1.14.3}/tests/test_include_package_fixtures.py +0 -0
  74. {hocon_parser-1.14.2 → hocon_parser-1.14.3}/tests/test_issue68_path_empty_segment.py +0 -0
  75. {hocon_parser-1.14.2 → hocon_parser-1.14.3}/tests/test_period.py +0 -0
  76. {hocon_parser-1.14.2 → hocon_parser-1.14.3}/tests/test_properties_conflict_fixtures.py +0 -0
  77. {hocon_parser-1.14.2 → hocon_parser-1.14.3}/tests/test_properties_syntax_fixtures.py +0 -0
  78. {hocon_parser-1.14.2 → hocon_parser-1.14.3}/tests/test_render_hocon.py +0 -0
  79. {hocon_parser-1.14.2 → hocon_parser-1.14.3}/tests/test_s13a12_prefix_self_ref.py +0 -0
  80. {hocon_parser-1.14.2 → hocon_parser-1.14.3}/tests/test_smoke.py +0 -0
  81. {hocon_parser-1.14.2 → hocon_parser-1.14.3}/tests/test_spec_concat_paths.py +0 -0
  82. {hocon_parser-1.14.2 → hocon_parser-1.14.3}/tests/test_spec_includes.py +0 -0
  83. {hocon_parser-1.14.2 → hocon_parser-1.14.3}/tests/test_spec_numeric_conversion.py +0 -0
  84. {hocon_parser-1.14.2 → hocon_parser-1.14.3}/tests/test_spec_parser_lexer.py +0 -0
  85. {hocon_parser-1.14.2 → hocon_parser-1.14.3}/tests/test_spec_s3_5_array_root.py +0 -0
  86. {hocon_parser-1.14.2 → hocon_parser-1.14.3}/tests/test_spec_substitutions.py +0 -0
  87. {hocon_parser-1.14.2 → hocon_parser-1.14.3}/tests/test_spec_units.py +0 -0
  88. {hocon_parser-1.14.2 → hocon_parser-1.14.3}/tests/test_units_default.py +0 -0
  89. {hocon_parser-1.14.2 → hocon_parser-1.14.3}/tests/test_unresolved_tracking.py +0 -0
  90. {hocon_parser-1.14.2 → hocon_parser-1.14.3}/tools/hocon_json.py +0 -0
@@ -2,9 +2,9 @@ name: Lint
2
2
 
3
3
  on:
4
4
  pull_request:
5
- branches: [develop, main]
5
+ branches: [develop, main, "release/**"]
6
6
  push:
7
- branches: [develop, main]
7
+ branches: [develop, main, "release/**"]
8
8
 
9
9
  jobs:
10
10
  ruff:
@@ -2,9 +2,9 @@ name: Test
2
2
 
3
3
  on:
4
4
  pull_request:
5
- branches: [develop, main]
5
+ branches: [develop, main, "release/**"]
6
6
  push:
7
- branches: [develop, main]
7
+ branches: [develop, main, "release/**"]
8
8
 
9
9
  jobs:
10
10
  test:
@@ -7,6 +7,41 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
7
7
 
8
8
  ## [Unreleased]
9
9
 
10
+ ## [1.14.3] - 2026-11-28
11
+
12
+ **Patch.** A substitution cycle written twice (`a = ${?b}` / `b = ${?a}`,
13
+ twice) no longer fails with a recursion-limit `ParseError`; it resolves as
14
+ Lightbend does (`{}` for the optional form, a `ResolveError` for the
15
+ required one), and resolution after a cut cycle is bounded in work and
16
+ value size (the counterpart of go.hocon#218 / rs.hocon#199). Every config
17
+ that loaded before reads the same.
18
+
19
+ ### Fixed
20
+
21
+ - **A substitution cycle written twice raised a `ParseError`** instead of
22
+ resolving (py counterpart of go.hocon#218 / rs.hocon#199, where it crashed
23
+ the process). For `a = ${?b}` / `b = ${?a}` written twice, the resolver
24
+ re-entered a key's saved prior forever until the recursion limit turned it
25
+ into "input is nested too deeply … or contains a cycle". A re-entry in an
26
+ unchanged resolver state is now treated as a cycle that cannot be broken:
27
+ an optional substitution is nonexistent and a required one is a
28
+ `ResolveError`, as in Lightbend (`{}` and `UnresolvedSubstitution` for the
29
+ input above). The state is the in-progress keys, the S13a.12 prefix-prior
30
+ guard, the relevant part of the field path, the concatenations being
31
+ resolved and the scope.
32
+ - **Two new errors bound what such a cycle may still cost** once the guard
33
+ has cut it, where a cycle through nested objects can otherwise nest its
34
+ value exponentially or keep branching: `resolved value too large: <path>
35
+ keeps growing (a cycle through nested objects?)` and `substitution cycle
36
+ too complex to resolve: ${<path>}`. Neither applies before a cut, so an
37
+ acyclic config, however large or deeply nested, is never limited.
38
+ - No config that loaded before was found to read differently, over ~160,000
39
+ generated and corpus inputs compared against the previous release; this is
40
+ measured, not proven. Some inputs that hit the recursion limit (a cycle
41
+ through string concatenation, for example) now return a value that still
42
+ differs from Lightbend's. Getting those right is the resolver redesign in
43
+ o3co/xx.hocon#67 / #125, which replaces this interim guard.
44
+
10
45
  ## [1.14.2] - 2026-10-17
11
46
 
12
47
  **Patch.** An opt-in `require_unit` option on the `Duration` / `Bytes` markers,
@@ -2,7 +2,8 @@ PYTHON ?= python3.11
2
2
  VENV := .venv
3
3
 
4
4
  TESTDATA_REPO := o3co/xx.hocon
5
- TESTDATA_REF := main
5
+ # 1.14.x maintenance: the corpus as of 1.14.2/1.14.3, before #130 / the window fixtures (xx#135, #136)
6
+ TESTDATA_REF := 38d02ca195477ad0227baa4bd2ec766ed272f048
6
7
  TESTDATA_DIR := tests/conformance/testdata
7
8
 
8
9
  .PHONY: setup test lint typecheck check bench testdata clean
@@ -35,7 +36,11 @@ bench:
35
36
  # (same convention as rs.hocon).
36
37
  testdata:
37
38
  @set -e; \
38
- sha="$$(git ls-remote "https://github.com/$(TESTDATA_REPO).git" "$(TESTDATA_REF)" | head -1 | cut -f1)"; \
39
+ if printf '%s' "$(TESTDATA_REF)" | grep -Eq '^[0-9a-f]{40}$$'; then \
40
+ sha="$(TESTDATA_REF)"; \
41
+ else \
42
+ sha="$$(git ls-remote "https://github.com/$(TESTDATA_REPO).git" "$(TESTDATA_REF)" | head -1 | cut -f1)"; \
43
+ fi; \
39
44
  if [ -z "$$sha" ]; then \
40
45
  echo "error: could not resolve $(TESTDATA_REPO)@$(TESTDATA_REF) SHA via git ls-remote" >&2; \
41
46
  exit 1; \
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: hocon-parser
3
- Version: 1.14.2
3
+ Version: 1.14.3
4
4
  Summary: Full Lightbend HOCON specification-compliant parser for Python
5
5
  Project-URL: Repository, https://github.com/o3co/py.hocon
6
6
  Project-URL: Issues, https://github.com/o3co/py.hocon/issues
@@ -6,7 +6,7 @@ build-backend = "hatchling.build"
6
6
  name = "hocon-parser"
7
7
  # Snapshot version; the release workflow sets the real version from the git tag
8
8
  # (same convention as the sibling implementations).
9
- version = "1.14.2"
9
+ version = "1.14.3"
10
10
  description = "Full Lightbend HOCON specification-compliant parser for Python"
11
11
  readme = "README.md"
12
12
  license = "Apache-2.0"
@@ -9,6 +9,7 @@ see the inline S-references for the governing spec items.
9
9
  from __future__ import annotations
10
10
 
11
11
  import weakref
12
+ from collections.abc import Iterator
12
13
  from typing import cast
13
14
 
14
15
  from ...errors import ResolveError
@@ -35,6 +36,93 @@ from .utils import (
35
36
 
36
37
  __all__ = ["SubstitutionResolver"]
37
38
 
39
+ # (in-progress set, S13a.12 prefix-prior guard set, truncated field path,
40
+ # concatenations mid-iteration by identity, scope by identity); see the prior
41
+ # re-entry guard in SubstitutionResolver._resolve_subst.
42
+ _PriorState = tuple[frozenset[str], frozenset[str], tuple[str, ...], frozenset[int], int]
43
+
44
+ # Substitutions the resolver may still resolve once the prior re-entry guard
45
+ # has cut a cycle. A cut stops one lap of a cycle, but a cycle that branches
46
+ # can be cut over and over while its laps multiply: inputs that failed in
47
+ # milliseconds before the guard (the recursion limit) ran for minutes after
48
+ # it. Only inputs that have been cut are counted, so an acyclic config, however
49
+ # large, is never limited. Interim, like the guard (o3co/xx.hocon#67 / #125).
50
+ _SUBST_CALLS_AFTER_CUT = 100_000
51
+
52
+
53
+ # Value nodes the resolver may cache per node of the document, once the prior
54
+ # re-entry guard has cut a cycle (rs.hocon#199 counterpart). The guard stops
55
+ # every cycle, but a cycle through nested objects can still nest its value
56
+ # exponentially before it does, and every resolved field is cached with each
57
+ # of its object descendants: a 7-line input spent 16 s in that walk and built a
58
+ # 1.8 MB value. The budget applies only after a cut, so an acyclic config
59
+ # (`a2 = {x = ${a1}, y = ${a1}}`, …, or a deeply nested one) is never charged.
60
+ # A cut can also happen on a config that loads (a re-entry the guard refuses
61
+ # whose result is then not used), so the budget is sized far above anything
62
+ # such a config was measured to reach. The charge matches rs (each cache entry
63
+ # costs the nodes of its value). Interim, like the guard (o3co/xx.hocon#67 /
64
+ # #125).
65
+ _VALUE_NODES_PER_SOURCE_NODE = 10_000
66
+ # Upper bound on that budget, whatever the document's size: a 10,000-element
67
+ # array or many saved priors inflated the node count until a 20 KB input could
68
+ # spend 1–3 GB before failing. Matches rs and go.
69
+ _VALUE_BUDGET_CAP = 2_000_000
70
+
71
+
72
+ def _node_weight(v: HoconValue) -> int:
73
+ """Weight of one resolved node for the value budget: 1, plus one per 16
74
+ bytes of scalar text or of object key text (a string or key that doubles on
75
+ every lap grows without adding nodes). Matches rs."""
76
+ if isinstance(v, HoconScalar):
77
+ return 1 + len(v.raw) // 16
78
+ if isinstance(v, HoconObject):
79
+ return 1 + sum(len(k) for k in v.fields) // 16
80
+ return 1
81
+
82
+
83
+ def _source_nodes(root: ResObj) -> int:
84
+ """Nodes in the unresolved document, saved priors included.
85
+
86
+ Iterative, and each container is visited once (see _walk_once)."""
87
+ return sum(1 for _ in _walk_once(root))
88
+
89
+
90
+ def _walk_once(root: ResObj) -> Iterator[object]:
91
+ """Every node under *root*, saved priors included, each container once.
92
+
93
+ Current values and saved priors share children: overriding nested
94
+ prefixes from the deepest to the shallowest and then replacing the outer
95
+ object gives a document whose tree, unshared, is exponential in its depth.
96
+ Tracking visited containers by identity keeps a walk linear in the
97
+ document."""
98
+ seen: set[int] = set()
99
+ stack: list[object] = [root]
100
+ while stack:
101
+ v = stack.pop()
102
+ if isinstance(v, ResObj | ConcatPlaceholder | HoconArray | HoconObject):
103
+ if id(v) in seen:
104
+ continue
105
+ seen.add(id(v))
106
+ yield v
107
+ if isinstance(v, ResObj):
108
+ stack.extend(v.fields.values())
109
+ stack.extend(v.prior_values.values())
110
+ elif isinstance(v, ConcatPlaceholder):
111
+ stack.extend(v.nodes)
112
+ elif isinstance(v, HoconArray):
113
+ stack.extend(v.items)
114
+ elif isinstance(v, HoconObject):
115
+ stack.extend(v.fields.values())
116
+
117
+
118
+ def _max_subst_len(root: ResObj) -> int:
119
+ """Longest substitution path (in segments) anywhere under *root*, priors
120
+ included. Iterative, and each container is visited once (see _walk_once)."""
121
+ return max(
122
+ (len(v.segments) for v in _walk_once(root) if isinstance(v, SubstPlaceholder)),
123
+ default=0,
124
+ )
125
+
38
126
 
39
127
  class SubstitutionResolver:
40
128
  def __init__(self, root: ResObj, opts: ResolveOptions) -> None:
@@ -52,6 +140,27 @@ class SubstitutionResolver:
52
140
  # a shape the fold could not see through — report it as unresolvable
53
141
  # instead of recursing forever.
54
142
  self.resolving_prefix_priors: set[str] = set()
143
+ # Resolver states seen when a key's saved prior started resolving in
144
+ # the in-progress branch of _resolve_subst, one per enclosing
145
+ # resolution of that prior. See the guard there.
146
+ self.prior_reentry: dict[str, list[_PriorState]] = {}
147
+ # Longest substitution path (segments) in the document, priors
148
+ # included. Only that many leading elements of resolving_field_path can
149
+ # steer a resolution (the S13a.12 prefix branch needs len(rfp) <
150
+ # len(segments); the owner check compares the first len(segments)
151
+ # elements), so the guard records only those.
152
+ self.max_subst_len = _max_subst_len(root)
153
+ # Value nodes resolution may still cache before it fails; see
154
+ # _VALUE_NODES_PER_SOURCE_NODE.
155
+ self.value_budget = min(
156
+ _source_nodes(root) * _VALUE_NODES_PER_SOURCE_NODE, _VALUE_BUDGET_CAP
157
+ )
158
+ # Times the prior re-entry guard refused a re-entry. The value budget
159
+ # applies only once this is non-zero.
160
+ self.cuts = 0
161
+ # Substitutions left to resolve after the first cut; see
162
+ # _SUBST_CALLS_AFTER_CUT.
163
+ self.subst_calls_left = _SUBST_CALLS_AFTER_CUT
55
164
 
56
165
  def _origin_prefix(self) -> str:
57
166
  return f"{self.opts.origin_description}: " if self.opts.origin_description else ""
@@ -83,12 +192,10 @@ class SubstitutionResolver:
83
192
  if isinstance(prior_resolved, HoconObject):
84
193
  final_value = deep_merge_hocon_values(prior_resolved, resolved)
85
194
  result[key] = final_value
86
- self.cache[full_cache_key] = final_value
87
- self._cache_descendants(full_cache_key, final_value)
195
+ self._cache_value(full_cache_key, final_value)
88
196
  continue
89
197
  result[key] = resolved
90
- self.cache[full_cache_key] = resolved
91
- self._cache_descendants(full_cache_key, resolved)
198
+ self._cache_value(full_cache_key, resolved)
92
199
  else:
93
200
  # Unresolved optional substitution: fall back to prior value.
94
201
  prior = obj.prior_values.get(key)
@@ -96,8 +203,7 @@ class SubstitutionResolver:
96
203
  prior_resolved = self._resolve_val(prior, obj)
97
204
  if prior_resolved is not None:
98
205
  result[key] = prior_resolved
99
- self.cache[full_cache_key] = prior_resolved
100
- self._cache_descendants(full_cache_key, prior_resolved)
206
+ self._cache_value(full_cache_key, prior_resolved)
101
207
  finally:
102
208
  # `continue` routes through here too — every exit pops.
103
209
  self.resolving_field_path.pop()
@@ -116,17 +222,79 @@ class SubstitutionResolver:
116
222
  cur = nxt
117
223
  return cur
118
224
 
119
- def _cache_descendants(self, prefix: str, value: HoconValue) -> None:
120
- if not isinstance(value, HoconObject):
121
- return
122
- for key, child in value.fields.items():
123
- child_key = f"{prefix}.{string_segments_to_key([key])}"
124
- self.cache[child_key] = child
125
- self._cache_descendants(child_key, child)
225
+ def _cache_value(self, key: str, value: HoconValue) -> None:
226
+ """Cache a resolved field value under *key*, and every object descendant
227
+ under its dotted path, charging the value budget (see
228
+ ``_VALUE_NODES_PER_SOURCE_NODE``).
229
+
230
+ The charge is the one rs makes: each cache entry costs the nodes of the
231
+ value it holds. Summed, that is each node times the entries on its path,
232
+ so one walk charges it; the walk never visits more nodes than it charges.
233
+ This is where a value that a cycle through nested objects keeps nesting
234
+ costs its time (building ever longer dotted keys). Iterative, so a deep
235
+ value cannot exhaust the stack.
236
+ """
237
+ # (cache key, or None inside an array; value; entries on the path above;
238
+ # the nearest cache key, named by the budget error)
239
+ stack: list[tuple[str | None, HoconValue, int, str]] = [(key, value, 0, key)]
240
+ # Charging starts only after the guard has cut a cycle (see
241
+ # _VALUE_NODES_PER_SOURCE_NODE); until then this only fills the cache.
242
+ charge = self.cuts > 0
243
+ while stack:
244
+ k, v, entries, at = stack.pop()
245
+ if k is not None:
246
+ entries += 1
247
+ at = k
248
+ self.cache[k] = v
249
+ if charge:
250
+ # The node, once per entry on its path, plus the cache-key
251
+ # string this entry builds.
252
+ self._spend(at, entries * _node_weight(v) + (len(k) // 16 if k else 0))
253
+ if isinstance(v, HoconObject):
254
+ for child_key, child in v.fields.items():
255
+ ck = f"{k}.{string_segments_to_key([child_key])}" if k is not None else None
256
+ stack.append((ck, child, entries, at))
257
+ elif charge and isinstance(v, HoconArray):
258
+ # Array elements are not cached, only charged.
259
+ stack.extend((None, item, entries, at) for item in v.items)
260
+
261
+ def _spend(self, key: str, n: int) -> None:
262
+ """Deduct *n* from the value budget, failing once it is exhausted."""
263
+ if n > self.value_budget:
264
+ raise ResolveError(
265
+ self._origin_prefix() + f"resolved value too large: {key} keeps growing "
266
+ "(a cycle through nested objects?)",
267
+ key,
268
+ 0,
269
+ 0,
270
+ )
271
+ self.value_budget -= n
272
+
273
+ def _charge_produced(self, key: str, value: HoconValue) -> None:
274
+ """After a cut, charge a substitution result as it is produced, so an
275
+ array or string that doubles on every lap of a cycle is stopped while
276
+ it is being built, not after its field is complete (a 16-key ring of
277
+ doubling strings took 4 GB). Iterative, and stops counting once the
278
+ budget is exceeded."""
279
+ n = 0
280
+ stack: list[HoconValue] = [value]
281
+ while stack:
282
+ v = stack.pop()
283
+ n += _node_weight(v)
284
+ if n > self.value_budget:
285
+ break
286
+ if isinstance(v, HoconObject):
287
+ stack.extend(v.fields.values())
288
+ elif isinstance(v, HoconArray):
289
+ stack.extend(v.items)
290
+ self._spend(key, n)
126
291
 
127
292
  def _resolve_val(self, v: ResolverValue, scope: ResObj) -> HoconValue | None:
128
293
  if is_subst(v):
129
- return self._resolve_subst(v, scope)
294
+ resolved = self._resolve_subst(v, scope)
295
+ if resolved is not None and self.cuts > 0:
296
+ self._charge_produced(segments_to_key(v.segments), resolved)
297
+ return resolved
130
298
  if is_concat(v):
131
299
  # Mark mid-iteration so _resolve_subst can detect a true self-ref.
132
300
  self.resolving_concats.add(v)
@@ -154,6 +322,16 @@ class SubstitutionResolver:
154
322
  return cast("HoconValue", v)
155
323
 
156
324
  def _resolve_subst(self, s: SubstPlaceholder, scope: ResObj) -> HoconValue | None:
325
+ if self.cuts > 0:
326
+ self.subst_calls_left -= 1
327
+ if self.subst_calls_left < 0:
328
+ k = segments_to_key(s.segments)
329
+ raise ResolveError(
330
+ self._origin_prefix() + f"substitution cycle too complex to resolve: ${{{k}}}",
331
+ k,
332
+ s.line,
333
+ s.col,
334
+ )
157
335
  if s.known_absent:
158
336
  # A required substitution folded to known_absent (S13a.12 prefix
159
337
  # fold with no below value at the navigated path) is the spec's
@@ -224,13 +402,50 @@ class SubstitutionResolver:
224
402
  if key in self.resolving:
225
403
  # Cycle detected: try prior value for self-referential substitutions.
226
404
  prior = self._lookup_prior(s, scope)
405
+ # A prior can reach another in-progress key and resolve that key's
406
+ # prior, which can come back here. Re-entering is legal and usually
407
+ # terminates, because something that steers the branches has changed
408
+ # the second time. But `a = ${?b}` / `b = ${?a}` written twice
409
+ # re-entered in the same state forever, until the recursion limit
410
+ # turned it into a ParseError. A re-entry whose state equals an
411
+ # enclosing one is treated as a cycle that cannot be broken: the
412
+ # optional form is nonexistent and the required form an error, as in
413
+ # Lightbend. py counterpart of go.hocon#218 / rs.hocon#199; interim
414
+ # guard, the full fix is the resolver redesign in o3co/xx.hocon#67 /
415
+ # #125.
416
+ #
417
+ # The state is what was found to steer the branches a substitution
418
+ # takes here: the in-progress set, the S13a.12 prefix-prior guard set,
419
+ # the field path up to the longest substitution path (the prefix
420
+ # branch and the owner check never compare deeper elements), the
421
+ # concatenations mid-iteration (the self-ref check), and the scope
422
+ # (which picks the prior). Each was added because leaving it out
423
+ # changed a config that loads. Other state is left out: the cache,
424
+ # which a cycle through nested objects grows by a deeper key every
425
+ # lap (a state including it would never repeat). So an equal state is
426
+ # not a proof of an equal computation; that no config that loads
427
+ # changes rests on differential runs, not on a proof. There are
428
+ # finitely many such states, so the nesting is finite.
227
429
  if prior is not None:
228
- saved = self.resolving
229
- self.resolving = set(saved)
230
- try:
231
- return self._resolve_val(prior, scope)
232
- finally:
233
- self.resolving = saved
430
+ outer = self.prior_reentry.setdefault(key, [])
431
+ state: _PriorState = (
432
+ frozenset(self.resolving),
433
+ frozenset(self.resolving_prefix_priors),
434
+ tuple(self.resolving_field_path[: self.max_subst_len]),
435
+ frozenset(id(c) for c in self.resolving_concats),
436
+ id(scope),
437
+ )
438
+ if state in outer:
439
+ self.cuts += 1
440
+ else:
441
+ outer.append(state)
442
+ saved = self.resolving
443
+ self.resolving = set(saved)
444
+ try:
445
+ return self._resolve_val(prior, scope)
446
+ finally:
447
+ self.resolving = saved
448
+ outer.pop()
234
449
  if s.optional:
235
450
  return None
236
451
  raise ResolveError(
@@ -0,0 +1,389 @@
1
+ r"""A substitution cycle written twice (py counterpart of go.hocon#218 /
2
+ rs.hocon#199).
3
+
4
+ ``a = ${?b}`` / ``b = ${?a}`` written twice made the in-progress branch of the
5
+ resolver re-enter a key's saved prior forever. go and rs overflowed the stack;
6
+ py hit its recursion limit and raised a ``ParseError`` ("nested too deeply …
7
+ or contains a cycle"), where Lightbend gives ``{}``. The interim guard treats
8
+ a re-entry in an unchanged in-progress state as an unbreakable cycle; the full
9
+ fix is the resolver redesign in o3co/xx.hocon#67 / #125. Expected values are
10
+ Lightbend 1.4.9.
11
+
12
+ Pinning fixtures (auto-discovered by the conformance harnesses once
13
+ ``make testdata`` syncs them): ``optional-cycle-repeat/oc01–oc06``
14
+ (o3co/xx.hocon#136).
15
+ """
16
+
17
+ from __future__ import annotations
18
+
19
+ import json
20
+ from pathlib import Path
21
+
22
+ import pytest
23
+
24
+ import hocon
25
+ from hocon import ResolveError
26
+
27
+
28
+ def _json(src: str) -> object:
29
+ return json.loads(hocon.parse_string(src, env={})._render_json_for_test())
30
+
31
+
32
+ @pytest.mark.parametrize(
33
+ ("src", "want"),
34
+ [
35
+ ("a = ${?b}\nb = ${?a}\na = ${?b}\nb = ${?a}\n", {}),
36
+ ("a = ${?b}\nb = ${?a}\na = ${?b}\nb = ${?a}\na = ${?b}\nb = ${?a}\n", {}),
37
+ ("a = ${?b}\nb = ${?c}\nc = ${?a}\na = ${?b}\nb = ${?c}\nc = ${?a}\n", {}),
38
+ ("o.a = ${?o.b}\no.b = ${?o.a}\no.a = ${?o.b}\no.b = ${?o.a}\n", {"o": {}}),
39
+ ("a = ${?b}\nb = ${?a}\na = ${?b}\nb = ${?a}\nc = ${?a}x\n", {"c": "x"}),
40
+ ("a = ${?b}\nb = ${?a}\na = ${?b}\nb = ${?a}\na = 1\n", {"a": 1, "b": 1}),
41
+ ],
42
+ ids=["twice", "thrice", "three-keys", "nested-path", "in-concat", "later-value"],
43
+ )
44
+ def test_unbreakable_cycle_through_priors(src: str, want: object) -> None:
45
+ assert _json(src) == want
46
+
47
+
48
+ @pytest.mark.parametrize(
49
+ ("src", "want"),
50
+ [
51
+ # The second pass through o.y's prior sees `a` in progress and stops
52
+ # on its own: the guard must let this re-entry through.
53
+ (
54
+ "o = { y = ${?a} }\na = ${o.y}\no.x = 5\no.y += [3]\n",
55
+ {"a": [[3]], "o": {"x": 5, "y": [[3]]}},
56
+ ),
57
+ # The second pass through k's prior terminates because `o` has
58
+ # meanwhile entered the S13a.12 prefix-prior guard set: the guard's
59
+ # state must include that set, not only the in-progress keys.
60
+ (
61
+ "o = ${?k}z\no.y = ${?o.y}\nk = ${?o.x}\nk = ${k}z\n",
62
+ {"k": "z", "o": {}},
63
+ ),
64
+ (
65
+ "o = ${?k}z\no.y.z = ${?o.y.z}\nk = ${?o.x}\nk = ${k}z\n",
66
+ {"k": "z", "o": {"y": {}}},
67
+ ),
68
+ (
69
+ "o = { y = ${?k} }\nk = [${?o.y}]\nk = ${?m}\nm = ${?k}\no = ${?k}\n",
70
+ {"k": [[]], "m": [[]], "o": [[]]},
71
+ ),
72
+ ("a = 1\na = ${a}x\na = ${a}y\nb = ${a}\n", {"a": "1xy", "b": "1xy"}),
73
+ ("a = ${?b}\nb = ${?a}\na = ${?b}\n", {}),
74
+ ],
75
+ ids=[
76
+ "legal-reentry",
77
+ "prefix-prior-two-element-path",
78
+ "prefix-prior-deep",
79
+ "field-path",
80
+ "self-ref-chain",
81
+ "cycle-once",
82
+ ],
83
+ )
84
+ def test_legal_reentry_unchanged(src: str, want: object) -> None:
85
+ assert _json(src) == want
86
+
87
+
88
+ @pytest.mark.parametrize(
89
+ "src",
90
+ [
91
+ "a = ${b}\nb = ${a}\na = ${b}\nb = ${a}\n",
92
+ "a = ${?b}\nb = ${a}\na = ${?b}\nb = ${a}\n",
93
+ ],
94
+ ids=["required", "mixed"],
95
+ )
96
+ def test_required_cycle_is_a_resolve_error(src: str) -> None:
97
+ with pytest.raises(ResolveError, match="circular substitution"):
98
+ hocon.parse_string(src, env={})
99
+
100
+
101
+ def test_cycle_through_include(tmp_path: Path) -> None:
102
+ (tmp_path / "inner.conf").write_text("a = ${?b}\nb = ${?a}\n")
103
+ main = tmp_path / "main.conf"
104
+ main.write_text('a = ${?b}\nb = ${?a}\ninclude "inner.conf"\n')
105
+ assert json.loads(hocon.parse_file(str(main), env={})._render_json_for_test()) == {}
106
+
107
+
108
+ def test_concat_cycle_terminates() -> None:
109
+ # Was a ParseError (recursion limit). The value still differs from
110
+ # Lightbend's ({"a":"yxyx","b":"yxy"}); that is the resolver redesign
111
+ # (o3co/xx.hocon#67 / #125), so only termination is asserted.
112
+ _json("a = ${?b}x\nb = ${?a}y\na = ${?b}x\nb = ${?a}y\n")
113
+
114
+
115
+ _R3 = (
116
+ "o.x = 2\n"
117
+ "o.x = ${?o}\n"
118
+ "o.y = { z = ${?o.y.z} }\n"
119
+ "o.y.z = ${?o}\n"
120
+ "o.x = ${?o.x}\n"
121
+ "o.y = { x = ${?o.y} }\n"
122
+ )
123
+
124
+
125
+ @pytest.mark.parametrize(
126
+ "src",
127
+ [
128
+ # r3c from review: the prior guard stops the cycle, but only after the
129
+ # value has nested deeply enough to build megabytes and burn minutes.
130
+ _R3 + "o.y = { q = ${?o.y.z} }\n",
131
+ # r3b with `o.y.q = ${?o.x}` written twice.
132
+ _R3 + "o.y = ${?o.y.z}\no.y.q = ${?o.x}\no.y.q = ${?o.x}\n",
133
+ ],
134
+ ids=["r3c", "r3b-plus-q"],
135
+ )
136
+ def test_value_budget_stops_a_growing_cycle(src: str) -> None:
137
+ # The value budget (rs.hocon#199 counterpart) turns it into an error.
138
+ # Both raised the recursion-limit ParseError before the guard.
139
+ with pytest.raises(ResolveError, match="resolved value too large"):
140
+ hocon.parse_string(src, env={})
141
+
142
+
143
+ def test_value_budget_spares_acyclic_configs() -> None:
144
+ # The budget applies only after the guard has cut a cycle, so large
145
+ # acyclic configs that load today are never charged: an exponential chain
146
+ # of references (billion laughs, N=12) and deeply nested objects.
147
+ src = "a0 = { v = 1 }\n" + "".join(
148
+ f"a{i} = {{ x = ${{a{i - 1}}}, y = ${{a{i - 1}}} }}\n" for i in range(1, 13)
149
+ )
150
+ leaf = _json(src)
151
+ for _ in range(12):
152
+ assert isinstance(leaf, dict)
153
+ leaf = leaf["a12"]["x"] if "a12" in leaf else leaf["x"]
154
+ assert leaf == {"v": 1}
155
+ deep = _json("a { " * 250 + "x = 1" + " }" * 250 + "\n")
156
+ for _ in range(250):
157
+ assert isinstance(deep, dict)
158
+ deep = deep["a"]
159
+ assert deep == {"x": 1}
160
+ path = _json(".".join(["a"] * 200) + " = 1\n")
161
+ for _ in range(199):
162
+ assert isinstance(path, dict)
163
+ path = path["a"]
164
+ assert path == {"a": 1}
165
+
166
+
167
+ @pytest.mark.parametrize(
168
+ ("name", "element"),
169
+ [("array", "[${?a%}, ${?a%}]"), ("string", "${?a%}${?a%}x")],
170
+ )
171
+ def test_doubling_ring_fails_without_exhausting_memory(name: str, element: str) -> None:
172
+ # A 16-key ring written twice whose value doubles on every lap (review of
173
+ # go.hocon#223 / rs.hocon#203: the string ring took 4 GB in py, a model of
174
+ # the array ring reaches 17 billion nodes). Before the guard it was a
175
+ # recursion-limit ParseError. After a cut every substitution result is
176
+ # charged as it is produced and the substitutions resolved are counted, so
177
+ # the ring is stopped while it is being built.
178
+ n = 16
179
+ ring = "".join(f"a{i} = {element.replace('%', str((i + 1) % n))}\n" for i in range(n))
180
+ with pytest.raises(
181
+ (ResolveError, hocon.ParseError),
182
+ match="resolved value too large|too complex to resolve|nested too deeply",
183
+ ):
184
+ hocon.parse_string(ring + ring, env={})
185
+
186
+
187
+ def test_document_walks_visit_shared_children_once() -> None:
188
+ # Current values and saved priors share children. Overriding nested
189
+ # prefixes from the deepest to the shallowest gives a document whose
190
+ # tree, unshared, is exponential in its depth: here 2**60 paths. The walks
191
+ # that size the guard state and the value budget must stay linear.
192
+ from hocon._internal.resolver import substitution_resolver as sr
193
+ from hocon._internal.resolver.types import ResObj
194
+ from hocon.value import HoconScalar
195
+
196
+ node = ResObj()
197
+ node.fields["v"] = HoconScalar("1", "number")
198
+ for _ in range(60):
199
+ parent = ResObj()
200
+ parent.fields["k"] = node
201
+ parent.prior_values["k"] = node
202
+ node = parent
203
+ assert sr._max_subst_len(node) == 0
204
+ assert sr._source_nodes(node) == 62
205
+
206
+
207
+ # Counterexamples from review of the py guard: each loads today, and each is
208
+ # cut by the guard. They pin the py-specific parts of the guard state: the
209
+ # concatenations mid-iteration and the scope (a state without them changed
210
+ # both results).
211
+ _CX1 = (
212
+ "a.a = ${?b}\nc.b { b { a += x, b += ${?a}, a += [${?c}] } }\nc.b { b { a"
213
+ " += [] } }\na = ${c}\na = ${?a}\n"
214
+ )
215
+ _CX1_WANT = (
216
+ '{"a":{"b":{"b":{"a":["x",[{"b":{"b":{"a":["x",[]],"b":[["x"],["x"]]}}}'
217
+ '],[]],"b":[["x"],["x",[{"b":{"b":{"a":["x",[]],"b":[["x"],["x"]]}}}]]]'
218
+ '}}},"c":{"b":{"b":{"a":["x",[{"b":{"b":{"a":["x",[{"b":{"b":{"a":["x",'
219
+ '[]],"b":[["x"],{"b":{"b":{"a":["x",[{"b":{"b":{"a":["x",[]],"b":[["x"]'
220
+ ',["x"]]}}}],[]],"b":[["x"],["x",[{"b":{"b":{"a":["x",[]],"b":[["x"],["'
221
+ 'x"]]}}}]]]}}}]}}}],[]],"b":[["x"],{"b":{"b":{"a":["x",[{"b":{"b":{"a":'
222
+ '["x",[]],"b":[["x"],["x"]]}}}],[]],"b":[["x"],["x",[{"b":{"b":{"a":["x'
223
+ '",[]],"b":[["x"],["x"]]}}}]]]}}}]}}}],[]],"b":[{"b":{"b":{"a":["x",[{"'
224
+ 'b":{"b":{"a":["x",[]],"b":[["x"],["x"]]}}}],[]],"b":[["x"],["x",[{"b":'
225
+ '{"b":{"a":["x",[]],"b":[["x"],["x"]]}}}]]]}}}]}}}}'
226
+ )
227
+ _CX2 = (
228
+ "b += { b { a { a = ${?c} }, a += [{ a = 1 }] }, b += { b { b { a = 1 }"
229
+ " ${?a}, a { a = 1 } } } } { b += 2, b = [[${?c}]] }\nc = [${?b}]\nc = ${"
230
+ "?b}\na.a.a = ${?c}\nb += { b { a { a { a = 1 } }, a += [{ a = 1 }] }, b "
231
+ "+= { b { b { a = 1 } { a = 1 } } } }\n"
232
+ )
233
+ _CX2_WANT = (
234
+ '{"a":{"a":{"a":[{"b":[[[{"b":[[[[2]]]]}]]]},{"b":[{"b":{"b":{"a":1}}}]'
235
+ '}]}},"b":[{"b":[[[{"b":[[[[2]]]]}]]]},{"b":[{"b":{"b":{"a":1}}}]}],"c"'
236
+ ':[{"b":[[[{"b":[[[[2]]]]}]]]},{"b":[{"b":{"b":{"a":1}}}]}]}'
237
+ )
238
+
239
+
240
+ @pytest.mark.parametrize(
241
+ ("src", "want"), [(_CX1, _CX1_WANT), (_CX2, _CX2_WANT)], ids=["cx1", "cx2"]
242
+ )
243
+ def test_cut_config_that_loads_reads_the_same(src: str, want: str) -> None:
244
+ assert _json(src) == json.loads(want)
245
+
246
+
247
+ # Inputs that failed fast before the guard and hung after it, until the state
248
+ # held the concatenations and the scope. They must fail fast, as before.
249
+ _S16427 = (
250
+ "o.o = { o = ${?o.a} ${?o.o} }\no.b = ${o.b}x\no.o.a = ${o.o.a} y\no.o.a +"
251
+ "= ${?o}[1]\no.o.a = x${?o.o}\no.a = ${o.o.a}y\no.o.a = ${o.o.a} y\no.o.a +"
252
+ "= ${?o}[1]\no.o.a = x${?o.o}\no.a = ${o.o.a}y\no.o.a = x${?o.o}\no.o.a = $"
253
+ "{o.o.a} y\no.o.a += ${?o}[1]\no.o.a = x${?o.o}\no.a = ${o.o.a}y\n"
254
+ )
255
+ _H04998 = (
256
+ "o.y = ${o.y} ${o.y}\nb = ${a}${b}\no.y.z = ${?o.y.z}${?o}\no.x = ${o.x} y"
257
+ "\no.y.z += ${?o.y.z} ${?c}\no.x = ${o.x}\no.y.z = ${?o.y.z}${?o}\no.x = ${"
258
+ "o.x} y\no.y.z += ${?o.y.z} ${?c}\no.x = ${o.x}\no.y.z = ${?o.y.z}${?o}\no."
259
+ "x = ${o.x} y\no.y.z += ${?o.y.z} ${?c}\no.x = ${o.x}\no.x = ${o.x}x\no.y.z"
260
+ " = ${o.y.z} y\n"
261
+ )
262
+
263
+
264
+ def test_former_fast_errors_still_fail() -> None:
265
+ with pytest.raises(ResolveError, match="circular substitution"):
266
+ hocon.parse_string(_S16427, env={})
267
+ with pytest.raises(hocon.ParseError, match="nested too deeply"):
268
+ hocon.parse_string(_H04998, env={})
269
+
270
+
271
+ def _wide_reference() -> str:
272
+ # w8: a two-key cycle written twice, each value referencing the other key
273
+ # eight times.
274
+ a = "a = " + "${?b}" * 8 + "\n"
275
+ b = "b = " + "${?a}" * 8 + "\n"
276
+ return (a + b) * 2
277
+
278
+
279
+ def _dense_cycle() -> str:
280
+ # e6: six keys, written twice, each referencing all six.
281
+ refs = "".join(f"${{?k{j}}}" for j in range(1, 7))
282
+ return "".join(f"k{i} = {refs}\n" for i in range(1, 7)) * 2
283
+
284
+
285
+ def _padded_object_ring() -> str:
286
+ # objring_64_p10000: a 10,000-element array inflates the document's node
287
+ # count (and so the uncapped value budget), next to a 16-key ring of
288
+ # objects with 64-byte keys, written twice.
289
+ pad = "pad = [" + ",".join(["1"] * 10_000) + "]\n"
290
+ x, y = "x" * 64, "y" * 64
291
+ ring = "".join(
292
+ f"a{i} = {{ {x} = ${{?a{(i + 1) % 16}}}, {y} = ${{?a{(i + 1) % 16}}} }}\n"
293
+ for i in range(16)
294
+ )
295
+ return pad + ring * 2
296
+
297
+
298
+ @pytest.mark.parametrize(
299
+ "build",
300
+ [_wide_reference, _dense_cycle, _padded_object_ring],
301
+ ids=["wide-reference", "dense-cycle", "padded-object-ring"],
302
+ )
303
+ def test_post_cut_work_is_bounded(build: object) -> None:
304
+ # Review of the rs memory exhaustion: before the value budget was capped
305
+ # and counted key text, a 20 KB input could reach 1–3 GB; a cycle that
306
+ # keeps branching could run for seconds. Each must now fail with one of
307
+ # the two post-cut limits.
308
+ assert callable(build)
309
+ with pytest.raises(ResolveError, match="too complex to resolve|resolved value too large"):
310
+ hocon.parse_string(build(), env={})
311
+
312
+
313
+ # Each state component of the prior re-entry guard is load-bearing: removing
314
+ # it alone changes the result below (verified by building the resolver with
315
+ # that component replaced by a constant). Review of the py guard.
316
+
317
+ # The S13a.12 prefix-prior guard set. Loads in base as shown. Without the
318
+ # prefix-prior set the guard cuts the second pass and it becomes
319
+ # `circular substitution: a`.
320
+ _STATE_PREFIX_PRIOR_SRC = "x = ${a}\nx = ${a}\na = ${?x.y}\na = ${?a}ok\n"
321
+ _STATE_PREFIX_PRIOR_WANT = '{"a":"ok","x":"ok"}'
322
+
323
+ # The concatenations mid-iteration. A recursion-limit ParseError in base.
324
+ # Without the concat set one nested `{"a":5}` becomes `{}`.
325
+ _STATE_CONCAT_SRC = "a = 5\na.a += { a = ${?a} }\na.a += ${?b.a}\n"
326
+ _STATE_CONCAT_WANT = '{"a":{"a":[{"a":{"a":[{"a":{"a":[{"a":{"a":[{"a":5}]}},{"a":5}]}}]}}]}}'
327
+
328
+ # The scope (which picks the prior). Loads in base as shown. Without the
329
+ # scope one `[[[[2]]]]` becomes `[[[]]]`.
330
+ _STATE_SCOPE_SRC = (
331
+ "b += { b += { a = { a = ${?c}, a = { a = 1 } ${?c} }, a += { a = ${?a}"
332
+ "x } }, b = { b = { b = { a = 1 } ${?a}, a = ${?c} }, a += [{ a = 1 } $"
333
+ "{a}] }, b += { b = { b += { a = 1 } ${?a}, b = 2, a += { a = 1 } ${?a."
334
+ "a} } } }\na.a.a = { b += 2, b = [[${?c}]] }\nc = [${?b}]\nc = ${?b}\na.a.a"
335
+ " = ${?c}\nb += { b += { a = { a = ${?c}, a = { a = 1 } ${?c} }, a += { "
336
+ "a = ${?a}x } }, b = { b = { b = { a = 1 } ${?a}, a = ${?c} }, a += [{ "
337
+ "a = 1 } ${a}] }, b += { b = { b += { a = 1 } ${?a}, b = 2, a += { a = "
338
+ "1 } ${?a.a} } } }\na.a.a = { b += 2, b = [[${?c}]] }\nc = [${?b}]\nc = ${"
339
+ "?b}\na.a.a = ${?c}\nb.a = [${?b}]\n"
340
+ )
341
+ _STATE_SCOPE_WANT = (
342
+ '{"a":{"a":{"a":[{"b":[{"b":{"a":[{"a":{"b":[[[[2]]]]}}],"b":2}}]},{"b"'
343
+ ':[{"b":{"a":[{"a":{"b":[[[[2]]]]}}],"b":2}}]}]}},"b":{"a":[[{"b":[{"b"'
344
+ ':{"a":[{"a":[{"b":[{"b":{"a":[{"a":{"b":[[[[2]]]]}}],"b":2}}]},{"b":[{'
345
+ '"b":{"a":[{"a":{"b":[[[[2]]]]}}],"b":2}}]}]}],"b":2}}]},{"b":[{"b":{"a'
346
+ '":[{"a":[{"b":[{"b":{"a":[{"a":{"b":[[[[2]]]]}}],"b":2}}]},{"b":[{"b":'
347
+ '{"a":[{"a":{"b":[[[[2]]]]}}],"b":2}}]}]}],"b":2}}]}]]},"c":{"a":[[{"b"'
348
+ ':[{"b":{"a":[{"a":[{"b":[{"b":{"a":[{"a":{"b":[[[[2]]]]}}],"b":2}}]},{'
349
+ '"b":[{"b":{"a":[{"a":{"b":[[[[2]]]]}}],"b":2}}]}]}],"b":2}}]},{"b":[{"'
350
+ 'b":{"a":[{"a":[{"b":[{"b":{"a":[{"a":{"b":[[[[2]]]]}}],"b":2}}]},{"b":'
351
+ '[{"b":{"a":[{"a":{"b":[[[[2]]]]}}],"b":2}}]}]}],"b":2}}]}]]}}'
352
+ )
353
+
354
+ # The truncated field path. A recursion-limit ParseError in base; no input in the 157,254-input
355
+ # differential that loads in base depends on the field path. Without it
356
+ # `"o":{"b":{"b":{"b":{}}}}` loses one level.
357
+ _STATE_FIELD_PATH_SRC = (
358
+ "o = { b = ${?o}${?o.b} }\na.a = { a = { a += { a = 1 } ${?o}, a = { a ="
359
+ " 1 } ${?a.a} } }\no = { b = ${?o}${?o.b} }\na.a = { a = { a += { a = 1 }"
360
+ " ${?o}, a = { a = 1 } ${?a.a} } }\n"
361
+ )
362
+ _STATE_FIELD_PATH_WANT = '{"a":{"a":{"a":{"a":{"a":{"a":{"a":1}}}}}},"o":{"b":{"b":{"b":{}}}}}'
363
+
364
+
365
+ @pytest.mark.parametrize(
366
+ ("src", "want"),
367
+ [
368
+ (_STATE_PREFIX_PRIOR_SRC, _STATE_PREFIX_PRIOR_WANT),
369
+ (_STATE_CONCAT_SRC, _STATE_CONCAT_WANT),
370
+ (_STATE_SCOPE_SRC, _STATE_SCOPE_WANT),
371
+ (_STATE_FIELD_PATH_SRC, _STATE_FIELD_PATH_WANT),
372
+ ],
373
+ ids=["prefix-prior", "concat", "scope", "field-path"],
374
+ )
375
+ def test_each_guard_state_component_is_load_bearing(src: str, want: str) -> None:
376
+ assert _json(src) == json.loads(want)
377
+
378
+
379
+ def test_snapshot_cost_stays_small_with_long_keys() -> None:
380
+ # pd_120_2000: a 121-step chain over 2,000-byte keys leading into the dense
381
+ # 6-key cycle. The snapshot is built from frozensets of keys and identities,
382
+ # so long keys do not make each guard entry expensive (rs had to bound its
383
+ # snapshot cost); it ends in the post-cut work limit.
384
+ q = "q" * 2000
385
+ chain = "".join(f"{q}{i} = ${{{q}{i + 1}}}\n" for i in range(120)) + f"{q}120 = ${{k1}}\n"
386
+ refs = "".join(f"${{?k{j}}}" for j in range(1, 7))
387
+ dense = "".join(f"k{i} = {refs}\n" for i in range(1, 7)) * 2
388
+ with pytest.raises(ResolveError, match="too complex to resolve|resolved value too large"):
389
+ hocon.parse_string(chain + dense, env={})
File without changes
File without changes
File without changes
File without changes