Skip to content

Binary replication: support types added/removed after program startup #4066

Closed as not planned

Description

@roji

We perform type loading at program startup, and this is what binary replication uses to decode binary data (just like regular queries). However, if a type was created late, we don't know about it and can't decode it. In contrast to regular programs which can call ReloadTypes after creating the type, we think that replication clients may frequently be long-lived programs, and that type creation happens via the main program (separate from replication clients); this may make it important to support this. Note that this only affects binary replication - for text replication we don't need to know anything about the types, since we don't decode them.

We should be able to detect unknown types either via an incoming TypeMessage, or just when we fail to look up a type OID in a RelationMessage. When this happens, we could automatically trigger type reloading. We can't do this on the main replication connection, since that connection is busy and has enqueued replication data (so we won't get the query results in time). So we must open an out-of-band connection purely for type loading; this must be a replication connection and not a normal one, since authentication credentials may be completely different and the replication client may not have access to open a normal connection.

/cc @Brar

Activity

  1. added this to the 7.0.0 milestone on Oct 25, 2021
  2. Brar commented on Oct 27, 2021

    @Brar
    Member

    I think we should really consider this for 6.0 because implementing it will probably change the API once again.
    Without it we are also lacking some quite fundamental and simple Npgsql features like reading domains over simple types which will prohibit roundtripping them as suggested in #4046 (comment).
    It shouldn't be too hard to do (in fact it already is part of #4024).

  3. roji commented on Oct 28, 2021

    @roji
    MemberAuthor

    @Brar I've taken another look, here's how I understand the situation (I may be missing something):

    • Npgsql's type mapper (with all the type OID/name mappings) are set up based on type loading, which happens only when the program starts up.
    • If a custom type is added before application startup, it would be loaded like any other type, we'd create the handler for it - basically everything should just work.
    • If a PG custom type is added after program startup, we don't know about it (unless ReloadTypes is called). The replication TypeMessage gets us the type name, but I can't see how that helps us... We have no idea whether that PostgreSQL type is a domain, range, enum or composite, we're lacking the mappings to a user CLR type (for enum/composite), and for domains we're also lacking the knowledge of what the underlying type is.
    • I saw the code in Initial working binary replication #4024 which falls back to resolving by the type name if the OID doesn't resolve, but I'm not sure where that would help.

    To summarize, as long as no types are modified after the replication client loaded the types, everything should work fine regardless of whether the type is built-in or custom. If types are modified after the replication client loaded, the best we can do is to somehow automatically trigger a type reload, no? But that's complicated, and it doesn't feel like a must-have for 6.0 (or why an API change would be needed for it if we do it later).

    Basically it feels like I've missed some aspect here 😅

  4. changed the title [-]Replication: improve support for custom types[/-] [+]Replication: support types added/removed after program startup[/+] on Nov 1, 2021
  5. changed the title [-]Replication: support types added/removed after program startup[/-] [+]Binary replication: support types added/removed after program startup[/+] on Nov 1, 2021
  6. roji commented on Nov 1, 2021

    @roji
    MemberAuthor

    @Brar updated the OP based on our offline discussion. This isn't just about custom types (enum/composite), since extensions can add types late as well.

  7. bwalendz commented on Jan 16, 2022

    @bwalendz

    Thanks for the work on this @roji

    I've been looking around existing discussions but haven't found anything that is exactly like this along with the newness of PG14 binary replication.

    I was experimenting with it using Npgsql 6.0.2 on PG14.1 and I am getting the classic "The field 'XXXXX' has a type currently unknown to Npgsql (OID XXXXX). You can retrieve it as a string by marking it as unknown, please see the FAQ."

    Disregarding the reloading functionality and looking at the existing documentation it's not clear to me the correct strategy to handle this in the replication scenario. I am not yet a power user of Npgsql so it wasn't clear what the proper approach is. Nothing on ReplicationTuple/ReplicationValue seemed obvious either.

    create type descriptor as (
        id   bigint
    ,   name text
    );

    Are there any examples of how PG user defined custom types can be handled for binary replication?

  8. roji commented on Jan 16, 2022

    @roji
    MemberAuthor

    @bwalendz assuming your composite type (descriptor) is present in the database before the program starts, have you mapped it as per the docs? If memory serves, once that's done you should be able to access your type as usual via ReplicationValue.Get<T>, where T is the .NET type you mapped to your PG composite.

  9. bwalendz commented on Jan 16, 2022

    @bwalendz

    @bwalendz assuming your composite type (descriptor) is present in the database before the program starts, have you mapped it as per the docs? If memory serves, once that's done you should be able to access your type as usual via ReplicationValue.Get<T>, where T is the .NET type you mapped to your PG composite.

    @roji Maybe I am doing something wrong but I have it setup as best as I can tell from the documentation.

    I would prefer that it is handled automatically like it's doing for existing .net types, and that seems feasible when we're explicitly defining the mapping via MapComposite? For my needs doing an explicit cast is troublesome when having a generic "handler" to initially process incoming logical messages that works for any table, especially when ReplicationValue OID is set as 0 (I instead was using the Relation and getting the OID from column position, it works but not ideal). But doing as you describe throws this

    System.InvalidCastException: Can't cast database type .<unknown> to Descriptor
       at Npgsql.Internal.TypeHandling.NpgsqlTypeHandler.ReadCustom[TAny](NpgsqlReadBuffer buf, Int32 len, Boolean async, FieldDescription fieldDescription)
       at Npgsql.Internal.TypeHandling.NpgsqlTypeHandler.Read[TAny](NpgsqlReadBuffer buf, Int32 len, Boolean async, FieldDescription fieldDescription)
       at Npgsql.Replication.PgOutput.ReplicationValue.<Get>g__GetCore|21_0[T](CancellationToken cancellationToken)
    

    and the error I posted previously is without casting ReplicationValue.Get()

    System.NotSupportedException: The field 'my_composite_field' has a type currently unknown to Npgsql (OID 16403). You can retrieve it as a string by marking it as unknown, please see the FAQ.
       at Npgsql.Internal.TypeHandlers.UnknownTypeHandler.Read(NpgsqlReadBuffer buf, Int32 byteLen, Boolean async, FieldDescription fieldDescription)
       at Npgsql.Internal.TypeHandling.NpgsqlTypeHandler.Read[TAny](NpgsqlReadBuffer buf, Int32 len, Boolean async, FieldDescription fieldDescription)
       at Npgsql.Internal.TypeHandling.NpgsqlTypeHandler`1.ReadAsObject(NpgsqlReadBuffer buf, Int32 len, Boolean async, FieldDescription fieldDescription)
       at Npgsql.Replication.PgOutput.ReplicationValue.<Get>g__GetCore|22_0(CancellationToken cancellationToken)
    

    The basic setup is

    var slot = new PgOutputReplicationSlot("test_slot");
    var publication = new PgOutputReplicationOptions("test_pub", 1, true);
    
    NpgsqlConnection.GlobalTypeMapper.MapComposite<Descriptor>("descriptor");
    
    await using var conn = new LogicalReplicationConnection(_connectionString);
    await conn.Open(stoppingToken);
    
    await foreach (var message in conn.StartReplication(slot, publication, stoppingToken))
    {
    /* fragment */
    var casted = await value.Get<Descriptor>(stoppingToken);
    /* fragment */
    }
    
    
    [PgName("descriptor")]
    public class Descriptor
    {
      [PgName("id")]
      public long Id { get; set; }
      [PgName("name")]
      public string Name { get; set; }
    }

    The type already exists before this code is started.

    +-----+------------+--------+-----------+--------+-------+------+-------+-----------+
    |oid  |typnamespace|typowner|typname    |typarray|typelem|typlen|typtype|typcategory|
    +-----+------------+--------+-----------+--------+-------+------+-------+-----------+
    |16402|2200        |10      |_descriptor|0       |16403  |-1    |b      |A          |
    |16403|2200        |10      |descriptor |16402   |0      |-1    |c      |C          |
    +-----+------------+--------+-----------+--------+-------+------+-------+-----------+

    Only obvious difference compared to native types is it living in public schema vs pg_catalog

  10. roji commented on Jan 16, 2022

    @roji
    MemberAuthor

    @Brar is this something you're interested in investigating?

  11. roji commented on Jan 16, 2022

    @roji
    MemberAuthor

    Ah, one more thing @bwalendz - can you try opening a regular (non-replication) connection to the same database, and selecting a composite value? If that fails, then we know the issue isn't related to replication.

    If it works, can you try executing your replication code after the initial non-replication connection does its thing? IIRC type loading works differently in replication connections and may not load composite types; if that's the case, opening a regular connection first, may allow the composite type to be loaded correctly, and be used afterwards by a replication connection.

  12. bwalendz commented on Jan 17, 2022

    @bwalendz

    Ah, one more thing @bwalendz - can you try opening a regular (non-replication) connection to the same database, and selecting a composite value? If that fails, then we know the issue isn't related to replication.

    If it works, can you try executing your replication code after the initial non-replication connection does its thing? IIRC type loading works differently in replication connections and may not load composite types; if that's the case, opening a regular connection first, may allow the composite type to be loaded correctly, and be used afterwards by a replication connection.

    Thanks for the info @roji. Looks like this is the issue. There is no problem with the custom type using a regular connection. Unfortunately, it doesn't appear to carry over to the replication connection in anyway. I have it creating a normal connection and executing a query that maps the custom type and then directly into the replication connection creation.

    I am not sure how that is supposed to work because one is created via new NpgsqlConnection vs new LogicalReplicationConnection. Unless there is an alternative to use the regular connection as the source for the replication connection that I am not aware.

  13. Brar commented on Jan 17, 2022

    @Brar
    Member

    @Brar is this something you're interested in investigating?

    I already did so, while working on #4024 and got it working but I'm not as good in understanding the internal dependencies as you are and as long as you don't understand what's going on here I'm not sure I can come up with a good solution.

  14. roji commented on Jan 19, 2022

    @roji
    MemberAuthor

    Isn't this simply because we do NoTypeLoading for replication connections? And opening a non-replication connection doesn't work because they don't share the same pool (connection string is different)?

  15. Brar commented on Jan 19, 2022

    @Brar
    Member

    Isn't this simply because we do NoTypeLoading for replication connections?

    After checking the current code I think you're right and that's an oversight.
    I definitely had removed that for logical replication connections and put a lot of ugliness into PostgresDatabaseInfo to make it work with the limited PostgreSQL replication scanner/parser (see repl_scanner.l supporting "\n" but not "\r\n" as newline and neither repl_scanner.l nor repl_gram.y supporting/removing comments) in #4024.

  16. roji commented on Jan 19, 2022

    @roji
    MemberAuthor

    Yeah, it's kinda coming back to me now, vaguely. So you think if we remove NoTypeLoading everything may just work?

  17. Brar commented on Jan 19, 2022

    @Brar
    Member

    So you think if we remove NoTypeLoading everything may just work?

    No. The limited replication scanner/parser will start causing exceptions.
    At the very least you'll have to remove the comments from the queries in https://github.com/Brar/npgsql/blob/main/src/Npgsql/PostgresDatabaseInfo.cs.
    If you happen to introduce a \r\n somewhere in the queries (like git does on Windows with core.autocrlf=true) you'll get extra trouble because of the \r that isn't recognized as whitespace by the scanner.
    See my ugliness part above.
    Also you still need NoTypeLoading for physical replication connections because they don't support arbitrary SQL commands.

  18. roji commented on Jan 20, 2022

    @roji
    MemberAuthor

    I definitely don't mind us removing the comments, if that's most of it. I also don't think the \r\n is too worrying - to be extra safe we can introduce code which replaces \r\n to \n in the string. Finally, I think it makes sense to retain NoTypeLoadnig for physical replication but to remove it for logical, since in physical replication Npgsql doesn't interact with the types as it does with logical.

    IIRC we discussed another way around this - we would silently do a normal connection the first time just for type loading purposes. But that could be problematic in various way (i.e. is the user given for the replication connection actually able to connect as a non-replication user). So I think we should avoid that unless we have to.

    How does that sound?

  19. Brar commented on Jan 20, 2022

    @Brar
    Member

    I completely agree.
    One problem might be testing type loading via replication connections in our tests because once the types are loaded from a normal connection in a previous test, type loading from the replication connection won't trigger again but I'm sure we can find a way around that.

  20. Brar commented on Jan 20, 2022

    @Brar
    Member

    once the types are loaded from a normal connection in a previous test, type loading from the replication connection won't trigger again

    That's probably also the reason why we didn't recognize this problem earlier

  21. roji commented on Jan 20, 2022

    @roji
    MemberAuthor

    OK. I've opened #4286 to track this, since this issue was originally about supporting types added after types have been loaded, which is different.

  22. Brar commented on Jan 22, 2022

    @Brar
    Member

    Hi @bwalendz,
    you can try version 7.0.0-preview.1-ci.20220122T123248 from the vNext feed.
    With this version your use case should work without using a regular connection to initiate type loading.

    Nevertheless for now it will only work if the types already exist in the database when the replication connection is opened, so this issue remains to track support for loading types after the replication connection has been opened (and probably more importantly after replication has started).

    If you run into any further problems with types that already exist when the replication connection is opened, please post on #4286

  23. bwalendz commented on Jan 23, 2022

    @bwalendz

    Hi @bwalendz, you can try version 7.0.0-preview.1-ci.20220122T123248 from the vNext feed. With this version your use case should work without using a regular connection to initiate type loading.

    Nevertheless for now it will only work if the types already exist in the database when the replication connection is opened, so this issue remains to track support for loading types after the replication connection has been opened (and probably more importantly after replication has started).

    If you run into any further problems with types that already exist when the replication connection is opened, please post on #4286

    Appreciate it @Brar!

  24. roji commented on Sep 11, 2022

    @roji
    MemberAuthor

    Closing as we don't think there's a problem worth fixing:

    • Built-in types are just... built-in
    • Composite/enum need explicit user mapping in .NET code, so not relevant
    • PostGIs requires a plugin, so again an explicit user mapping
    • So this pretty much affects only hstore, i.e. an extension type that's handled built-in in Npgsql

    In addition, we expect people to have resiliency of some form for network issues, so this would be handled as part of that.

  25. removed this from the 7.0.0 milestone on Oct 17, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions