We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
Multi-level self-nesting support
### Problem

In ECS a self-nesting is when one field set is nested inside itself using a different name:

Two examples:

* `process.parent.*` self-nests the `process` field set renamed as `parent`
* `user.target.*` self-nests the `user.*` field set renamed as `target` (same applies to `user.changes` and `user.effective`)

In a _very_ specific case, you may want to self nest the same field set twice:

1. Reuse `process.*` as `process.target.*`
2. Reuse `process` again but underneath `process.target.*` to create `process.target.parent.*`

The current ECS tooling allows specifying this in the `reusable.expected` section, but it will not produce the desired result:

```json
- name: process
  reusable:
    expected:
      - at: process
        as: target
      # collect the parent of the target process at process.target.parent
      - at: process.target
        as: parent
```

### Solution

Implement logic into the [self-nesting phase](https://github.com/elastic/ecs/blob/master/scripts/schema/finalizer.py#L78-L98) of `.finalize` to account for when the `at` attribute is not the top-level field set but an existing self-nesting.

--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `scripts/schema/finalizer.py`
Content:
```
1 import copy
2 import re
3 
4 from schema import visitor
5 
6 # This script takes the fleshed out deeply nested fields dictionary as emitted by
7 # cleaner.py, and performs field reuse in two phases.
8 #
9 # Phase 1 performs field reuse across field sets. E.g. `group` fields should also be under `user`.
10 # This type of reuse is then carried around if the receiving field set is also reused.
11 # In other words, user.group.* will be in other places where user is nested:
12 # source.user.* will contain source.user.group.*
13 
14 # Phase 2 performs field reuse where field sets are reused within themselves, with a different name.
15 # Examples are nesting `process` within itself, as `process.parent.*`,
16 # or nesting `user` within itself at `user.target.*`.
17 # This second kind of nesting is not carried around everywhere else the receiving field set is reused.
18 # So `user.target.*` is *not* carried over to `source.user.target*` when we reuse `user` under `source`.
19 
20 
21 def finalize(fields):
22     """Intended entrypoint of the finalizer."""
23     perform_reuse(fields)
24     calculate_final_values(fields)
25 
26 
27 def order_reuses(fields):
28     foreign_reuses = {}
29     self_nestings = {}
30     for schema_name, schema in fields.items():
31         if not 'reusable' in schema['schema_details']:
32             continue
33         reuse_order = schema['schema_details']['reusable']['order']
34         for reuse_entry in schema['schema_details']['reusable']['expected']:
35             destination_schema_name = reuse_entry['full'].split('.')[0]
36             if destination_schema_name == schema_name:
37                 # Accumulate self-nestings for phase 2.
38                 self_nestings.setdefault(destination_schema_name, [])
39                 self_nestings[destination_schema_name].extend([reuse_entry])
40             else:
41                 # Group foreign reuses by 'order' attribute.
42                 foreign_reuses.setdefault(reuse_order, {})
43                 foreign_reuses[reuse_order].setdefault(schema_name, [])
44                 foreign_reuses[reuse_order][schema_name].extend([reuse_entry])
45     return foreign_reuses, self_nestings
46 
47 
48 def perform_reuse(fields):
49     """Performs field reuse in two phases"""
50     foreign_reuses, self_nestings = order_reuses(fields)
51 
52     # Phase 1: foreign reuse
53     # These are done respecting the reusable.order attribute.
54     # This lets us force the order for chained reuses (e.g. group => user, then user => many places)
55     for order in sorted(foreign_reuses.keys()):
56         for schema_name, reuse_entries in foreign_reuses[order].items():
57             schema = fields[schema_name]
58             for reuse_entry in reuse_entries:
59                 # print(order, "{} => {}".format(schema_name, reuse_entry['full']))
60                 nest_as = reuse_entry['as']
61                 destination_schema_name = reuse_entry['full'].split('.')[0]
62                 destination_schema = fields[destination_schema_name]
63                 ensure_valid_reuse(schema, destination_schema)
64 
65                 new_field_details = copy.deepcopy(schema['field_details'])
66                 new_field_details['name'] = nest_as
67                 new_field_details['original_fieldset'] = schema_name
68                 new_field_details['intermediate'] = True
69                 reused_fields = copy.deepcopy(schema['fields'])
70                 set_original_fieldset(reused_fields, schema_name)
71                 destination_fields = field_group_at_path(reuse_entry['at'], fields)
72                 destination_fields[nest_as] = {
73                     'field_details': new_field_details,
74                     'fields': reused_fields,
75                 }
76                 append_reused_here(schema, reuse_entry, destination_schema)
77 
78     # Phase 2: self-nesting
79     for schema_name, reuse_entries in self_nestings.items():
80         schema = fields[schema_name]
81         ensure_valid_reuse(schema)
82         # Since we're about self-nest more fields within these, make a pristine copy first
83         reused_fields = copy.deepcopy(schema['fields'])
84         set_original_fieldset(reused_fields, schema_name)
85         for reuse_entry in reuse_entries:
86             # print("x {} => {}".format(schema_name, reuse_entry['full']))
87             nest_as = reuse_entry['as']
88             new_field_details = copy.deepcopy(schema['field_details'])
89             new_field_details['name'] = nest_as
90             new_field_details['original_fieldset'] = schema_name
91             new_field_details['intermediate'] = True
92             destination_fields = schema['fields']
93             destination_fields[nest_as] = {
94                 'field_details': new_field_details,
95                 # Make a new copy of the pristine copy
96                 'fields': copy.deepcopy(reused_fields),
97             }
98             append_reused_here(schema, reuse_entry, fields[schema_name])
99 
100 
101 def ensure_valid_reuse(reused_schema, destination_schema=None):
102     """
103     Raise if either the reused schema or destination schema have root=true.
104 
105     Second param is optional, if testing for a self-nesting (where source=destination).
106     """
107     if reused_schema['schema_details']['root']:
108         msg = "Schema {} has attribute root=true and therefore cannot be reused.".format(
109             reused_schema['field_details']['name'])
110         raise ValueError(msg)
111     elif destination_schema and destination_schema['schema_details']['root']:
112         msg = "Schema {} has attribute root=true and therefore cannot have other field sets reused inside it.".format(
113             destination_schema['field_details']['name'])
114         raise ValueError(msg)
115 
116 
117 def append_reused_here(reused_schema, reuse_entry, destination_schema):
118     """Captures two ways of denoting what field sets are reused under a given field set"""
119     # Legacy, too limited
120     destination_schema['schema_details'].setdefault('nestings', [])
121     destination_schema['schema_details']['nestings'] = sorted(
122         destination_schema['schema_details']['nestings'] + [reuse_entry['full']]
123     )
124     # New roomier way: we could eventually include contextual description here
125     destination_schema['schema_details'].setdefault('reused_here', [])
126     reused_here_entry = {
127         'schema_name': reused_schema['field_details']['name'],
128         'full': reuse_entry['full'],
129         # Check for a short override, if not present, fall back to the top-level fieldset's short
130         'short': reuse_entry['short_override'] if 'short_override' in reuse_entry else reused_schema['field_details']['short']
131     }
132     # Check for beta attribute
133     if 'beta' in reuse_entry:
134         reused_here_entry['beta'] = reuse_entry['beta']
135     destination_schema['schema_details']['reused_here'].extend([reused_here_entry])
136 
137 
138 def set_original_fieldset(fields, original_fieldset):
139     """Recursively set the 'original_fieldset' attribute for all fields in a group of fields"""
140     def func(details):
141         # Don't override if already set (e.g. 'group' for user.group.* fields)
142         details['field_details'].setdefault('original_fieldset', original_fieldset)
143     visitor.visit_fields(fields, field_func=func)
144 
145 
146 def field_group_at_path(dotted_path, fields):
147     """Returns the ['fields'] hash at the dotted_path."""
148     path = dotted_path.split('.')
149     nesting = fields
150     for next_field in path:
151         field = nesting.get(next_field, None)
152         if not field:
153             raise ValueError("Field {} not found, failed to find {}".format(dotted_path, next_field))
154         nesting = field.get('fields', None)
155         if not nesting:
156             field_type = field['field_details']['type']
157             if field_type in ['object', 'group', 'nested']:
158                 nesting = field['fields'] = {}
159             else:
160                 raise ValueError("Field {} (type {}) already exists and cannot have nested fields".format(
161                     dotted_path, field_type))
162     return nesting
163 
164 
165 def calculate_final_values(fields):
166     """
167     This function navigates all fields recursively.
168 
169     It populates a few more values for the fields, especially path-based values
170     like flat_name.
171     """
172     visitor.visit_fields_with_path(fields, field_finalizer)
173 
174 
175 def field_finalizer(details, path):
176     """This is the function called by the visitor to perform the work of calculate_final_values"""
177     name_array = path + [details['field_details']['node_name']]
178     flat_name = '.'.join(name_array)
179     details['field_details']['flat_name'] = flat_name
180     details['field_details']['dashed_name'] = re.sub('[_\.]', '-', flat_name).replace('@', '')
181     if 'multi_fields' in details['field_details']:
182         for mf in details['field_details']['multi_fields']:
183             mf['flat_name'] = flat_name + '.' + mf['name']
184
```
--- END FILES ---

Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.

Here is an example:

```diff
diff --git a/examples/server_async.py b/examples/server_async.py
--- a/examples/server_async.py
+++ b/examples/server_async.py
@@ -313,4 +313,4 @@
 
 
 if __name__ == "__main__":
-    asyncio.run(run_async_server("."), debug=True)
+    asyncio.run(run_async_server(), debug=True)
diff --git a/examples/server_sync.py b/examples/server_sync.py
--- a/examples/server_sync.py
+++ b/examples/server_sync.py
@@ -313,5 +313,5 @@
 
 
 if __name__ == "__main__":
-    server = run_sync_server(".")
+    server = run_sync_server()
     server.shutdown()

```

diff --git a/scripts/schema/finalizer.py b/scripts/schema/finalizer.py
--- a/scripts/schema/finalizer.py
+++ b/scripts/schema/finalizer.py
@@ -89,7 +89,11 @@
             new_field_details['name'] = nest_as
             new_field_details['original_fieldset'] = schema_name
             new_field_details['intermediate'] = True
-            destination_fields = schema['fields']
+            # to handle multi-level self-nesting
+            if reuse_entry['at'] != schema_name:
+                destination_fields = field_group_at_path(reuse_entry['at'], fields)
+            else:
+                destination_fields = schema['fields']
             destination_fields[nest_as] = {
                 'field_details': new_field_details,
                 # Make a new copy of the pristine copy

{"golden_diff": "diff --git a/scripts/schema/finalizer.py b/scripts/schema/finalizer.py\n--- a/scripts/schema/finalizer.py\n+++ b/scripts/schema/finalizer.py\n@@ -89,7 +89,11 @@\n             new_field_details['name'] = nest_as\n             new_field_details['original_fieldset'] = schema_name\n             new_field_details['intermediate'] = True\n-            destination_fields = schema['fields']\n+            # to handle multi-level self-nesting\n+            if reuse_entry['at'] != schema_name:\n+                destination_fields = field_group_at_path(reuse_entry['at'], fields)\n+            else:\n+                destination_fields = schema['fields']\n             destination_fields[nest_as] = {\n                 'field_details': new_field_details,\n                 # Make a new copy of the pristine copy\n", "issue": "Multi-level self-nesting support\n### Problem\r\n\r\nIn ECS a self-nesting is when one field set is nested inside itself using a different name:\r\n\r\nTwo examples:\r\n\r\n* `process.parent.*` self-nests the `process` field set renamed as `parent`\r\n* `user.target.*` self-nests the `user.*` field set renamed as `target` (same applies to `user.changes` and `user.effective`)\r\n\r\nIn a _very_ specific case, you may want to self nest the same field set twice:\r\n\r\n1. Reuse `process.*` as `process.target.*`\r\n2. Reuse `process` again but underneath `process.target.*` to create `process.target.parent.*`\r\n\r\nThe current ECS tooling allows specifying this in the `reusable.expected` section, but it will not produce the desired result:\r\n\r\n```json\r\n- name: process\r\n  reusable:\r\n    expected:\r\n      - at: process\r\n        as: target\r\n      # collect the parent of the target process at process.target.parent\r\n      - at: process.target\r\n        as: parent\r\n```\r\n\r\n### Solution\r\n\r\nImplement logic into the [self-nesting phase](https://github.com/elastic/ecs/blob/master/scripts/schema/finalizer.py#L78-L98) of `.finalize` to account for when the `at` attribute is not the top-level field set but an existing self-nesting.\n", "before_files": [{"content": "import copy\nimport re\n\nfrom schema import visitor\n\n# This script takes the fleshed out deeply nested fields dictionary as emitted by\n# cleaner.py, and performs field reuse in two phases.\n#\n# Phase 1 performs field reuse across field sets. E.g. `group` fields should also be under `user`.\n# This type of reuse is then carried around if the receiving field set is also reused.\n# In other words, user.group.* will be in other places where user is nested:\n# source.user.* will contain source.user.group.*\n\n# Phase 2 performs field reuse where field sets are reused within themselves, with a different name.\n# Examples are nesting `process` within itself, as `process.parent.*`,\n# or nesting `user` within itself at `user.target.*`.\n# This second kind of nesting is not carried around everywhere else the receiving field set is reused.\n# So `user.target.*` is *not* carried over to `source.user.target*` when we reuse `user` under `source`.\n\n\ndef finalize(fields):\n    \"\"\"Intended entrypoint of the finalizer.\"\"\"\n    perform_reuse(fields)\n    calculate_final_values(fields)\n\n\ndef order_reuses(fields):\n    foreign_reuses = {}\n    self_nestings = {}\n    for schema_name, schema in fields.items():\n        if not 'reusable' in schema['schema_details']:\n            continue\n        reuse_order = schema['schema_details']['reusable']['order']\n        for reuse_entry in schema['schema_details']['reusable']['expected']:\n            destination_schema_name = reuse_entry['full'].split('.')[0]\n            if destination_schema_name == schema_name:\n                # Accumulate self-nestings for phase 2.\n                self_nestings.setdefault(destination_schema_name, [])\n                self_nestings[destination_schema_name].extend([reuse_entry])\n            else:\n                # Group foreign reuses by 'order' attribute.\n                foreign_reuses.setdefault(reuse_order, {})\n                foreign_reuses[reuse_order].setdefault(schema_name, [])\n                foreign_reuses[reuse_order][schema_name].extend([reuse_entry])\n    return foreign_reuses, self_nestings\n\n\ndef perform_reuse(fields):\n    \"\"\"Performs field reuse in two phases\"\"\"\n    foreign_reuses, self_nestings = order_reuses(fields)\n\n    # Phase 1: foreign reuse\n    # These are done respecting the reusable.order attribute.\n    # This lets us force the order for chained reuses (e.g. group => user, then user => many places)\n    for order in sorted(foreign_reuses.keys()):\n        for schema_name, reuse_entries in foreign_reuses[order].items():\n            schema = fields[schema_name]\n            for reuse_entry in reuse_entries:\n                # print(order, \"{} => {}\".format(schema_name, reuse_entry['full']))\n                nest_as = reuse_entry['as']\n                destination_schema_name = reuse_entry['full'].split('.')[0]\n                destination_schema = fields[destination_schema_name]\n                ensure_valid_reuse(schema, destination_schema)\n\n                new_field_details = copy.deepcopy(schema['field_details'])\n                new_field_details['name'] = nest_as\n                new_field_details['original_fieldset'] = schema_name\n                new_field_details['intermediate'] = True\n                reused_fields = copy.deepcopy(schema['fields'])\n                set_original_fieldset(reused_fields, schema_name)\n                destination_fields = field_group_at_path(reuse_entry['at'], fields)\n                destination_fields[nest_as] = {\n                    'field_details': new_field_details,\n                    'fields': reused_fields,\n                }\n                append_reused_here(schema, reuse_entry, destination_schema)\n\n    # Phase 2: self-nesting\n    for schema_name, reuse_entries in self_nestings.items():\n        schema = fields[schema_name]\n        ensure_valid_reuse(schema)\n        # Since we're about self-nest more fields within these, make a pristine copy first\n        reused_fields = copy.deepcopy(schema['fields'])\n        set_original_fieldset(reused_fields, schema_name)\n        for reuse_entry in reuse_entries:\n            # print(\"x {} => {}\".format(schema_name, reuse_entry['full']))\n            nest_as = reuse_entry['as']\n            new_field_details = copy.deepcopy(schema['field_details'])\n            new_field_details['name'] = nest_as\n            new_field_details['original_fieldset'] = schema_name\n            new_field_details['intermediate'] = True\n            destination_fields = schema['fields']\n            destination_fields[nest_as] = {\n                'field_details': new_field_details,\n                # Make a new copy of the pristine copy\n                'fields': copy.deepcopy(reused_fields),\n            }\n            append_reused_here(schema, reuse_entry, fields[schema_name])\n\n\ndef ensure_valid_reuse(reused_schema, destination_schema=None):\n    \"\"\"\n    Raise if either the reused schema or destination schema have root=true.\n\n    Second param is optional, if testing for a self-nesting (where source=destination).\n    \"\"\"\n    if reused_schema['schema_details']['root']:\n        msg = \"Schema {} has attribute root=true and therefore cannot be reused.\".format(\n            reused_schema['field_details']['name'])\n        raise ValueError(msg)\n    elif destination_schema and destination_schema['schema_details']['root']:\n        msg = \"Schema {} has attribute root=true and therefore cannot have other field sets reused inside it.\".format(\n            destination_schema['field_details']['name'])\n        raise ValueError(msg)\n\n\ndef append_reused_here(reused_schema, reuse_entry, destination_schema):\n    \"\"\"Captures two ways of denoting what field sets are reused under a given field set\"\"\"\n    # Legacy, too limited\n    destination_schema['schema_details'].setdefault('nestings', [])\n    destination_schema['schema_details']['nestings'] = sorted(\n        destination_schema['schema_details']['nestings'] + [reuse_entry['full']]\n    )\n    # New roomier way: we could eventually include contextual description here\n    destination_schema['schema_details'].setdefault('reused_here', [])\n    reused_here_entry = {\n        'schema_name': reused_schema['field_details']['name'],\n        'full': reuse_entry['full'],\n        # Check for a short override, if not present, fall back to the top-level fieldset's short\n        'short': reuse_entry['short_override'] if 'short_override' in reuse_entry else reused_schema['field_details']['short']\n    }\n    # Check for beta attribute\n    if 'beta' in reuse_entry:\n        reused_here_entry['beta'] = reuse_entry['beta']\n    destination_schema['schema_details']['reused_here'].extend([reused_here_entry])\n\n\ndef set_original_fieldset(fields, original_fieldset):\n    \"\"\"Recursively set the 'original_fieldset' attribute for all fields in a group of fields\"\"\"\n    def func(details):\n        # Don't override if already set (e.g. 'group' for user.group.* fields)\n        details['field_details'].setdefault('original_fieldset', original_fieldset)\n    visitor.visit_fields(fields, field_func=func)\n\n\ndef field_group_at_path(dotted_path, fields):\n    \"\"\"Returns the ['fields'] hash at the dotted_path.\"\"\"\n    path = dotted_path.split('.')\n    nesting = fields\n    for next_field in path:\n        field = nesting.get(next_field, None)\n        if not field:\n            raise ValueError(\"Field {} not found, failed to find {}\".format(dotted_path, next_field))\n        nesting = field.get('fields', None)\n        if not nesting:\n            field_type = field['field_details']['type']\n            if field_type in ['object', 'group', 'nested']:\n                nesting = field['fields'] = {}\n            else:\n                raise ValueError(\"Field {} (type {}) already exists and cannot have nested fields\".format(\n                    dotted_path, field_type))\n    return nesting\n\n\ndef calculate_final_values(fields):\n    \"\"\"\n    This function navigates all fields recursively.\n\n    It populates a few more values for the fields, especially path-based values\n    like flat_name.\n    \"\"\"\n    visitor.visit_fields_with_path(fields, field_finalizer)\n\n\ndef field_finalizer(details, path):\n    \"\"\"This is the function called by the visitor to perform the work of calculate_final_values\"\"\"\n    name_array = path + [details['field_details']['node_name']]\n    flat_name = '.'.join(name_array)\n    details['field_details']['flat_name'] = flat_name\n    details['field_details']['dashed_name'] = re.sub('[_\\.]', '-', flat_name).replace('@', '')\n    if 'multi_fields' in details['field_details']:\n        for mf in details['field_details']['multi_fields']:\n            mf['flat_name'] = flat_name + '.' + mf['name']\n", "path": "scripts/schema/finalizer.py"}], "after_files": [{"content": "import copy\nimport re\n\nfrom schema import visitor\n\n# This script takes the fleshed out deeply nested fields dictionary as emitted by\n# cleaner.py, and performs field reuse in two phases.\n#\n# Phase 1 performs field reuse across field sets. E.g. `group` fields should also be under `user`.\n# This type of reuse is then carried around if the receiving field set is also reused.\n# In other words, user.group.* will be in other places where user is nested:\n# source.user.* will contain source.user.group.*\n\n# Phase 2 performs field reuse where field sets are reused within themselves, with a different name.\n# Examples are nesting `process` within itself, as `process.parent.*`,\n# or nesting `user` within itself at `user.target.*`.\n# This second kind of nesting is not carried around everywhere else the receiving field set is reused.\n# So `user.target.*` is *not* carried over to `source.user.target*` when we reuse `user` under `source`.\n\n\ndef finalize(fields):\n    \"\"\"Intended entrypoint of the finalizer.\"\"\"\n    perform_reuse(fields)\n    calculate_final_values(fields)\n\n\ndef order_reuses(fields):\n    foreign_reuses = {}\n    self_nestings = {}\n    for schema_name, schema in fields.items():\n        if not 'reusable' in schema['schema_details']:\n            continue\n        reuse_order = schema['schema_details']['reusable']['order']\n        for reuse_entry in schema['schema_details']['reusable']['expected']:\n            destination_schema_name = reuse_entry['full'].split('.')[0]\n            if destination_schema_name == schema_name:\n                # Accumulate self-nestings for phase 2.\n                self_nestings.setdefault(destination_schema_name, [])\n                self_nestings[destination_schema_name].extend([reuse_entry])\n            else:\n                # Group foreign reuses by 'order' attribute.\n                foreign_reuses.setdefault(reuse_order, {})\n                foreign_reuses[reuse_order].setdefault(schema_name, [])\n                foreign_reuses[reuse_order][schema_name].extend([reuse_entry])\n    return foreign_reuses, self_nestings\n\n\ndef perform_reuse(fields):\n    \"\"\"Performs field reuse in two phases\"\"\"\n    foreign_reuses, self_nestings = order_reuses(fields)\n\n    # Phase 1: foreign reuse\n    # These are done respecting the reusable.order attribute.\n    # This lets us force the order for chained reuses (e.g. group => user, then user => many places)\n    for order in sorted(foreign_reuses.keys()):\n        for schema_name, reuse_entries in foreign_reuses[order].items():\n            schema = fields[schema_name]\n            for reuse_entry in reuse_entries:\n                # print(order, \"{} => {}\".format(schema_name, reuse_entry['full']))\n                nest_as = reuse_entry['as']\n                destination_schema_name = reuse_entry['full'].split('.')[0]\n                destination_schema = fields[destination_schema_name]\n                ensure_valid_reuse(schema, destination_schema)\n\n                new_field_details = copy.deepcopy(schema['field_details'])\n                new_field_details['name'] = nest_as\n                new_field_details['original_fieldset'] = schema_name\n                new_field_details['intermediate'] = True\n                reused_fields = copy.deepcopy(schema['fields'])\n                set_original_fieldset(reused_fields, schema_name)\n                destination_fields = field_group_at_path(reuse_entry['at'], fields)\n                destination_fields[nest_as] = {\n                    'field_details': new_field_details,\n                    'fields': reused_fields,\n                }\n                append_reused_here(schema, reuse_entry, destination_schema)\n\n    # Phase 2: self-nesting\n    for schema_name, reuse_entries in self_nestings.items():\n        schema = fields[schema_name]\n        ensure_valid_reuse(schema)\n        # Since we're about self-nest more fields within these, make a pristine copy first\n        reused_fields = copy.deepcopy(schema['fields'])\n        set_original_fieldset(reused_fields, schema_name)\n        for reuse_entry in reuse_entries:\n            # print(\"x {} => {}\".format(schema_name, reuse_entry['full']))\n            nest_as = reuse_entry['as']\n            new_field_details = copy.deepcopy(schema['field_details'])\n            new_field_details['name'] = nest_as\n            new_field_details['original_fieldset'] = schema_name\n            new_field_details['intermediate'] = True\n            # to handle multi-level self-nesting\n            if reuse_entry['at'] != schema_name:\n                destination_fields = field_group_at_path(reuse_entry['at'], fields)\n            else:\n                destination_fields = schema['fields']\n            destination_fields[nest_as] = {\n                'field_details': new_field_details,\n                # Make a new copy of the pristine copy\n                'fields': copy.deepcopy(reused_fields),\n            }\n            append_reused_here(schema, reuse_entry, fields[schema_name])\n\n\ndef ensure_valid_reuse(reused_schema, destination_schema=None):\n    \"\"\"\n    Raise if either the reused schema or destination schema have root=true.\n\n    Second param is optional, if testing for a self-nesting (where source=destination).\n    \"\"\"\n    if reused_schema['schema_details']['root']:\n        msg = \"Schema {} has attribute root=true and therefore cannot be reused.\".format(\n            reused_schema['field_details']['name'])\n        raise ValueError(msg)\n    elif destination_schema and destination_schema['schema_details']['root']:\n        msg = \"Schema {} has attribute root=true and therefore cannot have other field sets reused inside it.\".format(\n            destination_schema['field_details']['name'])\n        raise ValueError(msg)\n\n\ndef append_reused_here(reused_schema, reuse_entry, destination_schema):\n    \"\"\"Captures two ways of denoting what field sets are reused under a given field set\"\"\"\n    # Legacy, too limited\n    destination_schema['schema_details'].setdefault('nestings', [])\n    destination_schema['schema_details']['nestings'] = sorted(\n        destination_schema['schema_details']['nestings'] + [reuse_entry['full']]\n    )\n    # New roomier way: we could eventually include contextual description here\n    destination_schema['schema_details'].setdefault('reused_here', [])\n    reused_here_entry = {\n        'schema_name': reused_schema['field_details']['name'],\n        'full': reuse_entry['full'],\n        # Check for a short override, if not present, fall back to the top-level fieldset's short\n        'short': reuse_entry['short_override'] if 'short_override' in reuse_entry else reused_schema['field_details']['short']\n    }\n    # Check for beta attribute\n    if 'beta' in reuse_entry:\n        reused_here_entry['beta'] = reuse_entry['beta']\n    destination_schema['schema_details']['reused_here'].extend([reused_here_entry])\n\n\ndef set_original_fieldset(fields, original_fieldset):\n    \"\"\"Recursively set the 'original_fieldset' attribute for all fields in a group of fields\"\"\"\n    def func(details):\n        # Don't override if already set (e.g. 'group' for user.group.* fields)\n        details['field_details'].setdefault('original_fieldset', original_fieldset)\n    visitor.visit_fields(fields, field_func=func)\n\n\ndef field_group_at_path(dotted_path, fields):\n    \"\"\"Returns the ['fields'] hash at the dotted_path.\"\"\"\n    path = dotted_path.split('.')\n    nesting = fields\n    for next_field in path:\n        field = nesting.get(next_field, None)\n        if not field:\n            raise ValueError(\"Field {} not found, failed to find {}\".format(dotted_path, next_field))\n        nesting = field.get('fields', None)\n        if not nesting:\n            field_type = field['field_details']['type']\n            if field_type in ['object', 'group', 'nested']:\n                nesting = field['fields'] = {}\n            else:\n                raise ValueError(\"Field {} (type {}) already exists and cannot have nested fields\".format(\n                    dotted_path, field_type))\n    return nesting\n\n\ndef calculate_final_values(fields):\n    \"\"\"\n    This function navigates all fields recursively.\n\n    It populates a few more values for the fields, especially path-based values\n    like flat_name.\n    \"\"\"\n    visitor.visit_fields_with_path(fields, field_finalizer)\n\n\ndef field_finalizer(details, path):\n    \"\"\"This is the function called by the visitor to perform the work of calculate_final_values\"\"\"\n    name_array = path + [details['field_details']['node_name']]\n    flat_name = '.'.join(name_array)\n    details['field_details']['flat_name'] = flat_name\n    details['field_details']['dashed_name'] = re.sub('[_\\.]', '-', flat_name).replace('@', '')\n    if 'multi_fields' in details['field_details']:\n        for mf in details['field_details']['multi_fields']:\n            mf['flat_name'] = flat_name + '.' + mf['name']\n", "path": "scripts/schema/finalizer.py"}]}