Tuesday, May 10, 2016

Benevolent Dictator vs. Part-time Parliament

Distributed systems require Leader Election and today I am going to try to explain two most popular algorithms - PAXOS and RAFT.  
Once the problem is defined and some basic building blocks are identified both the algorithms are very easy to understand. The Paxos protocol was first published in 1989 by Leslie Lamport as the basis of State Machine Replication method. Raft was designed in last couple years from "ground up" specifically for easy understandability. 

Background : Need For Consensus 

Army of clones

In a typical scale out architecture we have a number of clients making requests to a cluster of servers.
  • When these servers are identical and stateless any server can process any request from any client. That is the basis for "scale-out" architectures. When servers are stateful the same logic still applies as long as each server has the same state.
  • When the client request change the state, that is when we need consistency and atomicity with many concurrent clients talking to many servers. This is where you need to co-ordinate using consensus protocols

Electing a leader and following commands 

  • One very powerful approach is to elect a single leader who makes the changes to the state and then all other machines follow exact steps leader followed to make state change.
  • This change of state is defined by a deterministic state machine.(Mealy State Machine to be exact). Same sequence of input command executed on each nodes creates the identical state changes at each node. Leader broadcasts the input messages to this state machine and followers make local state changes.  This is what Leslie Lamport means when he says "State Machine Replication".
Crashes and Dropped Messages
  • Life would have been awesome if there were no crashes and no lost messages and no network partitions. But failures do happen and that's exactly the reason why we need complicated protocols.
  • The basic assumption of distributed system is that there is no global shared state and the state has to be transferred by passing messages. Messages have delays and so the state changes have delays.
  • Every node in the cluster will be slightly different due to delays between when commands were sent by the leader and when they were received and applied by each follower.

The basic requirement for Leader Election

The basic requirement of consensus is that despite crashes and network partitioning there is exactly one elected leader and every one knows about it when elected.

Toolbox: The Building Blocks 

Let's first start with examining some familiar concepts and tools before we analyze PAXOS and RAFT. In both algorithms any node can propose but only one is finally accepted as leader. "Proposer" proposes and "Voters" vote on it. In both algorithms once the leader is elected the results are broadcast. 

Optimistic Concurrency and Thomas Write Rule : 

  • The optimistic concurrency works by requiring every write to follow a two step process - first fetch the latest version of data and then update it. 
  • This is just Compare and Swap in different form. If your update is based on outdated version then it will be rejected. Thomas' write rule says ignore outdated writes.
  • This is "lock-free" and gives very high throughput.

 Two phase commit 

  • The classical commit protocol has two phases - a prepare phase and a commit phase . In prepare phase we solicit votes and leader is elected only when commit is issued and successful.  

Why we need majority ?

  • It is possible that two nodes simultaneously believe that they are the leaders.
  • But by definition and mathematical certainty only 1 can get the majority votes.  Therefore there can be only one leader - thus satisfying basic requirement.   

Bidding and Auctions

  • Think of leader election as as an auction - the highest bidder always wins. Proposals from higher bidder cancels voter's previous commitments - the transaction is aborted for previous bidder/proposal. 
  • There is always some well defined way of saying which Candidate has higher bid.
  • This bidding and auctioning process is integral part of the leader election.

Paxos

Below are the high level details of the algorithm. Here is how it works
  • At a higher level Paxos combines "read value" part of optimistic concurrency with propose phase of two phase commit in first step. In second step it combines "write value" part with commit phase.
  • In step 1, the proposer "makes up" a integer version number/timestamp and calls it "proposal number". In the spirit of Thomas's rule no voter accepts any "outdated version" by making sure it always accepts the highest proposal number. This pretty much looks like an auction - the highest bidder always wins. 
  • If proposal gets ACK from the majority of the nodes then proposer send the "commit message". The only confusing aspect of the algorithm is that if the value is already chosen then proposer just sets the same already chosen value instead of its own. (It sure does feel like an uneccesary no-op though)
  • Again using Thomas' rule voters reject the request to commit if they have seen a higher numbered proposal. Proposal to write higher version cancels voter's previous commitments - as far voter is concerned the commit is aborted for the proposer. 
  • When proposal gets majority of committed ACKs, the election is over.
  • Leslie Lamport compared this method to a fictional legislative consensus system used on the Paxos island in Greece. That is your "Part Time Parliament". Leslie envisioned that for each new state change a new leader is elected and everyone follows it only for that single change. For next state change request the process repeats.
RAFT
  •  RAFT instead elects a dictator for fixed term. Once elected, everyone follows the leader until a new leader is elected.
  • For each state change, the leader first sends a Prepare message on behalf of the client. When it receives majority of ACK on prepares it sends commit message. Commit is complete when majority have committed. The cycle continues for the next change..
  • New election is started when the term for current leader ends or any node thinks leader is dead. A node thinks a leader is dead if it has not received any heartbeat or  command from the leader in given timespan.
  • The node suspecting a leader death then decides to become a candidate. Candidates seek a majority vote. If the Candidate doesn't get elected in the first round then it just keeps on trying again and again until someone is elected.  As simple as that, keep on asking for vote until either you win or know that someone else is already a winner.  
  • If node itself is not a candidate then it always accept the candidate which has advanced most in its processing. Again this is kind of an auction. In other words the bid from the candidate with the most consistent state always wins.
  • But how does RAFT avoid or minimize the chance of election getting into the infinite loop where no one ever has the majority ? The answer is annoyingly simple - The node waits for a random amount of time before becoming a candidate and asking for a vote. It is statistically improbable that there will be two candidates asking for the vote at the same time. By carefully choosing the random wait time progress can be made - this is exactly how ethernets work !

Conclusion

Leader election is fact of life in distributed systems.  Although Paxos and Raft look very different at the surface , deep down they use the similar building blocks.
References:

Resilient Distributed Datasets and origins of my obsession

Yes- it is true. I am obsessed with in memory data processing and it goes waaayyy back. Back in my college days I had a very simple but very powerful insight or vision. I feel super lucky because over the years every now and then I just happen to stumble upon more and more opportunities to make it real...I'll talk about LINQ, Project Orleans and then finally RDDs.   
In the beginning 
The obsession  started some 17-18 years back when I was writing a paper for my college seminar. Being a compiler freak, my idea was to write a language that manipulated in memory collections using sql like syntax.  What remains today of that dream is a couple dozen hand written versions of that paper and reams of BNF grammars for that dream language.  Here are couple of examples ... 
And here is another example ...(didn't I tell that this obsession goes way back) 

While( !done) iterate;

One idea that I kept on toying with (rather ad infinitum) was that of representing a sql query as a enumeration. (See example of one such idea.) I didn't actually get it working in the college. I almost forgot about it.  
Later on while at Microsoft, my passion was rekindled . Off the normal day job hours, I tried to meddle with some research projects like COmega and Common compiler Infrastructure.  Unfortunately I was not able to make any real contributions.  I moved on and joined Amazon.com...a number of years passed.  

Laziness Pays Off

Later in 2008 Microsoft released LINQ and then eventually java followed it by lambdas and streams. It felt like my dream was realized by someone else already. I needed a a new obsession and so I was free to forget about the whole idea. Except - the Lazy Evaluation was destined to turn my world upside down again.  
Back to the Future<> in 2011 : Project Orleans at Microsoft Research
I was lucky enough to get a contract position in Microsoft's eXtreme Computing Group in Microsoft Research. More specifically in Cloud Computing Futures team. The project was using Asynchronous Message Passing to implement an Actor Model based compute engine. Think of these actors as objects distributed in a cluster using some sort of Consistent Hashing Ring. Almost like a memcache for actively callable objects. Admittedly this project was the coolest project I have ever worked on and worked with some of the brightest engineers I have ever met. ( I helped with implementing state management and code generation.)    With the help of "mostly in memory" processing we were able to achieve amazing throughput for live Halo 4 services. 

Enter Apache Spark and Resilient Distributed Datatypes 

After a trip down a memory lane we arrive at Today's state of the art - Resilient Distributed Datasets (RDDs), a distributed memory abstraction that lets programmers perform in-memory computations on large clusters in a fault-tolerant manner. From the RDD paper ...
.... RDDs provide an interface based on coarse-grained transformations (e.g., map, filter and join) that apply the same operation to many data items. If a parti-tion of an RDD is lost, the RDD has enough information about how it was derived from other RDDs to recompute just that partition. Thus, lost data can be recovered, often quite quickly, without requiring costly replication.

References :

Microservices: Managing for Frequent Reads and Rare Writes

It is a rare service that does not need to persist its state. 
Choice of your design critically depends on how frequently data gets written and allowable delay between when data gets written and the time when readers (and other nodes in the cluster) see that update. Let us examine a class of services where there are very infrequent rare writes and massive numbers of reads. This type is the most common kind of service in my experience.  Here I outline a common way to design such Microservice. I have used this simple "design recipe" for many services and it has worked for me every time over the last decade.  

Step 1 : Treat it as a Read Only Service

The first step towards designing a service is to assume it to be Read Only and optimize it for fast access and scalability. When data is readonly you can make million copies of your service and you don't need any coordination. They all return the same results for same input. 
An example would be a service that returns Maximum or Minimum recorded temperature for a given the Zip Code. Input for this service is historical data. We assume it is somehow injected in the system already. Temperature gets recorded daily and so it is okay to update the result set on daily basis.  Until we get new updates the service just serves readonly data. Another example would be Catalog Search on football memorabilia/ collectible site which will have some structured data in product catalog. It is highly unlikely that new products are added every hour and product details are upadated every second.   
  1. Precompute results: The first optimization obviously is to pre-compute results.Eg. min/max results for given zip codes are calculated offline in a batch (or hadoop) job. The resulting data is then loaded into some persistent database. Your service is then just the look up of this pre-computed data for given type.  Performance is increased many folds.  You can increase the performance even further by trading space for speed by denormalizing the results. How often you calculate the result set data is domain specific. It can range from minutes to daily to even weekly. Most domains tolerate delays extremely well and do not require true "as of now" results. Now where do you store the output of a batch job? I prefer using distributed high availability key-value stores for storing such "denormalized" and  pre-computed results. The resulting service code is then mostly looking up data in key-value stores (and do some parameter validation and minor post processing)  
  2. Cache results: But we are still hitting the datastore for every request. Networks are fast these days but not fast enough. Next optimization is to use distributed caching to decrease latency. The result data is treated readonly anyway.
  3. Cache results locally in memory: We can increase the performance even further by using multiple levels of cache by first storing some of the data locally in server memory.
The "hot data" lives mostly in memory,  the "warm data" is a RPC call away in  distributed cache and "cold data" is always reliably stored in distributed key value store and summoned at any time.  It is very easy to scale your service up or down by adding more caching or service instances. 

Now is the time to start thinking about those Writes. 

Step 2: Handle Writes

The writes are rare but DO change the state of the system. We must handle concurrency and consistency properly. 

Separation of Concerns

There is a common pattern called Command Query Responsibility Segregation (CQRS). Essentially you have two separate interfaces: one for update and the other for read.  We designed our read interface earlier.  
The Write interface is generally your plain vanilla 3-tier web service backed by a very high performance Relational Database.  The data in your database is the ultimate source of truth about your service.  I prefer this database to be strongly consistent i.e. ACID. The read interface never ever read from this database. They read from the key-value persistent store.  A batch job periodically reads the data from the master database and transforms it into key-values and stores in No-SQL store. We have already discussed how to handle this readonly key-value data effectively. Note that the eventual consistency comes from the delay between when data is added to master database and when it shows up in key-value stores. There are age old multi-phased state of the art protocols to handle failures and backups and fail-overs in case of master read/write RDBMS. It is very much appropriate to use standard database technology given low write traffic.  Again recall that this database does not contain the data about the entire universe but only the slice of reality that is relevant to out micro service. Usually the data size is not a problem these days. 

Optimistic Concurrency 

Although write traffic is low it still needs locking and properly scoping your transactions and using correct isolation levels. Use of optimistic concurrency and locking can increase performance of your database without sacrificing the consistency. 

Use Event Sourcing 

Event sourcing is a technique where we record and preserve each every change made to the system. This is yet another way to increase throughput and resiliency of the system.  

Use Complex Event Processing

So far we are relying on batch model . But this is not hard and fast requirement. You can build complex pipelines on top of event stream using likes of  Reactive X , Spark Streaming , Apache Storm

Step 3 : Get Closer to Data 

Use Ephemeral Local Store: One disadvantage of caching is that memory is limited and you still need to fetch data from remote machine (be it memcache or  your no-sql store). Yet another optimization is to copy data to each mid-tier machine. There are probably a dozen different ways to achieve this each with its own pros and cons. But the important point is that - the data access is then becomes just a local access and much faster than accessing remote machines.  
Use Actors: You can also use actor based run-times to add fault tolerance and optimize write performance.  Akka is one such example.  

Conclusion:

Many domains tolerate delay in data being updated and that update being visible to everyone.  Many micro services have very high read traffic but rare write traffic.  There is a simple and effective "design recipe" to build them that works wonderfully in practice.
Happy Coding !

References :

  1. Data  Concurrency and Consistency in Oracle Databases http://docs.oracle.com/cd/B28359_01/server.111/b28318/consist.htm
  2. Oracle High Availability Database http://www.oracle.com/us/products/database/high-availability/overview/index.html
  3. Oracle No-sql database http://www.oracle.com/us/products/database/nosql/overview/index.html
  4. Memcached http://memcached.org
  5. Leveraging Massively Parallel Processing in an Oracle Environment for Big Data Analytics
    http://www.oracle.com/technetwork/database/bi-datawarehousing/twp-hadoop-oracle-194542.pdf
  6. Why use event sourcing ?http://codebetter.com/gregyoung/2010/02/20/why-use-event-sourcing/
  7. Actor Models https://en.wikipedia.org/wiki/Actor_model 

Microservices: Settling Architecture vs Design Debate

It is an old religious war in software industry. Where does Software Design end and Software Architecture start ?  My answer to that question is - boundary that separates a microservice from the things outside of it from the stuff inside it. Inside a micro service we need Design, outside of micro service we need Architecture.

What is Software Architecture?

The wikipedia definition captures the essence of what Software Architecture is. I take liberty to re-iterpret it a little bit.  
Software Architecture is the set of structures needed to reason about the software system. Each structure comprises software elements (aka Micro-service), relations among them, and properties of both elements and relations.
Software architecture choices include specific structural options from possibilities in the design of software. Software architecture is about making fundamental structural choices which are costly to change once implemented.  
Martin Fowler defines the architecture in an interesting way. "The important stuff—whatever that is".  
ISO/IEC/IEEE 42010 defines it as "fundamental concepts or properties of a system in its environment embodied in its elements, relationships, and in the principles of its design and evolution"

Architecture vs Design

  • Architecture is defining the interactions and contracts of a micro service with the rest of the system. Design is making implementation choices (like internal OO Design, data structures and algorithms.) Your Architecture involves figuring out what micro services you need. Defining data they communicate and store. Details of database design, choice of MVC framework is Design.   
  • Architecture is strategic , Design is tactical. Making trade-offs around consistency and availability is Architecture. Making space/time tradeoffs or  deciding to precompute partial results or choosing a caching mechanism is then all part of the Design. 
  • Design is concerned with local issues, Architecture is concerned with global issues. We can change our Design without asking anyone else. (Eg. Change data structure, algorithm or refactor OO Model). To change Architecture we need to communicate it to others and the change has ripple effect. 
  • Design is executable. Architecture is not.

Discovering and Defining Microservices

There are two steps to discovering the Microservices 

1. User Story Mapping

Input : Our starting point is scenario or epic. A user has a concrete need in mind and a task to accomplish. User does that by interacting with our system through series of actions. Input to our architectural discovery process is long list of user stories. 
Activity: We group related stories into the clusters.  These clusters indicate the underlying feature or "capability" that the system must provide.
Output: Each feature or capability is potentially a micro-service. (Prune the list as required.) 

2. Component-Responsibility-Collaboration Cards

Input : List of microservices, list of user stories.
Activity:
  1. For each micro service create a card with two sections Responsibility and Collaboration. 
  2. Responsibility section includes (a)  What do I know ? (b) What do I do? (c) What do I decide ?
  3. In Collaboration section include (a) Who do I interact with? (b) What data I exchange with others? 
  4. For each major user story walk through the micro services and in the process assigning responsibilities to them and discovering collaborations and details of those interactions.
Output:  Well defined set of micro-services with clear responsibilities and identified interaction with collaborators.

References:

Microservices: Lego Blocks in Modern Architecture

Until recently there was no real word to describe the kind of software that I developed over the last decade. I have worked on distributed systems that were massively scalable with millions of users and billions of transactions. I have worked on service oriented architectures that delivered user functionality at rapid pace. I discovered, learned and practiced a particular style of software architecture. But until recently could not find a simple phrase to describe it.  
Now I can say I developed Microservices ! But what is Microservice ?

Defining Microservice

Wikipedia defines : Microservices is a software architectural style in which complex applications are composed of small, independent processes communicating with each other using language agnostic API. These services are small, highly decoupled and focus on doing a small task, facilitating a modular approach to system-building.
In short, for each service "Do one thing and do it well". 
But I like following definition better
Microservice Architecture is a service-oriented architecture composed of loosely coupled elements that have bounded contexts.

Loosely Coupled

Loosely coupled means each microservice is a unit of software that is independently replaceable and upgradeable and deployable. It is not microservice architecture If all services have to be deployed at once or they talk to the same database and requires coordinating schema changes. Micro services can be scaled independent of each other (ideally in elastic automated ways.). This allows separate development teams (perhaps geographically separated) to develop services using separate schedules, frameworks and methodologies.

Bounded Context

Bounded context as name suggests is a partition or silo of domain model that is mostly selfcontained – Microservices and its peers interact purely through APIs and don’t share data or schema. The key is that each organizes and manages its own data. This is a critical feature of this architecture.

Organized around business capabilities

Now essence of Microservice is that each Microservice is they expose business functionality as a component. And then you can build your application as as suit of services by putting these components together.

Using Language Agnostic API

With language agnostic APIs, it enforces clear separation between interface of the Microservice and its implementation. This ensures true interoperability between various components. SOAP and REST are two approaches that have already become industry standard.

Marriage made in Heaven: Containers as Deployment Units.

Containers are the future of application delivery. It is an application packaging and delivery method that guarantees that your containers will always run the same, regardless of the environment it is running in. In short it is well contained. This is exactly the fundamental requirement of Microservices
Container is an old concept. Most familiar being the java web archive and servlet containers. Latest and the most popular incarnation being the docker containers. Linux containers allow higher density and better utilization of hardware resources.
The advantages are  
  • Rapid provisioning
  • Scale quickly. 
  • Eliminates the environment inconsistencies
  • Improves the velocity of development by allowing development teams to choose the software stack that is best for their service.
  • Easy sharing
  • Isolate problems
  • Simplifies continuous integration and testing  

References 

For More Agility Do the Waterfall !

Yes you read it right. If you want to be more Agile then my recommendation is to do Waterfall model . But do it in reverse direction.  
Here is my simple theory -  If the Waterfall model is opposite of Agile, then by doing Waterfall in opposite direction you get Agile!   If Waterfall has long product cycles then we make them super short.
Without further ado..

Fail Early, Fail Often, Fail Cheap

Agile Development has  one and only one reason for its existence - We need to respond to changing customer requirements in timely manner by better utilization of productive resources. 
Now that requires discovering customer requirements. In his book Lean Startup author Eric Ries talks about using Validated Learning - a process in which one learns by trying out an initial idea and then measuring it and validating the effect. Our goal then is to define and discover a minimal viable product (MVP) which is the "version of a new product which allows a team to collect the maximum amount of validated learning about customers with the least effort" 

Turning back the Arrow Of Time

Let now do the Waterfall in opposite direction.
1. Announce your product's General Availability : Start with writing an internal press release of your finished product. The target audience is end user who is going to benefit from your solution. Describe how your product is better than your competition and how it exceeds customers expectations. Like a real  news story, include a narrative scenario of how one customer solved their most pressing problem using your product. 
At this point if there are not enough real benefits to make it a compelling value proposition then it is unlikely that product will succeed in the market place. Rework on your product idea. Don't rush this step. Get it right - are you appealing to right market segment ? Do they really have that problem that you are trying to solve? Remember Mr. Kano? Have you used right portfolio of exciting/cool features and must have functionality ? Have you covered all stages of Buyer Experience Cycle ?
Once you have this narrative scenario/ press release - use it as a light house to guide all your discussions and planning. This press release is what James D. Murphy, author of book Flawless Execution calls Future Picture - a high resolution description of the way we'd like things to be. The richness, the completeness is what makes it work by having sufficient content and clarity to provide guidance down the road.

2. Test with limited Beta Users

Invite your most friendly customers to test your product. At this point obviously what you don't have is the working code. But worry not , you can still conduct the usability testing by conducting what is called Paper Prototyping.  Instead of customers interacting with actual software they walk through the mockups and paper drawings.  http://interchangeproject.org/2013/11/02/paper-prototyping/
This is super useful because you get direct feedback about your product and discover missing and confusing features. It is super cheap and super easy - because all you require is paper and pencil. 
But make no mistake - this is NOT about UX design only. For every user interaction there must be an underlying API that must implement that functionality. Your services don't live in a vacuum - they are there to enable user scenarios - so first discover what those user stories are. This also uncovers  a underlying mental model that users, experts and developer use to think about the "stuff"  in your applications domain. In his book Domain Driven Design, author Eric Evans explains importance of discovering what he calls Ubiquitous Language. This model is input to your entity model. Using the ubiquitous language in conversations with domain experts and end users is an important part of testing it, and more importantly discovering the domain model. 
The most valuable outcome of this stage is domain model and set of user stories.
3. Deployment
Next you should write deployment scripts and figure out how you are going to deploy your software.  It helps resolve many issues early in the game
(a) how do you do branching ? Service release management? (b) How do you handle various deployment stages - (prod, pre-prod etc) (c) How do you package it - docker image? VM image? .jars ?  (d) How do you manage dependencies in your code ? (e) Do you have stateful services or stateless ? How many ? How many for each stage? How do you scale them up or down?  Where is the configuration stored (f) where do logs go ?  (h) what about test infrastructure ? How do you stress the product ? how do you measure performance ? (i) can you use open source ? do you have to open you code? (j) How do you configure CDN? (k) How do you charge the customer (l) What is your architecture ? 3 tier? 8 tiers ? how do micro-services discover each other ?....so on. 
All these decisions affect the way your team works.
In addition it is a pre-requisite for integration testing. The software does not need to be ready - yet. If your software is a command line utility, it just prints "hello world" . If it is a REST service it just returns 200 OK. If its a mobile app it just shows a logo. It is otherwise useless - does not do anything interesting. But most importantly - you can deploy it !!

4. Integration 

Next is integration. 
Define end to end Acceptance Tests: By this time you have broken down your news release scenario into manageable set of user stories.  You must now define acceptance criteria for each user story.
Assign clear responsibility to services/ components: You have an idea about how your architecture looks like and you have assigned capabilities to each micro-service/ component. It is time to define how they fit together. Are there missing components ? Is data lost in translation ? Do you need to transform data?  Walk through each scenario and user story to discover what functionality a service needs to implement, what data it needs to store and what data other services can provide.
Define perf and scalability goals: This is the time to define your performance/scalability goals for each scenario (and sometimes each user story). Having clearly defined  measurable targets helps drive implementation decisions.
Create Scenario Score Card : Create a score card to track how far are you from meeting all your goals - SLA, usability, capacity utilization.  

5. Unit Test 

Use Test Driven Development for each service/component. Ask your dev team to write test cases before writing any code.
This is a well established practice in many places. I need not elaborate...

6. Implementation

This is where you have reached the point in development process where there is lot less uncertainty and increased clarity about the intended functionality. 
Early in the cycle everything in the Scenario Score Card will be in red, but that motivates team to fix that and strive towards a green score card. Release criteria is simple - when everything is green you know you are ready to ship the product for real !
You are writing tons of quality code and completing feature after feature. You are  experiencing what the psychologists call - the Flow ! 
Flow, also known as the zone, is the mental state of operation in which a person performing an activity is fully immersed in a feeling of energized focus, full involvement, and enjoyment in the process of the activity. In essence, flow is characterized by complete absorption in what one does. 

7. Design 

You have shippable product.  You have well commented and well tested code. It is time to write one pager "Getting started .." design document, so that new hires know where to start looking for the executable design ! 

Conclusion

For More Agility Do the Waterfall !

Friday, May 18, 2012

Resurrecting Object Curry - Part 4 : Managed or Native ?

As I mentioned in earlier posts Object Curry was a language I was designing so to speak in my college days (1996-1998) and that I am planning to resurrect it and make it more modern.

One important issue is whether object curry is "Managed" or "Native" ?
It is very hard question for me to answer correctly but lets just go back to source and see what were original thoughts.
As it often happens ideas about language turn into a platform and then into OS concepts.  So for a while I started calling Object Curry by various names like Component Mantra , OS Mantra and even the name Winix
Here are the original thoughts , I think many of the ideas are still valid...
I'll add commentary to the posts and ideas in my next post after the weekend. But for now just paste the original notes..so here you go straight from the source.

Virtual Machine for C.



Two stage architecture.




  Web Pointers for Distributed Computing !


Some object memory layout stuff
Final thoughts

  1. I think I will still go with the C virtual machine design. The "C pointers" here are garbage collectable.
  2. For now we'll just output C code (instead of C++11) and pretend there is VM that handles it.
  3. Support web pointers . 
  4. I have a set of hand written documents that tell why VM should not be low level but should have very high level instruction set. (so that linker-loader has more knowledge that it can use to optimize , something very relevant even today. )  I will go over it again...


Wednesday, May 16, 2012

Resurrecting Object Curry - Part 3 : New/Experimental Parsing Algorithm.

In part two I talked about using parsing strategy that is inspired from Generalized Phrase Structure Grammar.  In Object Curry compiler I am going to use a new and experimental strategy.

Separation of Immediate Dominance and Linear Precedence

In BNF form of grammar the production rules are given in the following manner
A ::= B C D
Where A is a parent and it can have three child nodes in that order.
However my parsing strategy will separate immediate  dominance and linear precedence.
To best of my knowledge no one has attempted to define parsing strategy and grammar specification as defined below..


Immediate Dominance : In simple terms it says A is the parent of B, C and D . It does not specify in which order  B, C, D should occur.
Eg Rule A--> B, C, D specifies that A can have three children

Linear Precedence : Specifies order in which children are. Orders can be partially specified
Eg Rule  B < C specifies that under A,  B must occur before  C

Head Identifying Rule: Each such production has exactly one head element and must occur in the production.
Eg.  ConditionalBlock ~ IfClause

if {} is valid
if {} else {} is valid
but else {} is not because the head is missing.


[place holder for the diagram]

Example is
QueryExpression --> SelectClause, WhereClause, FromClause.

With the separation of Dominance and Precedence all of following are valid production of the rules.

select * from tbl where col == 10;
from tbl where col ==10 select *;
...

Syntax Directed Translation and Attribute Value Calculation.

The values of attributes at each node in a syntax tree is calculated in following manner.
Synthesized attributes : Values of the parent is a function of values of its children.
Eg.  In expression   from x join y , the value of tuple type is determined by value of its children

Inherited Attributes: Attribute value is inherited from parents to the children.
In java like try catch block the closable variables are inherited.

Inferred attributes : The attributes are calculated using rules that are applicable to only nodes that have certain properties.

Algorithm
1. Variant of recursive descent for creating syntax tree.
2.  Topological sort based evaluation of dependency graph of attribute values.

I might stumble upon unexpected problem.

Useful References : 
[1] Generalized Phrase Structure Grammar by Gazdar,Klien, Pullum and Sag
 - Book about theory of natural languages!
 - chapter 3 , nature of grammatical rules.
[2] Compilers : Principles, Techniques and Tools by Aho, Sethi, Ullman
- the compiler book
- chapter 5,  Syntax directed translation.


Resurrecting Object Curry - Part 2 : To Write is to think

In my earlier post I indicated that I plan to resurrect "my" language Object Curry. The source of this "inspiration" was my handwritten notes that I have kept from college days.
Many of the writeups seem silly ( but sme are really interesting) and had some new ideas.
But what are these "notes" and why I have kept them for so long ?

To teach is to understand - To write is to think.
I have just too many teachers in my family. My grandma was a teacher , my father is a medical doctor and of course a head of the department in a medical college. My mom was a principal of  high school. My other grandma's sister was teacher. Both my uncles married  teachers and my other aunt married a english professor and one of my cousin ... well you get the point. Something like Marisa Tomei in My Cousin Vinny.
The point is that my father says that to teach is to really understand. When you teach something to someone, you benifit the most during the process. You aquire clearer , crisper and potentially profound understanding ...
Somewhere in my my highschool years I started writing notes for myself as if I am teaching it myself! That habit remained though out the college days and even trace of it today .
Though I am writing for myself my tone was always as if I am teaching class or writing a tutorial.

Putting your fuzzy thoughts in writting helps make them concrete, crystal clear and most importantly durable.

Language is defined by how it is used.
Any language is ultimately defined by how it is used and how it feels to program in it. So instead of defing a precise spec and BNF grammar I will just go with sketch of an idea. Language is what my compiler will implement it ! 
I have tried thousands of syntax variations on my whiteboard and every time I try something out I discover some problem with it.


What's the plan then ?
  1. I will go through with my old writeups and try to see what is still useful and what can be extended. May be create new write ups. Benefit: may be I'll come up with something cool. 
  2. Implement parser in at least three langauges ( one of  C#, java, Objective C) Benefit: I will practice parser writing and practice writing in 4 different dev environments.
  3. Write as many algorithms in Object Curry as you possibly can. (Graph colouring or k-mean or page rank etc) Benefit: Revise my algorithms ! Make my Object Curry truely useful.
Unless of course I take project some place else or come up with even better idea.

Ground Rules for Parser
I am going to use parsing strategy that is recursive descent styled. But a twist taken from Generalized Phrase Structure Grammar. where child nodes may not be ordered and where there are still partial ordering.

The parser will for now output C++11 source code for now. 

Resurrecting "Object Curry" - Part 1: SQL/NF and Datalog

In my college days I was working on a language called Object Curry. (Around 1996-1998).
As I was cleaning my stuff yesterday,  I came across treasure trove of large numbers of my handwritten notes from college days. That's where I found "specs" for my language "Object Curry ™".


Many of the ideas are still applicable and I have decided to write a compiler and updated spec for the language. I plan to use parsing strategy from natural languages called Generalized Phrase Structure Grammar.
If the output is sensible enough I'll take it further.


What's in the name ?
The name is derived from my attempt to mix object oriented programming with sql/nf like querying.
That sounded like a tasty Indian Curry. On top of it can claim connection to currying in functional programming.


Renovation of syntax
I actually found two syntax for the language on Pascal like and other C like.  But over the years I have kind of merged it look like below.
The syntax remains pascal inspired but with more curly braces than before.


class Foo
{
    public x : int;
    private y : char; //note reverse order and pascal like colon
    protected arr : int { 1, 2 ,3};
    public Fn(param:string): int 
    { ... }


}


SQL/NF
SQL NF is form of nested relational calculus first published in 1985 , it has nested tables and two new operators nest and unnest.
Here are some of the original hand written notes. These ideas are still valid and used in new version of Object Curry. 

  • Original Object Curry was an attempt to solve impedance  mismatch between querying collections using declarative syntax and still being able to use in memory data structures. (see this note or this one) 
  • The enum keyword from C++ is repurposed to create some amazing syntax possibilities including piping and sequence generation. Mixing C++ pointers, streaming and iterators there was some good facility for cursor management.
  • The dynamic queries were also a possibility.
I will blog about the new syntax and semantics very soon.


How is this different than LINQ?

  • "Discovered" or rather stumbled upon by me before C# and Linq.
  • Uses SQL/NF as its basis and does not have group by.
  • Not Library based but syntax based. Compiler knows a lot more about the underlying collections.
  • "Query plan" so to speak is decided at compile time.  
Integration with Datalog and Prolog.
I was very fascinated by possibility of Object Curry having some capabilities like Datalog and better integration with Prolog.
Here are some initial thoughts from my college days  

Am I being nostalgic or this has some practical applications?
I think the concepts and syntax elements in the Object Curry are still valid in the era of NoSQL, json, GPGPU and map reduce. Hopefully I am able to come up with a practically useful implementation. 






Tuesday, April 26, 2011

Applying Radical Programming: Software is a Batch Process

Before applying the lean thinking to software engineering we must understand what are the concerns that lean thinking tries to solve and where exactly process of producing software fits in. 
See my earlier post What is radical programming? if you want and introduction to Radical Programming.


Mass Production vs Mass Customization 
Unlike craft production mass production relies on the standard components and economy of scale. Each unit is like every other unit and  parts are interchangeable. The assembly line can increase the throughput but then it becomes very difficult to change and to customize. 
On the other hand the more customization is required the less standard and costly the production becomes. Why is this relevant to software engineering ? That is because each software system is unique we have a need for high degree of custom software development and at the same time we need to bring in mass production techniques. 


User Story (Use case) is the unit of software production. 
In Radical Programming we treat user story as the unit of production. Our output is measured in terms of number of user stories implemented. We imagine an assembly line where a user story starts its life as a simple statement of user need which is developed into full set of acceptance tests and lightweight use case. It is then translated into design delta and finally implemented, tested and integrated. Individual user stories are the basis of calculations to make production decisions. 


Process Types 
One of the most critical factor in implementing efficient production system is to identify the process type that best achieves the tradeoffs between quality , time and flexibility.
There are five types to choose from

  1. Project Process - There is a high degree of customization and very low volume . Which means each project is unique. Flows and dependencies are very complicated.
  2. Job Process - Even though it is customized the volume is high enough. Which means each job is not as unique as project. Each new order is handled as a single unit and produced made to order. Flows and dependencies are jumbled. Examples are your doctors's visit, jobs with car mechanic, process for auto loan approval. Variety is achieved through "made to order" strategy.
  3. Batch Process: There is high volume and variety is achieved through "assemble to order". Most importantly items are produced as a batch. Some intermediate products might be pre-processed.
  4. Line Process: Volumes are very high. Fast food services and car assembly lines are examples of line processes. There are line flows with very little inventory held between operations.
  5. Continuous Process: It requires extremely high volume and very generic standardized product.
Software as a batch process with Time Boxing 
Like Scrum the radical programming achieves its goal using series of scrums. In radical programming we treat the software production as a Batch Process where we produce batch of user stories each iteration.


by Sachin Joshi
for Washington Technical Resources

Simple theory of Management: 8 Ps

I have a very simple theory about what senior managers need to do.  There job is to convert potential into profitability through internal and external interaction. 
And that means specifically managing 8 Ps described below. Call it "Sachin Joshi Model of Management" if you wish.
Discussion is more relevant to executives and other senior managers who in my vocabulary are called "business owners".
Financial Perspective 

1. Profitability : The reality is that businesses need to keep themselves profitable which means managers must take right financial decisions. At minimum it means managers must be financially  literate. Beyond budgeting and forecasting there are many decisions that require using finance/accounting tools. Selecting the right project size and team size. Pricing the products. Making buy vs build vs rent decisions. One of the most useful concepts are   Minimum Marketable Feature and idea of Real Options.   
External Perspective
2. Positioning : Nothing is so critical than finding the right fit to market and positioning the products in a market place. Nothing succeeds like an idea whose time has come. Your talent as a manager is in finding that right idea. The entire process of dividing the markets in right segments, selecting the right customers and solving right set of problems for them is all what I call "positioning". It requires making right decisions all the time. And that doesn't happen without instituting the customer focus. Customer focus is not some magic thing you do but a value system and tool that results in a well defined procedure for "positioning" your service.
3. Partnerships: No business works in isolation. So yet another job is to manage partnerships with vendors and clients.
Internal Perspective
4. Programs: Many managers make mistake of thinking that what they are delivering is product or a project. But in reality what they are doing is managing series of projects and set of products which requires Program Management. Defining and managing program objectives is a top item in job description of senior manager. A successful manager must be able to map strategy into programs and then translate the vision in terms of program objectives. (I plan to write a blog about mapping strategy into program objectives.)
5. Process : No software gets built without proper process in place. One of the important jobs of manager is to define process and actively manage it. There is a large body of knowledge dedicated to project management and process improvements. Wisdom and drive in applying these principals to increase quality is what managers demonstrate everyday.
6. Policy: Make sure that technical standards are defined and followed. Rather than actually making each and every decision themselves senior managers define policy. To me policy is framework in which those decisions are made.  One of the most important job of managers is to define that framework and provide guidance in applying it to everyday decisions. 



Growth Perspective 


7. People: The generative power of business comes from the talent and creativity of its people. And no where is this more important than in software. Success in providing the environment where people can grow is how we must measure our progress
8. Productivity : Equally important is increasing our production capability or "Productivity". Smart tools turn smart people into even smarter geniuses.   

by Sachin Joshi
For Washington Technical Resources