You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Binary replication: support types added/removed after program startup #4066
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.
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).
@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.
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 😅
changed the title [-]Replication: improve support for custom types[/-][+]Replication: support types added/removed after program startup[/+]on Nov 1, 2021
changed the title [-]Replication: support types added/removed after program startup[/-][+]Binary replication: support types added/removed after program startup[/+]on Nov 1, 2021
@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.
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.
createtypedescriptoras (
id bigint
, name text
);
Are there any examples of how PG user defined custom types can be handled for binary replication?
@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.
@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
varslot=newPgOutputReplicationSlot("test_slot");varpublication=newPgOutputReplicationOptions("test_pub",1,true);NpgsqlConnection.GlobalTypeMapper.MapComposite<Descriptor>("descriptor");awaitusingvarconn=newLogicalReplicationConnection(_connectionString);awaitconn.Open(stoppingToken);awaitforeach(varmessageinconn.StartReplication(slot,publication,stoppingToken)){/* fragment */varcasted=awaitvalue.Get<Descriptor>(stoppingToken);/* fragment */}[PgName("descriptor")]publicclassDescriptor{[PgName("id")]publiclongId{get;set;}[PgName("name")]publicstringName{get;set;}}
The type already exists before this code is started.
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.
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.
@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.
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)?
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.
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.
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.
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.
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
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
Activity
Brar commentedon Oct 27, 2021
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).
roji commentedon Oct 28, 2021
@Brar I've taken another look, here's how I understand the situation (I may be missing something):
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 😅
[-]Replication: improve support for custom types[/-][+]Replication: support types added/removed after program startup[/+][-]Replication: support types added/removed after program startup[/-][+]Binary replication: support types added/removed after program startup[/+]roji commentedon Nov 1, 2021
@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.
bwalendz commentedon Jan 16, 2022
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/ReplicationValueseemed obvious either.Are there any examples of how PG user defined custom types can be handled for binary replication?
roji commentedon Jan 16, 2022
@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 viaReplicationValue.Get<T>, where T is the .NET type you mapped to your PG composite.bwalendz commentedon Jan 16, 2022
@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 thisand the error I posted previously is without casting
ReplicationValue.Get()The basic setup is
The type already exists before this code is started.
Only obvious difference compared to native types is it living in
publicschema vspg_catalogroji commentedon Jan 16, 2022
@Brar is this something you're interested in investigating?
roji commentedon Jan 16, 2022
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.
bwalendz commentedon Jan 17, 2022
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 NpgsqlConnectionvsnew LogicalReplicationConnection. Unless there is an alternative to use the regular connection as the source for the replication connection that I am not aware.Brar commentedon Jan 17, 2022
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.
roji commentedon Jan 19, 2022
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)?
Brar commentedon Jan 19, 2022
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.
roji commentedon Jan 19, 2022
Yeah, it's kinda coming back to me now, vaguely. So you think if we remove NoTypeLoading everything may just work?
Brar commentedon Jan 19, 2022
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.
roji commentedon Jan 20, 2022
I definitely don't mind us removing the comments, if that's most of it. I also don't think the
\r\nis too worrying - to be extra safe we can introduce code which replaces\r\nto\nin 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?
Brar commentedon Jan 20, 2022
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.
Brar commentedon Jan 20, 2022
That's probably also the reason why we didn't recognize this problem earlier
roji commentedon Jan 20, 2022
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.
Brar commentedon Jan 22, 2022
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
bwalendz commentedon Jan 23, 2022
Appreciate it @Brar!
roji commentedon Sep 11, 2022
Closing as we don't think there's a problem worth fixing:
In addition, we expect people to have resiliency of some form for network issues, so this would be handled as part of that.