Tcl Source Code

View Ticket
Login
Ticket UUID: b8f575aa2398b0e44b5a037326b9d75037e2da4a
Title: Tcl 9: eof erroneously flagged with not reported encoding read error
Type: Bug Created on: 2022-12-08 22:59:16
Submitter: pointsman Assigned to: jan.nijtmans
Subsystem: 25. Channel System Severity: Important
Priority: 5 Medium Last modified: 2023-03-23 16:13:15
Status: Closed Closed by: jan.nijtmans
Resolution: Fixed Closed on: 2023-03-23 16:13:15
Version: 9.04a, trunk
Description:

Create the test data:

set myfd [open "data.txt" w+]
fconfigure $myfd -encoding binary
puts -nonewline $myfd A\x81BCDEFG
close $myfd

Then try this:

set myfd [open "data.txt"]
fconfigure $myfd -encoding utf-8 -strictencoding true -nocomplainencoding false
set data [read $myfd]
puts "eof [eof $myfd]"
puts "fblocked [fblocked $myfd]"
puts "data length [string length $data]"
puts "data: $data"
set data [read $myfd]

I get:

eof 1
fblocked 0
data length 1
data: A
error reading "file6": illegal byte sequence
    while executing
"read $myfd"
    invoked from within
"set data [read $myfd]"

I guess this isn't supposed to work this way?

User Comments:
jan.nijtmans added on 2022-12-09 08:06:10:

Compare this with (which works in both 8.7 and 9.0), using same data.txt

% set myfd [open "data.txt"]
file4
% fconfigure $myfd -encoding utf-8 -eofchar D
% set data [read $myfd]
ABC
% puts "eof [eof $myfd]"
eof 1
% puts "fblocked [fblocked $myfd]"
fblocked 0
% puts "data length [string length $data]"
data length 4
% puts "data: $data"
data: ABC
% set data [read $myfd]
% puts "data: $data"
data:
% puts "data length [string length $data]"
data length 0

It's the same surprise. Since "-eofchar D", stops reading the stream when the 'D' is encountered, "-strictencoding 1" stops reading the stream when \x81 is encountered. The remaining of the characters are read as well, but stored in an internal buffer. So the "eof 1" is - kind of - logical but surprising: the stream reached EOF, but it's not visible yet because not all characters are returned.

I could imagine that we want eof to report 0 in this case. That would encourage doing another "read", which throws an exception showing why the previous "read" stopped there.

Thanks for the report!


oehhar added on 2022-12-09 09:30:06:

Thanks for looking into this. This is all difficult and new code.

For me, an "eof" is always set be the read, if there is no information any more available, and the channel may be closed.

This is not the case, here. A "read" is pending to get the final information on the channel. So, eof should not be 1.

If it is read in an internal buffer is not important. eof should display the situation on the script level. The script is not aware of internal buffers.

In consequence, I second the opinion, that "eof" should be 0 until the error is reported by a read.

We will probably also have to look into read fileevents. The read file event should be fired to flag the pending error.

Thank you all, Harald


jan.nijtmans added on 2022-12-09 10:26:32:

Partial solution [6808b459d3682d1c|here], but that's not the whole story.

1) More testcases should be added (like for this situation)

2) If both -eofchar and -strictencoding is used, and the stream contains both an eofchar and an invalid byte, then the behavior should depend on which of the two comes first in the stream. Not a very likely cornercase .....

More to come ....


pointsman added on 2022-12-09 13:05:54:

Even if it seemed clear to me that despite of -strictencoding true -nocomplainencoding false neither the [read] itself nor [eof] giving no sign of error could not really be how this is supposed to work -- I have to confess that I haven't a clear picture about how this in fact is supposed to work.

May I ask: Since I gave -strictencoding true -nocomplainencoding false - that is, I made clear that I wanted to be informed about encoding errors - why doesn't the first [read] raised error in the first place?

It is true that immediately raising error atm doesn't provide information about where in the input the error is (byte or char position). Or did I have missed something here?

But even if the behaviour is changed so that [eof] returns 0 to signal that something happend (as proposed here) that would mean that I need a combination of while {![eof]} {} and a catch/try around the [read], something like

fd [open "somefile"]
set data ""
while {![eof $fd]} {
  if {[catch {append data [read $fd]}]} {
    # Handle error
  }
}

It's this how this is supposed to work.

Isn't this a bit awkwarded / convoluted? Especially given that most programmers are typically don't expect to have to check [eof] if they want to read the whole data out of a file in one go with [read $fd].


jan.nijtmans added on 2022-12-09 15:07:56:

> Isn't this a bit awkwarded / convoluted? Especially given that most programmers are typically don't expect to have to check [eof] if they want to read the whole data out of a file in one go with [read $fd].

Indeed, in Tcl 8.x, doing a [read $fd] get the whole content of the file (unless using -eofchar, then everything after the eofchar is stripped). That - indeed - should stay in Tcl 9.0. The reason that it succeeds always, is that there is no error-reporting for encoding errors. For utf-8, \x81 is an invalid byte sequence, but it will silently be handled as if it was \xC2\x01, assuming iso-8859-1 in stead of utf-8 as fallback.

When -strictencoding is specified, [read] is no longer guaranteed to read the whole file. It will read until EOF, or until the eofchar or until an encoding error is encountered. [eof] can be used to make the distinction, and a further [read] will throw an exception. It's up to the user how to handle this. One possibility would be to change the encoding of the channel, and do another read.

So, yes, I think this is how I would expect it to work. In short: If you are not prepared to handle errors, don't use -strictencoding.

Thank you for this report and the test-case! Whenever [eof] returns true, any follow-up [read] should return the empty string (or return more data if it became availble in the meantime). That's an assumption from Tcl 8.x that I would like to keep in 9.0. In your example, that was violated, which means that I - indeed - consider this a real bug (which - hopefully - is fixed with this change)


jan.nijtmans added on 2022-12-09 23:28:47:

[d156af9fb76dd2f4|fix] now merged to core-8-branch and trunk, with testcases


pooryorick added on 2022-12-28 12:05:02:

This fix is not the correct behaviour for synchronous read, which must result in an error when invalid data is encountered.


pooryorick added on 2022-12-28 12:09:32:

[00995080d6378c6d] is a fix that maintains the expected behaviour of synchronous [read].


pooryorick added on 2022-12-28 12:23:31:

When synchronous read encounters invalid encoded data, it's desirable to have access to the data that has been correctly decoded up to the invalid point. Asynchronous [read] doesn't have the this problem because its semantics are different. This new fix accomplishes this for synchronous [read] by stuffing the correctly read portion of the data into the "-result" entry of the return options dictionary. This is new behaviour, but it's not nearly as extreme as the previous new behaviour of having synchronous [read] only produce on error on a second call.


pooryorick added on 2022-12-29 09:48:01:
[9b6c29fa98a33be5] improves the fix so that the full test suite passes.

jan.nijtmans added on 2022-12-29 23:38:34:

Closing again, since it's better not to hijack an existing ticket while an appropriate new ticket is already there: [1bedc53c8c]


pooryorick added on 2023-01-16 20:29:23:

All of the discussion for this issue is in this ticket, so I'm closing [1bedc53c8cb878f0b], which was caused by Jan's proposed fix,[d156af9fb76dd2f4], and is therefore a duplicate, an moving the description to this ticket.


pooryorick added on 2023-01-16 20:31:36:

Jan's proposed fix, [d156af9fb76dd2f4], changed the semantics of [read] (and [gets]?), as follows:

In trunk, test io-12.9, "ReadChars: multibyte chars split FAILED" does not result in an error when the test is changed so that the channel is configured with -strictencdoing 1:

test io-12.9 {ReadChars: multibyte chars split} -body {
    set f [open $path(test1) w]
    fconfigure $f -translation binary
    puts -nonewline $f [string repeat a 9]\xC2
    close $f
    set f [open $path(test1)]
    fconfigure $f -strictencoding 1 -encoding utf-8 -buffersize 10
    set in [read $f]
    close $f
    scan [string index $in end] %c
} -cleanup {
    catch {close $f}
} -result 194

This is incorrect. An error should be returned.

If a second [read] is added, it returns an error:

test io-12.9 {ReadChars: multibyte chars split} -body {
    set f [open $path(test1) w]
    fconfigure $f -translation binary
    puts -nonewline $f [string repeat a 9]\xC2
    close $f
    set f [open $path(test1)]
    fconfigure $f -strictencoding 1 -encoding utf-8 -buffersize 10
    set in [read $f]
    read $f
    close $f
    scan [string index $in end] %c
} -cleanup {
    catch {close $f}
} -result 194

This is also incorrect, because [read $chan] is defined to read all characters up until the end of the channel, implying that all data on the channel has been correctly read.

The first [read] should return an error.


jan.nijtmans added on 2023-01-17 08:21:06:

Since this ticket is about the behavior of "eof", while [1bedc53c8cb878f0b] is about the behavior of "read"/"gets", they are not duplicates.

Therefore, closing this one (again)


pooryorick added on 2023-01-17 09:49:15:

The problem is that the fix for this ticket, [d156af9fb76dd2f4], added tests to the test suite that hard-code broken semantics for [read] and [gets] into their success case. Therefore, this ticket should remain open at least until those tests no-longer rely on broken semantics of [read] and [gets].


pooryorick added on 2023-01-17 16:04:15:

[1a225bd50e984fdc] is another attempt to fix the issue for read: The return value is always the characters that have been successfully read, and in the case of an error the error information is found in the -errorinfo entry in the return options dictionary. This is in contrast with the earlier proposed fix, which in the case of an error placed the successfully-read characters in the -result read entry in the return options dictionary.

I don't see many alternatives apart from these two. One other alternative would be to restore the current access position in the file to the position it was at prior to the call to read, but there are so many disadvantages to this that it seems entirely unworkable. First, it wouldn't work for non-seekable channels. Second, it doesn't provide access to the position of the bad bytes. Third, it doesn't allow the caller to implement their own handling of bad parts of the data. Fourth, it doesn't provide access to all the data decoded up to the error. Fifth, the current state of the implementation makes it difficult to implement.

The other alternative is to change the semantics of read and gets, as the test cases provided with Jan's proposed fix do. That means that all code that uses read would have to be modified to include a subsequent call to read in order to expose a latent error. I see this as the worst of the possible solutions, and probably nearly everyone would reject this alternative (even though it is the status-quo on trunk).


pooryorick added on 2023-01-17 20:14:12:

[4cdf4836aa18a07b] fixes [gets] in the same way, so that characters successfully read up until the error are returned, and the error message can be found in "-errorinfo" of the options dictionary.


pooryorick added on 2023-01-17 20:33:23:

Now there are two alternate fixes ready to merge to core-8-branch, each one addressing both [gets] and [read]:

return value is characters successfully read so far, and the error message is in -errorinfo: [1a225bd50e984fdc] ([read]) and [4cdf4836aa18a07b] ([gets]).

return value is the error message, and the {-result read} is characters read successfully so far: [080b9a1c81595f39] (both [read] and [gets]).


pooryorick added on 2023-02-02 22:56:08:

Fixed in [11c7f071cb0f3e9f], where the code that exposes the string decoded up until the failure point has been commented out so that it can be merged to trunk.


jan.nijtmans added on 2023-02-03 09:39:41:

Well, it looks like [11c7f071cb0f3e9f] originates from the "py-b8f575aa23" branch, not from trunk. Is this - actually - your TIP #653 implementation?


pooryorick added on 2023-02-03 22:34:14:

TIP 653 emerged from the process of fixing this bug. When walking through the code to figure out how to fix the problem, one learns that the succesfully-read data has already accummulated in a result object, which must either be discarded or made available. My preference is to make it available. Since adding a new key in the result option dictionary proved controversial, I commented out the parts that do that, leaving only the part that fixes this bug. Re-enabling the parts that make the partial results available is a matter of uncommenting a few line of code. In my opinion making the sucessfully-decoded data available doesn't even require a TIP.


pooryorick added on 2023-02-14 10:46:22:

Fixed, along with the fix for the subsequent issue, [dab7fd5973] in [ecd7aaec80804dc8].


pooryorick added on 2023-02-17 08:05:44:

In [ecd7aaec80804dc8], I merged the fix for this issue and for [154ed7ce564a7b4c] to core-8-branch, but it was quickly reverted without explanation. Any details that would require a TIP were commented out, so there's no reason to reject this fix on that basis. Jan, is there something about this fix that you are opposed to? There's a pretty broad consensus that requiring second [read] on a synchronous channel to expose the encoding error is a no-go, and there has been no other proposal on how to fix the indefinite hanging problem with [gets] in core-8-branch. Anyone that dives into the code to fix this issue will find that the fix I've proposed is really the right one given the current implementation of the relevant functions.


jan.nijtmans added on 2023-02-17 08:53:35:

Yes, I don't agree with this 'fix'.

1) The fix contains 4 patches:

Modified generic/tclEncoding.c from [578f90f1a7] to [4bb3b51208].    [diff]
Modified generic/tclIO.c from [b2f243d333] to [13b3995977].    [diff]
Modified generic/tclIOCmd.c from [9fbd001df2] to [97e2c7aabd].    [diff]
Modified tests/io.test from [5cd7966f20] to [a6a0abc4e9].    [diff]

The first contains a readablility change, which is good but not fixing anything. Such fixes don't belong in the patch, just commit those separately (and merge it forward to trunk). The 3th adds comments about what it isn't doing, but should do in your opinion. The last (io.test) contains so many changes, I even don't want to look at it.

2) You refuse merging forward to "trunk". I won't do that for you.

3) I already told you that this patch is opening the worm-hole of losing information. I'm sure I'm able to create a test-case demonstrating that, but there are higher priorities to worry about now.

Sorry, but that's the way I feel. But ... feel free to keep your patch around, trying to improve it. You can ask Ashok/Rolf for their feedback on your patch too. Don Porter already removed your patch once, I now did it twice. I hate to do that, I very much prefer that you dedicate your precious time to higher-priority TIP's/bug-fixes. Sure, this one will be discussed in the future.


pooryorick added on 2023-02-17 19:46:15:

On core-8-branch we have broken semantics for [read], [get] hangs indefinitely, on encoding errors, and you don't consider those things high priority. That's surprising, and I don't understand it.


pooryorick added on 2023-02-18 10:23:42:

At this point, we have a problem. Jan, you have taken the following actions:

  1. You made commit [d156af9fb76dd2f4], which broke [reads] and [gets]. In the case of [read] an encoding error will never be surfaced unless the caller remembers to call [read] again, and that is new semantics for the command. In the case of [gets] the command not only would have these new semantics, but also simply hangs indefinitely when an encoding error occurs. Such a change to Tcl semantics requires an accepted TIP, which you did not bother with.
  2. You reverted my commit, [00995080d6378c6d], which ensured no data loss, in the case of an encoding error, by returning successfully-read data in the return options dictionary, which required no change to the current function signatures of [read] and [gets], and preserved existing semantics. Your reasoning was that adding a new key to the return options dictionary requires a TIP.
  3. I subsequently submitted TIP 653, which specifies the new key in the return options dictionary. I requested a vote, on it, and you refused to call the vote.
  4. I made a new commit, [11c7f071cb0f3e9f], which omitted those parts of the fix that change the return options dictionary so that no TIP was necessary. You reverted this commit on the grounds that it loses data.

So if I commit a fix that doesn't lose data, you revert it on the grounds that it changes the return options dictionary, and if I commit a fix that does lose data, you revert it on the grounds that the caller can't get at that data. Meanwhile you happily have your own un-TIP'd semantics-changing commit sitting in both core-8-branch and trunk. This situation is unfair: There's a set rules for you, and a different set of rules for others. If my commits can't be on core-8-branch or trunk, then you should at least keep your commit off those branches as well until they are properly accepted via a TIP.

I've repaired the semantics of [read] and [gets] on trunk by reverting your fix. You should not reinstate it unilaterally.


pointsman added on 2023-02-18 15:30:04:
Jan, it seems to me that you just not agree with [read] and [gets] should raise error if an encoding error happens on the channel to read from. Or in other words you think the current implementation is the right way to do this (and the hanging [gets] is just a bug pending to be fixed).

Some folks (including me) think [read] and [gets] should rise error right away on encoding error on the channel. If I understood correctly most if not all participants on the February Tcl video meeting agrees on that. 

We should then perhaps try to get agreement on high level about that question.

On the formal side I think the current trunk behaviour (need double read to raise error on encoding error) isn't described clearly by any TIP. Please correct me, if I'm wrong.

The difference between the two approaches is mainly the reporting of the so far decoded data from the channel. This is perhaps a bit more convenient done with what is currently on trunk. Some folks in the video meeting also claimed that it is important to get to the decoded data up to the error.

While I agree that there must be a way to get to that data for/in special cases (and pooryoricks approach also fullfill that) I think that in the huge majority of cases an encoding error on the channel will just be handled in aborting the action and to notice the user about that.

What else will you do with incomplete input data, especially because the so far decoded data may even be mis-interpreted (if the read data it in another encoding than expected by the channel)?

So changing the semantics of read/gets in a bit surprising way (for Tclers as well as programmers familiar with other langugages) for a bit more convenience in rare / special cases seems wrong to me.

jan.nijtmans added on 2023-02-19 11:52:19:

Ho Rolf. I already gave my reaction below (see: 2023-02-17 08:53:35), I see that my arguments are totally ignored. What's happening now looks like "You reverted my patch, so now I revert your patch!" (not blaming that on you, Rolf!). I'm preparing a use-case for this situation, but I only have 2 hands ....


apnadkarni added on 2023-02-21 17:00:24:

Jan,

I have been preoccupied with the actual encoding system and not really looked at the I/O implementation.

At a high level, assuming I understood you correctly wrt fconfigure -eof D, here's why I think your analogy does not hold.

When an application does a fconfigure -eof, it's essentially saying that the logical content of the file from its perspective ends when D is encountered. So a read $chan does in fact return "entire" content as expected from the application's perspective.

In the encoding case (with strict mode), the application is not changing what it views as the content of the file. It is rather saying the content is expected to strictly adhere to the encoding. If the read completes successfully, the natural expectation is that the entire file contents were encoded correctly and were retrieved in their entirety.

The two cases are thus very different.

/Ashok


jan.nijtmans added on 2023-02-21 18:00:37:

This ticket is not the right place to discuss this. But ... this use-case of using "read" simply to read a complete file is only one use-case in stake. Yes, "read" without special options should continue working as it works now. But there are also high-end applications (such as NaviServer), which use "read" in another (much more advanded) way. Gustaf Neumann will kill me if I screw up those use-cases.


pointsman added on 2023-02-21 20:57:52:

Jan,

if this isn't the right place to discuss this could you kindly tell me what is the right place? You participated only sparly on the related disussions on the tcl-core mailing list.

Your arguments in this ticket at 2023-02-17 08:53:35 are about why you refused to accept pooryoricks patch.

As Ashok I already tried to discuss the question here on a higher level: Do you think the current trunk behaviour ([read] and [gets] not rasing error on encoding error) is better than raising error? Then I would love to read (or hear) your arguments about that.

On the formal side I think current trunk is a changed script level behaviour which isn't spelled out in a TIP. At least I asked several times for the TIP descriping the new chanced [read] and [gets] behaviour without an answer and my own search in the related TIPs revealed something.

So perhaps this should be made up; as TCT member your in the right position to call a vote on this.

I'm not so much interested in this formal side but to find the best solution for Tcl 9. The major points why I think raising error on encoding error would be the better semantics are:

- It seems to me lesser surprising, both to long-time Tclers as well as to programmers comming from other languages to Tcl (or working most of their time with other languages.)

- In the vast majority of cases an encoding error on the channel will just be handled in aborting the action with notice to the user about that. It seems natural to wrap a command which may fail to do what it was told to do into a catch or try.

- I agree that there are (rare) advanced cases in which one want to have the already decoded data or even somehow to recover from the encoding error (although I only have so far an only vague picture and some questions about how this should work in a sensible way). But I don't see hard technical reason which would make this impossible with [read] and [gets] raising (immediately) error. The decoded data can be returned in the error dict and the channel is still open, after the error and the channel position (what [tell] would return) could be at the same access position as in the current trunk model.

- It provides the more defensively migration part. If somebody adds -strictencoding to its scripts with Tcl 9 but forget (or just not realize) to add the necessary code to its read the script will happily work without sign of error with current trunk, but produce wrong results. If the commands raise (an uncatched, in this example scenario) error the script will bail out. Which seems to be the better behaviour in my book.

I stop here, leaving out a few other considerations.

We should try to find consent about the [read] and [gets] semantic for Tcl 9. If we succed with that the implementation could be hammered out in much more cooperative manner.


pooryorick added on 2023-02-28 11:46:54:

Although he didn't state it here in the ticket, Jan subsequently moved [ff103e776b] off core-8-branch, reasoning that it puts core-8-branch back into its previous buggy state. It's true that it does that, and the reason is that a "fix" that changes the semantics of [read]/[gets] is not an acceptable fix. core-8-branch should remain in its original state regarding this issue until a proper fix is introduced. A commit that breaks the semantics of [read]/[gets] should simply not be incorporated into core-8-branch.

Fortunately, we have come to some agreement on the proper fix, and the issue should be resolved shortly. In the meantime, I've once again moved [d156af9fb76dd2f4], which breaks the semantics of [read]/[gets], off core-8-branch.


jan.nijtmans added on 2023-03-23 16:13:15:

Let's forget about this ticket, (which got spammed on "read" and "gets", while this ticket is really about "eof" ....)

Closing.