If a state only always returns to the state that transitioned to it then is it a sustate or a stand alone state? - state-machine

New to state machines and dotnet-state-machine.
I have a path that looks like this from Homed:
Homed -> Automatic -> Automatic.Paused (substate of automatic) -> Purge
Homed -> Automatic -> Purge
Homed -> Purge
Homed -> Manual -> Purge
The purge is EXACTLY the same in all four cases. The only difference is where they came from. If a transition is made from any state to purge then when purge is finished it needs to go back the the state it came from. A purge can only return back to the state it came from ... ever. It never can go to another state.
How is this normally done? It seems like I have two options:
Have one state "Purge" and keep track of where it came from so when it's time to go back I make the transition back to the state it came from.
-OR-
Do I have four discrete substates for purge where they are each of substate of the state it came from?
I have tried charting this out with Purge as a stand alone state and the chart is quite messy. I have found that in cases like these it helps to understand what the "normal" design pattern is.
Any help would be appreciated.

Either of the options you list here is valid. The separation of persistent variables, transitions, and states is essentially an implementation detail. Much as the use of a state machine for a particular problem is a choice.
Complete state diagrams often end up looking messy. I think it's a reflection of the nature of solving real problems.
My preference is to create new special-case Purge states because I think it will result in easier code maintenance. And because hiding real-world complications (in a prior state variable for example) is not ideal unless you can abstract them away thoroughly.
Finally, the academic literature on state machines does not address a state's implementation. If we use a combination of persistent variables and an implementation function that is considered a unique state. So, if you carry around an integer variable that is important to your Purge state for example, then academically you have as many Purge states as valid values for your integer.

Related

Possible Reset domain crossing?

I have an ICG that gates a clock.
The enable of the ICG is driven from one reset domain, say rst1.
The gated clock drives a flop from another reset domain, say rst2.
Is this a "reset domain crossing" (RDC)?
Does a tool like spyglass/jasper can find this issue like it finds a conventional RDC (that exists on the data path)?
I will take a stab at this, giving some background on what I have seen.
Firstly, I would argue there is no such thing as a "Reset Domain Crossing". I would call it a "Clock Domain Crossing, involving a reset signal". Because resets are no different than the D or Q when going from one point to another in sequential logic.
Let's say for clarity that we ignore RST1/RST2, and talk in terms of CLK1 and CLK2. RST1 is synchronous with respect to CLK1(from a deassertion standpoint as Pradyuman Bissa stated), and RS2 the same but with respect to CLK2.
The circuit you described, I am assuming looks like this:
This is a CDC issue, and would most likely be captured by a CDC tool (Jasper I thought was more for formal verification so it may not catch this). Things that would cause this to NOT be caught by a CDC tool would be any type of additional constraints that are added. Say you did some exclusion between CLK1 and CLK2, or you wildcarded some exclusion or cell. These would remove this from the failure list so you would not see this.
Having done CDC evaluation on designs with 50+ clocks, I can tell you that the failure list is so long that chances are good you coverup your own mistakes with incorrect exclusions/wildcards.
It's possible that this circuit still works. Particularly if the CLK1(gated) is enabled sometime after the reset has deasserted.
So to answer your question about a tool catching it, yea it probably would. End here before old man rant.
But I would argue, and what I believe Pradyuman Bissa is saying is that you should create a module/cell that gives you this functionality without the need to explicitly define the logic. This also allows you to reduce the chances that you introduce a CDC in the first place. Sometimes the best way to remove these errors is to reduce the chance you make them in the first place.
An example could be something like looks like the diagram below:
You can then instantiate this anytime you have a need to gate a clock and have an accompanying reset with the other clock domain. There is obviously some issues with needing to ensure that the reset from CLK2 is held long enough for the reset sync to see it.
I have seen many issues where people take something like this and hand place the logic instead of just creating one particular cell and instantiating that when needed. The amount of gates/flops required for this cell are generally minimal in the grand scheme of a design.

How to name an event describing the acknowledgment of the existence of an entity in an event sourced system?

I am new to Event Sourcing and I am considering using it for an industrial application to track events happening in a production facility.
Since the book of record is the production facility itself and not the system, and also because not everything is automated, workers will need to report at a given point in time (the recorded time) what they did at another point in time (the effective time). Therefore, I will be using events such as: TankFilledRecorded, TankOutputConnectedToPipeInputRecorded, ContainerMovedToFacilityAreaRecorded, etc. where these events refer to entities such as a tank, a pipe, or a facility area for example. These events will have both a recorded time and an effective time. Note that there is no submission or approval process for a record to be considered legit.
Domain-driven design (DDD) encourages to design events that are representative of what happens in the domain (like the ones above).
However, in my domain, I don’t care so much about how a tank, a pipe or a facility area came to existence. I just need to know that something exists from a particular point in time, and I also need to know if it is not there after a particular point in time. The main objective of the software is to track liquids and powders flowing in a circuit made of these pipes, tanks and other components. It is not an asset management system and should not become one.
Therefore, what would be the correct DDD way to design an event that represents the fact that there is a tank, a pipe or an area in the production facility?
It is a subtle question but language is important, particularly in DDD.
Here is what I came up with:
1 EntityExistenceAcknowledgmentRecorded
TankExistenceAcknowledgmentRecorded
PipeExistenceAcknowledgmentRecorded
FacilityAreaExistenceAcknowledgmentRecorded
TankDisappearanceAcknowledgmentRecorded
PipeDisappearanceAcknowledgmentRecorded
FacilityAreaDisappearanceAcknowledgmentRecorded
It seems awful to use this in the ubiquitous language. I don’t see myself talking in these terms or providing a UI with such vocabulary. But it does represent exactly what happens though.
2 EntityRegistered
TankRegistered
PipeRegistered
FacilityAreaRegistered
TankUnregistered
PipeUnregistered
FacilityAreaUnregistered
It seems much simpler and it also seems to be meaningful except for one thing. “Registered” conveys the existence of the representation of an entity in the system with immediate effect, without the possibility of saying now that the entity existed 2 days ago. Think about a UserRegistered event in a website that would indicate that the user “existed” from 10 days ago. What would that even mean?
Events are facts and you cannot change the past. However, I do need a way for my users to invalidate a record in which they made a mistake such as a typo. They can record now that they acknowledged the existence of a facility area a week ago and might realize later than there was something wrong, such as a typo in the name of the entity. They would invalidate the record and create a new one. But, invalidate something that has been “registered” does not sound right.
3 Keep looking
Try to dig more in the domain (event storming) and find the real events that brought the entities into existence even if these events are of no use in the problem that needs to be solved.
TankBuiltRecorded
PipeBuiltRecorded, PipeDeliveredRecorded
FacilityArea<something_meaningful>Recorded
TankDestroyedRecorded, TankDecommissionedRecorded
PipeDecommissionedRecorded
FacilityArea<something_meaningful>Recorded
A caution
TankFilled
TankFilledReported
TankFilledReportSubmitted
TankFilledReportSubmissionReceived
Think carefully about whether the increased precision is motivated by business value.
Therefore, what would be the correct DDD way to design an event that represents the fact that there is a tank, a pipe or an area in the production facility?
What is the business doing today? Is there already a process in place for tracking the lifetime of the hardware in the plant (a maintenance log, perhaps?) There's likely to be vocabulary in that place that gives you ideas as to what spellings would make sense in the code.
Events are facts and you cannot change the past.
That's true - but you can back date events. The effective date of the information is often distinct from the reported date of information.
I do need a way for my users to invalidate a record in which they made a mistake such as a typo.
Yes - error correction is an important part of the process that you are modeling.
You should probably review Greg Young's talk Answering a Question, which was based on this thread. It's a discussion of capturing and modeling of temporality.
Here's the good news: you are running into the right problem. Because you are capturing information about an external system, there are going to be opportunities for errors and conflicts, and you need to (a) figure out the protocols for addressing them, and then (b) model that process correctly. That might include exception reports generated by the system when it observes conflicting information, or compensating events, or even automated conflict resolution (for the easy cases -- see also Stop Over Engineering).

F# update list in multiple threads at same time

I am new to F# so maybe the solution can be clear to someone, but I can not find it.
Imagine a game world of world chunks (similar to Minecraft), but for more players.
In theory language like C++, java, or C# can modify multiple chunks of world at same time. Two or more players try to place or remove block in different chunks and all these actions can change the state of the world without affecting each other as long as no more than one action in each chunk is happening. Serializing will only happen when multiple players in one chunk perform the modification.
My understanding of F# is I need to serialize these actions on global level and no two actions can happen in same time in entire world, because the update function need actual world state update params(like add/remove blok) and return new world state.
For that example the world state contains chunk list.
Is there a way to do world update in parallel?
Can the world state be stored differently to allow update to multiple chunks at same time?
It sounds like you need to ensure that each chunk has one action run at a time. You can protect pieces of state by storing them inside mailbox processors (often referred to as just "agents"). You can send agents several messages from several threads. They will be queued and processed one at a time.
There is a detailed discussion of this here: https://fsharpforfunandprofit.com/posts/concurrency-actor-model/
Firstly, I don't this really adds any technical detail to a previous answer, so you if you like their solution you should go ahead and mark that as the answer. However, I hope this gives some extra context...
Underlying your problem is the question of how consistent do you require the state of your world to be in order to make decisions about modifying chunks.
Consider a world where I have two chunks, let's call them A and B. Consider the use case where I want to add or remove a block from chunk A. The all important question is:
Do I need to know about the blocks in chunk B in order to validate, and then perform the addition / removal of a block from chunk A.
For example, if I only have finite number of blocks in my world, I may well need this information to validate that I can actually add a block without going over my limit. The key here is that my "consistency boundary" is my entire world - in order to perform the addition of a new block to chunk A I need consistent information about everythign in my world. It is no good if halfway through my decision making another thread jumps in and adds a block to chunk B. If this is a requirement then you have no option - even in the C#/C++ case - you need to lock down access to your world so only one such action can be performed at anyone time.
From the way you phrase the question, I suspect this is not the case. In which case we need to examine exactly what your consistency requirements are. A weaker requirement is that if I'm adding blocks to chunk A, I at least have to have consistent information about the number (and position) of blocks in chunk A. In the C#/C++ case this would mean having to put locks around accessing to individual "chunk data", but not the whole world.
A simple way of modelling this in F# would be (using the suggestion in this answer):
open FSharp.Core
type ChunkMessage =
AddBlock
| RemoveBlock
type MyWorld =
{
Blocks : List<MailboxProcessor<ChunkMessage>>
}
Note that MyWorld is a mutable, but each MailboxProcessor encapsulates state which can only change through processing one message at a time.
The implementation of Blocks doesn't have to be a list of MailboxProcessor's, you could use a thread-safe collection of objects for which you had thread-safe methods on, but the use of them here as suggested by The Quick Brown Fox leads to a particularly nice programming model.

Washing machine petri net

It is my first time doing a Petri net, and I want to model a washing machine. I have started and it looks like this so far:
Do you have any corrections or help? I obviously know its not correct, but I am a beginner and not aware of the mistakes you guys might see. Thanks in advance.
First comments on your net's way of working:
there is no arrow back to the off state. So once you switch on your washing machine, won't you never be able to switch it off again ?
drain and dry both conduct back to idle. But when idle has a token, it will either go to delicate or to T1. The conditions ("program" chosen by the operator) don't vanish, so they would be triggered again and again.
Considering the last point, I'd suggest to have a different idle for the end of the program to avoid this cycling. If you have to pass several times through the same state but take different actions depending on the progress, you have to work with more tokens.
Some remarks about the net's form:
you don't need to put the 1 on every arc. You could make this more readable by Leaving the 1 out and indicating a number on an arc, only when more than one tokens would be needed.
usually, the transitions are not aligned with the arcs (although nothing forbids is) but rather perpendicular to the flow (here, horizontal)
In principle, "places" (nodes) represent states or resources, and "transitions" (rectangles) represent an event that changes the state (or an action that consumes resources). Your naming convention should better reflect this
Apparently you're missing some condition to stop the process. Now once you start your washing will continue in an endless loop.
I think it would be nice to leave the transition graphics unshaded or unfilled if it is not enabled. Personally I fill it green if it is enabled.
If you want someone to check if you modeled a logic properly in your Petri Net then it would be nice if you include a description of your system logic in prose.

Should I use Command to implement a domain derivations in CQRS

I'm using CQRS on an air booking application. one use case is help customer cancel their tickets. But before the acutal cancellation, the customer wants to know the penalty.
The penalty is calculated based on air rules. Some of our provider could calculate the penalty through exposing an web service while the others don't. (They publish some paper explaining the algorithm instead). So I define a domain service
public interface AirTicketService {
//ticket demand method
MonetaryAmount penalty(String ticketNumber);
void cancel(String ticketNumber, MonetaryAmount penalty);
}
My question is which side(command/query) is responsible for invoking this domain service and returning result in a CQRS style application?
I want to use a Command: CalculatePenlatyCommand, In this way, it's easy to resuse the domain model, but it's a little odd because this command does not modify state.
Or should I retrieve a readmodel of ticket if this is a query? But the same DomainService is needed on both command and query side, it's odd too.
Is domain derivation a query?
There is no need to shoehorn everything in to the command-query pipeline. You could query this service independently from the UI without issuing a command or asking the read-model.
There is nothing wrong with satisfying a query using an existing model if it "fits" both the terminology and the structure of that model. No need to build up a separate read model for that purpose. It's not without risk, since the semantics and the context of the query should be closely tied to the model that is otherwise used for write purposes only. The risk I allude to is the fact that the write and read concerns could drift apart (and we're back at square one, i.e. the reason why people pick CQRS in the first place). So you must keep paying attention as new requirements come in.
Queries that fit this model really well are what I call "simulators', where you want to run a simulation using current state to e.g. to give feedback to an end user. On more than one occasion I've found that the simulation logic could be reused both as a feedback mechanism and as an execution (of a write operation/command) steering mechanism. The difference is in what we do with the outcome of the simulation. Again, this is not without risk and requires careful judgement.
You may bring arguments that Calculate Penalty Command is not odd at all.
The user asks the system to do something - command enough.
You can even have a Penalty Calculation Requested Event event in your domain, and it would feel right. Because, at some time, you may be interested in, let's say, unsure clients, ones that want to cancel tickets but they change their mind every time etc. The calculation may be performed asynchronously, too - you can provide the result (penalty cost) to the user in various ways afterwards...
Or, in some other way: on your ticket booked event, store cancellation penalty, too. Then, you can make that value accessible any time, without the need to recompute it... But this may be wrong (?) because penalty would largely depend on time, right (the late you cancel your ticket, the more you pay)?
If all this would like over-complications etc., then I guess I agree with rmac's answer, too :)

Resources