Skip to content

Explore recreating definitions from nodes #818

Open

Description

@ssalbdivad

Using the new metadata attached to type nodes, we could convert a type node back into a minimal definition for that node in a given scope.

This could be extremely useful for both generating ArkType definitions from other formats as well as testing.

Using a library like fast-check, we could generate thousands of random valid definitions in the minimal format and ensure that each is parsed successfully as a type node that can then be converted back to its original input.

Activity

  1. moved this from To do to Backlog in arktypeioon Jul 6, 2023
  2. ahrjarrett commented on Jul 8, 2023

    @ahrjarrett
    Contributor

    If I understand this correctly, this task involves taking a node and, from its metadata, deriving (or "recovering") the larger entity that it belongs to?

    This is something I've just finished working on in a project of my own. I'd be happy to hop on a call sometime today (Saturday) and check my understanding. Depending on what metadata you've been collecting (which I would assume is pretty good), I should have time to work on this feature.

  3. ssalbdivad commented on Jul 8, 2023

    @ssalbdivad
    MemberAuthor

    @ahrjarrett I do think it is a very interesting problem, and the work you've done could definitely be relevant.

    which I would assume is pretty good

    Unfortunately, this is this is not the case. The current type system is totally isolated from any kind of metadata. Once a definition is parsed and converted to its type representation, there is no remaining association between the type node and its original definition.

    This was partly because in general, decoupling the definition syntax from the type is a good thing. Most validators have to rely on traversing their AST to try and derive types- it's much better to maintain a fully reduced representation.

    However, the new node structure designed to accommodate metadata like custom error messages also allows for other attached information, including potentially the original definition.

    Not every type node will have a real definition that was directly provided by the user, e.g. for a chained expression like type({a: "string"}).or({b: "number"}), we would create a synthetic definition using a tuple expression like [{a: "string"}, "|", {b: "number"}].

    This will be more complicated when the type node is the result of an intersection at some nested path, as there won't be a direct way to represent it like this at all. When props are intersected, if we always want to maintain some validation representation of the definition, we'll need to create some kind of tuple expression representation at the nested path, though I'd need to think more about exactly what this would entail.

    So the goal of this would not be so much to recreate the original definition exactly, but more to create a certain "isomorphic" form of the definition that would have a set of rules according to which various sets of constraints were minimally represented.

    Any definition could be parsed, then converted to a definition of this form. Any subsequent parse => unparse sequences would not change that representation. Having this capability for testing in particular would be incredibly powerful, as it would establish a universal property that could be checked to guarantee a definition (as long as our input is of the right form) is parsed correctly without us having to specify the expected result, which opens the door for us to rely on fast-check to generate many test cases based on those rules and to remove a lot of the manually specified edge cases that currently exist.

    I'm happy to talk about this in more detail, though work on the issue will have to wait until I at least finish up a stable version of the metadata representation within the type system so it would be clear where that information could begin to be integrated.

  4. ahrjarrett commented on Jul 8, 2023

    @ahrjarrett
    Contributor

    Got it -- let me now when you're ready to have this conversation.

    So the goal of this would not be so much to recreate the original definition exactly, but more to create a certain "isomorphic" form of the definition that would have a set of rules according to which various sets of constraints were minimally represented.

    Having this capability for testing in particular would be incredibly powerful, as it would establish a universal property that could be checked to guarantee a definition (as long as our input is of the right form) is parsed correctly without us having to specify the expected result, which opens the door for us to rely on fast-check to generate many test cases based on those rules and to remove a lot of the manually specified edge cases that currently exist.

    Precisely the use case I had in mind. As long as you have an isomorphic transformation, using a library like fast-check makes testing a breeze -- in the past I used a test runner called ava because of its support for macros, which enables some pretty nice patterns when used with fast-check.

    But assuming a switch to ava is not one of the goals of this change, we'd still be able to generate a pretty robust test suite by any isomorphism by testing

    a -> b -> a === a
    b -> a -> b === b
    a -> b !== a (to protect against accidental "identity" transformations / false positives)
    b -> a !== b (to protect against accidental "identity" transformations / false positives)
    

    It sounds like this is what you have in mind, which is exactly what I just finished working on. It took a substantial amount of work because of the number of edge cases it uncovered

  5. ssalbdivad commented on Jul 8, 2023

    @ssalbdivad
    MemberAuthor

    @ahrjarrett Amazing! So you have a lot of context on this stuff then. I'll tentatively just assign this to you for now so I don't accidentally forget about this conversation somehow and implement it next time I'm trying to test the million edge cases for range intersections 😆

    Just for a bit of additional background, the core piece of information we'd need from the metadata to map back to a canonical-ish definition is the scope. Without it, we'd have no way to associate type nodes with aliases, so nothing could be defined in a string- even keywords like number exist in the same way a custom alias in a scope does. The original definition itself would probably just lead us astray, because if we ever have to rely on it, we'd be missing a core part of the mapping that's important if it were specified in some other format.

    I will let you know as soon as we're at a point where this is stable enough to follow up on, which should be quite soon! In the meantime if you're really anxious to get started, if you haven't looked at the structure of the type system yet, that might be a useful area to explore a bit so you have an idea of how various constraints are internally represented so it's not all foreign when you go to map it back. If you're interested, TypeNode on beta is probably a good balance between being up to date and working 🤣

  6. moved this from Backlog to In progress in arktypeioon Dec 2, 2023
  7. moved this from In progress to Planned in arktypeioon Dec 12, 2023
  8. moved this from Planned to Backlog in arktypeioon May 22, 2024
  9. gabrielgrant commented on Dec 8, 2024

    @gabrielgrant
    Contributor

    Perhaps I'm misunderstanding exactly what this issue is about, but it does seem that some of this recreation of the "pretty" type def is already happening somewhere:

    const deviceFluent = type({
    	platform: type('"android"', "|", '"ios"'),
    	versions: type.number.or(type.string).array().optional()
    })
    
    const userFluent = type({
    	name: type.string,
    	device: deviceFluent,
    	placeOfBirth: type.string.optional()
    })
    
    console.log(userFluent.toString())
    // --> { device: { platform: "android" | "ios", versions?: (number | string)[] }, name: string, placeOfBirth?: string }
    

    But it's just a flattened string, not a parsable JSON/JS object

    (sidenote: some related discussion in #1225 )

  10. gabrielgrant commented on Dec 8, 2024

    @gabrielgrant
    Contributor

    Ah, looking through the source a bit more, it seems these string representations (which seem to be internally called "expressions") is built up node-by-node via direct string manipulation. eg:

    let expression =
    node.structure?.expression ||
    `${node.basis ? node.basis.nestableExpression + " " : ""}${node.refinements.map(n => n.expression).join(" & ")}` ||
    "unknown"
    if (expression === "Array == 0") expression = "[]"

  11. ssalbdivad commented on Dec 8, 2024

    @ssalbdivad
    MemberAuthor

    @gabrielgrant This is not totally dissimilar to how the canonical definition would need to be built, just with more precise rules to ensure we can always make an accurate round trip. Since there are a few ways to express most types, we'd have to define what exactly that normalized form looked like so we could translate to it.

    Like expression though, that would likely take the form of a method on each node.

  12. gabrielgrant commented on Dec 8, 2024

    @gabrielgrant
    Contributor

    Thinking about this more, there are two subtly different issues/approaches here:

    1. the flattened/der-referenced definitions as returned by .json and .toString() that can round-trip to the same internal type representation when passed back into type() independent of the scope in which they were originally created
    2. the definitions closer to as-provided, with the names of other custom types from their defining scope intact

    IIUC (2) seems to be closer to what you're discussing above, and does seem useful (though still need to think through some of how this could/should work -- possibly the ideal would be to return a whole scope, including a definition for any additional types on which the given type depends?). (1) Also seems useful sometimes, while also being more straightforward to implement. Thoughts?

  13. ssalbdivad commented on Dec 8, 2024

    @ssalbdivad
    MemberAuthor

    It's important that no reference to the user's original def is stored on a type node so that we can cache equivalent nodes.

    .json can already round trip for the most part, but testing the parsing isn't quite as useful as testing E2E from ArkType's syntax (though I should probably still do it :P ).

    .toString() is not meant to ever be parsable and is optimized only for visual display in errors etc.

    All ArkType definitions are scoped. It's just that the scope of those defined with the root-level type export is our default scope. But even that would be an assumption, so yes if we want anything close to ArkType syntax bidirectionally, we need it to be scoped. That said, methods/props like .references of a node are already available, so hopefully we could reuse a lot there.

    I think the most challenging thing will be figuring out what to do string-embed and how. We can probably assume that the output definition can reference any types from its own scope other than itself

  14. gabrielgrant commented on Dec 8, 2024

    @gabrielgrant
    Contributor

    Think I must be misunderstanding what you're proposing here -- it seems contradictory, so assuming I'm missing something

    I get that types' internal representation is independent of the original def, but doesn't that also mean it's independent of whether it is defined as references to a (non-default) scope vs as an independent, de-referenced type def?

    eg

    const typesScope = scope({
    	device: {
    		platform: "'android' | 'ios'",
    		"versions?": "(number | string)[]"
    	},
    	user: {
    		name: "string",
    		device: "device",
    		"placeOfBirth?": "string"
    	}
    })
    
    const types = typesScope.export()
    
    console.dir(types.user.json, { depth: 6 }) 
    

    outputs:

    {
      required: [
        {
          key: 'device',
          value: {
            required: [ { key: 'platform', value: [ [Object], [Object] ] } ],
            optional: [
              {
                key: 'versions',
                value: { sequence: [Array], proto: 'Array' }
              }
            ],
            domain: 'object'
          }
        },
        { key: 'name', value: 'string' }
      ],
      optional: [ { key: 'placeOfBirth', value: 'string' } ],
      domain: 'object'
    }
    

    ie no reference to the scope, or the fact that device is originally declared as a separate type

    I'm also not seeing a .references prop on the type itself, only on the scope (typeScope in this case). From a quick poke, though, it isn't really clear what this is (in this example it's a 40-element array). Mind explaining a bit more how you envision this being used? (also totally understand if you're busy, I'm sure I can figure it out by diving into the code more)

    Overall, though, what am I missing? Are you proposing that, in order to implement definition recreation, the types should carry a reference to the scope within which they were originally defined? (if not a ref to the full original user-supplied definition)

    Also -- is there a public way to round-trip .json today? From a quick test, just passing it back into type() doesn't seem to work

  15. ssalbdivad commented on Dec 8, 2024

    @ssalbdivad
    MemberAuthor

    Mind explaining a bit more how you envision this being used? (also totally understand if you're busy, I'm sure I can figure it out by diving into the code more)

    There are a lot of questions here and I am a bit underwater trying to finish the docs + some optimizations at the moment!

    However, the biggest things that will help a lot based on what's here:

    • the arktype package contains only the logic for parsing + inferring TS syntax
    • under the hood, a Type is actually just a set of fancy type declarations describing a BaseRoot from @ark/schema, the package containing all the underlying type logic as you've seen
    • scopes work similarly, with the exception of some methods specific to TS syntax parsing vs. parsing @ark/schema, which is what the schema method provides and the format .json outputs to.
    • for both of these objects and others, you can see other available properties from @ark/schema under internal
    • round trip generally works but there are exceptions for non-serializable values and possibly others

    Hopefully that is enough to get started! It's dense stuff but the type system is very uniform in the way its nodes are implemented so once it clicks, hopefully things will be clearer!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    • Status
      Backlog

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions