Skip to content

Fix inconsistent behavior when negative bound is supplied to TBQueue - #17

Closed
lehins wants to merge 5 commits into
haskell:masterfrom
lehins:negative-tbqueue-bound
Closed

lehins wants to merge 5 commits into
haskell:masterfrom
lehins:negative-tbqueue-bound

Conversation

@lehins

@lehins lehins commented Sep 10, 2018

Copy link
Copy Markdown
Contributor

This PR fixes inconsistent behavior described below by enforcing TBQueue size to be always non-negative and fixing the capacity checks in the writeTBQueue function.

Supplying negative size to both newTBQueueIO and newTBQueue yields a TBQueue that is still writable. We end up with queue that is both full and empty, yet we can still write into it as much as we like (theoretically maxBound :: Word in fact, due to wraparound):

λ> q <- newTBQueueIO (-1) :: IO (TBQueue Int)
λ> atomically $ isFullTBQueue q -- That's correct, it is full
True
λ> atomically $ isEmptyTBQueue q -- That's correct too
True
λ> mapM_ (atomically . writeTBQueue q) [1..20] -- yet we can write into it
λ> atomically $ isFullTBQueue q
True
λ> atomically $ readTBQueue q
1
λ> atomically $ isFullTBQueue q -- now queue with negative capacity is no longer full
False

@hvr
hvr requested review from hvr and removed request for hvr September 11, 2018 06:51
@hvr

hvr commented Sep 11, 2018

Copy link
Copy Markdown
Member

cc @mitchellwrosen

@hvr

hvr commented Sep 11, 2018

Copy link
Copy Markdown
Member

@lehins can you also add a regression test to the new testsuite in the testsuite/ folder?

@lehins

lehins commented Sep 11, 2018

Copy link
Copy Markdown
Contributor Author

@hvr Done. Added Issue17.hs

@mitchellwrosen

mitchellwrosen commented Sep 11, 2018 •

Copy link
Copy Markdown
Contributor

lgtm, I don't think this modification is likely to be relevant in the wild, but who knows. I looked around for some similar functions, e.g. Data.Vector.replicate, which also silently bumps a negative number to 0.

IMO, another acceptable implementation would be to error for any size <= 0, since a queue with no capacity is totally useless.

@hvr

hvr commented Sep 11, 2018

Copy link
Copy Markdown
Member

IMO, another acceptable implementation would be to error for any size <= 0, since a queue with no capacity is totally useless.

I'd actually prefer this, because requesting something with negative size (I'm on the fence though whether to consider size == 0 an error) smells like a bug to me somehwere in the code which we shouldn't silently cover up by clamping to 0...

@lehins

lehins commented Sep 11, 2018

Copy link
Copy Markdown
Contributor Author

@hvr and @mitchellwrosen I do agree with both of you that a negative value for the size is incorrect, it was the source of the bug afterall, together with incorrect conditional checks in writeTBQueue, of course. But I do disagree that an error is an appropriate way to go about it in this situation:

  • First of all, with a fix I applied to writeTBQueue, I believe, clamping size to zero is no longer necessary, for the proper functionality of all the functions that operate on TBQueue, I did it just as a safety precaution.
  • It's not clear at a type level that negative value is invalid. If the type of size was Word, some newtype wrapper Positive Int or even better a Natural, but it is an Int.
  • And lastly, it seems to be a common pattern to adjust the value to make it valid, instead of throwing an exception in such situations. Here are some of the common examples that I could think of, which will not result in an error for invalid arguments:
    • As you mentioned replicate, replicateM and other similar functions in vector will clamp to 0
    • replicate from bytestring and text will do the same
    • newArray (-1, -3) 0, will result in an empty array (even for TArray)
    • threadDealy (-100000), forkOn (-20) will work just fine too
    • and that's not even talking about all the extremely common ones like take, splitAt, etc.

Moreover error is very uninformative, and impossible to properly distinguish from other errors, if I was voting for an exception here, I'd rather throw a specific one with throwSTM and throwIO respectfully, which would allow for a safe recovery, but that would require a separate exception type.

As far as size 0, I certainly do not agree that it's a bug to have a TBQueue that can't store any elements, all of the functions that operate on TBQueue will work as expected. Is it useless to have size 0? Very much so, but it's definitely not a bug and would not deserve an exception.

@mitchellwrosen

Copy link
Copy Markdown
Contributor

It's not clear at a type level that negative value is invalid. If the type of size was Word, some newtype wrapper Positive Int or even better a Natural, but it is an Int.

It is true that it's not clear at a type level that the negative value is invalid, but I feel Int is a good choice here, regardless. (Refinement types are the best solution I know of).

  • Word is not great because underflow is just a massive word. I'd argue that an effectively unbounded queue is less desirable than some in-your-face exception.
  • Positive Int is not great because it will likely have a Num instance to be at all tolerable to use. Then this instance's fromInteger would be partial, and we are back to error territory, no? (Please clarify if you had a different Positive Int in mind).
  • Natural has the right semantics, but it is partial, so I see this as equivalent to my error suggestion. It's also arbitrarily large, but of course a queue cannot be.

And lastly, it seems to be a common pattern to adjust the value to make it valid, instead of throwing an exception in such situations. Here are some of the common examples that I could think of, which will not result in an error for invalid arguments:

I think it's a common pattern to both adjust the value to make it valid and blow up with an error. Also - I think an argument could be made that the functions you found should call error instead. Reliable software already has to be instrumented with logging, monitoring, failover, backup, persistence, restarting, etc. I'd personally rather deal with a crashing program than a silently broken program that has a nonsense negative-capacity queue somewhere inside.

Moreover error is very uninformative, and impossible to properly distinguish from other errors, if I was voting for an exception here, I'd rather throw a specific one with throwSTM and throwIO respectfully, which would allow for a safe recovery, but that would require a separate exception type.

This is an interesting suggestion, but I'm not convinced that being able to catch a "negative size provided to newTBQueue" is very useful. The fix is the same in either case: provide a positive number instead ;)

I would also like to clarify that I don't speak with any authority over this codebase or anything, and this patch is totally fine with me, for what it's worth. I just find the discussion interesting so I figured I'd respond point by point :)

@lehins

lehins commented Sep 12, 2018

Copy link
Copy Markdown
Contributor Author

I find this topic extremely interesting as well! Hence are the long comments ;)

Refinement types are the best solution I know of

Very much so. Even (KnownNat n, n > 0) => n -> TBQueue a would do the trick here.

Just to be clear, I didn't recommend Word as a solution :) it would be just as bad as the bug this PR is fixing, so it was just a way to make my point of no type level information about negative values.

Natural, I think, would be a very good solution though, even though it is partial, it does gives a user expectation at the type level and a decent Underflow exception. The fact that it's unbounded isn't important, queue of size maxBound :: Int is just as much arbitrarily big on 64 bit machines, if you ask me. Problem with that solution is that it's not very much backwards compatible and introduces an inconvenient breaking change.

I'm not convinced that being able to catch a "negative size provided to newTBQueue" is very useful.

It's really not, but if you do want to make your code safe, then you are forced to catch all exceptions, which isn't nice. Moreover, doing a throwSTM would at least roll back a transaction, and that could possibly be useful.

All of the above are just my thoughts on the topic. And since I really don't like error, anyone that is willing can go ahead and adjust this PR to throw an error instead. Such a bug that this PR fixes, could never affect me ;) I found it simply by looking at the code and wanted to make stm safer.

@hvr

hvr commented Sep 13, 2018 •

Copy link
Copy Markdown
Member

Well, this comes down to the fundamental design choice in APIs of whether to validate input parameters and, in case of invalid or nonsensical parameters, fail loudly, or whether to succeed silently (there'd actually be a 3rd option if we allowed for logging side-effects: succeed loudly by emitting warnings).

Both approaches have their merit but different trade-offs and a similar discussion came up when deciding whether Natural ought to have saturated or partial subtraction by default (given that the Num class's signature for (-) forced us to make a choice).

As we know, the partial subtraction was picked, and there's a function now

GHC.Natural.minusNaturalMaybe :: Natural -> Natural -> Maybe Natural

by which you can easily implement saturated subtraction if you combine that with e.g. fromMaybe 0. So yet another way to color the bikeshed would be to have

newTBQueue :: Num n => STM (Maybe (TBQueue a))

and map invalid input parameters to a Nothing and avoids throwing exceptions in the STM monad (such as e.g. throwSTM Underflow). However, I'd also be fine with using Natural (with the minor caveat that we'd likely drop support for base < 4.8.

NB: We're about to release stm-2.5, i.e. a major version bump signalling breaking changes -- we might as well break the API a bit more if it's for a good cause ;-)


PS: If we had a loudly failing newTBQueue w/ the old type-sig by default, it's easy to recover the clamping version which ignores invalid parameters by e.g.

q <- newTBQueue (n `max` 0)

or maybe you'd even want

q <- newTBQueue (n `max` 1)

or even clamp both sides

q <- newTBQueue ((n `max` 1) `min` 1024)

The other way round is more awkward IMO.

@lehins

lehins commented Sep 13, 2018 •

Copy link
Copy Markdown
Contributor Author

@hvr I think switching to Natural is a right thing to do as well, especially considering that new breaking release is not far ahead.

Would you like me to go ahead and switch both of these?

newTBQueue :: Natural -> STM (TBQueue a)

lengthTBQueue :: TBQueue a -> STM Natural

The actual internal implementation of size and capacities should stay as Int for performance reasons, but the conversion using fromIntegral will be safe for both functions, so it shouldn't be a problem.

PS. I meant all three, of course, I wouldn't skip newTBQueueIO ;)

@hvr

hvr commented Sep 13, 2018

Copy link
Copy Markdown
Member

The actual internal implementation of size and capacities should stay as Int for performance reasons, but the conversion using fromIntegral will be safe for both functions, so it shouldn't be a problem.

I disagree that it isn't a problem. In fact, you reminded me about checking the rest of stm for potential overflows, see e.g. a39a7ec

Note that fromIntegral on a Natural value simply truncates the upper bits away, resulting in e.g.

> fromIntegral (18446744073709551617 :: Natural) :: Int
1

Moreover, when incrementing Int counters, it's better to be safe than sorry; the performance penalty of a simple machine-word comparison operation should be minor compared (when you take into account branch-prediction) to the rest of the overhead involved.

@lehins

lehins commented Sep 13, 2018 via email

Copy link
Copy Markdown
Contributor Author

@lehins

lehins commented Sep 13, 2018

Copy link
Copy Markdown
Contributor Author

@hvr Another approach would be to clamp TBQueue bound to maxBound :: Int, since in practice it's impossible to have that many elements in the queue anyways :)
But instead I followed your suggestion and switched it everywhere in TBQueue to use Natural. Also, did a quick benchmark, which didn't seemed to have any impact when compared to all Int implementation. Which is great.

Also did drop support for GHC < 7.10 due to Natural and all the stuff that is no longer needed: Typable derivations and travis builds

Looked in other places in the library where integral numbers are used and only thing I found that could be fixed was in TSem.

* Switch to Natural in signalTSem
* make newTSem accept Integer
* Got rid of deriving Typeable
* Removed redundant CPP
@lehins
lehins force-pushed the negative-tbqueue-bound branch from dffeba0 to a6b6363 Compare September 14, 2018 17:42
hvr pushed a commit that referenced this pull request Sep 16, 2018
hvr pushed a commit that referenced this pull request Sep 16, 2018
* Switch to Natural in signalTSem
* make newTSem accept Integer
@hvr

hvr commented Sep 16, 2018

Copy link
Copy Markdown
Member

@lehins Thanks! I've manually merged your commits to the master branch (while slightly rearranging them); if you have time, please review them in case I missed something.

@hvr hvr closed this Sep 16, 2018
@lehins

lehins commented Sep 16, 2018

Copy link
Copy Markdown
Contributor Author

@hvr Looks great. Thanks. Totally forgot about nats. It's really good thing that we don't have to loose support for older GHC. 👍

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants