Your browser may have trouble rendering this page. See supported browsers for more information.

This page shows the source for this entry, with WebCore formatting language tags and attributes highlighted.

Title

A provably safe parallel language extension for C#

Description

The paper <a href="http://research.microsoft.com/apps/pubs/default.aspx?id=170528" source="Microsoft Research" author="Colin S. Gordon, Matthew J. Parkinson, Jared Parsons, Aleks Bromfield, Joe Duffy">Uniqueness and Reference Immutability for Safe Parallelism</a> is quite long (26 pages), detailed and involved. To be frank, most of the notation was foreign to me---to say nothing of making heads or tails of most of the proofs and lemmas---but I found the higher-level discussions and conclusions quite interesting. The abstract is concise and describes the project very well: <bq>A key challenge for concurrent programming is that side-effects (memory operations) in one thread can affect the behavior of another thread. In this paper, we present a type system to restrict the updates to memory to prevent these unintended side-effects. We provide a novel combination of immutable and unique (isolated) types that ensures safe parallelism (race freedom and deterministic execution). The type system includes support for polymorphism over type qualifiers, and can easily create cycles of immutable objects. Key to the system's flexibility is the ability to recover immutable or externally unique references after violating uniqueness without any explicit alias tracking. Our type system models a prototype extension to C# that is in active use by a Microsoft team. We describe their experiences building large systems with this extension. We prove the soundness of the type system by an embedding into a program logic.</bq> The project proposes a type-system extension with which developers can write provably safe parallel programs---i.e. <iq>race freedom and deterministic execution</iq>---with the amount of actual parallelism determined when the program is analyzed and compiled rather than decided by a programmer creating threads of execution. <h>Isolating objects for parallelism</h> The "isolation" part of this type system reminds me a bit of the way that SCOOP addresses concurrency. That system also allows programs to designate objects as "separate" from other objects while also releasing the program from the onus of actually creating and managing separate execution contexts. That is, the syntax of the language allows a program to be written in a provably correct way (at least as far as parallelism is concerned; see the "other provable-language projects" section below). In order to execute such a program, the runtime loads not just the program but also another file that specifies the available virtual processors (commonly mapped to threads). Sections of code marked as "separate" can be run in parallel, depending on the available number of virtual processors. Otherwise, the program runs serially. In SCOOP, methods are used as a natural isolation barrier, with input parameters marked as "separate". See <a href="http://www.eiffel.com/products/concurrency/scoop.html" source="Eiffel.com">SCOOP: Concurrency for Eiffel</a> and <a href="http://en.wikipedia.org/wiki/SCOOP_(software)" source="Wikipedia">SCOOP (software)</a> for more details. The paper also contains an entire section listing other projects---many implemented on the the JVM---that have attempted to make provably safe programming languages. The system described in this paper goes much further, adding immutability as well as isolation (the same concept as "separate" in SCOOP). An interesting extension to the type system is that isolated object trees are free to have references to immutable objects (since those can't negatively impact parallelism). This allows for globally shared immutable state and reduces argument-passing significantly. Additionally, there are readable and writable references: the former can only be read but may be modified by other objects (otherwise it would be immutable); the latter can be read and written and is equivalent to a "normal" object in C# today. In fact, <iq>[...] writable is the default annotation, so any single-threaded C# that does not access global state also compiles with the prototype.</iq> <h>Permission types</h> In this safe-parallel extension, a standard type system is extended so that every type can be assigned such a permission and there is <iq>support for polymorphism over type qualifiers</iq>, which means that the extended type system includes the permission in the type, so that, given <c>B => A</c>, a reference to <c>readable B</c> can be passed to a method that expects an <c>immutable A</c>. In addition, covariance is also supported for generic parameter types. When they say that the <iq>[k]ey to the system's flexibility is the ability to recover immutable or externally unique references after violating uniqueness without any explicit alias tracking</iq>, they mean that the type system allows programs to specify sections that accept isolated references as input, lets them convert to writable references and then convert back to isolated objects---all without losing provably safe parallelism. This is quite a feat since it allows programs to benefit from isolation, immutability and provably safe parallelism without significantly changing common programming practice. In essence, it suffices to decorate variables and method parameters with these permission extensions to modify the types and let the compiler guide you as to further changes that need to be made. That is, an input parameter for a method will be marked as <c>immutable</c> so that it won't be changed and subsequent misuse has to be corrected. Even better, they found that, in practice, it is possible to use extension methods to allow parallel and standard implementations of collections (lists, maps, etc.) to share most code. <bq>A fully polymorphic version of a map() method for a collection can coexist with a parallelized version pmap() specialized for immutable or readable collections. [...] Note that the parallelized version can still be used with writable collections through subtyping and framing as long as the mapped operation is pure; no duplication or creation of an additional collection just for concurrency is needed.</bq> <h>Real projects and performance impact</h> Much of the paper is naturally concerned with proving that their type system actually does what it says it does. As mentioned above, at least 2/3 of the paper is devoted to lemmas and large swaths of notation. For programmers, the more interesting part is the penultimate section that discusses the extension to C# and the experiences in using it for larger projects. <bq>A source-level variant of this system, as an extension to C#, is in use by a large project at Microsoft, as their primary programming language. The group has written several million lines of code, including: core libraries (including collections with polymorphism over element permissions and data-parallel operations when safe), a webserver, a high level optimizing compiler, and an MPEG decoder.</bq> Several million lines of code is, well, it's an enormous amount of code. I'm not sure how many programmers they have or how they're counting lines or how efficiently they write their code, but millions of lines of code suggests generated code of some kind. Still, taken with the next statement on performance, that much code more than proves that the type system is viable. <bq>These and other applications written in the source language are performance-competitive with established implementations on standard benchmarks; we mention this not because our language design is focused on performance, but merely to point out that heavy use of reference immutability, including removing mutable static/global state, has not come at the cost of performance in the experience of the Microsoft team.</bq> Not only is performance not impacted, but the nature of the typing extensions allows the compiler to know much more about which values and collections can be changed, which affects how aggressively this data can be cached or inlined. <bq>In fact, the prototype compiler exploits reference immutability information for a number of otherwise-unavailable compiler optimizations. [...] Reference immutability enables some new optimizations in the compiler and runtime system. For example, the concurrent GC can use weaker read barriers for immutable data. The compiler can perform more code motion and caching, and an MSIL-to-native pass can freeze immutable data into the binary.</bq> <h>Incremental integration ("unstrict" blocks)</h> In the current implementation, there is an <c>unstrict</c> block that allows the team at Microsoft to temporarily turn off the new type system and to ignore safety checks. This is a pragmatic approach which allows the software to be run before it has been proven 100% parallel-safe. This is still better than having no provably safe blocks at all. Their goal is naturally to remove as many of these blocks as possible---and, in fact, this requirement drives further refinement of the type system and library. <bq>We continue to work on driving the number of unstrict blocks as low as possible without over-complicating the type system’s use or implementation.</bq> The project is still a work-in-progress but has seen quite a few iterations, which is promising. The paper was written in 2012; it would be very interesting to take it for a test drive in a CTP. <h>Other provable-language projects</h> A related project at Microsoft Research <a href="http://research.microsoft.com/en-us/projects/specsharp/">Spec#</a> contributed a lot of basic knowledge about provable programs. The authors even state that the <iq>[...] type system grew naturally from a series of efforts at safe parallelism. [...] The earliest version was simply copying Spec#’s [Pure] method attribute, along with a set of carefully designed task-and data-parallelism libraries.</iq> Spec#, in turn, is a <iq>[...] formal language for API contracts (influenced by JML, AsmL, and Eiffel), which extends C# with constructs for non-null types, preconditions, postconditions, and object invariants</iq>. Though the implementation of this permissions-based type system may have started with Spec#, the primary focus of that project was more a valiant attempt to bring Design-by-Contract principles (<a href="http://encodo.com/en/dev-design-by-contract.php" source="encodo.com">examples and some discussion here</a>) to the .NET world via C#. Though spec# has <a href="http://specsharp.codeplex.com/" source="CodePlex">downloadable code</a>, the project hasn't really been updated in years. This is a shame, as support for <a href="http://eiffel.com">Eiffel</a><fn> in .NET, mentioned above as one of the key influences of spec#, was dropped by ISE Eiffel long ago. Spec#, in turn, was mostly replaced by Microsoft Research's <a href="http://research.microsoft.com/en-us/projects/contracts/">Contracts</a> project (an older version of which was covered in depth in <a href="http://earthli.com/news/view_article.php?id=2183" source="earthli.com">Microsoft Code Contracts: Not with a Ten-foot Pole</a>). The Contracts project seems to be alive and well: the most recent release is from October, 2012. I have not checked it out since my initial thumbs-down review (linked above) but did note in passing that the implementation is still (A) library-only and (B) does not support Visual Studio 2012. The library-only restriction is particularly galling, as such an implementation can lead to repeated code and unwieldy anti-patterns. As documented in the <a href="http://research.microsoft.com/en-us/projects/contracts/faq.aspx">Contracts FAQ</a>, the current implementation of the <iq>tools take care of enforcing consistency and proper inheritance of contracts</iq> but this is presumably accomplished with compiler errors that require the programmer to include contracts from base methods in overrides. The seminal work <i>Object-oriented Software Construction</i> by <i>Bertrand Meyer</i> (vol. II in particular) goes into tremendous detail on a type system that incorporates contracts directly. The type system discussed in this article covers only parallel safety: null-safety and other contracts are not covered at all. If you're at all interested in these types of language extensions, the vol.2 of OOSC is a great read. The examples are all in <a href="http://en.wikipedia.org/wiki/Eiffel_(programming_language)">Eiffel</a> but should be relatively accessible. Though some features---generics, notably but also tuples, once routines and <a href="http://earthli.com/news/view_article.php?id=1586" source="earthli.com">agents</a>---have since made their way into C# and other more commonly used languages, many others---such as contracts, anchored types (contravariance is far too constrained in C# to allow them), covariant return types, covariance everywhere, multiple inheritance, explicit feature removal, loop variants and invariants, etc.---are still not available. Subsequent interesting work has also been done on extensions that allow creation of <a href="http://earthli.com/news/view_article.php?id=820" source="earthli.com">provably null-safe programs</a>, something also addressed in part by Microsoft Research's <a href="http://research.microsoft.com/en-us/projects/contracts/">Contracts</a> project.