Lecture Notes in Computer Science Commenced Publication in 1973 Founding and Former Series Editors: Gerhard Goos, Juris Hartmanis, and Jan van Leeuwen
Editorial Board David Hutchison Lancaster University, UK Takeo Kanade Carnegie Mellon University, Pittsburgh, PA, USA Josef Kittler University of Surrey, Guildford, UK Jon M. Kleinberg Cornell University, Ithaca, NY, USA Friedemann Mattern ETH Zurich, Switzerland John C. Mitchell Stanford University, CA, USA Moni Naor Weizmann Institute of Science, Rehovot, Israel Oscar Nierstrasz University of Bern, Switzerland C. Pandu Rangan Indian Institute of Technology, Madras, India Bernhard Steffen University of Dortmund, Germany Madhu Sudan Massachusetts Institute of Technology, MA, USA Demetri Terzopoulos University of California, Los Angeles, CA, USA Doug Tygar University of California, Berkeley, CA, USA Moshe Y. Vardi Rice University, Houston, TX, USA Gerhard Weikum Max-Planck Institute of Computer Science, Saarbruecken, Germany
4421
Rocco De Nicola (Ed.)
Programming Languages and Systems 16th European Symposium on Programming, ESOP 2007 Held as Part of the Joint European Conferences on Theory and Practics of Software, ETAPS 2007 Braga, Portugal, March 24 - April 1, 2007 Proceedings
13
Volume Editor Rocco De Nicola Dipartimento di Sistemi e Informatica Università di Firenze Viale Morgagni 65 50134 Firenze, Italy E-mail:
[email protected]fi.it
Library of Congress Control Number: 2007922404 CR Subject Classification (1998): D.3, D.1, D.2, F.3, F.4, E.1 LNCS Sublibrary: SL 1 – Theoretical Computer Science and General Issues ISSN ISBN-10 ISBN-13
0302-9743 3-540-71314-X Springer Berlin Heidelberg New York 978-3-540-71314-2 Springer Berlin Heidelberg New York
This work is subject to copyright. All rights are reserved, whether the whole or part of the material is concerned, specifically the rights of translation, reprinting, re-use of illustrations, recitation, broadcasting, reproduction on microfilms or in any other way, and storage in data banks. Duplication of this publication or parts thereof is permitted only under the provisions of the German Copyright Law of September 9, 1965, in its current version, and permission for use must always be obtained from Springer. Violations are liable to prosecution under the German Copyright Law. Springer is a part of Springer Science+Business Media springer.com © Springer-Verlag Berlin Heidelberg 2007 Printed in Germany Typesetting: Camera-ready by author, data conversion by Scientific Publishing Services, Chennai, India Printed on acid-free paper SPIN: 12032907 06/3142 543210
Foreword
ETAPS 2007 is the tenth instance of the European Joint Conferences on Theory and Practice of Software, and thus a cause for celebration. The events that comprise ETAPS address various aspects of the system development process, including specification, design, implementation, analysis and improvement. The languages, methodologies and tools which support these activities are all well within its scope. Different blends of theory and practice are represented, with an inclination towards theory with a practical motivation on the one hand and soundly based practice on the other. Many of the issues involved in software design apply to systems in general, including hardware systems, and the emphasis on software is not intended to be exclusive. History and Prehistory of ETAPS ETAPS as we know it is an annual federated conference that was established in 1998 by combining five conferences [Compiler Construction (CC), European Symposium on Programming (ESOP), Fundamental Approaches to Software Engineering (FASE), Foundations of Software Science and Computation Structures (FOSSACS), Tools and Algorithms for Construction and Analysis of Systems (TACAS)] with satellite events. All five conferences had previously existed in some form and in various colocated combinations: accordingly, the prehistory of ETAPS is complex. FOSSACS was earlier known as the Colloquium on Trees in Algebra and Programming (CAAP), being renamed for inclusion in ETAPS as its historical name no longer reflected its contents. Indeed CAAP’s history goes back a long way; prior to 1981, it was known as the Colleque de Lille sur les Arbres en Algebre et en Programmation. FASE was the indirect successor of a 1985 event known as Colloquium on Software Engineering (CSE), which together with CAAP formed a joint event called TAPSOFT in odd-numbered years. Instances of TAPSOFT, all including CAAP plus at least one software engineering event, took place every two years from 1985 to 1997 inclusive. In the alternate years, CAAP took place separately from TAPSOFT. Meanwhile, ESOP and CC were each taking place every two years from 1986. From 1988, CAAP was colocated with ESOP in even years. In 1994, CC became a “conference” rather than a “workshop” and CAAP, CC and ESOP were thereafter all colocated in even years. TACAS, the youngest of the ETAPS conferences, was founded as an international workshop in 1995; in its first year, it was colocated with TAPSOFT. It took place each year, and became a “conference” when it formed part of ETAPS 1998. It is a telling indication of the importance of tools in the modern field of informatics that TACAS today is the largest of the ETAPS conferences.
VI
Foreword
The coming together of these five conferences was due to the vision of a small group of people who saw the potential of a combined event to be more than the sum of its parts. Under the leadership of Don Sannella, who became the first ETAPS steering committee chair, they included: Andre Arnold, Egidio Astesiano, Hartmut Ehrig, Peter Fritzson, Marie-Claude Gaudel, Tibor Gyimothy, Paul Klint, Kim Guldstrand Larsen, Peter Mosses, Alan Mycroft, Hanne Riis Nielson, Maurice Nivat, Fernando Orejas, Bernhard Steffen, Wolfgang Thomas and (alphabetically last but in fact one of the ringleaders) Reinhard Wilhelm. ETAPS today is a loose confederation in which each event retains its own identity, with a separate programme committee and proceedings. Its format is open-ended, allowing it to grow and evolve as time goes by. Contributed talks and system demonstrations are in synchronized parallel sessions, with invited lectures in plenary sessions. Two of the invited lectures are reserved for “unifying” talks on topics of interest to the whole range of ETAPS attendees. The aim of cramming all this activity into a single one-week meeting is to create a strong magnet for academic and industrial researchers working on topics within its scope, giving them the opportunity to learn about research in related areas, and thereby to foster new and existing links between work in areas that were formerly addressed in separate meetings. ETAPS 1998–2006 The first ETAPS took place in Lisbon in 1998. Subsequently it visited Amsterdam, Berlin, Genova, Grenoble, Warsaw, Barcelona, Edinburgh and Vienna before arriving in Braga this year. During that time it has become established as the major conference in its field, attracting participants and authors from all over the world. The number of submissions has more than doubled, and the numbers of satellite events and attendees have also increased dramatically. ETAPS 2007 ETAPS 2007 comprises five conferences (CC, ESOP, FASE, FOSSACS, TACAS), 18 satellite workshops (ACCAT, AVIS, Bytecode, COCV, FESCA, FinCo, GTVMT, HAV, HFL, LDTA, MBT, MOMPES, OpenCert, QAPL, SC, SLA++P, TERMGRAPH and WITS), three tutorials, and seven invited lectures (not including those that were specific to the satellite events). We received around 630 submissions to the five conferences this year, giving an overall acceptance rate of 25%. To accommodate the unprecedented quantity and quality of submissions, we have four-way parallelism between the main conferences on Wednesday for the first time. Congratulations to all the authors who made it to the final programme! I hope that most of the other authors still found a way of participating in this exciting event and I hope you will continue submitting. ETAPS 2007 was organized by the Departamento de Inform´ atica of the Universidade do Minho, in cooperation with
Foreword
VII
– – – –
European Association for Theoretical Computer Science (EATCS) European Association for Programming Languages and Systems (EAPLS) European Association of Software Science and Technology (EASST) The Computer Science and Technology Center (CCTC, Universidade do Minho) – Camara Municipal de Braga – CeSIUM/GEMCC (Student Groups) The organizing team comprised: – – – – – – – – – –
Jo˜ ao Saraiva (Chair) Jos´e Bacelar Almeida (Web site) Jos´e Jo˜ao Almeida (Publicity) Lu´ıs Soares Barbosa (Satellite Events, Finances) Victor Francisco Fonte (Web site) Pedro Henriques (Local Arrangements) Jos´e Nuno Oliveira (Industrial Liaison) Jorge Sousa Pinto (Publicity) Ant´ onio Nestor Ribeiro (Fundraising) Joost Visser (Satellite Events)
ETAPS 2007 received generous sponsorship from Funda¸c˜ao para a Ciˆencia e a Tecnologia (FCT), Enabler (a Wipro Company), Cisco and TAP Air Portugal. Overall planning for ETAPS conferences is the responsibility of its Steering Committee, whose current membership is: Perdita Stevens (Edinburgh, Chair), Roberto Amadio (Paris), Luciano Baresi (Milan), Sophia Drossopoulou (London), Matt Dwyer (Nebraska), Hartmut Ehrig (Berlin), Jos´e Fiadeiro (Leicester), Chris Hankin (London), Laurie Hendren (McGill), Mike Hinchey (NASA Goddard), Michael Huth (London), Anna Ing´ olfsd´ ottir (Aalborg), Paola Inverardi (L’Aquila), Joost-Pieter Katoen (Aachen), Paul Klint (Amsterdam), Jens Knoop (Vienna), Shriram Krishnamurthi (Brown), Kim Larsen (Aalborg), Tiziana Margaria (G¨ ottingen), Ugo Montanari (Pisa), Rocco de Nicola (Florence), Jakob Rehof (Dortmund), Don Sannella (Edinburgh), Jo˜ ao Saraiva (Minho), Vladimiro Sassone (Southampton), Helmut Seidl (Munich), Daniel Varro (Budapest), Andreas Zeller (Saarbr¨ ucken). I would like to express my sincere gratitude to all of these people and organizations, the programme committee chairs and PC members of the ETAPS conferences, the organizers of the satellite events, the speakers themselves, the many reviewers, and Springer for agreeing to publish the ETAPS proceedings. Finally, I would like to thank the organizing chair of ETAPS 2007, Jo˜ ao Saraiva, for arranging for us to have ETAPS in the ancient city of Braga. Edinburgh, January 2007
Perdita Stevens ETAPS Steering Committee Chair
Preface
This volume contains 34 papers presented at ESOP 2007, the annual European Symposium on Programming, held in Braga, Portugual, in March 2007. The goal of ESOP has always been to bridge the gap between theory and practice of programming, and the conferences continue to be devoted to addressing fundamental issues in the specification, analysis, and implementation of programming languages and systems. The volume begins with a summary of the invited talk by Andy Pitts and continues with the contributed ESOP papers. The papers deal with important issues such as models and languages for services, logics, type theories and other verification techniques, language-based security, static analysis and abstract interpretation, semantic theories for object-oriented languages, process algebraic techniques for proving systems properties, and term-rewriting theories. The 34 papers contained in this volume were selected by the Program Committee out of 136 submissions, each reviewed by at least three researchers. The reviews were made by the Program Committee and by 181 additional referees, listed below. The accepted papers were selected during a two-week electronic discussion by the Program Committee. Thanks go to the authors, the members of the Program Committee, and the external referees for their excellent work, to the ETAPS Steering Committee Chair Perdita Stevens and the ETAPS 2007 Local Organization chaired by Jo˜ ao Saraiva for providing infrastructure and gentle reminders, and finally to Andrei Voronkov and the maintainers of the Easychair Conference Management Systems that was very useful in all the phases of paper handling. January 2007
Rocco De Nicola
Organization
Program Chair Rocco De Nicola Dipartimento di Sistemi e Informatica Universit` a di Firenze, Italy
Program Committee Steve Brookes Gerard Boudol Giuseppe Castagna Patrick Cousot Mads Dam Pierpaolo Degano Sophia Drossopoulou Cedric Fournet Stefania Gnesi Joshua Guttman Chris Hankin Matthew Hennessy Alan Jeffrey John Mitchell Fleming Nielson Catuscia Palamidessi Benjamin Pierce Andrei Sabelfeld Don Sannella Bernhard Steffen Walid Taha Jan Vitek Martin Wirsing Xavier Leroy Gianluigi Zavattaro
CMU Pittsburgh, USA INRIA Sophia Antipolis, France ENS Paris, France ENS Paris, France KTH Stockolm, Sweden Univ. Pisa, Italy Imperial College, UK Microsoft Cambridge, UK ISTI CNR, Italy MITRE, USA Imperial College, UK Univ. Sussex, UK Bell Labs, USA Stanford Univ., USA IMM Copenhagen, Denmark INRIA Paris, France U. Pennsylvania, USA Chalmers Univ., Sweden Univ. Edinburgh, UK Univ. Dortmund, Germany Rice Univ. , USA Purdue Univ., USA LMU Munich, Germany INRIA Paris, France Univ. Bologna, Italy
Additional Referees Andreas Abel Pedro Adao Irem Aktug
Tristan Allwood Davide Ancona Jesus Aranda
Zena Ariola Aslan Askarov Robert Atkey
XII
Organization
Roberto Bagnara Adam Barker Massimo Bartoletti Joerg Bauer Hubert Baumeister Maurice ter Beek Lennart Beringer Clara Bertolissi Lorenzo Bettini Hariolf Betz Karthik Bhargavan Nicole Bidoit Gavin Bierman Chiara Bodei Viviana Bono Marcello Bonsangue Michele Boreale Gilles Brassard Mario Bravetti Roberto Bruni Cristiano Calcagno Nick Cameron Brian Campbell Luca Cardelli Magnus Carlsson K. Chatzikokolakis James Cheney Antonio Cisternino Ricardo Corin Andrea Corradini Antonio Cunei David Cunningham Mika Cohen Ferruccio Damiani Vincent Danos Olivier Danvy Pierre-Malo Deni´elou Moshe Deutsch Alessandra Di Pierro Dino Distefano Kevin Donnelly Stephan Ellner Moreno Falaschi Alessandro Fantechi J´erˆome Feret
Gianluigi Ferrari Gian-Luigi Ferrari Jean-Christ. Filliatre Robby Findler Andrea Flexeder Nate Foster Alain Frisch Thom Frhwirth Rachele Fuzzati Fabio Gadducci Han Gao St´ephane Gaubert Thomas Gawlitza Stephen Gilmore Sabine Glesner Johan Glimming Jens C. Godskesen Ulla Goltz Dilian Gurov Rene Rydhof Hansen Fritz Henglein Rolf Hennicker Stephan Herrmann Mike Hicks Thomas Hildebrandt Tom Hirschowitz Matthias H¨ olzl Suresh Jagannathan Johan Jeuring Stefan Kahrs Gerwin Klein Alexander Knapp Naoki Kobayashi Ivan Lanese Cosimo Laneve Diego Latella Christopher League Jooyong Lee James Leifer Francesca Levi Ruy Ley-Wild Cedric Lhoussaine Michele Loreti Markus M¨ uller-Olm Kenneth MacKenzie
Patrick Maier Luc Maranget Luca Martini Franco Mazzanti Hernan Melgratti Dale Miller Antoine Min´e David Monniaux Anders Møller Ralf Nagel Sebastian Nanz Joachim Niehren Christoffer R. Nielsen Peter O’Hearn Chris Okasaki Carlos Olarte Peter Olvecki Karol Ostrovsky Luca Padovani Catuscia Palamidessi Matthew Parkinson Emir Pasalic Marius Petria Andrew Phillips Henrik Pilegaard Andrew Pitts Randy Pollack Christian W. Probst Riccardo Pucella Rosario Pugliese Harald Raffelt Julian Rathke Axel Rauschmayer Yann Regis-Gianas Bernhard Reus Tamara Rezk M. Birna van Riemsdijk Xavier Rival Alessandro Romanel Mads Rosendahl Claudio Russo Alejandro Russo Didier Remy Oliver R¨ uthing Matthew Sackman
Organization
Jens-Wolfhard Schicke Andreas Schroeder Peter Sewell Vitaly Shmatikov Jeremy Siek Julien Signoles Sam Staton Martin Sulzmann Hans Svensson Deian Tabakov Javier Thayer Stephan Thesing Alwen Tiu
Jacques Thomas Simon Thompson Alwen Tiu Andrew Tolmach Terkel K. Tolstrup Angelo Troina Frank D. Valencia Wim Vanhoof Daniele Varacca Betti Venneri Cristian Versari Eelco Visser Jan Vitek
David Walker Herbert Wiklicky Verena Wolf Hongwei Xi Zhe Yang Steve Zdancewic Noam Zeilberger Gefei Zhang Ye Zhang Elena Zucca Roberto Zunino
XIII
Table of Contents
Invited Talk Techniques for Contextual Equivalence in Higher-Order, Typed Languages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Andrew Pitts
1
Models and Languages for Web Services Structured Communication-Centred Programming for Web Services . . . . Marco Carbone, Kohei Honda, and Nobuko Yoshida
2
CC-Pi: A Constraint-Based Language for Specifying Service Level Agreements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Maria Grazia Buscemi and Ugo Montanari
18
A Calculus for Orchestration of Web Services . . . . . . . . . . . . . . . . . . . . . . . . Alessandro Lapadula, Rosario Pugliese, and Francesco Tiezzi
33
A Concurrent Calculus with Atomic Transactions . . . . . . . . . . . . . . . . . . . . Lucia Acciai, Michele Boreale, and Silvano Dal Zilio
48
Verification Modal I/O Automata for Interface and Product Line Theories . . . . . . . . . Kim G. Larsen, Ulrik Nyman, and Andrzej Wasowski
64
Using History Invariants to Verify Observers . . . . . . . . . . . . . . . . . . . . . . . . . K. Rustan M. Leino and Wolfram Schulte
80
Term Rewriting On the Implementation of Construction Functions for Non-free Concrete Data Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Fr´ed´eric Blanqui, Th´er`ese Hardin, and Pierre Weis
95
Anti-pattern Matching . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Claude Kirchner, Radu Kopetz, and Pierre-Etienne Moreau
110
Language Based Security A Certified Lightweight Non-interference Java Bytecode Verifier . . . . . . . Gilles Barthe, David Pichardie, and Tamara Rezk
125
XVI
Table of Contents
Controlling the What and Where of Declassification in Language-Based Security . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Heiko Mantel and Alexander Reinhard
141
Cost Analysis of Java Bytecode . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . E. Albert, P. Arenas, S. Genaim, G. Puebla, and D. Zanardini
157
Logics and Correctness Proofs On the Relationship Between Concurrent Separation Logic and Assume-Guarantee Reasoning . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Xinyu Feng, Rodrigo Ferreira, and Zhong Shao Abstract Predicates and Mutable ADTs in Hoare Type Theory . . . . . . . . Aleksandar Nanevski, Amal Ahmed, Greg Morrisett, and Lars Birkedal Structure of a Proof-Producing Compiler for a Subset of Higher Order Logic . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Guodong Li, Scott Owens, and Konrad Slind
173 189
205
Static Analysis and Abstract Interpretation I Modular Shape Analysis for Dynamically Encapsulated Programs . . . . . . N. Rinetzky, A. Poetzsch-Heffter, G. Ramalingam, M. Sagiv, and E. Yahav
220
Static Analysis by Policy Iteration on Relational Domains . . . . . . . . . . . . . Stephane Gaubert, Eric Goubault, Ankur Taly, and Sarah Zennou
237
Computing Procedure Summaries for Interprocedural Analysis . . . . . . . . . Sumit Gulwani and Ashish Tiwari
253
Small Witnesses for Abstract Interpretation-Based Proofs . . . . . . . . . . . . . Fr´ed´eric Besson, Thomas Jensen, and Tiphaine Turpin
268
Static Analysis and Abstract Interpretation II Interprocedurally Analysing Linear Inequality Relations . . . . . . . . . . . . . . . Helmut Seidl, Andrea Flexeder, and Michael Petter
284
Precise Fixpoint Computation Through Strategy Iteration . . . . . . . . . . . . Thomas Gawlitza and Helmut Seidl
300
Semantic Theories for Object Oriented Languages A Complete Guide to the Future . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Frank S. de Boer, Dave Clarke, and Einar Broch Johnsen
316
Table of Contents
XVII
The Java Memory Model: Operationally, Denotationally, Axiomatically . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Pietro Cenciarelli, Alexander Knapp, and Eleonora Sibilio
331
Immutable Objects for a Java-Like Language . . . . . . . . . . . . . . . . . . . . . . . . C. Haack, E. Poll, J. Sch¨ afer, and A. Schubert
347
Process Algebraic Techniques Scalar Outcomes Suffice for Finitary Probabilistic Testing . . . . . . . . . . . . . Yuxin Deng, Rob van Glabbeek, Carroll Morgan, and Chenyi Zhang
363
Probabilistic Anonymity Via Coalgebraic Simulations . . . . . . . . . . . . . . . . . Ichiro Hasuo and Yoshinobu Kawabe
379
A Fault Tolerance Bisimulation Proof for Consensus . . . . . . . . . . . . . . . . . . Adrian Francalanza and Matthew Hennessy
395
A Core Calculus for a Comparative Analysis of Bio-inspired Calculi . . . . Cristian Versari
411
Applicative Programming A Rewriting Semantics for Type Inference . . . . . . . . . . . . . . . . . . . . . . . . . . . George Kuan, David MacQueen, and Robert Bruce Findler
426
Principal Type Schemes for Modular Programs . . . . . . . . . . . . . . . . . . . . . . Derek Dreyer and Matthias Blume
441
A Consistent Semantics of Self-adjusting Computation . . . . . . . . . . . . . . . . Umut A. Acar, Matthias Blume, and Jacob Donham
458
Multi-language Synchronization . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Robert Ennals and David Gay
475
Types for Systems Properties Type-Based Analysis of Deadlock for a Concurrent Calculus with Interrupts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Kohei Suenaga and Naoki Kobayashi
490
Type Reconstruction for General Refinement Types . . . . . . . . . . . . . . . . . . Kenneth Knowles and Cormac Flanagan
505
Dependent Types for Low-Level Programming . . . . . . . . . . . . . . . . . . . . . . . Jeremy Condit, Matthew Harren, Zachary Anderson, David Gay, and George C. Necula
520
Author Index . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
537
Techniques for Contextual Equivalence in Higher-Order, Typed Languages Andrew Pitts University of Cambridge
Abstract. Two phrases in a programming language are said to be contextually equivalent if, roughly speaking, they are interchangeable in any complete program without affecting the observable behaviour of the program. I will discuss precise formalisations of this fundamental notion of semantic equivalence for the case of higher-order, typed (HOT) languages, such as ML and Haskell. How does the structure of a type affect properties of contextual equivalence of expressions of that type? It can be very difficult to answer this question when working directly from the definition of contextual equivalence—mainly because HOT programs can make use of their constituent sub-expressions in dynamically complicated ways. This talk will survey some of the semantic techniques (both denotational and operational) that have been devised for proving properties of HOT contextual equivalence.
R. De Nicola (Ed.): ESOP 2007, LNCS 4421, p. 1, 2007. c Springer-Verlag Berlin Heidelberg 2007
Structured Communication-Centred Programming for Web Services Marco Carbone1 , Kohei Honda2 , and Nobuko Yoshida1 1
2
Department of Computing, Imperial College London Department of Computer Science, Queen Mary University of London
Abstract. This paper relates two different paradigms of descriptions of communication behaviour, one focussing on global message flows and another on end-point behaviours, using formal calculi based on session types. The global calculus, which originates from a web service description language (W3C WS-CDL), describes an interaction scenario from a vantage viewpoint; the end-point calculus, an applied typed π-calculus, precisely identifies a local behaviour of each participant. We explore a theory of end-point projection, by which we can map a global description to its end-point counterpart preserving types and dynamics. Three principles of well-structured description and the type structures play a fundamental role in the theory.
1
Introduction
Communication-Centred Programming. The explosive growth of Internet in the last decades has led to the de facto, global standards for naming scheme (URI, Domain Names), communication protocols (SOAP, HTTP, TCP/IP) and message format (XML). These elements offer a useful basis for building applications centring on communication among distributed agents through these standards. Such communication-centred applications are sometimes called web services. Web services are an active area of infrastructural development, involving the major standardisation bodies such as W3C and OASIS. A concrete application area of communication-centred applications is business protocol. A business protocol is a series of structured and automated interactions among business entities. It is predominantly inter-domain, is often regulation-bound, and demands clear shared understanding about its meaning. Some protocols such as industry standards will remain unchanged for a long time once specified; others may undergo frequent updates. Because of its inherent inter-organisational nature, there is a strong demand for a common standard for specifying business protocols on a sound technical basis. Global Description of Interaction. One of the standardisation efforts for a language to specify business protocols is the Web Services Choreography Description Language (WS-CDL) [26], developed by W3C WS-CDL Working Group since 2004 in collaboration with π-calculus experts including the present authors. WS-CDL offers a fully expressive global description language for channel-based R. De Nicola (Ed.): ESOP 2007, LNCS 4421, pp. 2–17, 2007. c Springer-Verlag Berlin Heidelberg 2007
Structured Communication-Centred Programming for Web Services
3
communication equipped with general control constructs (e.g. sequencing, conditionals and recursion), and is conceived with potential usage of type-based formal validation from the outset. The intuition behind the term choreography may be summarised thus: “Dancers dance following a global scenario without a single point of control” WS-CDL is conceived as a language for describing such a “global scenario”: once specified, this scenario is to be executed by individual distributed processes without a single point of control.1 Another significant feature is WS-CDL’s informal use of sessions for communication: at the outset of each run of a protocol, a session is established between communication parties so that involved communications can be distinguished from different runs of the same or other protocols. End-Point Projection. The global description of a communication behaviour is useful since, among others, it offers a clear view of dynamics of the whole interactions. Real execution of the description, however, is always through communication among distributed end-points which (as the notion of choreography dictates) may as well involve no centralised control. Thus we ask: How can we project a global description to end-point processes so that their interactions precisely realise the original global description? Such a projection may be called end-point projection (EPP), a terminology from WS-CDL Working Group. Having a universally agreed and well-founded EPP is fundamental for the engineering use of global descriptions, from design to implementations to validations/verifications to run-time monitoring (see § 5). This paper establishes a formal theory of EPP by introducing the two typed calculi for interaction, a distilled version of WS-CDL (a global calculus) and an applied π-calculus (an end-point calculus), and defining a mapping from the former to the latter. This mapping is highly non-trivial due to the different nature of descriptions: a global calculus directly describes interactions among multiple participants involving sequencing, branching and recursion, which differs from the end-point-based description given in the π-calculus. A central contribution of this work is the identification of three basic principles for global descriptions under which we can define a sound and complete EPP, in the sense that, through a given EPP, all and only globally described behaviour is realised as communication among end-points. The three principles are: connectedness (a basic local causality principle), well-threadedness (a stronger locality principle based on session types [23,16,12,25,13,6]) and coherence (a consistency principle for description of each participant in a global description). Schematically, the EPP mapping has the following shape: I 1
→ A[P ] | B[Q] | C[R] | · · ·
A related idea is orchestration where one master component, “conductor”, directly controls activity of one or more slave components, which is useful when communicating parties can be placed under a common administrative domain, see [1].
4
M. Carbone, K. Honda, and N. Yoshida
where I is a global description, A, B and C are participants of the protocol and P , Q and R are projections of I onto A, B and C respectively. We shall show that, when applied to well-typed interactions following the three principles, the EPP mapping thus defined satisfies type preservation, soundness and completeness. The EPP theory opens a conduit between global descriptions and accumulated studies on process calculi, allowing the use of the latter’s rich theories for engineering aims. The EPP theory will be published as an associated document of WS-CDL 1.0 [11] (which contains many examples and full technical details), and will form part of its open-source implementation [19]. Related Work. Global methods for describing communication have been practiced in many different forms, including MSCs, UML diagrams and Petri-Nets [24]. In the context of security study, Strand Space [15] is a model for analysing security protocols based on their global representation; while Briais and Nestmann [7] present a notation for representing protocol narrations and relate it to the π-calculus (which is a form of end-point projection in our sense). These notations and models offer a useful basis for design/specification/analysis, but are not intended as full-fledged programming languages, so that they lack in e.g. general control structures and constructs for value passing and state change. DiCons is a global notation for programming Internet applications [2] whose primitives include web server invocation, email, and web form filing. A formal notion of end-point projection has not been studied in [2]. The present work shares with many recent works its use of types of the mobile processes, including, but not limited to, Pict [20], Polyphonic C [3] and the preceding studies on session type disciplines [6,12,13,16,23,25]. In the context of session types, our work extends their usage to global descriptions and intrasession parallel communications. These preceding works are based on end-point languages and calculi. The EPP theory offers a passage through which these and other related studies can be reflected onto global descriptions. Fournet, Gordon, Bhargavan and Corin studied security-related aspects of web services. In [5], they have implemented part of WS-Security libraries, and analyse them through a translation into the π-calculus. The benefits of such a tool may be reflected onto global descriptions through the theory of EPP. Laneve and Padovani [17] give a model of orchestrations using an extensions of π-calculus to join patterns. Busi et al. [8] study a bisimulation-based correspondence between choreography and orchestration. In [14], they further studied a calculus for web services of end-point descriptions based on predicate-driven communication. A formal theory of end-point projection is the main difference of our work from these preceding works.
2 2.1
The Global Calculus Buyer-Seller Protocol
We outline the key technical ideas using an example from [21], the “Buyer-Seller Protocol”. The participants involved are a Buyer, a Seller and a Shipper. We describe the protocol with both text and a sequence diagram.
Structured Communication-Centred Programming for Web Services
(1) Buyer asks Seller for quote;
Buyer
quote
(3) Buyer accepts or rejects;
(5) In case of rejection, (a) terminate.
Shipper
Seller quoteCh
(2) Seller replies with a quote; (4) In case of acceptance, (a) Seller orders from Shipper; (b) Shipper sends back details; (c) Seller forwards to Buyer.
5
+
accept reject deliveryCh details details
The diagram is ambiguous at the branching (+) actions in (4) and (5): the purpose of such diagrams is to offer an informal overview: they naturally omit detailed control structures (choices, loops, etc.) and manipulation of values/states. The reason why such global descriptions are practised in engineering is because they enable a clear grasp of the whole interaction structure, lessening synchronisation and other errors at the design stage. WS-CDL is intended to extend these virtues of global notations to a full fledged description language. We find, through our involvement in its design process, that it is based on two engineering principles: the Service Channel Principle (SCP) where invocation channels (e.g. a channel at which Buyer first communicates to Seller, or Seller to Shipper) can be shared and invoked repeatedly; and the Session Principle (SP) where a sequence of conversations belonging to a protocol should not be confused with other concurrent runs of this or other protocols by the participants i.e. each such sequence should form a logical unit of a conversation, or a session. (SCP) corresponds to the repeated availability of replicated input channels in the π-calculus (called uniformly receptive [22] and server channels in [4]), or, in practice, of public URLs. (SP) is a basic principle in many communicationcentred programs, and can be given simple type abstraction with decidable type checking [12,16,25].2 The global calculus is built from formalisation of these two principles, as well as combinators for composing descriptions. Before introducing the syntax formally, we first outline its basic ideas using an example. Figure 1 (a) gives a description of the Buyer-Seller Protocol in the global calculus. In (a), Line 1 describes Action (1) in the protocol. The quoteCh is a service channel, which may be considered as a public URL for a specific service. The invocation marks the start of a session between the buyer and the seller: the ν-bound s is a session channel, a fresh name to be used for later communication in this session. Unlike standard process calculi, the syntax no longer describes input and output actions separately: the information exchange between two parties is directly described as one interaction. 2
In implementations of web services, sessions are implemented using so-called correlation identities (which may be considered as nonces in cryptographic protocols).
6
M. Carbone, K. Honda, and N. Yoshida
1. Buyer → Seller : quoteCh(ν s). 2. Seller → Buyer : squote, 300, x. { 3. {Buyer → Seller : saccept. 4. Seller → Shipper : delivCh(ν t). 5. Shipper → Seller : tdetails, v, x. 6. Seller → Buyer : sdetails, x, y. 0 } 7. + 8. {Buyer → Seller : sreject. 0} }
(a) Protocol for Buyer-Seller Example
1. 2. 3. 4. 5. 6. 7. 8. 9. 10.
Buyer → Seller : quoteCh(ν s). rec X. { Seller → Buyer : squote, q, x. if reasonable(x)@Buyer then {Buyer → Seller : saccept. Seller → Shipper : delivCh(ν t). Shipper → Seller : tdetails, v, x. Seller → Buyer : sdetails, x, y. 0 } else {Buyer → Seller : sreject. q@Seller := q@Seller−1. X } } (b) Protocol with Recursion
Fig. 1. Business Protocols in the Global Calculus
Line 2 describes Action (2), Seller’s reply to Buyer. The session has already been started and now the two participants communicate using the session channel s. In addition, three factors involved: quote identifies the particular operation used in this communication (i.e. request for quote), 300 is the quote sent by Seller; x is a variable located at Buyer where the communicated value will be stored. Lines 3/8 describe Action (3), where Buyer communicates its choice (accept or reject) to Seller through s. Two series of actions which follow these choices are combined by + in Line 7. If accept is chosen, Seller sends Shipper the Buyer’s details via the service channel delivCh of Shipper, creating a fresh session channel t (Line 4). Then in Line 5, Shipper sends back the shipping details through t. Finally in Line 6, Seller forwards the details to Buyer by sending the value stored in variable x: here the protocol terminates. In Line 8, Buyer communicates reject, in which case the protocol immediately terminates. In (a), we can observe the distinction between service channels and session channels implements (SCP) and (SP); sessions offer logical grouping of threads of interactions, where each thread starts with a procedure-call-like service invocation at a service channel and carry out in-session communications at associated session channels. This point can be seen more clearly in Fig. 1 (b), a refinement of (a). In (b), if Buyer chooses reject, the protocol recurs to Line 3, after decrementing the quote. In Line 4, a unary predicate reasonable(x) is evaluated at Seller’s site (“@” indicates a location, similarly in Line 10). The session notation makes it clear that all quote-messages from Seller to Buyer in the recursion are done within a single session. §4 shall show that such session information plays a crucial role in tractable end-point projection. 2.2
Syntax and Dynamics
The syntax of the global calculus [9] is given by BNF. I, I , . . . denote terms of the calculus, also called interactions. ch, ch . . . range over service channels; s, t, . . . range over session channels; s˜ indicates a vector of session channels; A, B, C, . . . range over participants; x, y, z, . . . over variables local to each participant; X, X , . . . over term variables; and e, e , . . . over arithmetic and other first-order expressions.
Structured Communication-Centred Programming for Web Services A → B : ch(ν s˜). I
I ::=
(init)
|
(νs) I
|
A → B : sop, e, y. I
(comm)
|
X
|
x@A := e. I
(assign)
|
I1 + I2
|
I1 | I2
|
if e@A then I1 else I2
(par)
|
μX. I
(cond)
|
0
7
(new) (recvar) (sum) (rec) (inaction)
(init) denotes a session initiation by A via B’s service channel ch, with fresh session channels s˜ and continuation I. (comm) denotes an in-session communication over a session channel s, where op is an operator name. Note that y does not bind in I. “|” and “+” denote respectively parallel and choice. (νs) I is the π-calculus-like name restriction, binding s in I. Since such a hiding is only generated by session initiation, we stipulate that a hiding never occurs inside a prefix, sum or conditional. (cond) and (assign) are standard conditional and assignment (e@A indicates e is located at A). μX. I is recursion, where the variable X is bound in I. 0 denotes termination. The free and bound session channels and term variables are defined in the usual way. We often omit 0 and empty vectors. The reduction of the global calculus is close to that of imperative languages. A state σ assigns a value to the variables located at each participant. We shall write σ@A to denote the portion of σ local to A, and σ[y@A → v] to denote a new state σ which is identical to σ except that σ @A(y) is equal to v. A reduction “(σ, I) → (σ , I )” says that I in the state σ performs one-step computation and becomes I with the new state σ . Below we list some of the rules generating the reduction (a complete set of rules can be found in [11]). (G-Init) (σ, A → B : ch(ν s˜). I) → (σ, (ν s˜) I) (G-Com) σ = σ[x@B → v] σ e@A ⇓ v (σ, A → B : sop, e, x. I) → (σ , I)
(G-Asgn) σ e@A ⇓ v σ = σ[x@A → v] (σ, x@A := e. I) → (σ , I)
(G-Init) is for session initiation: after A initiates a session with B on service channel ch, A and B share s˜ locally (indicated by (ν˜ s)), and the next I is unfolded. The initiation channel ch will play an important role for typing and the end-point projection later. (G-Com) is a key rule: the expression e is evaluated into v in the A-portion of the state σ and then assigned to the variable x located at B resulting in the new state σ[x@B → v]. The same variable (say x) located at different participants are distinct (hence σ@A(x) and σ@B(x) may differ). Other rules for parallel, summation, recursion and restriction are omitted. As an example of reduction, consider, for instance: Buyer → Seller : quoteCh(ν s). Seller → Buyer : squote, 300, x. I with state σ. By (G-Init), we get (σ, (νs) Seller → Buyer : squote, 300, x. I ). Now, by rule (G-Com), this evolves into (σ[x@Buyer → 300], (νs) I ).
8
M. Carbone, K. Honda, and N. Yoshida
2.3
Session Types for Global Descriptions
We use a generalisation of session types [16]. The grammar of types follows. α ::= s Σi opi (θi ). αi | s Σi opi (θi ). αi | α1 | α2 | end | μt. α | t where θ, θ , . . . range over value types. α, α , . . . are session types. s Σi opi (θi ). αi is a branching input type at session channel s, indicating a process is ready to receive any of the (pairwise distinct) operators {opi }, each with a value of type θi ; s Σi opi (θi ). αi , a branching output type at s, is its exact dual. The type α1 | α2 is a parallel composition of α1 and α2 , abstracting parallel composition of two sessions. We take | to be commutative and associative, with end, the inaction type indicating session termination, being the identity. We demand session channels in α1 and α2 to be disjoint: this guarantees a linear use of session channels. t is a type variable, while μt.α is a recursive type, where μt binds free occurrences of t in α. In recursive types, we assume each recursion is guarded, i.e., in μt.α, α is an n-ary parallel composition of input/output types. Recursive types are regarded as regular trees in the standard way [13]. Note that session channels occur free in session types: this is necessary to allow multiple session channels to be used in parallel in a single session; with this, we can faithfully capture use cases of web services which exchange different data simultaneously, leading to a generalisation of session types in the literature. Let us show a simple example: s quote(int). end | s extra(string). end Here a participant is sending a quote (integer) at s and extra information about the product at s in a single session: without using distinct session channels, two communications can get confused and result in a type error. A typing judgment has the form Γ I : Δ where Γ is service typing and Δ session typing. The grammar of typings follows where A = B in s˜[A, B]: Γ ::= ∅ | Γ, ch@A : (˜ s)α | Γ, x@A : θ | Γ, X : Δ Δ ::= ∅ | Δ, s˜[A, B] : α | Δ, s˜ : ⊥ Each time a session is initiated, session channels need be freshly generated. Thus, the type of a service channel indicates a vector of session channels to be initially exchanged, in addition to how they are used. This is formulated by service type (˜ s)α where s˜ is a vector of pairwise distinct session channels covering all session channels in α, and α does not contain free type variables. In a service typing, ch@A : (˜ s)α says that ch is located at A and offers a service interface (˜ s)α; x@A : θ says that a variable x located at A may store values of type θ; finally, X : Δ says that when the interaction recurs to X, it should have the typing Δ. The typing uses a primary type assignment s˜[A, B] : α, which says that a vector of session channels s˜, all belonging to a same session between A and B, has the session type α when seen from the viewpoint of A. We write Γ1 , Γ2 (resp. Δ1 , Δ2 ) if there is no overlap between the free variables/names in Γ1 and Γ2 (resp. Δ1 and Δ2 ). The notation fsc(Δ) denotes the set of free service/session channels in Δ. In the following, we present the main typing rules:
Structured Communication-Centred Programming for Web Services
(G-TCom)
Γ I Δ, s˜ [A, B] : αj Γ e@A : θj Γ x@B : θj s ∈ {˜ s} j ∈ J Γ A → B : sopj , e, x. I Δ, s˜ [A, B] : s Σi∈J opi (θi ). αi
(G-TCom2 )
Γ I Δ, s˜ [B, A] : αj Γ e@A : θj Γ x@B : θj s ∈ {˜ s} j ∈ J Γ A → B : sopj , e, x. I Δ, s˜ [B, A] : s Σi∈J opi (θi ). αi
9
(G-TInit) Γ, ch@B : (˜ s)α I Δ, s˜ [B, A] : α Γ, ch@B : (˜ s)α A → B : ch(ν s˜). I Δ
(G-TPar) Γ I 1 Δ1 Γ I 2 Δ2 Γ I 1 | I 2 Δ1 • Δ2
Rule (G-TCom) states that, for typing an in-session communication of e from A to B at s with the choice opj , (1) the body I should assign αj to s˜ containing s; (2) the value e should be typed in the source (A) with θj ; and (3) the variable (parameter) x should be typed in the target (B) with the same type. Then, in the conclusion, a branching type is formed whose j-th branch consists of opj , θj and αi . In (G-TCom), the session type in focus is considered direction from the viewpoint of A. We may also regard it from the receiver’s viewpoint (B), which is its symmetric variant (G-TCom2 ). Rule (G-TPar) uses the linearity condition found in [16]. The the operator • is well-defined whenever the linearity condition is satisfied and is such that s˜[A, B] : α ∈ Δ1 • Δ2 iff either s˜[A, B] : α1 ∈ Δ1 , s} ∩ fsc(Δ2 ) = ∅; or s˜[A, B] : α2 ∈ Δ2 and α = α1 | α2 ; or s˜[A, B] : α ∈ Δ1 and {˜ its symmetric case. The other rules are standard [11]. As a simple example, we type the Buyer-Seller interaction I in Fig. 1 (a). Service channel quoteCh is assigned with the following service type: (s) s quote(integer). s ( accept(null). s details(string). end + reject(null). end ) Service channel deliveryCh has type (t) t details(string). end. Denoting two types by (s)α1 and (t)α2 , we have: quoteCh : (s) α1 , deliveryCh : (t) α2 I ∅. Similarly, we can type the interaction in Figure 1 (b) where we have recursion. The typing of the service channel quoteCh will differ in the ”rejection” branch, given as: (s) μt. s quote(integer). s ( . . . + reject(null). t). The typing system also incorporates subtyping based on an inclusion ordering on each type (formalised using simulation like in [13]). Theorem 1 (Subject Reduction). Assume Γ σ. Then Γ I Δ and (σ, I) → (σ , I ) imply Γ σ and Γ I Δ for some Δ s.t. fsc(Δ ) ⊂ fsc(Δ).
3 3.1
The End-Point Calculus Syntax and Dynamics
The end-point calculus is the π-calculus [18] extended with sessions [16] as well as locations and store [10]. P, Q, . . . denote processes, M, N, . . . networks. P ::= ! ch(˜ s). P | ch(ν s˜). P | s Σi opi (yi ). Pi | s ope. P | x := e. P | if e then P1 else P2 | P1 ⊕ P2 | P1 | P2 | (νs) P | X | μX. P | 0 N ::= A[ P ]σ
|
N1 | N2
|
(νs) N
|
10
M. Carbone, K. Honda, and N. Yoshida
The first two processes describe session initiations; the next two, in-session communications (where yi in the first construct, branching input, is not bound in Pi , and {opi } should be pairwise distinct). Next, x := e. P assigns a value v to x in its store then continues as P . The rest is standard. Networks are parallel composition of participants, where a participant is of the shape A[ P ]σ , with A being the name of the participant, P its behaviour, and σ its local state. We often omit σ when irrelevant. The reduction semantics for the end-point calculus follows the π-calculus. Below we list the three key rules (other rules are found in [11]). (E-Init) A[ ! ch(˜ s). P | P ]σ | B[ ch(ν s˜). Q | Q ]σ → (ν s˜) (A[ ! ch(˜ s). P | P | P ]σ | B[ Q | Q ]σ ) (E-Com) A[ s Σi opi (xi ). Pi | P ]σ | B[ s opj e. Q | Q ]σ → A[ Pj | P ]σ[xj →v] | B[ Q | Q ]σ
(E-Asgn) A[ x := e. P | P ]σ → A[ P | P ]σ[x→v]
(σ e ⇓ v) (σ e ⇓ v)
(E-Init) defines the session initiation: two participants A and B will synchronise to start a session, ! ch(˜ s). P denoting a service and ch(ν s˜). Q a request. It will result in sharing fresh session names s˜ local to A and B. These session names are then used in (E-Com) for communication. In (E-Com), communicated values are assigned to local variables, rather than substituted, for having the correspondence with the global calculus. (E-Asgn) updates a local store. 3.2
Session Typing of End-Point Calculus
In the end-point calculus, we use two typing judgements, Γ A P Δ (where P is typed as a behaviour for A) and Γ M Δ. Γ (service typing) and Δ (session typing) are given as before except (1) Γ adds ch@A : (˜ s)α; and (2) we replace s˜[A, B] : α by s˜@A : α. The selected typing rules are given below. (E-TB)
j ∈ J K ⊆ J s ∈ s˜ Γ xj : θj Γ A Pj Δ · s˜@A : αj Γ s Σi∈J opi (xi ).Pi Δ · s˜@A : s Σi∈K opi (θi ). αi
(E-TS) (E-TServ)
j ∈ J ⊆ K Γ e : θj Γ A P Δ · s˜@A : αj Γ A s opj e.P Δ · s˜@A : s Σi∈K opi (θi ). αi
Γ A P s˜@A : α Γ, ch@A : (˜ s)α A ! ch(˜ s). P ∅
(E-TReq) s)α A P Δ · s˜@A : α Γ, ch@B : (˜ Γ, ch@B : (˜ s)α A ch(ν s˜).P Δ
(E-TB) is for branching input. The resulting typing can have less branches than the real process, so that the process is prepared to receive any operator specified in the type. (E-TS) is its dual: the typing can have more branches than the real process, so that the process invokes at most those operators specified in the typing. Combining (E-TB) and (E-TS), an output never invokes a non-existent option in the input. (E-TServ) is for the server side of initialisation. In the premise, the session typing should not have session channels other than the target of initialisation: this prevents free session channels from occurring under the replicated input, thus guaranteeing their linear usage. By our
Structured Communication-Centred Programming for Web Services
11
convention, neither ch nor ch occurs in Γ in the conclusion. The output side of initialisation (E-TReq) is analogous, except it does not need the linearity constraint. The remaining rules are standard [16]: for example, with parallel composition, we ensure that an input of type α is composed with an output of its dual. We recall our running example, Figure 1 (a) in § 2.1. An end-point representation of this example for Buyer may be written: Buyer[ quoteCh(νs). s quote(x). (s accept. s details(y). 0 ⊕ s reject. 0) ] Above Buyer[P ] indicates a participant (a named agent) whose behaviour is given by the process P . The Seller’s code is given as: Seller[! quoteCh(s). s quote300. s (accept. deliveryCh(νt). t delivery(x). s deliveryx. 0 + reject. 0)] The end-point representation for Shipper is given similarly. These end-point descriptions do not directly and explicitly describe how interaction proceeds globally, which may often be the central concern of communication-centred applications designers/users. However, they precisely represent local communication behaviours which give rise to global interactions. The two service channels quoteCh and deliveryCh are replicated and ready to be invoked, following (SCP). We can type these processes using the service types (s)α1 and (t)α2 from § 3.3. The type of the seller becomes (writing P for its process): quoteCh : (s) α1 , deliveryCh : (t) α2 Seller[ P ]σ ∅. Note that the service channel deliveryCh is overlined, indicating the direction: this is because the input channel is located at the shipper’s. In the global calculus, a channel is always used for both input and output, so there is no such need. Similarly we may type the end-point processes for Buyer and Seller with recursion as in Figure 1 (b), as: Buyer[ μX. quoteCh(νs). s quote(x). if reasonable(x) then s accept. s details(y). 0 else s reject. X ]
|
Seller[ ! quoteCh(s). μX. s quote300. s (accept. deliveryCh(νt). t delivery(x). s deliveryx. 0 + reject. X)] We may also note, both in its term and in its typing, the end-point process for Shipper in Figure 1 (b) does not involve recursion, since its session is selfcontained inside a recursion. Theorem 2 (subject reduction). If Γ N Δ and N → N then Γ N Δ. A significant corollary of this result is the lack of communication error in the sense that typed processes never invoke missing operations and never communicate ill-typed values. This is fundamental for end-point processes since they describe inputs and outputs separately, unlike global descriptions.
12
4 4.1
M. Carbone, K. Honda, and N. Yoshida
The End-Point Projection Three Principles for End-Point Projections
A theory of EPP assigns to global descriptions the precise and transparent operational content as communicating processes. This task becomes subtle because a global calculus allows descriptions that do not make sense at end-points, i.e. as distributed communicating processes. Below we discuss three issues in this regard one by one, together with the corresponding disciplines which disallow them. Connectedness. Consider the following code snippet for global description. Buyer → Seller : ch1 (ν s). Shipper → Depot : ch2 (ν t) Remembering “.” indicates sequencing, Shipper is described as contacting Depot only after Buyer has performed a request to Seller in the description above. Implementing this behaviour as distributed processes demands that Shipper be notified once the first communication is performed by message passing, for instance in: Buyer → Seller : ch1 (ν s). Seller → Shipper : ch(ν s ). Shipper → Depot : ch2 (ν t) Observe the second description is directly realisable as end-point processes, while the first one is not. Even if one may informally write down the first description, it is the second one which can have a precise correspondence with end-point behaviour. Thus we preclude descriptions like the first one, by demanding each participant acts only as a result of its local event. We call this principle connectedness. Connectedness is simply defined by tracking active/passive participants of each action, as formally given in [11]. Informally, for each A, A’s sending action or its self-contained action (e.g. assignment and evaluation of a conditional guard) should always be immediately preceded by A’s receiving action or its another self-contained action. Connectedness is closed under reductions. Well-threadedness. The next condition is also about causality, but a slightly more subtle one. Consider the following connected interaction: Buyer → Seller : ch1 (ν s). Seller → Shipper : ch2 (ν t). Shipper → Buyer : ch3 (ν u). Buyer → Seller : sop, v, x. I We claim that this global code (regardless of I) is unrealisable at end-points. In fact, the first action tells us that there is a thread in Buyer which invokes Seller. This thread becomes inactive in the second line where a service at ch3 in Buyer is invoked. In the final line, Buyer communicates to Seller via s opened in the initial action. Written in the end-point calculus: Buyer[ Seller[ Shipper[
ch1 (νs). s opv. P | ! ch3 (t). Q ! ch1 (s). ch2 (νt). s op(x). Q ! ch2 (t). ch3 (νu). R
]σ1 ]σ2 ]σ2
| |
Structured Communication-Centred Programming for Web Services
13
The first process of Buyer invokes ch1 and sends v with operation op in the same session, while the second is a service at ch3 (by SCP this channel should be ready to receive invocations). s opv cannot be located under ch3 , as it belongs to a session s. When the three processes interact, first, Buyer invokes ch1 , then Seller invokes ch2 of Shipper: up to here the interaction follows the original global scenario. However, at this point, the action s op(x) is free to react with its dual action s opv, before Shipper invokes Seller’s other component, the service at ch3 . Thus the sequencing in the global description gets violated. The fundamental issue in the example above is that the given global code assumes a false, or unrealisable, dependency among actions: the last action belongs to a thread which started from the invocation of ch1 , while the description says it should take place as a direct result of the third action at a distinct thread which has been opened by the invocation at ch3 . If a global description is free from such false dependency, we say it is well-threaded. For the formal definition, we first annotate a global interaction with identifiers for threads. Annotated interactions, denoted by A, A , . . ., are given by the following grammar. A ::=
Aτ1 → B τ2 : ch(ν s˜). A | x@Aτ := e. A | A1 |τ A2 | μτ X A . A | XτA | Aτ1 → B τ2 : sop, e, y. A | A1 +τ A2 | if e@Aτ then A1 else A2 | 0
where τi ∈ N (called thread) and τ1 = τ2 in the first two lines. Our task is to find a notion of “consistent annotation” so that causality specified globally is precisely realisable locally. We demand: if an input is annotated by τ then its directly succeeding output is annotated by τ again, similarly for self-contained actions; that two actions by A in the same session are annotated by the same thread; and that the input of session initiation is always given a fresh thread. We say I is well-threaded when it is connected and has a consistent annotation. If I is well-threaded and has no free session channels, it has a primary annotation from which all of its consistent annotations are derivable [11, §14, Prop. 11]. As an example, consider the following annotated interaction. Buyerτ1 → Sellerτ2 : ch1 (ν s). Sellerτ3 → Shipperτ4 : ch2 (ν t). Shipperτ5 → Buyerτ6 : ch3 (ν u). Buyerτ7 → Sellerτ8 : sop, v, x. I
By the first two conditions, we have τ1 = τ7 and τ6 = τ7 , hence τ6 = τ1 , which violates the third condition. So this is not well-threaded. But the following annotated interaction is well-threaded: Buyer1 → Seller2 : ch1 (ν s). Seller2 → Buyer3 : ch2 (ν t). Buyer3 → Seller2 : top1 , v1 , x. Seller2 → Buyer1 : sop2 , v2 , y. 0
and in fact gives rise to the following correct end-points. Buyer[ ch1 (νs). s op2 v2 .0 | ! ch2 (t). t op1 (x). 0 Seller[ ! ch1 (s). ch2 (νt). t op1 v1 .s op(y). 0
] ]
|
There is a type discipline accepting all and only well-threaded interactions, from which we can derive a sound and complete algorithm for checking wellthreadedness and for calculating, if any, (primary) consistent annotations [11].
14
M. Carbone, K. Honda, and N. Yoshida
Coherence. The final principle concerns consistency of descriptions of a behaviour belonging to the same service. We first note that it is often necessary to merge threads to obtain the final end-point behaviour of a single service. Consider the parallel composition: Buyer → Seller : ch(ν s). Seller → Buyer : sop1 , e, x1 . I1 | Buyer → Seller : ch(ν t). Seller → Buyer : top2 , e, x2 . I2
where op1 = op2 . Above, Buyer invokes Seller’s service at ch twice in parallel. Now consider constructing the code for this service at channel ch: we need to merge these two threads into one end-point behaviour. But the global description is contradictory, since in one invocation the service reacts with op1 , while in the other the service reacts with op2 . As can be observed from this example, in a global description, the description of the behaviour of a single end-point can be scattered in different portions of the code. Hence we need to guarantee, in EPP, that these scattered descriptions are mergeable. This mergeablity condition is called coherence. Let A be consistently annotated. We list the key rules defining the partial operation TP(A, τ ) (see [11] for a full definition): def
TP(Aτ1 → B τ2 : b(ν s˜). A, τ ) =
def
TP(Aτ1 → B τ2 : sopi , ei , xi . A, τ ) =
def
TP(A1 +τ A2 , τ ) =
⎧ ⎨ b(ν s˜). TP(A, τ1 ) if τ = τ1 ! b(˜ s). TP(A, τ2 ) if τ = τ2 ⎩ TP(A, τ ) otherwise ⎧ ⎨ s ope. TP(A, τ ) if τ = τ1 s opi (xi ). TP(A, τ ) if τ = τ2 ⎩ TP(A, τ ) otherwise TP(A1 , τ ) ⊕ TP(A2 , τ ) if τ = τ TP(A1 , τ ) TP(A2 , τ ) otherwise
In the third rule, is a partial commutative binary operator on processes such that: (1) if P is a prefixed process with a service channel as its subject, then def
P 0 = 0 P = P ; and (2) s Σi∈J opi (yi ). Pi s Σi∈K opi (yi ). Qi = Σi∈J∩K opi (yi ). (Pi Qi ) + Σi∈J\K opi (yi ). Pi + Σi∈K\J opi (yi ). Qi with Pi Qi , where P Q says that the operation P Q is defined (thus we demand overlapping branches be mutually consistent); and (3) otherwise P Q is defined congruently up to ≡. The partial operation P Q is called merging operation. Given an annotated interaction A, we write τ1 ≡A τ2 whenever τ1 and τ2 in A belong to the same service channel. We say that A is coherent if it is consistently annotated (hence well-threaded) and TP(A, τ ) is well-defined for each τ , and moreover satisfies: for each pair of threads τ1 , τ2 in A such that τ1 ≡A τ2 , it holds that TP(A, τ1 ) TP(A, τ2 ) is defined. Coherence of a welltyped interaction is decidable [11, §15, Prop.13]. With coherence as the final principle, we can now project a well-structured global description to end-point processes that precisely realise the original global scenario (the projection is essentially invariant under different consistent annotations [11, §16.1, Prop.14]). Formally, let I be a restriction-free and coherent interaction with free session names s˜ and let A be one of its consistent annotations. Then the end point projection of (ν s˜) A under σ is defined as: EPP((ν s˜) A, σ)
def
=
(ν s˜) ΠA∈part(A) A[ Π[τ ] τ ∈[τ ] TP(A, τ ) ]σ
Structured Communication-Centred Programming for Web Services
15
where ΠPi denotes the parallel composition, part(A) denotes the set of participants mentioned in A and [τ ] denotes the equivalence class (≡A ) of τ . 4.2
Pruning and Main Theorem
Consider an interaction which is composed from two branches whose first two interactions are Buyer → Seller : ch(ν s). Seller → Buyer : sack and then in one branch we have Buyer → Seller : sgo and in the other Buyer → Seller : sstop. We then obtain its EPP: Buyer[ch(νs).sack.sgo ⊕ ch(νs).sack.sstop] | Seller[! ch(s).sack.s(go+stop)]
Let us reduce the original global description, which, by dropping one branch, leads to Seller → Buyer : sack. Buyer → Seller : sgo. This EPP is: Buyer[ch(νs).s ack.s go] | Seller[! ch(s).s ack.s go)]
Now we compare this end-point process with the reductum of the original EPP before, which is Buyer[ch(νs).sack.sgo] | Seller[! ch(s).sack.s(go + stop)], where Seller has a redundant, useless branch “stop”. This example shows that reduction in a global description can lose information which is still kept in the corresponding reduction in its EPP. This motivates the asymmetric relation of pruning P ≺ Q, which indicates that if we cut off such unnecessary branches and replication from Q then we obtain P (see [11] for a formal definition). If P ≺ Q, then P and Q are strong bisimilar under the minimal typing of P . The main result of the paper follows. Below, by abuse of notation, I denotes consistently annotated interaction. ≡μ is the extension of ≡ with the folding/unfolding of recursion. The proof is found in [11, §16.2–5]. (1) implies the lack of communication errors for the result of EPP. Theorem 3 (end-point projection). Let I be coherent, Γ I Δ and Γ σ: (1) (type preservation) If Γ I ∅ and Γ σ, then Γ EPP(I, σ) ∅. (2) (soundness) If EPP(I, σ) → N then there exists (I , σ ) such that (σ, I) → (σ , I ) and EPP(I , σ ) ≺ ≡μ N . (3) (completeness) If (σ, I) → (σ , I ) then EPP(I, σ) → N s.t. EPP(I , σ ) ≺ N .
5
Extensions and Future Work
Channel passing is a practically useful extension for business protocols, for example in the scenarios where participants need to send links to other participants. A typical example is when Buyer wants to buy from Seller, but Buyer does not know Seller’s address (service channel) on the net. The only information Buyer has is a service channel of DirectoryService, which will send back the address of Seller to Buyer which in turn interacts with Seller through the obtained channel. Can we have a consistent EPP theory with unknown participants and channels? This has been an open problem left in WS-CDL’s current specification (which allows
16
M. Carbone, K. Honda, and N. Yoshida
channel passing only for fixed participants). A possible extension of the EPP theory to channel passing, together with the treatment of other useful additional constructs, is discussed in [11]. Another interesting future topic is relaxations of the well-formedness principles while maintaining a sound EPP theory, on which some ideas are also discussed in [11]. The EPP theory has been developed with practical use in mind. There are several engineering scenes where the theory and its extensions may be useful. – Code generation. We can create a complete distributed application by projecting a detailed global description to each of its end-points. – Prototype generation. Projection can also be used for generating a skeleton code for each end-point which only contains basic communication behaviour, to be elaborated to full code. This is already used in [19]. – Use of conformance. A team of programmers initially agree on a shared global specification for communications among end-points: during/after programming, each programmer can check if her/his code conforms to the specification by conformance checking against projection. The conformance scheme is useful in other scenes, for example when we wish to check the usability of an existing service/library in a given global description. – Runtime monitoring, testing and debugging. At runtime, each end-point can check if ongoing communications at his/her site conform to the global description by checking against its projection to that end-point. The monitoring can also be used for debugging and testing existing code. Further, many static analyses/logical validation methods would become available for a global description from their well-developed end-point counterpart. The present work is intended as an initial trial towards a well-founded framework for communication-centred programming based on two distinct, and mutually complementary, descriptive paradigms, underpinned by a theory of EPP. Acknowledgements. We thank Robin Milner for instigating and setting up the directions of our ongoing collaboration with W3C WS-CDL WG; the WG members, in particular Gary Brown, Steve Ross-Talbot and Nickolas Kavantzas for collaboration; and Joshua Guttman for his comments on an early version of the paper. This work is supported by EPSRC GR/T04236, GR/S55545, GR/S55538, GR/T04724, GR/T03208, GR/T03258 and IST2005-015905 MOBIUS.
References 1. Conversation with Steve Ross-Talbot. ACM Queue, 4(2), 2006. 2. Jos Baeten, Harm van Beek, and Sjouke Mauw. Specifying internet applications with DiCons. In SAC’01, pages 576–584. ACM Press, 2001. 3. Nick Benton, Luca Cardelli, and Cedric Fournet. Modern concurrency abstractions for C#. ACM Trans. Program. Lang. Syst., 26(5):769–804, 2004. 4. Martin Berger, Kohei Honda, and Nobuko Yoshida. Sequentiality and the π-calculus. In TLCA’01, volume 2044 of LNCS, pages 29–45, 2001.
Structured Communication-Centred Programming for Web Services
17
5. K. Bhargavan, C. Fournet, and A. Gordon. Verified reference implementations of WS-Security protocols. In WS-FN’06, LNCS, 2006. 6. Eduardo Bonelli, Adriana B. Compagnoni, and Elsa L. Gunter. Correspondence assertions for process synchronization in concurrent communications. JFP, 15(2):219–247, 2005. 7. S´ebastien Briais and Uwe Nestmann. A formal semantics for protocol narrations. In TGC, volume 3705, pages 163–181, 2005. 8. Nadia Busi, Roberto Gorrieri, Claudio Guidi, Roberto Lucchi, and Gianluigi Zavattaro. Choreography and orchestration conformance for system design. In Coordination, volume 4038 of LNCS, pages 63–81, 2006. 9. M. Carbone, K. Honda, and N. Yoshida. A calculus of global interaction based on session types. In DCM ’06, ENTCS, 2006. 10. M. Carbone, M. Nielsen, and V. Sassone. A calculus for trust management. In FSTTCS ’04, volume 3328 of LNCS, pages 161–173. Springer, 2004. 11. Marco Carbone, Kohei Honda, Nobuko Yoshida, Robin Milner, Gary Brown, and Steve Ross-Talbot. A theoretical basis of communication-centred concurrent programming. To be published by W3C. Available at www.dcs.qmul.ac.uk/ ∼carbonem/cdlpaper, 2006. 12. Mariangiola Dezani-Ciancaglini, Dimitris Mostrous, Nobuko Yoshida, and Sophia Drossopoulou. Session Types for Object-Oriented Languages. In ECOOP’06, volume 4067 of LNCS, pages 328–352, 2006. 13. Simon Gay and Malco Hole. Subtyping for session types in the pi calculus. Acta Informatica, 42(2-3):191–225, November 2005. 14. Claudio Guidi, Roberto Lucchi, Gianluigi Zavattaro, Nadia Busi, and Roberto Gorrieri. SOCK: a calculus for service oriented computing. In ICSOC’06, volume 4294 of LNCS, 2006. 15. J. D. Guttman, F. J. Thayer, and L. D. Zuck. The faithfulness of abstract protocol analysis: message authentication. In CCS ’01, pages 186–195. ACM Press, 2001. 16. Kohei Honda, Vasco Vasconcelos, and Makoto Kubo. Language primitives and type disciplines for structured communication-based programming. In ESOP’98, volume 1381 of LNCS, pages 22–138, 1998. 17. Cosimo Laneve and Luca Padovani. Smooth orchestrators. In FoSSaCS’06, volume 3921 of LNCS, pages 32–46, 2006. 18. R. Milner, J. Parrow, and D. Walker. A calculus of mobile processes, I and II. Information and Computation, 100(1):1–40,41–77, September 1992. 19. PI4SOA. http://www.pi4soa.org. 20. Benjamin C. Pierce and David N. Turner. Pict: A programming language based on the pi-calculus. In Proof, Language and Interaction: Essays in Honour of Robin Milner. MIT Press, 2000. 21. S. Ross-Talbot and T. Fletcher. WS-CDL Primer. To be published by W3C, 2006. 22. D. Sangiorgi. The name discipline of uniform receptiveness. In ICALP’97, volume 1256 of LNCS, pages 303–313. Springer, 1997. 23. Kaku Takeuchi, Kohei Honda, and Makoto Kubo. An interaction-based language and its typing system. In PARLE’94, volume 817 of LNCS, pages 398–413, 1994. 24. W.M.P. van der Aalst. Inheritance of interorganizational workflows: How to agree to disagree without loosing control? Info. Tech. and Management, 2(3):195–231, 2002. 25. Vasco Vasconcelos, Ant´ onio Ravara, and Simon J. Gay. Session types for functional multithreading. In CONCUR’04, volume 3170 of LNCS, pages 497–511, 2004. 26. W3C WS-CDL Working Group. Web services choreography description language version 1.0. http://www.w3.org/TR/2004/WD-ws-cdl-10-20040427/.
CC-Pi: A Constraint-Based Language for Specifying Service Level Agreements Maria Grazia Buscemi1 and Ugo Montanari2 1
2
IMT Lucca Institute for Advanced Studies, Italy
[email protected] Dipartimento di Informatica, University of Pisa, Italy
[email protected]
Abstract. Service Level Agreements are a key issue in Service Oriented Computing. SLA contracts specify client requirements and service guarantees, with emphasis on Quality of Service (cost, performance, availability, etc.). In this work we propose a simple model of contracts for QoS and SLAs that also allows to study mechanisms for resource allocation and for joining different SLA requirements. Our language combines two basic programming paradigms: name-passing calculi and concurrent constraint programming (cc programming). Specifically, we extend cc programming by adding synchronous communication and by providing a treatment of names in terms of restriction and structural axioms closer to nominal calculi than to variables with existential quantification. In the resulting framework, SLA requirements are constraints that can be generated either by a single party or by the synchronisation of two agents. Moreover, restricting the scope of names allows for local stores of constraints, which may become global as a consequence of synchronisations. Our approach relies on a system of named constraints that equip classical constraints with a suitable algebraic structure providing a richer mechanism of constraint combination. We give reduction-preserving translations of both cc programming and the calculus of explicit fusions.
1 Introduction An important aspect of web services concerns client requirements and service guarantees with emphasis on Quality of Service, such as cost, performance, availability. These are commonly referred to as Service Level Agreements. SLAs between organisations are used in several areas of IT services, like hosting and communication services. The terms and conditions appearing in a SLA contract can be negotiated among the contracting parties prior to service execution. In this paper we present a simple calculus, called cc-pi calculus, for modeling processes able to specify QoS requirements and to conclude SLA contracts. The proposed language is also equipped with mechanisms for resource allocation and for joining different SLA requirements. Our approach combines basic features of name-passing calculi and of concurrent constraint (cc) programming.
Research supported by the EU IST-FP6 16004 Integrated Project S ENSORIA .
R. De Nicola (Ed.): ESOP 2007, LNCS 4421, pp. 18–32, 2007. c Springer-Verlag Berlin Heidelberg 2007
CC-Pi: A Constraint-Based Language for Specifying Service Level Agreements
19
Name-passing calculi, such as the pi-calculus [7], are a key paradigm of computation whose interaction mechanism may dynamically change the communication topology. Since the introduction of name-passing calculi, the notion of names has been recognised as crucial in theories for concurrency and mobility. The name-passing calculus we start with is the pi-F calculus [19]. The pi-F calculus is a variant of the pi-calculus [7], whose synchronisation mechanism is global and, instead of binding formal names to actual names, it yields explicit fusions, i.e. simple constraints expressing name equalities. For example, consider two processes uv.P and ux.Q, that are ready to make an output and an input on u, respectively. The interaction between these processes results in the explicit fusion of v and x. This fusion will also affect any further process R running in parallel: R | uv.P | ux.Q → R | P | Q | x = v. The restriction operator (x) can be used to limit the scope of a fusion, e.g.: R | (x)( uv.P | ux.Q) → R |(x)( P | Q | x = v). The cc-pi calculus extends the pi-F calculus by generalising explicit fusions like x = v to named constraints and by adding primitives for handling such constraints. While the informal concept of constraint is widely used in a variety of different fields, a very general, formal notion of constraint system has been introduced in the cc programming paradigm [15]. Actually, cc programming is a simple and powerful computing model based on a shared store of constraints that provides partial information about possible values that variables can take. Concurrent agents can act on this store by performing either a tell action (for adding a constraint, if the resulting store is consistent) or an ask action (for checking if a constraint is entailed by the store). As computation proceeds, more and more information are accumulated, thus the store is monotonically refined. Of the classical cc programming paradigm we keep the ask and tell constructs, but we extend/modify several other aspects. Maybe the most radical change is to give up the monotonicity requirement. While non-monotonicity was already present in the socalled linear cc programming [14], the introduction in our calculus of a retract construct, whose effect is to erase a previously told constraint, is strongly suggested by the need of allocating a resource and of deallocating the same resource. Of course monotonicity is the basis of several properties of cc programming, which thus do not hold in our framework. However whenever retracts are forbidden, or their usage is limited, some of the useful properties could be reinstated. We also introduce a check operation for verifying if a constraint is consistent with the store of constraints. Another important difference with respect to [15] is that we adopt a different concept of general, abstract constraint system. While the classical notion is equipped with an operation of entailment and a predicate of consistency, being based on Dana Scott’s information systems, we employ constraints forming c-semirings [2]. Roughly, a csemiring consists of a set equipped with two binary operations, the sum + and the product ×, such that + is associative, commutative and idempotent, × is associative and commutative and × distributes over +. A c-semiring is automatically equipped with a partial ordering a ≤ b, which means that a is more constrained than b, or, more interestingly, that a entails b, a b. The sum a + b chooses the worst constraint better than a and b, while the product a × b combines two constraints. The simplest c-semiring consists of the booleans with ∨ as + and ∧ as ×.
20
M.G. Buscemi and U. Montanari
Our c-semirings enjoy two kinds of nice properties. On the one hand they are very stable, since cartesian products, functional spaces and powerdomains of c-semirings are c-semirings. On the other hand c-semirings are quite adequate for modeling the socalled soft constraints, i.e. constraints which do not return only true or false, but more informative values instead. In fact it is easy to define c-semirings expressing fuzzy, hierarchical, or probabilistic values. Also, optimization algorithms work on the c-semiring consisting of the reals plus infinity with the operations of sum as × and min as +. Several efficient algorithms defined for ordinary, crisp constraints, like local propagation or dynamic programming, can be generalized to c-semirings. The former kind of properties is used in the paper to model networks of constraints for defining constraint satisfaction problems (CSPs) [8]. In fact, a single constraint, or even a network of constraints, is a function which, given an assignment of the variables to some domain D, returns a boolean, or rather a value in a generic c-semiring in the soft case. CSPs are a well-established formalism, especially studied in the artificial intelligence area, adequate to specify many kinds of real-life problems. In this paper we do not fully explore the latter aspect of c-semirings. However we consider it as extremely valuable and we plan to further exploit it in the future. In fact, we believe that a lot of non-functional requirements of QoS can be adequately modeled using c-semirings. The last, important difference with respect to [15] is that we handle variables, or rather names, in a very different way. In ordinary cc programming, constraints involving variables are seen as relations, in the style of Tarski’s cylindrical algebras. This interpretation is particularly visible in the axioms for hiding (written as ∃) and variable equality. Instead, in our named constraints we regard variables as ordinary names in the pi-calculus style. More precisely, names are introduced, as for pi-calculus agents [9], by means of permutation algebras. Operations of permutation algebras are permutations of names. A key concept of permutation algebras is the support of a value, that specifies the set of names such that the permutations which do not affect them do not modify the value. Thus, equipping a c-semiring with a permutation algebra structure allows to characterise the set of relevant, i.e. free, names of a constraint c as the support of c. Since the treatment of names is the same, we can handle constraints as processes, making both syntax and semantics of our calculus simpler and more natural. Besides ask, tell, retract and check there is another way in which agents can interact with the constraints existing in the system. In fact, synchronization of processes works like a global ask and tell construct. Two agents trying to perform an output xy and an input x y action can synchronize only if the constraint x = x is entailed by the store. The result of the synchronization is a new constraint y = y which is told to the store. Fusion y = y can modify deeply the store, depending on the actual constraint system. For instance it can allow two local constraints to interact, establishing a SLA between the two partners. However, if the resulting constraint is inconsistent, the synchronization is forbidden. It can become possible at some later time if some other agent performs a retract action which makes the store less constrained. The special role of fusions in the control mechanisms of our calculus requires their presence in all constraint systems. Thus, we propose named c-semirings with name fusions, or equalities, as the underlying data model of cc-pi calculus.
CC-Pi: A Constraint-Based Language for Specifying Service Level Agreements
21
In the paper, we show the generality of our approach by proposing three examples of named c-semirings, i.e. name equalities, Herbrand constraint systems, and soft CSPs, and we prove that they are effectively named c-semirings. We also show how our model can be applied in specifying and monitoring SLAs. Finally, we explore the expressiveness of our calculus by giving reduction-preserving translations of Pi-F and cc programming into cc-pi. A motivating example. Consider a service offering computing resources (e.g. units of CPUs of a given power) and suppose the service provider and a client want to reach a SLA. The provider PN , with N available resources and the client Cn requiring at least n resources can be specified in our framework as follows, being max the maximum number of resources that can be allocated to each client: PN = (x0 ) (tell (x0 = N).Q(x0 )) Q(x) = (v) (x ) (tell (x = x − v). tell (v ≤ max). cv. Q(x )). Cn = (y) (tell (y ≥ n). cy. τ. retract (y ≥ n). tell (y = 0) ). In words, PN first sets the initial number of resources to N and evolves to Q. Process Q creates a name v representing the resources available to a client and a non-negative name x counting the resources left after concluding a contract with the client; Q then adds the constraints x = x − v for setting the value of x and v ≤ max for imposing the bound max on v. Finally, Q signs the contract, i.e. it synchronises on a channel c with a client and, if the synchronisation succeeds, Q becomes ready to accept a new request. On the other side, Cn initially creates a local name y and places the constraint y ≥ n. Next, Cn tries to synchronise on a public port c with a server. In case of success, Cn makes some calculation involving the obtained resources, which is modelled as a silent action τ. Then, Cn releases the allocated resources by removing the above constraint on y (retract (y ≥ n)). Hence, a negotiation between PN and Cn begins with the two parties placing their constraints. PN and Cn can then synchronise (thus yielding the fusion of names v and y), if the resulting constraint system is consistent, i.e. if n ≤ min(N, max), as shown by the graph representation below. provider PN x0
x0 = N
v ≤ max
x
x = x0 − v
v
v=y
client Cn y
y≥n
Related work. Bacciu et al. [1] also propose a framework for specifying client requirements and provider guarantees on the offered services, along with negotiation mechanisms. Unlike our model, their approach relies on fuzzy sets rather than on csemirings. The process calculus introduced in [4] focuses on controlling and coordinating distributed process interactions respecting QoS parameters expressed as c-semiring values, but the model does not cover negotiations. The ρ-calculus [11] is a concurrent calculus with first-order constraints and high-order procedural abstraction. Akin to our approach, the ρ-calculus is parametric to a certain constraint system. In [18] the ρ-calculus has been encoded into the Fusion Calculus [13]. Thus, we expect that ρ can
22
M.G. Buscemi and U. Montanari
also be encoded into cc-pi. The pi+ -calculus [5] is an extension of the pi-calculus with constraint agents that can perform tell and ask actions. In contrast to our model, the constraint systems are first-order theories rather than algebraic structures and they do not support local stores. However, to our knowledge, none of the above languages has been applied for specifying SLA contracts. SLAng [17] and WSLA [6] are XML-based languages for defining SLAs at a lower level of abstractions. The elements of SLAng are also constraints on the behaviour of associated services and service clients, but their are specified in OCL. WSLA provides the ability to create new SLAs as functions over existing metrics. This is useful to formalise requirements that are expressed in terms of multiple QoS parameters. The semantics for expressions over metrics is not formally defined, though.
2 Background 2.1 C-Semirings We give here the basic definitions and properties concerning c-semirings. We refer to [2] for a more detailed treatment. Definition 1 (c-semiring). A constraint semiring (c-semiring) is a tuple A, +, ×, 0, 1 such that: (i) A is a set and 0, 1 ∈ A; (ii) + is commutative, associative, idempotent, 0 is its unit element and 1 is its absorbing element; (iii) × is associative, commutative and distributes over +. Let us consider the relation ≤ over A such that a ≤ b iff a + b = b. Then, it is possible to prove that (see [2]): (i) ≤ is a partial order; (ii) + and × are monotone on ≤; (iii) × is intensive on ≤: a × b ≤ a, b; (iv) 0 is its minimum and 1 its maximum; (v) A, ≤ is a complete lattice and, for all a, b ∈ A, + is the least upper bound operator, that is, a + b = lub(a, b). Moreover, if × is idempotent, then: + distributes over ×; A, ≤ is a distributive lattice and × is its greatest lower bound. Informally, the relation ≤ gives us a way to compare semiring values and constraints. Typical examples are the c-semiring for classical CSPs {False, True}, ∨, ∧, False, True, the c-semiring for fuzzy CSPs [0, 1], max, min, 0, 1, and the c-semiring for probabilistic CSPs [0, 1], max, ·, 0, 1. Since the Cartesian product of two c-semirings is still a c-semiring, it is also possible to model multicriteria optimization in this framework. 2.2 Permutation Algebras We denote by N the infinite, countable, totally ordered set of names and we use x, y, z . . . to denote names. We write x for the tuple of names x1 , . . . , xn . A substitution is a function σ : N → N . We denote by [y1 /x1 , · · · , yn /xn ] the substitution that maps xi into yi for i = 1, . . . , n and which is the identity on the other names. The identity substitution is denoted by id. A permutation is a bijective name substitution. We let ρ range over permutations. The kernel, K(ρ) of a permutation ρ is the set of the names that are changed by the permutation. A permutation algebra is defined by a carrier set and by a function defining how states are transformed by the finite-kernel permutations.
CC-Pi: A Constraint-Based Language for Specifying Service Level Agreements
23
An interesting example is given by the permutation algebra for the pi-calculus [9]. In that case, the carrier contains all the processes, up to structural congruence, and the interpretation of a permutation is the associated name substitution. The carrier of a permutation algebra can be partitioned into orbits, where two elements are in the same orbit if one can be obtained from the other by applying some permutation. To every element a a symmetry sym(a) can be associated, i.e. the group of all permutations ρ such that a = ρ(a). The support supp(a) of an element a is the smallest set of names such that all the permutations that do not modify them are in sym(a). Intuitively, the names in supp(a) are the free names of a, the permutations which do not modify them are obviously not influent on a. Indeed, the permutations exchanging names in supp(a) with names not in supp(a) are renamings of the free names and do not belong to sym(a), while the permutations in sym(a) which modify only names in the support are genuine self-transformations of the element. A permutation algebra is finite-support if each element of its carrier has finite support.
3 Named Constraints In this section, we propose a definition of named constraints that relies on the notion of named c-semirings. Essentially, a named c-semiring is a c-semiring enriched with a notion of name fusions, a permutation algebra A and a hiding operator (ν x. ). In particular, A allows to characterise the finite set of relevant names of each element of the c-semiring as the support supp(c) of c in A, and ν x. c makes a name x local in c, in the style of process calculi. A named constraint is an element of a named c-semiring with an associated support. Definition 2. We define (name) fusions as total equivalence relations on N with only finitely many non-singular equivalence classes. By x=y we denote the fusion with a unique non-singular equivalence class containing x and y. Definition 3. A named c-semiring C = C, +, ×, ν x. , ρ, 0, 1 is a tuple where: (i) x=y ∈ C for all x and y in N ; (ii) C, +, ×, 0, 1 is a c-semiring; (iii) C, ρ is a finite-support permutation algebra; (iv) ν x. : C → C, for each name x, is a unary operation; (v) for all c, d ∈ C and for all ρ the following axioms hold. (F USE ) x=y × c = x=y × [y/x] c (H IDE ) ν x. 1 = 1 ν x. ν y. c = ν y. ν x. c ν x. (c × d) = c × ν x. d if x ∈ supp(c) ν x. (c + d) = c + ν x. d if x ∈ supp(c) ν x. c = ν y. [y/x] c if y ∈ supp(c) (P ERM ) ρ 0 = 0 ρ 1 = 1 ρ (c × d) = ρ c × ρ d ρ (c + d) = ρ c + ρ d ρ (ν x. c) = ν x. (ρ c) if x ∈ / K(ρ)
The (F US ) axiom accounts for combining fusions and generic elements of c-semirings: x=y × c is equivalent to the product x=y × [y/x] c where y is replaced by x in c. The (H IDE ) and (P ERM ) axioms rule how the ν and ρ operations, respectively, interact with the operations of the c-semiring. The axioms (H IDE ) are inspired by the analogous structural congruence axioms for restriction in process calculi. Roughly, the c-semiring product × corresponds to the parallel composition of processes and constraint hiding is the
24
M.G. Buscemi and U. Montanari
counterpart of restriction on processes. The notion of support supp(c) associated with permutation algebras recalls the concept of free names in process calculi. According to the (P ERM ) axioms, ρ distributes with respect to × and +, and ρ is inactive on 0 and 1. Finally, the order of ρ and ν can be changed if x is not affected by ρ. We propose below three examples of named c-semirings aimed at showing the generality of our approach. Specifically, we consider c-semirings for name equalities, for Herbrand constraint systems and for soft CSPs. Note that these named c-semirings can be suitably composed to model more complex constraint systems. Example 1 (Name Equalitites). Let R be the set of all equivalence relation on N . We define CE as the tuple CE = C, +, ×, ν x. , ρ, 0, 1 such that: (i) C = R ; (ii) R1 + R2 = R1 ∩ R2 ; (iii) R1 × R2 = (R1 ∪ R2 ) , i.e. R1 × R2 is the reflexive, transitive, and symmetric closure of R1 ∪ R2 ; (iv) ν x. R = R + {(y, z) | y, z = x or y = z = x}, i.e. ν x. R is obtained from R by replacing the equivalence class of x with the singleton {x}; (v) ρR = {(ρ(x), ρ(y)) | (x, y) ∈ R}; (vi) 0 = (N × N ) and 1 = {(x, x) | x ∈ N }. Proposition 1. CE is a named c-semiring with idempotent product ×. Example 2 (Herbrand Constraint System). Given a signature Σ, let =E be an equational theory on TΣ (N ), plus the additional axioms: f (t1 , . . . ,tn ) =E f (t1 , . . . ,tn ) ti =E ti
i = 1, . . . , n
x =E t
t1 =E t2
[t/x]t1 =E [t/x]t2
and with the restrictions: x =E t(x) and f (t1 , . . . ,tn ) =E g(t1 , . . . ,tm ), where t(x) is any term different than x which contains x and f = g. We define CH as the tuple CH = C, +, ×, ν x. , ρ, 0, 1 where: (i) C is the set of the above-defined equational theories plus a bottom element ⊥; (ii) E1 + E2 = E1 ∩ E2 ; (iii) E1 × E2 is the unification of E1 and E2 , i.e. it is the smallest equational theory largest than or equal to E1 ∪ E2 , if it ¯ where t1 =E¯ t2 iff t1 = t2 or x does not occur exists, otherwise ⊥; (iv) ν x. E = E ∩ E, in t1 ,t2 ; (v) ρt1 =ρE ρt2 iff t1 =E t2 ; (vi) 0 = ⊥ and 1 = {(t,t) |t ∈ TΣ (N )}. Proposition 2. CH is a named c-semiring with idempotent product ×. Example 3 (soft CSPs). Given a domain D of interpretation for N , and a c-semiring S = A, +, ×, 0, 1, a soft constraint c can be represented as a function c = (N → D) → A associating to each variable assignment η = N → D a value of A. We define Csoft as the tuple Csoft = C, + , × , ν x. , ρ, 0 , 1 such that: (i) C is the set of all soft constraints over N , D and S; (ii) fusions x=y are defined as (x = y)η = 1 if η(x) = η(y), (x = y)η = 0 otherwise; (iii) (c1 + c2 )η = c1 η + c2 η; (iv) (c1 × c2 )η = c1 η × c2 η; (v) (ν x. c)η = ∑d∈D (cη[d/x]), where the assignment η[d/x] is defined, as usual, as η[d/x](y) = d if x = y, η(y) otherwise; (vi) (ρ c)η = cη with η(x) = η(ρ(x)); (vii) 0 η = 0 and 1 η = 1 for all η. Proposition 3. Csoft is a named c-semiring with idempotent product ×. Note that the support supp(c) of an element of Csoft coincides with the support of a functional constraint c as defined in [3].
CC-Pi: A Constraint-Based Language for Specifying Service Level Agreements
25
Definition 4 ((named) constraint). Given a named c-semiring with equalities A, +, ×, ρ, ν x. , 0, 1, a (named) constraint c is an element of A. We define here the notions of consistency and entailment of constraints. They are analogous to the corresponding definitions given by Saraswat and Rinard [15]. Below we abbreviate by (×C) the product c1 × . . . × cn with C = {c1 , . . . , cn }. Definition 5. Let A, +, ×, ρ, ν x. , 0, 1 be a named c-semiring and C ⊆ A be a set of constraints. C is consistent if (×C) = 0. Moreover, given a constraint c ∈ A, we say that C entails c, written C c, if (×C) ≤ c.
4 The cc-pi Calculus 4.1 Syntax We assume the countable set of names N and a set of process identifiers, ranged over by D. We let c range over constraints of an arbitrary named c-semiring C . Definition 6. The sets of prefixes and cc-pi processes are defined as follows: ˜ tell c ask c retract c check c P REFIXES π ::= τ xy ˜ xy U NCONSTRAINED U ::= 0 U|U ∑i πi .Ui (x)U D(y) ˜ P ROCESSES C ONSTRAINED P ROCESSES
P ::= U c P|P (x)P
The τ prefix stands for a silent action, the output prefix x y for emitting over the port x the message y and the input prefix x y for receiving over x a message and binding it to y. Prefix tell c generates a constraint c and puts it in parallel with the other constraints, if the resulting parallel composition of constraints is consistent; tell c is not enabled otherwise. Prefix ask c is enabled if c is entailed by the set of constraints in parallel. Prefix retract c removes a constraint c, if c is present. Prefix check c is enabled if c is consistent with the set of constraints in parallel. Unconstrained processes U are essentially processes that can only contain constraints c in prefixes tell c, ask c, retract c, and check c. As usual, 0 stands for the inert process and U |U for the parallel composition. ∑i πi .Ui denotes an external choice in which some guarded unconstrained process Ui is chosen when the corresponding guard πi is enabled. Restriction (x)U makes the name def
x local in U. A defining equation for a process identifier D is of the form D(x) ˜ =U with |x| ˜ = |y|. ˜ Constrained processes P are defined like unconstrained processes U but for the fact that P may have constraints c in parallel with processes. We simply write processes to refer to constrained processes. We extend the usual notion of free names of a process by stating that the set of free names of a constraint c is the support supp(c) defined in the previous section. Formally, the set fn(P) is inductively defined as follows:
26
M.G. Buscemi and U. Montanari fn(0) = 0/ fn(τ.U) = fn(U) fn(xy.U) ˜ = {x, y} ∪ fn(U) fn(xy.U) ˜ = {x, y} ∪ fn(U) fn(π.U) = supp(c) ∪ fn(U)
if π = tell c, ask c, retract c, check c def
˜ = fn(U) if D(x) ˜ =U fn(∑i πi .Ui ) = ∪i fn(πi .Ui ) fn(D(x)) fn(c) = supp(c) fn(P | Q) = fn(P) ∪ fn(Q) fn((x) P) = fn(P) \ {x}
We write n(P) for the set of names of a process P and bn(P) = n(P) \ fn(P) for the set of bound names; the usual notion of α-conversion on bound names holds. By σ P we denote the process obtained from P by simultaneously substituting each free occurrence of z in P by σ(z), possibly α-converting bound names. 4.2 Operational Semantics The reduction semantics, as usual, is given in two steps: the definition of a structural congruence, which rearranges processes into adjacent positions, and a notion of reduction relation that captures computations. Definition 7. We let structural congruence, ≡, be the least congruence over processes closed with respect to α-conversion and satisfying the following rules. (A X -PAR )
P|0 ≡ P
(A X -R ES )
(x)0 ≡ 0 (x)(y)P ≡ (y)(x)P
(A X -R EC )
P|Q ≡ Q|P
D(y) ˜ ≡ [y/ ˜ x]U ˜
(P|Q)|R ≡ P|(Q|R) P|(x)Q ≡ (x)(P|Q)
if x ∈ fn(P)
def
if D(x) ˜ =U
These axioms can be applied for reducing every process P into a normal form (x1 ) . . . (xn ) (C |U), where C is a parallel composition of constraints and U is an unconstrained process. Specifically, the axioms are applied from left to right in the following order: (A X -R ES ) for moving forward restrictions, and (A X -PAR ) for grouping constraints together, and (A X -R EC ). Definition 8. The reduction relation over processes → is the least relation satisfying the following inference rules. We use the following notations: C stands for the parallel composition of constraints c1 | . . . | cn ; C consistent means (c1 × . . . × cn ) = 0; C c if (c1 × . . . × cn ) ≤ c; C− c stands for c1 | . . . | ci−1 | ci+1 | . . . | cn if c = ci for some i, while C− c = C otherwise. ( TAU ) C | τ.U → C |U
( TELL ) C | tell c.U → C | c |U if C | c consistent
( ASK ) C | ask c.U → C |U
if C c ( RETRACT ) C | retract c.U → (C− c) |U
( CHECK ) C | tell c.U → C |U if C | c consistent y.U + ∑ πi .Ui | zw.V + ∑ πj .V j −→ C ∪ { y = w} |U |V ( COM ) C | x if | y| = |w|, C | y = w consistent and C x = z ( SUM )
( RES )
C | πi .Ui → P C | ∑ πi .Ui → P P → P (x) P → (x) P
( PAR )
( STRUCT )
P → P P |U → P |U P ≡ P
P → Q P→Q
Q ≡ Q
CC-Pi: A Constraint-Based Language for Specifying Service Level Agreements
27
The idea behind this reduction relation is to proceed as follows. First, rearranging processes into the normal form (x1 ) . . . (xn ) (C |U) by means of rule ( STRUCT ). Next, applying the rules ( TELL ), ( ASK ), ( RETRACT ), and ( CHECK ) for primitives on constraints and the rule ( COM ) for synchronising processes. Finally, closing with respect to parallel composition and restriction (( PAR ), ( RES )). More in detail, rule ( TELL ) states that if C | c is consistent then a process can place c in parallel with C, the process is stuck otherwise. Rules ( ASK ) and ( CHECK ) specify that a process starting with an ask c or, respectively, check c prefix evolves to its continuation if c is entailed by C or, respectively, if c |C is consistent, and that the process is stuck otherwise. By rule ( RETRACT ) a process can remove c if c is among the syntactic constraints in C; e.g., the process x=y | y = z | retract x = z.U does not affect x=y | y = z. In rules ( COM ), we write y = w to denote the parallel composition of fusions y1 = w1 | . . . , | yn = wn . Intuitively, two processes x y.P and zw.Q can synchronise if the equality of the names x and z is entailed by C and if the parallel composition C | y = w is consistent. Note that it is legal to treat fusions as constraints c over C , because we only consider named c-semiring with fusions, as noted in § 3. Rule ( PAR ) allows for closure with respect to unconstrained processes in parallel. This rule imposes to take into account all constraints in parallel when applying the rules for constraints and synchronisation. The present semantics does not specify how to solve at each step the constraint system given by the parallel composition of constraints C. However, in [10] it is shown how to apply dynamic programming to solve a CSP by solving its subproblems and then by combining solutions to obtain the solution of the whole problem. A visual representation of the problem is given by considering a graph where names are represented as nodes and constraints as arcs connecting the names involved in each constraint. Example 4. Let P and Q be the following two processes (we write c(x1 , . . . , xn ) for a constraint c with support supp(c) = {x1 , . . . , xn }): Q ≡ (w) tell c (w, v).yw.wv.0
P ≡ (x) (z) tell c(x).yx.xz.0
First, P and Q make their respective tell actions, which necessarily succeed as the constraint system is initially empty and the constraints c and c have different support. The graph representation of the resulting store of constraints is depicted in Fig. (a) below. Next, the two processes try to synchronise on port y and, according to rule ( COM ), the synchronisation takes place if the constraint combination c × c × x = w has a solution (Fig. (b)). Finally, the processes synchronise on port x, which is identified to w, thus yielding the fusion z = v (Fig. (c)). c
x
c
w
x
x=w
c
x
x=w
w
c
v
(a)
c
w
v
(b)
c z
z=v
v
(c)
Remark on retract. We have chosen to introduce the retract operation in the calculus in order to model non-monotonic constraint systems. For instance, an agent can
28
M.G. Buscemi and U. Montanari
perform a retract action for removing from a store a constraint that it had previously placed, thus enabling a tell operation which would be stuck otherwise or for releasing some resources after using them. Nevertheless, we can consider a version of the cc-pi calculus not including the retract primitive. For this fragment of the calculus the following additional axioms for relating parallel composition with product and restriction with hiding hold: c1 | c2 ≡ c1 × c2 and (x) c ≡ ν x. c. These axioms cannot be included in the original cc-pi calculus. In fact, a constraint c can be removed only if c is syntactically present in the store of constraints, while by applying product or hiding we generate new syntactic constraints. Note that the axioms for structural congruence in Def. 7 along with the above ones lead to processes into a normal form (x) ˜ (c |U), where U does not contain restrictions.
5 Specifying Service Level Agreements In this section we show how to model within our framework SLA contracts. The idea is to specify each SLA parameter as a variable and each SLA requirement or guarantee as a constraint that connects the involved variables. The parties are modelled as communicating processes. A constraint can be generated either by a single process or by the synchronisation of two processes that induces the identification of the communicated values. Note that our constraint-based approach allows to specify not only negotiations to reach a SLA contract, but also run-time checks that the contracts is not violated by the involved parties. Here we consider two examples that show how to apply our approach in modelling the SLA management system. The first example is centered around the basic mechanism for reaching and validating a contract. The second example extends the example given in the introduction with three clients. For simplicity, in both examples we take the constraint system to be a CSP by instantiating cc-pi with the named c-semiring Csoft , defined in Example 3, over the c-semiring S = {False, True}, ∨, ∧, False, True. This choice leads to solutions consisting of the set of tuples of legal domain values. We could generalise such constraint system with soft constraints by replacing S with an arbitrary c-semiring. 5.1 A Web Hosting Service Consider a service that offers different web hosting solutions, varying in cost and in bandwidth. Let P be the service provider and C be a client. Suppose that P obtains its bandwidth resources from a third party T . Before the execution of the service, P and C want to sign a SLA contract. The success of such an agreement also depends on the resources provided by T . This scenario is depicted below. Third party T
Service provider P
Client C x
x
cost ≤ max cost z
z
cost ≥ min cost cost = bw × 25Euros
y
y
bw ≤ max bw
CC-Pi: A Constraint-Based Language for Specifying Service Level Agreements
29
The interaction protocol is as follows. Each party imposes its SLA requirements or guarantees: P specifies the minimum cost min cost for the service and the cost per unit of bandwidth cost = bw · 25 Euros, C imposes a maximum cost max cost it can pay for the service, and T fixes the maximum bandwidth max bw that it can supply. Next, P communicates with C and with T on ports x and y, respectively. If the above constraints are consistent with each other, i.e. if c = ((min cost ≤ cost ≤ max cost) × (bw ≤ max bw) × (cost = bw · 25 Euros) × (cost = cost ) × (bw = bw = bw )) = 0, P and C can sign this contract c, by synchronising on z. Then, the service is executed and, assuming P provides C with a certain bandwidth act bw and the corresponding cost, the two parties validate the contract by performing check operations on their respective parameters. Note that the semantics of check enables this validation while not modifying the constraints of the contract. The specification of P, C, and T in cc-pi is as below and the whole system is represented by the parallel composition of the three parties. Pmin cost
≡
Pact bw
≡
Cmax cost C Tmax bw
≡ ≡ ≡
(bw)(cost)(tell ( (cost ≥ min cost) × (cost = bw · 25 Euros) ). xbw, cost. ybw. z.Pact bw ) xact bw, act bw · 25 Euros. check((act bw · 25 Euros = cost)× (act bw = bw)). z (bw )(cost )(tell (cost ≤ max cost). xbw , cost . z.C ) (b , c )(xb , c .check((b = bw ) × (c = cost )).z) (bw )(tell (bw ≤ max bw).ybw )
5.2 Resource Allocation We consider a slightly more complex scenario of the example given in the introduction with one provider PN and three clients Cn1 , Cn2 , and Cn3 . The graph representation of the constraint system resulting from the negotiation among the parties is depicted below. Each node represents a variable, and each constraint is modelled by a hyperedge connecting the variables involved in the constraint. provider PN x0 = N x1
x2
x0
v1 = y1
v1 ≤ max v1
x1 = x0 − v1 v2 ≤ max
v2 = y2 v2
y1
x3 = x2 − v3
v3
v3 = y3
y 1 ≥ n1
client Cn2 y2
x2 = x1 − v2 v3 ≤ max
x3
client Cn1
y 2 ≥ n2
client Cn3 y3
y 3 ≥ n3
Suppose that PN has allocated the resources y1 and y2 , with yi ≥ ni for i = 1, 2, to Cn1 and Cn2 , respectively. If Cn3 makes a request y3 ≥ n3 that PN is not able to satisfy because n1 + n2 + n3 ≥ N, the synchronisation between PN and Cn3 cannot take place until some resources yi , with yi ≥ n3 , are released.
30
M.G. Buscemi and U. Montanari
6 Expressiveness Results Encoding Pi-F calculus. We start by recalling the Pi-F calculus. For better relating the calculus with cc-pi, we present the Pi-F in the standard pi-calculus fashion rather than in the ‘commitment’ style [19]. Definition 9. The syntax of Pi-F processes is the same as the one given in Definition 6 minus summation, tell, ask, retract, and check and where constraints c are taken over the named c-semiring of equalities CE defined in Example 1. The structural congruence ≡F is as in Def. 7 plus the axioms below: x=x ≡F 0 x=y ≡F y=x x=y | y=z ≡F x=z | y=z (x) (x=y) ≡F 0 x=y | xz.P ≡F x=y | yz.P x=y | xz.P ≡F x=y | yz.P z=y | xz.P ≡F z=y | zy.P z=y | xz.P ≡F z=y | xy.P The reduction relation →F between processes is the smallest relation closed with respect to | , (x) and ≡F , which satisfies: x z.P | xw.Q →F P | Q | { z = w}
if | z| = |w|
Note that this syntax rules out processes containing name fusions under prefixes. This choice follows the analogous restriction applied in cc-pi, which avoids that two processes synchronise and, simultaneously, add some constrains to the store, thus possibly yielding an inconsistency. Definition 10. The translation [[ ]]F of pi-F processes into cc-pi processes is trivial: it maps pi-F constructs on their homonymous versions in cc-pi. Theorem 1. 1. If P →F Q then [[P]]F → [[Q]]F . 2. If [[P]]F → Q then P →F Q and Q ≡ [[Q]]F . By exploiting Theorem 1 and similar results proved in [19], it is also possible to give reduction-preserving translations of pi-calculus and Fusion [13] in cc-pi. Encoding cc programming. First, we briefly recall cc programming [15]. For the purpose of a more straightforward translation into cc-pi, we present a slightly modified version of the language. The basic ingredients of the cc programming constraint system are a set D of primitive constraints or tokens and a reflexive and transitive entailment relation . A constraint c in a constraint system P (D), is an element of P (D) , i.e. the closure of the powerset P (D) under entailment. The notion of consistency is given by identifying a set of inconsistent constraints I. The existential operator on constraints ∃x c is formalised in terms of cylindric algebras. Definition 11. The syntax of cc programming is defined as follows: P REFIXES π ::= tell c ask c ˜ P ROCESSES A ::= success π.A A | A ∑i πi .Ai ∃x,c A p(y)
CC-Pi: A Constraint-Based Language for Specifying Service Level Agreements
31
Following standard lines [16,12], we replace the classical hiding operator ∃x A with ∃x,c A that represents the evolution of a process of the form ∃x A , where c is the local constraint produced during the evolution. Moreover, p(y) ˜ is a procedure call, where p is the name of the procedure and y˜ is the tuple of actual parameters. The meaning of a process is given with respect to a set of procedure declarations of the form p(x) ˜ := A. An instantiation of p(x) ˜ := A is an object of the form p(y) ˜ := [y/ ˜ x] ˜ A. A configuration is a pair c, A with a constraint c representing the store and a process A. The reduction relation →C over configurations is the smallest relation given by the following rules. ( TELL ) c, tell c .A → (c ∪ c ) , A ( ASK ) c, ask c .A → c, A ( SUM )
c, πi .Ai → c , A c, ∑i πi .Ai → c , A
( PAR )
( PROC )
c, A → c , A c, B | A → c , B | A c, [y/ ˜ x]A ˜ → c , A
if (c ∪ c ) consistent
if c c ( PAR )
( HIDE ) and
c, A → c , A c, A | B → c , A | B c ∪ ∃x d, A → c ∪ ∃x d, A d, ∃x,c A → d, ∃x,c A
p(x) ˜ := A
c, p( y) → c , A
Definition 12. The translation [[ ]]F of cc processes in cc-pi is trivial: [[success]]C = 0 [[ask c.A]]C = ask c.[[A]]C [[tell c.A]]C = tell c.[[A]]C [[A | B]]C = [[A]]C | [[B]]C [[∃x,c A]]C = (x) (c | [[A]]C ) [[∑ πi .Ai ]]C = ∑[[πi .Ai ]]C [[p(y)]] ˜ C = D p (y) ˜ ˜ := A we give a defining equation where for each cc procedure declaration p(x) D p (x) ˜ = Q with [[A]]C = Q. Lemma 1. A constraint system P (D), can be represented as a named c-semiring C, +, ×, ν x. , ρ, 0, 1 with: (i) C = P (D) ∪ ⊥, where ⊥ corresponds to the set I; (ii) c1 + c2 = (c1 ∩ c2 ); (iii) c1 × c2 = (c1 ∪ c2 ) ; (iv) ν x. c = ∃x c and ρc = ρ c; (v) 0 = ⊥ and 1 = C. Theorem 2. 1. If c, A → c , A then c | [[A]]C → c | [[A ]]C . 2. If c | [[A]]C → P then c, A → c , A and P ≡ c | [[A ]]C . Note that cc programming handles the evolution of local stores of constraints through the rule ( HIDE ), while cc-pi (without retract) obtains the same effect by reducing processes into a normal form in which names are conveniently α-converted. This fact plays a crucial role in the proof of Theorem 2.
7 Concluding Remarks This paper is mainly focused on presenting the cc-pi calculus and on showing its flexibility as a constrained-based model for specifying SLA contracts and resource allocation. We foresee several directions for future work. We plan to consider a distributed
32
M.G. Buscemi and U. Montanari
version of the calculus by equipping, e.g., processes with locations and by limiting the synchronous behavior of processes and constraints to a single locality. It would also be interesting to study suitable mechanisms for assuring transactional and security properties of process executions, e.g. by enforcing that only the process which has told a constraint can retract it. We also intend to further study the ability of c-semirings to model soft constraints to express nonfunctional properties of SLAs. Acknowledgments. We thank the anonymous referees for helpful comments.
References 1. A. Bacciu, A. Botta, and H. Melgratti. A fuzzy approach for negotiating quality of services. In Proc. TGC ’06. To appear. 2. S. Bistarelli, U. Montanari, and F. Rossi. Semiring-based constraint satisfaction and optimization. Journal of the ACM, 44(2):201–236, 1997. 3. S. Bistarelli, U. Montanari, and F. Rossi. Soft concurrent constraint programming. ACM Trans. Comput. Logic, 7(3):563–589, 2006. 4. R. De Nicola, G. Ferrari, U. Montanari, R. Pugliese, and E. Tuosto. A process calculus for QoS-aware applications. In Proc. COORDINATION’05, volume 3454 of Lect. Notes in Comput. Sci. Springer, 2005. 5. J. F. Diaz, C. Rueda, and F. Valencia. A calculus for concurrent processes with constraints. CLEI Electronic Journal, 1(2), 1998. 6. A. Keller and H. Ludwig. The WSLA framework: Specifying and monitoring service level agreements for web services. Jour. Net. and Sys. Manag., 11(1):57–81, 2003. 7. R. Milner, J. Parrow, and J. Walker. A calculus of mobile processes, I and II. Inform. and Comput, 100(1):1–40,41–77, 1992. 8. U. Montanari. Networks of constraints: fundamental properties and application to picture processing. Information Science, 7:95–132, 1974. 9. U. Montanari and Pistore M. Structured coalgebras and minimal hd-automata for the picalculus. Theoret. Comput. Sci, 340(3):539–576, 2005. 10. U. Montanari and F. Rossi. Constraint relaxation may be perfect. Artif. Intell., 48(2):143– 170, 1991. 11. J. Niehren and M. Mueller. Constraints for free in concurrent computation. In Proc. Asian ’95, volume 1023 of Lect. Notes in Comput. Sci. Springer, 1995. 12. M. Nielsen, C. Palamidessi, and F. Valencia. On the expressive power of temporal concurrent constraint programming languages. In Proc. PPDP’02. ACM, 2002. 13. J. Parrow and B. Victor. The fusion calculus: Expressiveness and symmetry in mobile processes. In Proc. LICS’98. IEEE, Computer Society Press, 1998. 14. V. Saraswat and P. Lincoln. Higher-order linear concurrent constraint programming, 1992. Technical Report, Xerox Parc. 15. V. Saraswat and M. Rinard. Concurrent constraint programming. In Proc. POPL’90. ACM Press, 1990. 16. V. Saraswat, M. Rinard, and P. Panangaden. Semantic foundations of concurrent constraint programming. In Proc. POPL’91. ACM Press, 1991. 17. J. Skene, D. Lamanna, and W. Emmerich. Precise service level agreements. In Proc. ICSE’04, 2004. 18. B. Victor and J. Parrow. Constraints as processes. In Proc. CONCUR’96, volume 1119 of Lect. Notes in Comput. Sci. Springer, 1996. 19. L. Wischik and P. Gardner. Explicit fusions. Theoret. Comput. Sci, 340(3):606–630, 2005.
A Calculus for Orchestration of Web Services Alessandro Lapadula, Rosario Pugliese, and Francesco Tiezzi Dipartimento di Sistemi e Informatica Universit`a degli Studi di Firenze
Abstract. We introduce COWS (Calculus for Orchestration of Web Services), a new foundational language for SOC whose design has been influenced by WS-BPEL, the de facto standard language for orchestration of web services. COWS combines in an original way a number of ingredients borrowed from wellknown process calculi, e.g. asynchronous communication, polyadic synchronization, pattern matching, protection, delimited receiving and killing activities, while resulting di erent from any of them. Several examples illustrates COWS peculiarities and show its expressiveness both for modelling imperative and orchestration constructs, e.g. web services, flow graphs, fault and compensation handlers, and for encoding other process and orchestration languages.
1 Introduction Web services are a successful instantiation of service-oriented computing (SOC), an emerging paradigm for developing loosely coupled, interoperable, evolvable systems and applications which exploits the pervasiveness of the Internet and its related technologies. Web services are autonomous, stateless, platform-independent and composable computational entities that can be published, located and invoked through the Web via XML messages. These very features foster a programming style based on service composition and reusability: new customized service-based applications can be developed on demand by appropriately assembling other existing, heterogeneous services. Service definitions are used as templates for creating service instances that deliver application functionality to either end-user applications or other instances. The loosely coupled nature of SOC implies that the connection between communicating instances cannot be assumed to persist for the duration of a whole business activity. Therefore, there is no intrinsic mechanism for associating messages exchanged under a common context or as part of a common activity. Even the execution of a simple request-response message exchange pattern provides no built-in means of automatically associating the response message with the original request. It is up to each single message to provide a form of context thus enabling services to associate the message with others. This is achieved by embedding values in the message which, once located, can be used to correlate the message with others logically forming a same stateful interaction ‘session’. To support the web service approach, many new languages, most of which based on XML, have been designed, like e.g. business coordination languages (such as WSBPEL, WSFL, WSCI, WS-CDL and XLANG), contract languages (such as WSDL and SWS), and query languages (such as XPath and XQuery). However, current software engineering technologies for development and composition of web services remain at This work has been supported by the EU project SENSORIA, IST-2 005-016004. R. De Nicola (Ed.): ESOP 2007, LNCS 4421, pp. 33–47, 2007. c Springer-Verlag Berlin Heidelberg 2007
34
A. Lapadula, R. Pugliese, and F. Tiezzi
the descriptive level and do not integrate such techniques as, e.g., those developed for component-based software development. Formal reasoning mechanisms and analytical tools are still lacking for checking that the web services resulting from a composition meet desirable correctness properties and do not manifest unexpected behaviors. The task of developing such verification methods is hindered also by the very nature of the languages used to program the services, which usually provide many redundant constructs and support quite liberal programming styles. Recently, many researchers have exploited the studies on process calculi as a starting point to define a clean semantic model and lay rigorous methodological foundations for service-based applications and their composition. Process calculi, being defined algebraically, are inherently compositional and, therefore, convey in a distilled form the paradigm at the heart of SOC. This trend is witnessed by the many process calculi-like formalisms for orchestration and choreography, the two more common forms of web services composition. Most of these formalisms, however, do not suit for the analysis of currently available SOC technologies in their completeness because they only consider a few specific features separately, possibly by embedding ad hoc constructs within some well-studied process calculus (see, e.g., the variants of -calculus with transactions [2,19,20] and of CSP with compensation [9]). Here, we follow a di erent approach and exploit WS-BPEL [1], the de facto standard language for orchestration of web services, to drive the design of a new process calculus that we call COWS (Calculus for Orchestration of Web Services). Similarly to WS-BPEL, COWS supports shared states among service instances, allows a same process to play more than one partner role and permits programming stateful sessions by correlating di erent service interactions. However, COWS intends to be a foundational model not specifically tight to web services’ current technology. Thus, some WS-BPEL constructs, such as e.g. fault and compensation handlers and flow graphs, do not have a precise counterpart in COWS, rather they are expressed in terms of more primitive operators (see Section 3). Of course, COWS has taken advantage of previous work on process calculi. Its design combines in an original way a number of constructs and features borrowed from well-known process calculi, e.g. asynchronous communication, polyadic synchronization, pattern matching, protection, delimited receiving and killing activities, while however resulting di erent from any of them. The rest of the paper is organized as follows. Syntax and operational semantics of COWS are defined in Section 2 where we also show many illustrative examples. Section 3 presents the encodings of several imperative and orchestration constructs, while Section 4 presents the encoding of the orchestration language Orc [28]. Finally, Section 5 touches upon comparisons with related work and directions for future work.
2 COWS: Calculus for Orchestration of Web Services The basic elements of COWS are partners and operations. Alike channels in [10], a communication endpoint is not atomic but results from the composition of a partner name p and of an operation name o, which can also be interpreted as a specific implementation of o provided by p. This results in a very flexible naming mechanism that allows a same service to be identified by means of di erent logic names (i.e. to play more than one partner role as in WS-BPEL). Additionally, it allows the names
A Calculus for Orchestration of Web Services
35
composing an endpoint to be dealt with separately, as in a request-response interaction, where usually the service provider knows the name of the response operation, but not the partner name of the service it has to reply to. This mechanisms is also suÆciently expressive to support implementation of explicit locations: a located service can be represented by using a same partner for all its receiving endpoints. Partner and operation names can be exchanged in communication, thus enabling many di erent interaction patterns among service instances. However, as in [25], dynamically received names cannot form the communication endpoints used to receive further invocations. COWS computational entities are called services. Typically, a service creates one specific instance to serve each received request. An instance is composed of concurrent threads that may o er a choice among alternative receive activities. Services could be able to receive multiple messages in a statically unpredictable order and in such a way that the first incoming message triggers creation of a service instance which subsequent messages are routed to. Pattern-matching is the mechanism for correlating messages logically forming a same interaction ‘session’ by means of their same contents. It permits locating those data that are important to identify service instances for the routing of messages and is flexible enough for allowing a single message to participate in multiple interaction sessions, each identified by separate correlation values. To model and update the shared state of concurrent threads within each service instance, receive activities in COWS bind neither names nor variables. This is di erent from most process calculi and somewhat similar to [29,30]. In COWS, however, interservice communication give rise to substitutions of variables with values (alike [29]), rather than to fusions of names (as in [30]). The range of application of the substitution generated by a communication is regulated by the delimitation operator, that is the only binder of the calculus. Additionally, this operator permits to generate fresh names (as the restriction operator of the -calculus [27]) and to delimit the field of action of the kill activity, that can be used to force termination of whole service instances. Sensitive code can however be protected from the e ect of a forced termination by using the protection operator (inspired by [8]). Syntax. The syntax of COWS, given in Table 1, is parameterized by three countable and pairwise disjoint sets: the set of (killer) labels (ranged over by k k ), the set of values (ranged over by v, v , . . . ) and the set of ‘write once’ variables (ranged over by x, y, . . . ). The set of values is left unspecified; however, we assume that it includes the set of names, ranged over by n, m, . . . , mainly used to represent partners and operations. The language is also parameterized by a set of expressions, ranged over by e, whose exact syntax is deliberately omitted; we just assume that expressions contain, at least, values and variables. Notably, killer labels are not (communicable) values. Notationally, we prefer letters p p when we want to stress the use of a name as a partner, o o when we want to stress the use of a name as an operation. We will use w to range over values and variables, u to range over names and variables, and d to range over killer labels, names and variables. Services are structured activities built from basic activities, i.e. the empty activity 0, the kill activity kill( ) , the invoke activity ! and the receive activity ? , by means of prefixing , choice , parallel composition , protection , delimitation [ ] and replication . Notably, as in the L [25], communication endpoints of receive
36
A. Lapadula, R. Pugliese, and F. Tiezzi Table 1. COWS syntax s :: kill(k) g :: 0
u u !¯e p o?w¯ s
g
s s
gg
s
[d] s
s
(services)
(input-guarded choice)
Table 2. COWS structural congruence (excerpt of laws) 0 s [d1 ] [d2 ] s
0 s [d2 ] [d1 ] s
s1
s [d] s [d] s2
s s 0 0 [d] s [d] 0 0 [d] (s1 s2 ) if d fd(s1 ) fk(s2 )
activities are identified statically because their syntax only allows using names and not variables. The decreasing order of precedence among the operators is as follows: monadic operators, choice and parallel composition. Notation ¯ stands for tuples of objects, e.g. x¯ is a compact notation for denoting the tuple of variables x1 xn (with n 0). We assume that variables in the same tuple are pairwise distinct. All notations shall extend to tuples component-wise. In the sequel, we shall omit trailing occurrences of 0, writing e.g. p o?w¯ instead of p o?w¯ 0, and use [d1 dn ] s in place of [d1 ] [dn ] s. The only binding construct is delimitation: [d] s binds d in the scope s. The occurrence of a namevariablelabel is free if it is not under the scope of a binder. We denote by fd(t) the set of names, variables and killer labels that occur free in a term t, and by fk(t) the set of free killer labels in t. Two terms are alpha-equivalent if one can be obtained from the other by consistently renaming bound namesvariableslabels. As usual, we identify terms up to alpha-equivalence. Operational Semantics. COWS operational semantics is defined only for closed services, i.e. services without free variableslabels (similarly to many real compilers, we consider terms with free variableslabels as programming errors), but of course the rules also involve non-closed services (see e.g. the premises of rules (del )). Formally, the semantics is given in terms of a structural congruence and of a labelled transition relation. The structural congruence identifies syntactically di erent services that intuitively represent the same service. It is defined as the least congruence relation induced by a given set of equational laws. We explicitly show in Table 2 the laws for replication, protection and delimitation, while omit the (standard) laws for the other operators stating that parallel composition is commutative, associative and has 0 as identity element, and that guarded choice enjoys the same properties and, additionally, is idempotent. All the presented laws are straightforward. In particular, commutativity of consecutive delimitations implies that the order among the di in [d1 dn ] s is irrelevant, thus in the sequel we may use the simpler notation [d1 dn ] s. Notably, the last law can be used to extend the scope of names (like a similar law in the -calculus), thus enabling communication of restricted names, except when the argument d of the delimitation is a free killer label of s2 (this avoids involving s1 in the e ect of a kill activity inside s2 ).
A Calculus for Orchestration of Web Services
37
Table 3. Matching rules
(x v) x v
(v v)
(w1 v1 ) 1
(w¯ 2 v¯ 2 ) 2
((w1 w¯ 2 ) (v1 v¯ 2 )) 1 2
To define the labelled transition relation, we need a few auxiliary functions. First, we exploit a function [[ ]] for evaluating closed expressions (i.e. expressions without variables): it takes a closed expression and returns a value. However, [[ ]] cannot be explicitly defined because the exact syntax of expressions is deliberately not specified. Then, through the rules in Table 3, we define the partial function ( ) that permits performing pattern-matching on semi-structured data thus determining if a receive and an invoke over the same endpoint can synchronize. The rules state that two tuples match if they have the same number of fields and corresponding fields have matching valuesvariables. Variables match any value, and two values match only if they are identical. When tuples w¯ and v¯ do match, (w¯ v¯ ) returns a substitution for the variables in w; ¯ otherwise, it is undefined. Substitutions (ranged over by ) are functions mapping variables to values and are written as collections of pairs of the form x v. Application of substitution to s, written s , has the e ect of replacing every free occurrence of x in s with v, for each x v , by possibly using alpha conversion for avoiding v to be captured by name delimitations within s. We use to denote the number of pairs in and 1 2 to denote the union of 1 and 2 when they have disjoint domains. We also define a function, named halt( ), that takes a service s as an argument and returns the service obtained by only retaining the protected activities inside s. halt( ) is defined inductively on the syntax of services. The most significant case is halt( s) s. In the other cases, halt( ) returns 0, except for parallel composition, delimitation and replication operators, for which it acts as an homomorphism. Finally, we define a predicate, noc( ), that takes a service s, an endpoint p o, a tuple of receive parameters w¯ and a matching tuple of values v¯ as arguments and holds true if either there are no conflicting receives within s (namely, s cannot immediately perform a receive activity matching v¯ over the endpoint p o), or p o?w¯ is the most defined conflicting receive. The predicate exploits the notion of active context, namely a service with a ‘hole’ [[ ]] such that, once the hole is filled with a service s, if the resulting term [[s]] is a COWS service then it is capable of immediately performing an activity of s. Formally, active contexts are generated by the grammar: :: [[ ]] g g s s Now, predicate noc(s p o w¯ v¯ ) can be defined as follows: ( s [[p o?w¯ s ]]
(w¯ v¯ ) )
[d]
(w¯ v¯ )
where s [[p o?w¯ s ]] means that s can be written as p o?w¯ s filling the hole of some active context . The labelled transition relation is the least relation over services induced by the rules in Table 4, where label is generated by the following grammar:
:: k
(p o) v¯
(p o) w¯
p o w¯ v¯
38
A. Lapadula, R. Pugliese, and F. Tiezzi Table 4. COWS operational semantics (po) w ¯
k
kill(k)
0 (kill) [[¯e]] v¯
p o?w¯ s
s (rec) g1
(inv)
(po)v¯
po xv¼ w¯ v¯
k
(delsub )
po w¯ v¯
d d()
s [[kill(d)]] k
s
s (del pass )
(po) w¯
s1
(po)v¯
s2
s2
s1 s2 s1
po w¯ v¯
s1
s1 s2 s1
s1
po w¯ v¯
s1 s2
(p o
(w¯ v¯ )
po w¯ v¯
noc(s2 p o w¯ v¯ )
s1 s2
(par pass )
(prot)
s
(com)
s1 s2 s1 s1 s2
w¯ v¯ ) k
s
noc(s1 s2 p o w¯ v¯ )
(parcon f )
s1 s2
(delkill )
[k] s [k] s
x v
[d] s
[d] s s1
(choice) s
s
s
s
s [x] s
s
s
g1 g2
p o!¯e
0
s
s
s s1
k
k
s1
(parkill )
s1 halt(s2 )
s1
s2
s2
s (cong)
s
s
In the sequel, we use d() to denote the set of names, variables and killer labels occurring in , except for p o w¯ v¯ for which we let d(p o w¯ v¯ ) d(), where d( x v) x v and d(1 2 ) d(1 ) d(2 ). The meaning of labels is as follows: k denotes execution of a request for terminating a term from within the delimitation [k] , (p o) v¯ and (p o) w¯ denote execution of invoke and receive activities over the endpoint p o, respectively, p o w¯ v¯ (if ) denotes execution of a communication over p o with receive parameters w¯ and matching values v¯ and with substitution to be still applied, and p o w¯ v¯ denote computational steps corresponding to taking place of forced termination and communication (without pending substitutions), respectively. Hence, a computation from a closed service s0 is a sequence of connected transitions of the form 3 1 2 s0 s1 s2 s3 where, for each i, i is either or p o w¯ v¯ (for some p o w¯ and v¯ ); services si , for each i, will be called reducts of s0 . We comment on salient points. Activity kill(k) forces termination of all unprotected parallel activities (rules (kill) and (parkill )) inside an enclosing [k] , that stops the killing e ect by turning the transition label k into (rule (delkill )). Existence of such delimitation is ensured by the assumption that the semantics is only defined for closed services.
A Calculus for Orchestration of Web Services
39
Sensitive code can be protected from killing by putting it into a protection ; this way, s behaves like s (rule (prot)). Similarly, [d] s behaves like s, except when the transition label contains d or when a kill activity for d is active in s and does not correspond to a kill activity (rule (del pass )): in such cases the transition should be derived by using rules (delkill ) or (delsub ). In other words, kill activities are executed eagerly. A service invocation can proceed only if the expressions in the argument can be evaluated (rule (inv)). Receive activities can always proceed (rule (rec)) and can resolve choices (rule (choice)). Communication can take place when two parallel services perform matching receive and invoke activities (rule (com)). Communication generates a substitution that is recorded in the transition label (for subsequent application), rather than a silent transition as in most process calculi. If more than one matching receive activity is ready to process a given invoke, then only the more defined one (i.e. the receive that generates the ‘smaller’ substitution) progresses (rules (com) and (parcon f )). This mechanism permits to correlate di erent service communications thus implicitly creating interaction sessions and can be exploited to model the precedence of a service instance over the corresponding service specification when both can process the same request. When the delimitation of a variable x argument of a receive is encountered, i.e. the whole scope of the variable is determined, the delimitation is removed and the substitution for x is applied to the term (rule (delsub )). Variable x disappears from the term and cannot be reassigned a value. Execution of parallel services is interleaved (rule (par pass )), but when a kill activity or a communication is performed. Indeed, the former must trigger termination of all parallel services (according to rule (parkill )), while the latter must ensure that the receive activity with greater priority progresses (rules (com) and (parcon f )). The last rule states that structurally congruent services have the same transitions. Examples. We end this section with a few observations and examples aimed at clarifying the peculiarities of our formalism. Communication of private names. Communication of private names is standard and exploits scope extension as in -calculus.1 Receive and invoke activities can interact only if both are in the scopes of the delimitations that bind the variables argument of the receive. Thus, to enable communication of private names, besides their scopes, we must possibly extend the scopes of some variables, as in the following example: [x] (p o? x s s ) [n] p o!n [n] [x] (p o? x s s [n] (s s ) x n
p o!n)
(n fresh)
po x n
Notice that the substitution x n is applied to all terms delimited by [x] , not only to the continuation s of the service performing the receive. This accounts for the global scope of variables and permits to easily model the delayed input of fusion calculus [30]. Protected kill activity. The following simple example illustrates the e ect of executing a kill activity within a protection block: [k] ( s1 1
s2
kill(k)
s3 )
s4
[k] s2
s4
The variant of -calculus closest to COWS is localised -calculus [25] and, indeed, in [21] we define an encoding that enjoys operational correspondence.
40
A. Lapadula, R. Pugliese, and F. Tiezzi
where, for simplicity, we assume that halt(s1 ) halt(s3 ) 0. In essence, kill(k) terminates all parallel services inside delimitation [k] (i.e. s1 and s3 ), except those that are protected at the same nesting level of the kill activity (i.e. s2 ). Conflicting receive activities. This example shows a persistent service (implemented by mean of replication), that, once instantiated, enables two conflicting receives: [x] ( p1 o? x s1 p2 o? x s2 ) [x] ( p1 o? x s1 p2 o? x s2 )
p1 o x v
p1 o!v p2 o!v s1 x v p2 o?v s2 x v p2 o!v
Now, the persistent service and the created instance, being both able to receive the same tuple v along the endpoint p2 o, compete for the request p2 o!v. However, our (prioritized) semantics, in particular rule (com) in combination with rule (parcon f ), allows only the existing instance to evolve (and, thus, prevents creation of a new instance):
[x] ( p1 o? x s1 p2 o? x s2 )
s1
x v
s2
x v
Message correlation. Consider now uncorrelated receive activities executed by a same instance, like in the following service:
[x] p1 o1 ? x[y] p2 o2 ?y s
The fact that the messages for operations o1 and o2 are uncorrelated implies that, e.g., if there are concurrent instances then successive invocations for a same instance can mix up and be delivered to di erent instances. If one thinks it right, this behaviour can be avoided simply by correlating successive messages by means of some correlation data, e.g. the first received value as in the following service:
[x] p1 o1 ? x[y] p2 o2 ?y x s
3 Modelling Imperative and Orchestration Constructs In this section, we present the encoding of some higher level imperative and orchestration constructs (mainly inspired by WS-BPEL). The encodings illustrate flexibility of COWS and somehow demonstrate expressiveness of the chosen set of primitives. In the sequel, we will write Zv¯ W to assign a symbolic name Zv¯ to the term W and to indicate the values v¯ occurring within W. Thus, Zv¯ is a family of names, one for each tuple of values v¯ . We use nˆ to stand for the endpoint n p no . Sometimes, we write nˆ for the tuple n p no and rely on the context to resolve any ambiguity. Imperative constructs. Due to lack of space, we only present the encodings of those constructs that will be further exploited in the rest of the section. We refer the interested reader to [21] for deeper explanations and additional encodings. We start adding matching with assignment [w¯ e¯ ] to COWS basic activities. If w¯ and e¯ do match, service [w¯ e¯ ] s returns a substitution that will eventually assign to the variables in w¯ the corresponding values of e¯ , and service s can proceed. In COWS, this meaning can be rendered through the following encoding (for m ˆ fresh) [w¯ e¯ ] s
[m] ˆ (m!¯ ˆ e m? ˆ w¯ s)
A Calculus for Orchestration of Web Services
41
Notably, the new construct di ers from standard assignment both because values can occur on the left of , in which case it behaves as a matching mechanism, and because, like the receive activity, it does not bind the variables on the left of , thus it cannot reassign a value to them if a value has already been assigned (more details are in [21]). Conditional choice is encoded similarly: if (e) then s1 else s2
[m] ˆ (m! ˆ e (m? ˆ true s1 m? ˆ false s2 ) )
where true and false are the values that can result from evaluation of e. Sequential composition can be encoded alike in CCS [26, Chapter 8] however, due to the asynchrony of invoke and kill activities, the notion of well-termination must be relaxed wrt CCS. Firstly, we settle that services may indicate their termination by exploiting the invoke activity xdone odone !, where xdone is a distinguished variable and odone is a distinguished name. Secondly, we say that a service s is well-terminating if, for every reduct s of s and partner p, s
xdone
(podone )
p implies that
– either s s for some or k and s is well-terminating – or s s implies (p o) v¯ , for some s , p, o and v¯ . Notably, well-termination does not demand a service to terminate, but only that whenever the service can perform activity p odone ! and cannot perform any kill activities, then it terminates except for, possibly, some parallel pending invoke activities. As usual, the encoding relies on the assumption that all calculus operators themselves (in particular, parallel composition) can be rendered as to preserve well-termination. Finally, if we only consider well-terminating services, then, for a fresh p, we can let:
s1 ; s2
[p] ( s1 xdone p p odone ? s2 )
Fault and compensation handlers. Fault handling is strictly related to the notion of compensation, namely the execution of specific activities (attempting) to reverse the e ects of previously executed activities. We consider here a minor variant of the WSBPEL compensation protocol. To begin with, we extend COWS syntax as shown in the upper part of Table 5. The scope activity [s : catch(1 ) s1 : : catch(n ) sn : sc ] permits explicitly grouping activities together. The declaration of a scope activity contains a unique scope identifier , a service s representing the normal behaviour, an optional list of fault handlers, and a compensation handler sc . The fault generator activity throw() can be used by a service to rise a fault signal . This signal will trigger execution of activity s , if a construct of the form catch() s exists within the same scope. The compensate activity undo() can be used to invoke a compensation handler of an inner scope named that has already completed normally (i.e. without faulting). Compensation can only be invoked from within a fault or a compensation handler. As in WS-BPEL, we fix two syntactic constraints: handlers do not contain scope activities and for each undo() occurring in a service there exists at least an inner scope . In fact, it is not necessary to extend COWS syntax because fault and compensation handling can be easily encoded. The most interesting cases of the encoding are shown in the lower part of Table 5 (in the remaining cases, the encoding acts as an homomorphism), where the killer labels used to identify scopes and the introduced partner
42
A. Lapadula, R. Pugliese, and F. Tiezzi Table 5. Syntax and encoding of fault and compensation handling s :: . . . throw() undo() [s : catch(1 ) s1 :
: catch(n ) sn : sc ]
(services) (fault generator) (compensate) (scope)
[s : catch(1 ) s1 : : catch(n ) sn : sc ] k [p1 pn ] ( catch(1 ) s1 k catch(n ) sn k [k ] ( sk ; ( xdone odone ! p ocomp ? sc k ) ) ) ß
catch() sk
undo()k
throw()k
ß
p o f ault ? [k ] s
p ocomp !
p o f ault !
¼
k
xdone odone ! xdone odone ! kill(k)
names are taken fresh for s, s1 , . . . , sn and sc . The two distinguished names o f ault and ocomp denote the operations for receiving fault and compensation signals, respectively. We are assuming that for each scope identifier or fault signal named n, the partner used to activate scope compensation or fault handling, respectively, is pn . The encoding k is parameterized by the identifier k of the closest enclosing scope, if any. The parameter is used when encoding a fault generator, to launch a kill activity that forces termination of all the remaining activities of the enclosing scope, and when encoding a scope, to delimit the field of action of inner kill activities. The compensation handler sc of scope is installed when the normal behaviour s successfully completes, but it is activated only when signal p ocomp ! occurs. Similarly, if during normal execution a fault occurs, a signal p o f ault ! triggers execution of the corresponding fault handler (if any). Installed compensation handlers are protected from killing by means of . Notably, both the compensate activity and the fault generator activity can immediately terminate (thus enabling possible sequential compositions); this, of course, does not mean that the corresponding handler is terminated. Flow graphs. Flow graphs provide a direct and intuitive way to structure workflow processes, where activities executed in parallel can be synchronized by settling dependencies, called (flow) links, among them. At the beginning of a parallel execution, all involved links are inactive and only those activities with no synchronization dependencies can execute. Once all incoming links of an activity are active (i.e., they have been assigned either a positive or negative state), a guard, called join condition, is evaluated. When an activity terminates, the status of the outgoing links, which can be positive, negative or undefined, is determined through evaluation of a transition condition. When an activity in the flow graph cannot execute (i.e., the join condition fails), a join failure fault is emitted to signal that some activities have not completed. An attribute called ‘suppress join failure’ can be set to yes to ensure that join condition failures do not throw the join failure fault (this e ect is called Dead-Path Elimination [1]). To express the constructs above, we extend the syntax of COWS as illustrated in the upper part of Table 6. A flow graph activity [ f l] ls is a delimited linked service, where
A Calculus for Orchestration of Web Services
43
Table 6. Syntax and encoding of flow graphs s ::
È
[ f l] ls
i I
ls :: ( jc) s ( f l e¯ ) sjf
jc :: true s j f :: yes
pi oi ?w¯ i si
(services)
s ( f l e¯ ) fl
false
ls ls
jc
jc jc
(linked services) jc jc
no
(join conditions) (supp. join failure)
[ f l] ls [ f l] ls
ls1 ls2 ls1
ls2
s ( f l e¯ ) s; [ f l e¯ ]
( jc) s ( f l e¯ ) if ( jc) then s; [ f l e¯ ] else [outLinkO f (s) false] yes
( jc) s ( f l e¯ ) if ( jc) then s; [ f l e¯ ] else throw( join f ) no
È
i1n
Ë
pi oi ?w¯ i si p1 o1 ?w¯ 1 [ j2n outLinkO f (s j ) false] s1 pn on ?w¯ n [ j1n 1 outLinkO f (s j ) false] sn
Ë
the activities within ls can synchronize by means of the flow links in f l, rendered as (boolean) variables. A linked service is a service equipped with a set of incoming flow links that forms the join condition, and a set of outgoing flow links that represents the sjf
transition condition. Incoming flow links and join condition are denoted by ( jc) . Outgoing links are represented by ( f li I e¯ i I ) where each pair ( f li ei ) is composed of a flow link f li and the corresponding transition (boolean) condition ei . Attribute s j f permits suppressing possible join failures. Input-guarded summation replaces binary choice, because we want all the branches of a multiple choice to be considered at once. Again, we show that in fact it is not necessary to extend the syntax because flow graphs can be easily encoded by relying on the capability of COWS of modelling a state shared among a group of activities. The most interesting cases of the encoding are shown in the lower part of Table 6. The encoding exploits the auxiliary function outLinkO f (s), that returns the tuple of outgoing links in s. Flow graphs are rendered as delimited services, while flow links are rendered as variables. A join condition is encoded as a boolean condition within a conditional construct, where the transition conditions are rendered as the assignment [ f l e¯ ]. In case attribute ‘suppress join failure’ is set to no, a join condition failure produces a fault signal that can be caught by a proper fault handler. Choice among (linked) services is implemented in such a way that, when a branch is selected, the links outgoing from the activities of the discarded branches are set to f alse (the encoding of conditional choice can be modified similarly).
4 Encoding the Orchestration Language Orc We present here the encoding of Orc [28], a recently proposed task orchestration language with applications in workflow, business process management, and web service orchestration. Orc expressions are generated by the following grammar: f g :: 0
S (w)
E(w)
f xg
f g
g where x : f
44
A. Lapadula, R. Pugliese, and F. Tiezzi
where S ranges over site names, E over expression names, x over variables, and w over parameters, i.e. variables or values (ranged over by v). Each expression name E has a unique declaration of the form E(x) f . Expressions f x g and g where x : f bind variable x in g. We now briefly describe the semantics of Orc expressions (and refer the interested reader to [21] for a formal account). Evaluation of expressions may call a number of sites and returns a (possibly empty) stream of values. In [28], this is formalized through a labelled transition relation, where label indicates an internal event while label !v indicates publication of the value v resulting from evaluating an expression. A site call can progress only when the actual parameter is a value; it elicits one response. While site calls use a call-by-value mechanism, expression calls use a call-by-name mechanism, namely the actual parameter replaces the formal one and then the corresponding expression is evaluated. Symmetric parallel composition f g consists of concurrent evaluations of f and g. Sequential composition f x g activates a concurrent copy of g with x replaced by v, for each value v returned by f . Asymmetric parallel composition g where x : f starts in parallel both f and the part of g that does not need x. The first value returned by f is assigned to x and the continuation of f and all its descendants are then terminated. The encoding of Orc expressions in COWS exploits function rˆ shown in Table 7. The function is defined by induction on the syntax of expressions and is parameterized by the communication endpoint rˆ used to return the result of expressions evaluation. Thus, a site call is rendered as an invoke activity that sends a pair made of the parameter of the invocation and the endpoint for the reply along the endpoint Sˆ corresponding to site name S . Expression call is rendered similarly, but we need two invoke activiˆ rˆ rˆ activates a new instance of the body of the declaration, while z!w sends ties: E! the value of the actual parameter (when this value will be available) to the created instance, by means of a private endpoint stored in z received from the encoding of the corresponding expression declaration along the private endpoint rˆ previously sent. Sequential composition is encoded as the parallel composition of the two components sharing a delimited endpoint, where a new instance of the component on the right is created every time that on the left returns a value along the shared endpoint. Symmetric parallel composition is encoded as parallel composition, where the values produced by the two components are sent along the same return endpoint. Finally, asymmetric parallel composition is encoded in terms of parallel composition in such a way that, whenever the encoding of f returns its first value, this is passed to the encoding of g and a kill activity is enabled. Due to its eager semantics, the kill will terminate what remains of the term corresponding to the encoding of f . Moreover, for each site S , we define the service:
[x y] Sˆ ? x yy!eSx
(1)
that receives along the endpoint Sˆ a value (stored in x) and an endpoint (stored in y) to be used to send back the result, and returns the evaluation of eSx , an unspecified expression corresponding to S and depending on x. Similarly, for each expression declaration E(x) f we define the service:
ˆ y z[ˆr] (z!rˆ [x] (ˆr? x f y ) ) [y z] E?
(2)
A Calculus for Orchestration of Web Services
45
Table 7. Orc encoding 0rˆ
0
f
x grˆ
S (w)rˆ
[ˆr f ] ( f
g where x : f rˆ
rˆ f
Sˆ ! w rˆ
[x] rˆ f ? x grˆ )
[ˆr f x] ( g
rˆ
E(w)rˆ
ˆ rˆ rˆ [ˆr ] (E!
f grˆ
f
rˆ
[z] rˆ ?z z!w)
grˆ
[k] ( f rˆ f rˆ f ? x kill(k) ) )
Here, the received value (stored in x) is processed by the encoding of the body of the declaration, that is activated as soon as the expression is called. Finally, the encoding of an Orc expression f , written [[ f ]]rˆ , is the parallel composition of f rˆ , of a service of the form (1) or (2) for each site or expression called in f , in any of the expressions called in f , and so on recursively. In [21], we prove that there is a formal correspondence, based on the operational semantics, between Orc expressions and the COWS services resulting from their encoding. This is another sign of COWS expressiveness because it is known that Orc can express the most common workflow patterns identified in [31]. By letting s s to mean that there exist two services, s1 and s2 , such that s1 is a reduct of s, s1 s2 and s is a reduct of s2 , the above property can be stated as follows l
Theorem 1. Given an Orc expression f and an endpoint rˆ, f f implies [[ f ]]rˆ f rˆ s f rˆ s, where rˆ v if l !v, and (p o w¯ v¯ ) if l .
l
The proof (see [21]) proceeds by induction on the length of the inference of f f .
5 Concluding Remarks We have introduced COWS, a formalism for specifying and combining services, while modelling their dynamic behaviour (i.e. it deals with service orchestration rather than choreography). COWS borrows many constructs from well-known process calculi, e.g. -calculus, update calculus, StACi , and L , but combines them in an original way, thus being di erent from all existing calculi. COWS permits modelling di erent and typical aspects of (web) services technologies, such as multiple start activities, receive conflicts, routing of correlated messages, service instances and interactions among them. The correlation mechanism was first exploited in [32], that, however, only considers interaction among di erent instances of a single business process. Instead, to connect the interaction protocols of clients and of the respective service instances, the calculus introduced in [3], and called SCC, relies on explicit modelling of sessions and their dynamic creation (that exploits the mechanism of private names of -calculus). Interaction sessions are not explicitly modelled in COWS, instead they can be identified by tracing all those exchanged messages that are correlated each other through their same contents (as in [14]). We believe that the mechanism based on correlation sets (also used by WS-BPEL), that exploits business data and communication protocol headers to correlate di erent interactions, is more robust and fits the loosely coupled world of Web
46
A. Lapadula, R. Pugliese, and F. Tiezzi
Services better than that based on explicit session references. Another notable di erence with SCC is that in COWS services are not necessarily persistent. Many works put forward enrichments of some well-known process calculus with constructs inspired by those of WS-BPEL. The most of them deal with issues of web transactions such as interruptible processes, failure handlers and time. This is, for example, the case of [19,20,23,24] that present timed and untimed extensions of the calculus, called and , tailored to study a simplified version of the scope construct of WS-BPEL. Other proposals on the formalization of flow compensation are [5,4] that give a more compact and closer description of the Sagas mechanism [13] for dealing with long running transactions. We have focused on service orchestration rather than on service choreography. In [6,7] both aspects are studied. Other approaches are based on the use of schema languages [11] and Petri nets [15]. In [18] a sort of distributed input-guarded choice of join patterns, called smooth orchestrators, gives a simple and e ective representation of synchronization constructs. The work closest to ours is [22], where - is introduced to formalize the semantics of WS-BPEL. COWS represents a more foundational formalism than - in that it does not rely on explicit notions of location and state, it is more manageable (e.g. has a simpler operational semantics) and, at least, equally expressive (as the encoding of - in COWS shows, [21]). This paper has focussed on showing the descriptive power of COWS. We leave as a future work the task of developing a formal account of its expressiveness. We also plan to develop analytical tools, such as e.g. behavioural equivalences and type systems, supporting services verification. Behavioural equivalences could provide a means to establish formal correspondences between di erent views (abstraction levels) of a service, e.g. the contract it has to honour and its true implementation. Type systems, possibly based on behavioural types (see e.g. [12,16,17]), could permit to express and enforce policies of interest for (web) services for, e.g., disciplining resources usage, constraining the sequences of messages accepted by services, ensuring service interoperability and compositionality, guaranteeing absence of deadlock in service composition, checking that interaction obeys a given protocol. Acknowledgements. We thank the anonymous referees for their useful comments.
References 1. A. Alves et al. Web Services Business Process Execution Language Version 2.0. Technical report, WS-BPEL TC OASIS, August 2006. . 2. L. Bocchi, C. Laneve, and G. Zavattaro. A calculus for long-running transactions. In FMOODS, LNCS 2884, pp. 124–138, 2003. 3. M. Boreale, R. Bruni, L. Caires, R. De Nicola, I. Lanese, M. Loreti, F. Martins, U. Montanari, A. Ravara, D. Sangiorgi, V. T. Vasconcelos, and G. Zavattaro. SCC: a Service Centered Calculus. In WS-FM, LNCS 4184 , pp. 38–57, 2006. 4. R. Bruni, M. Butler, C. Ferreira, T. Hoare, H. Melgratti, and U. Montanari. Comparing two approaches to compensable flow composition. In CONCUR, LNCS 3653, pp. 383–397, 2005. 5. R. Bruni, H.C. Melgratti, and U. Montanari. Theoretical foundations for compensations in flow composition languages. In POPL, pp. 209–220. ACM, 2005.
A Calculus for Orchestration of Web Services
47
6. N. Busi, R. Gorrieri, C. Guidi, R. Lucchi, and G. Zavattaro. Choreography and orchestration: A synergic approach for system design. In ICSOC, LNCS 3826, pp. 228–240, 2005. 7. N. Busi, R. Gorrieri, C. Guidi, R. Lucchi, and G. Zavattaro. Choreography and orchestration conformance for system design. In COORDINATION, LNCS 4038, pp. 63–81, 2006. 8. M.J. Butler and C. Ferreira. An operational semantics for StAC, a language for modelling long-running business transactions. In COORDINATION, LNCS 2949, pp. 87–104, 2004. 9. M.J. Butler, C.A.R. Hoare, and C. Ferreira. A trace semantics for long-running transactions. In 25 Years Communicating Sequential Processes, LNCS 3525, pp. 133–150, 2005. 10. M. Carbone and S. Ma eis. On the expressive power of polyadic synchronisation in - calculus. Nordic J. of Computing, 10(2):70–98, 2003. 11. S. Carpineti and C. Laneve. A basic contract language for web services. In ESOP, LNCS 3924, pp. 197–213, 2006. 12. S. Chaki, S. K. Rajamani, and J. Rehof. Types as models: model checking message-passing programs. In POPL, pp. 45–57, 2002. 13. H. Garcia-Molina and K. Salem. Sagas. In SIGMOD, pp. 249–259. ACM Press, 1987. 14. C. Guidi, R. Lucchi, R. Gorrieri, N. Busi, and G. Zavattaro. SOCK: a calculus for service oriented computing. In ICSOC, LNCS 4294, pp. 327–338, 2006. 15. S. Hinz, K. Schmidt, and C. Stahl. Transforming BPEL to petri nets. In Business Process Management 3649, pp. 220–235, 2005. 16. A. Igarashi and N. Kobayashi. A generic type system for the pi-calculus. Theor. Comput. Sci., 311(1-3):121–163, 2004. 17. N. Kobayashi, K. Suenaga, and L. Wischik. Resource usage analysis for the -calculus. In VMCAI, LNCS 3855, pp. 298–312, 2006. 18. C. Laneve and L. Padovani. Smooth orchestrators. In FoSSaCS, LNCS 3921, pp. 32–46, 2006. 19. C. Laneve and G. Zavattaro. Foundations of web transactions. In FoSSaCS, LNCS 3441, pp. 282–298, 2005. 20. C. Laneve and G. Zavattaro. web-pi at work. In TGC, LNCS 3705, pp. 182–194, 2005. 21. A. Lapadula, R. Pugliese, and F. Tiezzi. A calculus for orchestration of web services (full version). Technical report, Dipartimento di Sistemi e Informatica, Univ. Firenze, 2006.
22. A. Lapadula, R. Pugliese, and F. Tiezzi. A WSDL-based type system for WS-BPEL. In COORDINATION, LNCS 4038, pp. 145–163, 2006. 23. M. Mazzara and I. Lanese. Towards a unifying theory for web services composition. In WS-FM, LNCS 4184, pp. 257–272, 2006. 24. M. Mazzara and R. Lucchi. A pi-calculus based semantics for WS-BPEL. Journal of Logic and Algebraic Programming, 70(1):96–118, 2006. 25. M. Merro and D. Sangiorgi. On asynchrony in name-passing calculi. Mathematical Structures in Computer Science, 14(5):715–767, 2004. 26. R. Milner. Communication and concurrency. Prentice-Hall, 1989. 27. R. Milner, J. Parrow, and D. Walker. A calculus of mobile processes, I and II. Inf. Comput., 100(1):1–40, 41–77, 1992. 28. J. Misra and W. R. Cook. Computation orchestration: A basis for wide-area computing. Journal of Software and Systems Modeling. Springer, May 2006. 29. J. Parrow and B. Victor. The update calculus. In AMAST, LNCS 1349, pp. 409–423, 1997. 30. J. Parrow and B. Victor. The fusion calculus: Expressiveness and symmetry in mobile processes. In Logic in Computer Science, pp. 176–185, 1998. 31. W.M.P. van der Aalst, A.H.M. ter Hofstede, B. Kiepuszewski, and A.P. Barros. Workflow patterns. Distributed and Parallel Databases, 14(1):5–51. Springer, 2003. 32. M. Viroli. Towards a formal foundational to orchestration languages. ENTCS, 105:51–71. Elsevier, 2004.
A Concurrent Calculus with Atomic Transactions Lucia Acciai1 , Michele Boreale2 , and Silvano Dal Zilio1 2
1 LIF, CNRS and Université de Provence, France Dipartimento di Sistemi e Informatica, Università di Firenze, Italy
Abstract. The Software Transactional Memory (STM) model is an original approach for controlling concurrent accesses to resources without the need for explicit lock-based synchronization mechanisms. A key feature of STM is to provide a way to group sequences of read and write actions inside atomic blocks, similar to database transactions, whose whole effect should occur atomically. In this paper, we investigate STM from a process algebra perspective and define an extension of asynchronous CCS with atomic blocks of actions. We show that the addition of atomic transactions results in a very expressive calculus, enough to easily encode other concurrent primitives such as guarded choice and multiset-synchronization (à la join-calculus). The correctness of our encodings is proved using a suitable notion of bisimulation equivalence. The equivalence is then applied to prove interesting “laws of transactions” and to obtain a simple normal form for transactions.
1 Introduction The craft of programming concurrent applications is about mastering the strains between two key factors: getting hold of results as quickly as possible, while ensuring that only correct results (and behaviors) are observed. To this end, it is vital to avoid unwarranted access to shared resources. The Software Transactional Memory (STM) [18] model is an original approach for controlling concurrent accesses to resources without using explicit lock-based synchronization mechanisms. Similarly to database transactions, the STM approach provides a way to group sequences of read and write actions inside atomic blocks whose whole effect should occur atomically. The STM model has several advantages. Most notably, it dispenses the programmer from the need to explicitly manipulate locks, a task widely recognized as difficult and error-prone. Moreover, atomic transactions provide a clean conceptual basis for concurrency control, which should ease the verification of concurrent programs. Finally, the model is effective: there exist several STM implementations for designing software for multiprocessor systems; these applications exhibit good performances in practice (compared to equivalent, hand-crafted, code using locks). We investigate the STM model from a process algebra perspective and define an extension of asynchronous CCS [20] with atomic blocks of actions. We call this calculus AT CCS. The choice of a dialect of CCS is motivated by an attention to economy: to focus on STM primitives, we study a calculus as simple as possible and dispense with
This work was partially supported by the French ANR ARASSIA project COPS and the EU FET-GC2 initiative, project SENSORIA.
R. De Nicola (Ed.): ESOP 2007, LNCS 4421, pp. 48–63, 2007. c Springer-Verlag Berlin Heidelberg 2007
A Concurrent Calculus with Atomic Transactions
49
orthogonal issues such as values, mobility of names or processes, etc. We believe that our work could be easily transferred to a richer setting. Our goal is not only to set a formal ground for reasoning on STM implementations but also to understand how this model fits with other concurrency control mechanisms. We also view this calculus as a test bed for extending process calculi with atomic transactions. This is an interesting direction for investigation since, for the most part, works that mix transactions with process calculi consider compensating transactions, see e.g. [3,5,7,8,9,11,19]. The idea of providing hardware support for software transactions originated from works by Herlihy and Moss [18] and was later extended by Shavit and Touitou [22] to software-only transactional memory. Transactions are used to protect the execution of an atomic block. Intuitively, each thread that enters a transaction takes a snapshot of the shared memory (the global state). The evaluation is optimistic and all actions are performed on a copy of the memory (the local state). When the transaction ends, the snapshot is compared with the current state of the memory. There are two possible outcomes: if the check indicates that concurrent writes have occurred, the transaction aborts and is rescheduled; otherwise, the transaction is committed and its effects are propagated instantaneously. Very recently, Harris et al. [17] have proposed a (combinator style) language of transactions that enables arbitrary atomic operations to be composed into larger atomic expressions. We base the syntax of AT CCS on the operators defined in [17]. The main contributions of this work are: (1) the definition of a process calculus with atomic transactions; and (2) the definition of an asynchronous bisimulation equivalence ≈a that allows compositional reasoning on transactions. We also have a number of more specific technical results. We show that AT CCS is expressive enough to easily encode interesting concurrent primitives, such as (preemptive versions of) guarded choice and multiset-synchronization, and the leader election problem (Section 3). Next, we define an equivalence between atomic expressions and prove that ≈a and are congruences (Section 4). These equivalences are used to prove the correctness of our encodings, to prove interesting “behavioral laws of transactions” and to define a simple normal form for transactions. We also show that transactions (modulo ) have an algebraic structure close to that of a bound semilattice, an observation that could help improve the design of the transaction language. The proofs of the main theorems can be found in a long version of this paper [1].
2 The Calculus We define the syntax and operational semantics of AT CCS, which is essentially a cut down version of asynchronous CCS, without choice and relabeling operators, equipped with atomic blocks and constructs for composing (transactional) sequences of actions. Syntax of Processes and Atomic Expressions. The syntax of AT CCS, given in Table 1, is divided into syntactical categories that define a stratification of terms. The definition of the calculus depends on a set of names, ranged over by a, b, . . . . As in CCS, names model communication channels used in process synchronization, but they also occur as objects of read and write actions in atomic transactions.
50
L. Acciai, M. Boreale, and S. Dal Zilio
Atomic expressions, ranged over by M, N, . . . , are used to define sequences of actions whose effect should happen atomically. Actions rd a and wt a represent attempts to input and output to the channel a. Instead of using snapshots of the state for managing transaction, we use a log-based approach. During the evaluation of an atomic block, actions are recorded in a private log δ (a sequence α1 . . . αn ) and have no effects outside the scope of the transaction until it is committed. The action retry aborts an atomic expression unconditionally and starts its execution afresh, with an empty log ε. The termination action end signals that an expression is finished and should be committed. If the transaction can be committed, all actions in the log are performed at the same time and the transaction is closed, otherwise the transaction aborts. Finally, transactions can be composed using the operator orElse, which implements (preemptive) alternatives between expressions. In M orElse N, the expression N is executed if M aborts and has the behavior of M otherwise. Processes, ranged over by P, Q, R, . . . , model concurrent systems of communicating agents. We have the usual operators of CCS: the empty process, 0, the parallel composition P | Q, and the input prefix a.P. There are some differences though. The calculus is asynchronous, meaning that a process cannot block on output actions. Also, we use replicated input ∗ a .P instead of recursion (this does not change the expressiveness of the calculus) and we lack the choice and relabeling operators of CCS. The hiding operator P \n a bounds the scope of name a to P (we consider processes up-to α-renaming of bound names; we discuss the meaning of the annotation n in page 53). Finally, the main addition is the presence of the operator atom(M), which models a transaction that safeguards the expression M. The process {|A|}M represents the ongoing evaluation of an atomic block M: the subscript is used to keep the initial code of the transaction, in case it is aborted and executed afresh, while A holds the remaining actions that should be performed. An ongoing atomic block, A, B, . . . , is essentially an atomic expression enriched with an evaluation state σ and a log δ of the currently recorded actions. A state σ is a multiset of names that represents the output actions visible to the transaction when it was initiated. (This notion of state bears some resemblance with tuples space in coordination calculi, such as Linda [10].) When a transaction ends, the state σ recorded in the block (M)σ;δ (the state at the initiation of the transaction) can be compared with the current state (the state when the transaction ends) to check if other processes have concurrently made changes to the global state, in which case the transaction should be aborted. Notation. In the following, we write σ {a} for the multiset σ enriched with the name a and σ \ σ for the multiset obtained from σ by removing elements found in σ , that is the smallest multiset σ such that σ ⊆ σ σ . The symbol 0/ stands for the empty / multiset while {an } is the multiset composed of exactly n copies of a, where {a0 } = 0. Given a log δ, we use the notation WT ( δ) for the multiset of names which appear as objects of a write action in δ. Similarly, we use the notation RD( δ) for the multiset of names that are objects of read actions. The functions WT and RD may be inductively defined as follows: WT ( wt a .δ) = WT ( δ) {a}; RD ( rd a .δ) = RD ( δ) {a}; WT ( rd a .δ) = WT ( δ); RD ( wt a .δ) = RD ( δ) and WT ( ε) = RD ( ε) = ε.
A Concurrent Calculus with Atomic Transactions
51
Table 1. Syntax of AT CCS: Processes and Atomic Expressions Actions α, β ::= rd a wt a (Atomic) Expressions M, N ::= end
(tentative) read access to a (tentative) write access to a termination
retry
abort and retry the current atomic block
α.M
action prefix
M orElse N
alternative
Ongoing expressions A, B ::= (M)σ;δ A orElse B Processes P, Q ::= 0
execution of M with state σ and log δ ongoing alternative nil
a
(asynchronous) output
a.P
input
∗ a .P
replicated input
P|Q
parallel composition
P \n a
hiding
atom(M)
atomic block
{|A|}M
ongoing atomic block
Example: Composing Synchronization. Before we describe the meaning of processes, we try to convey the semantics of AT CCS (and the usefulness of the atomic block operator) using a simple example. We take the example of a concurrent system with two memory cells, M1 and M2 , used to store integers. We consider here a straightforward extension of the calculus with “value-passing.” In this setting, we can model a cell with value v by an output mi !v and model an update by a process of the form mi ?x.(mi !v | . . . ). With this encoding, the channel name mi acts as a lock protecting the shared resource Mi . Assume now that the values of the cells should be synchronized to preserve a global invariant on the system. For instance, we model a flying aircraft, each cell store the pitch of an aileron and we need to ensure that the aileron stay aligned (that the values of the cells are equal). A process testing the validity of the invariant is for example P1 below (we suppose that a message on the reserved channel err triggers an alarm). There are multiple design choices for resetting the value of both cells to 0, e.g. P2 and P3 .
P1 = m1 ?x.m2 ?y.if x != y then err! P3 = m1 ?x. m1 !0 | m2 ?y.m2 !0 P2 = m2 ?x.m1 ?y. m1 !0 | m2 !0
52
L. Acciai, M. Boreale, and S. Dal Zilio Table 2. Operational Semantics: Processes ( OUT ) a ; σ → 0 ; σ {a}
( REP ) ∗ a .P ; σ {a} → P | ∗ a .P ; σ
( IN ) a.P ; σ {a} → P ; σ
( COM )
P ; σ → P ; σ {a} Q ; σ {a} → Q ; σ P| Q → P | Q
( HID )
P ; σ {an } → P ; σ {am } a∈ / σ, σ n m P \ a;σ → P \ a;σ
( PAR L)
P ; σ → P ; σ P | Q ; σ → P | Q ; σ
( PAR R)
Q ; σ → Q ; σ P | Q ; σ → P | Q ; σ
( AT S T ) atom(M) ; σ → {|(M)σ;ε |}M ; σ
A → A {|A|}M ; σ → {|A |}M ; σ
( AT R E ) {|(retry)σ ;δ |}M ; σ → atom(M) ; σ
( AT PASS )
RD ( δ) σ {|(end)σ ;δ |}M ; σ → atom(M) ; σ
( AT FAIL )
( AT O K )
σ = σ RD( δ) WT ( δ) = {a1 , . . . , an } {|(end)σ ;δ |}M ; σ → a1 | · · · | an ; σ
RD( δ) ⊆ σ
Each choice exemplifies a problem with lock-based programming. The composition of P1 with P2 leads to a race condition where P1 acquire the lock on M1 , P2 on M2 and each process gets stuck. The composition of P1 and P3 may break the invariant (the value of M1 is updated too quickly). A solution in the first case is to strengthen the invariant and enforce an order for acquiring locks, but this solution is not viable in general and opens the door to priority inversion problems. Another solution is to use an additional (master) lock to protect both cells, but this approach obfuscate the code and significantly decreases the concurrency of the system. Overall, this simple example shows that synchronization constraints do not compose well when using locks. This situation is consistently observed (and bears a resemblance to the inheritance anomaly problem found in concurrent object-oriented languages). The approach advocated in this paper is to use atomic transactions. In our example, the problem is solved by simply wrapping the two operations in a transaction, like in the process atom rd ( m2 ?y).wt ( m2 !0).rd ( m1 ?x).wt ( m1 !0) , which ensures that all cell updates are effected atomically. More examples may be found on the paper on composable memory transactions [17], which makes a compelling case that “even correctly-implemented concurrency abstractions cannot be composed together to form larger abstractions.” Operational Semantics. Like for the syntax, the semantics of AT CCS is stratified in two levels: there is one reduction relation for processes and a second for atomic expressions. With a slight abuse of notation, we use the same symbol (→) for both relations.
A Concurrent Calculus with Atomic Transactions
53
Table 3. Operational Semantics: Ongoing Atomic Expression
(AR D O K )
RD ( δ) {a} ⊆ σ (rd a .M)σ;δ → (M)σ;δ.rd a
(AR D F)
RD( δ) {a} σ (rd a .M)σ;δ → (retry)σ;δ
(AW R ) (wt a .M)σ;δ → (M)σ;δ.wt a (AOI)
(M1 orElse M2 )σ;δ → (M1 )σ;δ orElse (M2 )σ;δ
(AOF) (retry)σ;δ orElse B → B (AOL)
A → A A orElse B → A orElse B
(AOE) (end)σ;δ orElse B → (end)σ;δ (AOR)
B → B A orElse B → A orElse B
Reduction for Processes. Table 2 gives the semantics of processes. A reduction is of the form P ; σ → P ; σ where σ is the state of P. The state σ records the names of all output actions visible to P when reduction happens. It grows when an output is reduced, ( OUT ), and shrinks in the case of inputs, ( IN ) and ( REP ). A parallel composition evolves if one of the component evolves or if both can synchronize, rules ( PAR L), ( PAR R) and ( COM ). In a hiding P \n a, the annotation n is an integer denoting the number of outputs on a that are visible to P. Intuitively, in a “configuration” P \n a ; σ, the outputs visible to P are those in σ {an }. This extra annotation is necessary because the scope of a is restricted to P, hence it is not possible to have outputs on a in the global state. Rule ( HID ) allows synchronization on the name a to happen inside a hiding. For instance, we have (P | a) \n a ; σ → P \n+1 a ; σ. The remaining reduction rules govern the evolution of atomic transactions. Like in the case of ( COM ), all those rules, but ( AT O K ), leave the global state unchanged. Rule ( AT S T ) deals with the initiation of an atomic block atom(M): an ongoing block {|(M)σ;ε |}M is created which holds the current evaluation state σ and an empty log ε. An atomic block {|A|}M reduces when its expression A reduces, rule ( AT PASS ). (The reduction relation for ongoing expressions is defined by the rules in Table 3.) Rules ( AT R E ), ( AT FAIL ) and ( AT O K ) deal with the completion of a transaction. After a finite number of transitions, the evaluation of an ongoing expression will necessarily result in a fail state, (retry)σ;δ , or a success, (end)σ;δ . In the first case, rule ( AT R E ), the transaction is aborted and started again from scratch. In the second case, we need to check if the log is consistent with the current evaluation state. A log is consistent if the read actions of δ can be performed on the current state. If the check fails, rule ( AT FAIL ), the transaction aborts. Otherwise, rule ( AT O K ), we commit the transaction: the names in RD ( δ) are taken from the current state and a bunch of outputs on the names in WT ( δ) are generated. Reduction for Ongoing Expressions. Table 3 gives the semantics of ongoing atomic expressions. We recall that, in an expression (rd a .M)σ;δ , the subscript σ is the initial state,
54
L. Acciai, M. Boreale, and S. Dal Zilio
that is a copy of the state at the time the block has been created and δ is the log of actions performed since the initiation of the transaction. Rule (AR D O K ) states that a read action rd a is recorded in the log δ if all the read actions in δ.rd a can be performed in the initial state. If it is not the case, the ongoing expression fails, rule (AR D F). This test may be interpreted as a kind of optimization: if a transaction cannot commit in the initial state then, should it commit at the end of the atomic block, it would mean that the global state has been concurrently modified during the execution of the transaction. Note that we consider the initial state σ and not σ WT ( δ), which means that, in an atomic block, write actions are not directly visible (they cannot be consumed by a read action). This is coherent with the fact that outputs on WT ( δ) only take place after commit of the block. Rule (AW R ) states that a write action always succeeds and is recorded in the current log. The remaining rules govern the semantics of the retry, end and orElse constructs. These constructs are borrowed from the STM combinators used in the implementation of an STM system in Concurrent Haskell [17]. We define these operators with an equivalent semantics, with the difference that, in our case, a state is not a snapshot of the (shared) memory but a multiset of visible outputs. A composition M orElse N corresponds to the interleaving of the behaviors of M and N, which are independently evaluated with respect to the same evaluation state (but have distinct logs). The orElse operator is preemptive: the ongoing block M orElse N ends if and only M ends or M aborts and N ends.
3 Encoding Concurrency Primitives Our first example is a simple solution to the celebrated leader election problem that does not yield to deadlock. Consider a system composed by n processes and a token, named t, that is modeled by an output t. A process becomes a leader by getting (making an input on) t. As usual, all participants run the same process (except for the value of their identity). We suppose that there is only one copy of the token in the system and that leadership of process i is communicated to the other processes by outputting on a reserved name wini . A participant that is not a leader outputs on losei . The protocol followed by the participants is defined by the following process: Li = atom rd t .wt k .end orElse wt k .end | k. wini | k .losei \0 k \0 k In this encoding, the atomic block is used to protect the concurrent accesses to t. If the process Li commits its transaction and grabs the token, it immediately release an output on its private channel k. The transactions of the other participants may either fail or commit while releasing an output on their private channel k . Then, the elected process Li may proceed with a synchronization on k that triggers the output wini . The semantics of atom( ) ensures that only one transaction can acquire the lock and commit the atomic block, then no other process have acquired the token in the same round and we are guaranteed that there could be at most one leader. This expressivity result is mixed blessing. Indeed, it means that any implementation of the atomic operator should be able to solve the leader election problem, which is
A Concurrent Calculus with Atomic Transactions
55
known to be very expensive in the case of loosely-coupled systems or in presence of failures (see e.g. [21] for a discussion on the expressivity of process calculi and electoral systems). On the other hand, atomic transactions are optimistic and are compatible with the use of probabilistic approaches. Therefore it is still reasonable to expect a practical implementation of AT CCS. In the following, we show how to encode two fundamental concurrency patterns, namely (preemptive versions of) the choice and join-pattern operators. Guarded choice. We consider an operator for choice, µ1 .P1 + · · · + µn .Pn , such that every process is prefixed by an action µi that is either an output ai or an input ai . The semantics of choice is characterized by the following three reduction rules (we assume that Q is also a choice): ( C - INP ) a.P + Q ; σ {a} → P ; σ ( C - PASS )
( C - OUT ) a.P + Q ;σ → P ; σ {a}
a∈ / σ Q ; σ → Q ; σ a.P + Q ;σ → Q ; σ
A minor difference with the behavior of the choice operator found in CCS is that our semantics gives precedence to the leftmost process (this is reminiscent of the preemptive behavior of orElse). Another characteristic is related to the asynchronous nature of the calculus, see rule ( C - OUT ): since an output action can always interact with the environment, a choice a.P + Q may react at once and release the process a | P. Like in the example of the leader election problem, we can encode a choice µ1 .P1 + · · · + µn .Pn using an atomic block that will mediate the interaction with the actions µ1 , . . . , µn . We start by defining a straightforward encoding of input/output actions into atomic actions: [[a]] = wt a and [[a]] = rd a . Then the encoding of choice is the process [[µ1 .P1 + · · · + µn .Pn ]] = atom [[µ1 ]].[[k1 ]].end orElse · · · orElse [[µn ]].[[kn ]].end | k1 .[[P1 ]] | · · · | kn .[[Pn ]] \0 k1 . . . \0 kn The principle of the encoding is essentially the same that in our solution to the leader election problem. Actually, using the encoding for choice, we can rewrite our solution in the following form: Li = t. wini + losei .0 . Using the rules in Table 2, it is easy to see that our encoding of choice is compatible with rule ( C - INP ), meaning that: [[a.P + Q]] ; σ {a} →∗ {|(end)σ{a};rd a .wt k1 |}M | k1 .[[P]] | . . . \0 k1 \ . . . ; σ {a} → k1 | k1 .[[P]] | . . . \0 k1 \ . . . ; σ → [[P]] | . . . \0 k1 \ . . . ; σ where the processes in parallel with [[P]] are harmless. In the next section, we define a weak bisimulation equivalence ≈a that can be used to garbage collect harmless processes in the sense that, e.g. (P | k.Q) \0 k ≈a P if P has no occurrences of k. Hence, we could prove that [[a.P + Q]] ; σ {a} →∗ ≈a [[P]] ; σ, which is enough to show that our encoding is correct with respect to rule ( C - INP ). The same is true for rules ( C - OUT ) and ( C - PASS ).
56
L. Acciai, M. Boreale, and S. Dal Zilio
Join Patterns. A multi-synchronization (a1 × · · · × an ).P may be viewed as an extension of input prefix in which communication requires a synchronization with the n outputs a1 , . . . , an at once. that is, we have the reduction: ( J - INP )
(a1 × · · · × an).P ; σ {a1, . . . , an } → P ; σ
This synchronization primitive is fundamental to the definition of the Gamma calculus of Banâtre and Le Métayer and of the Join calculus of Fournet and Gonthier. It is easy to see that the encoding of a multi-synchronization (input) is a simple transaction: [[ a1 × · · · × an .P]] = atom([[a1 ]]. · · · .[[an ]].[[k]].end) | k.[[P]] \0 k (where k is fresh) and thatwe have [[ a1 × · · · × an .P]] ; σ {a1 , . . . , an } →∗ 0 | [[P]] \0 k ; σ, where the process 0 | [[P]] \0 k is behaviorally equivalent to [[P]], that is: [[ a1 × · · · × an .P]] ; σ {a1, . . . , an } →∗ ≈a [[P]] ; σ Based on this encoding, we can define two interesting derived operators: a mixed version of multi-synchronization, (µ1 × · · · × µn ).P, that mixes input and output actions; and a replicated version, that is analogous to replicated input. [[ µ1 × · · · × µn .P]] = atom([[µ1 ]]. · · · .[[µn ]].[[k]].end) | k.[[P]] \0 k [[∗ µ1 × · · · × µn .P]] = r | ∗ r .atom([[µ1 ]]. · · · .[[µn ]].[[r]].[[k]].end) | ∗ k .[[P]] \0 r \0 k By looking at the possible reductions of these (derived) operators, we can define derived reduction rules. Assume δ is the log [[µ1 ]]. · · · .[[µn ]], we have a simulation result comparable to the case for multi-synchronization, namely: [[ µ1 × · · · × µn .P]] ; σ RD( δ) →∗ ≈a [[P]] ; σ WT ( δ) [[∗ µ1 × · · · × µn .P]] ; σ RD( δ) →∗ ≈a [[∗ µ1 × · · · × µn .P]] | [[P]] ;σ WT ( δ) To obtain join-definitions, we only need to combine a sequence of replicated multisynchronizations using the choice composition defined precedently. (We also need hiding to close the scope of the definition.) Actually, we can encode even more flexible constructs mixing choice and join-patterns. For the sake of simplicity, we only study examples of such operations. The first example is the (linear) join-pattern (a × b).P ∧ (a × c).Q, that may fire P if the outputs {a, b} are in the global state σ and otherwise fire Q if {a, c} is in σ (actually, real implementations of join-calculus have a preemptive semantics for pattern synchronization). The second example is the derived operator (a × b) + (b × c × a).P, such that P is fired if outputs on {a, b} are available or if outputs on {b, c} are available (in which case an output on a is also generated). These examples can be easily interpreted using atomic transactions: [[(a × b).P ∧ (a × c).Q]] = atom [[a]].[[b]].[[k1 ]].end orElse [[a]].[[c]].[[k2 ]].end | k1 .P | k2 .Q \0 k1 \0 k2 [[ a × b + b × c × a .P]] = atom [[a]].[[b]].[[k]].end orElse [[b]].[[c]].[[a]].[[k]].end | k.P \0 k
A Concurrent Calculus with Atomic Transactions
57
In the next section we define the notion of bisimulation used for reasoning on the soundness of our encodings. We also define an equivalence relation for atomic expressions that is useful for reasoning on the behavior of atomic blocks.
4 Bisimulation Semantics A first phase before obtaining a bisimulation equivalence is to define a Labeled Transition System (LTS) for AT CCS processes related to the reduction semantics. Labeled Semantics of AT CCS. It is easy to derive labels from the reduction semantics given in Table 2. For instance, a reduction of the form P ; σ → P ; σ {a} is clearly an a output transition and we could denote it using the transition P− →P , meaning that the effect of the transition is to add a message on a to the global state σ. We formalize the notion of label and transition. Besides output actions a, which corresponds to an application of rule ( OUT ), we also need block actions, which are multisets of the form {a1 , . . . , an } corresponding to the commit of an atomic block, that is to the deletion of a bunch of names from the global state in rule ( AT O K ). Block actions include the usual labels found in LTS for CCS and are used for labeling input and communication transitions: an input action a, which intuitively corresponds to rules ( IN ) and ( REP ), is a shorthand for the (singleton) block action {a}; the silent action τ, which corresponds / In the following, we use to rule ( COM ), is a shorthand for the empty block action 0. the symbols θ, γ, . . . to range over block actions and µ, µ , . . . to range over labels, µ ::= a θ τ a. µ →P satisfying the two The labeled semantics for AT CCS is the smallest relation P− following clauses: a
→P if there is a state σ such that P; σ → P ; σ {a}; 1. we have P− θ →P if there is a state σ such that P; σ θ → P ; σ. 2. we have P− τ
Note that, in the case of the (derived) action τ, we obtain from clause 2 that P− →P if there is a state σ such that P ; σ → P ; σ. As usual, silent actions label transitions that do not modify the environment (in our case the global state) and so are invisible to an outside observer. Unlike CCS, the calculus has more examples of silent transition than mere internal synchronization, e.g. the initiation and evolution of an atomic block, see e.g. rules ( AT ST) and ( AT PASS ). Consequently, a suitable (weak) equivalence for AT CCS should not distinguish e.g. the processes atom(retry), atom(end), (a.a) and 0. The same is true with input transitions. For instance, we expect to equate the processes a.0 and atom(rd a .end). Our labeled semantics for AT CCS is not based on a set of transition rules, as it is usually the case. Nonetheless, we can recover an axiomatic presentation of the semantics using the tight correspondence between labeled transitions and reductions characterized by Proposition 1. Proposition 1. Consider two processes P and Q. The following implications are true: a
a
τ
→P and Q− →Q then P | Q− →P | Q ; ( COM ) if P− µ µ µ ( PAR ) if P− →P then P | Q− →P | Q and Q | P− →Q | P ;
58
L. Acciai, M. Boreale, and S. Dal Zilio µ
µ
( HID ) if P− →P and the name a does not appear in µ then P \n a− →P \n a; a τ n+1 n ( HID O UT ) if P− →P then P \ a− →P \ a; µ ( HIDAT ) if P− →P and µ = θ {am }, where a is a name that does not appear in the θ →P \n a. label θ, then P \n+m a− µ
→P . By definition, there are Proof. In each case, we have a transition of the form P− states σ and σ such that P ; σ → P ; σ . The property is obtained by a simple induction on this reduction (a case analysis on the last reduction rule is enough). We define additional transition relations used in the remainder of the paper. As usual, we denote by ⇒ the weak transition relation, that is the reflexive and transitive closure of µ µ τ − →. We denote by = ⇒ the relation ⇒ if µ = τ and ⇒ − → ⇒ otherwise. If s is a sequence s s → the relation such that P− →P if and only if there is a of labels µ0 . . . µn , we denote − µ0 µ1 ...µn s process Q such that P− →Q and Q−−−→P (and − → is the identity relation when s is the s ⇒ of this relation in the same way. empty sequence ε). nWe also define a weak version = a a a a Lastly, we denote − → the relation − → ... − →, the composition of n copies of − →. Asynchronous Bisimulation for Processes and Expressions. Equipped with a labeled transition system, we can define a weak asynchronous bisimulation relation, denoted ≈a , in the style of [2]. Definition 1 (weak asynchronous bisimulation). A symmetric relation R is a weak asynchronous bisimulation if whenever PR Q then the following holds: a
a
→P then there is Q such that Q= ⇒Q and P R Q ; 1. if P− γ θ →P then there ⇒Q and 2. if P − is a process Q and a block action γ such that Q= P | ∏a∈(γ\θ) a R Q | ∏a∈(θ\γ) a . We denote with ≈a the largest weak asynchronous bisimulation. τ
Assume P ≈a Q and P− →P , the (derived) case for silent action entails that there is θ Q and θ such that Q= ⇒Q and P | ∏a∈θ a ≈a Q . If θ is the silent action, θ = { }, we recover the usual condition for bisimulation, that is Q= ⇒Q and P ≈a Q . If θ is an input action, θ = {a}, we recover the definition of asynchronous bisimulation of [2]. Due to the presence of block actions γ, the definition of ≈a is slightly more complicated than in [2], but it is also more compact (we only have two cases) and more symmetric. Hence, we expect to be able to reuse known methods and tools for proving the equivalence of AT CCS processes. Another indication that ≈a is a good choice for reasoning about processes is that it is a congruence. Theorem 1. Weak asynchronous bisimulation ≈a is a congruence. Proof. It suffices to prove that ≈a is preserved by every operator of the calculus [1]. We need to define a specific equivalence relation to reason on transactions. Indeed, the obvious choice that equates two expressions M and N if atom(M) ≈a atom(N) does not lead to a congruence. For instance, we have (rd a .wt a .end) equivalent to end while atom(rd a .wt a .end orElse wt b .end) ≈a atom(end orElse wt b .end) . The first transaction may output a message on b while the second always end silently.
A Concurrent Calculus with Atomic Transactions
59
Table 4. Algebraic Laws of Transactions Laws for atomic expressions: α.β.M β.α.M
( COMM )
α.(M orElse N) (α.M) orElse (α.N)
( DIST ) ( ASS )
M1 orElse (M2 orElse M3 ) (M1 orElse M2 ) orElse M3
( IDEM ) ( ABS RT 1) ( ABS RT 2) ( ABS E ND )
M orElse M M α.retry retry retry orElse M M M orElse retry end orElse M end
Laws for processes: ( ASY ) ( A - ASY ) ( A -1)
a.a ≈a 0 atom(rd a .wt a .end) ≈a 0 atom(rd a .end) ≈a a.0
We define an equivalence relation between atomic expressions , and a weak atomic preorder , that relates two expressions if they end (or abort) for the same states. We also ask that equivalent expressions should perform the same changes on the global state when they end. We say that two logs δ, δ have same effects, denoted δ =σ δ if σ \ RD( δ) WT ( δ) = σ \ RD ( δ ) WT ( δ ). We say that M σ N if and only if either (1) (N)σ;ε ⇒ (retry)σ,δ ; or (2) (N)σ;ε ⇒ (end)σ,δ and (M)σ;ε ⇒ (end)σ;δ . Similarly, we have M σ N if and only if either (1) (M)σ;ε ⇒ (retry)σ,δ and (N)σ;ε ⇒ (retry)σ,δ ; or (2) (M)σ;ε ⇒ (end)σ;δ and (N)σ;ε ⇒ (end)σ,δ with δ =σ δ . Definition 2 (weak atomic equivalence). Two atomic expressions M, N are equivalent, denoted M N, if and only if M σ N for every state σ. Similarly, we have M N if and only if M σ N for every state σ. While the definition of and depend on a universal quantification over states, testing the equivalence of two expressions is not expensive. First, we can rely on a monotonicity property of reduction: if σ ⊆ σ then for all M the effect of (M)σ,δ is included in those of (M)σ ,δ . Moreover, we define a normal form for expressions later in this section (see Proposition 2) that greatly simplifies the comparison of expressions. Another indication that is a good choice of equivalence for atomic expressions is that it is a congruence. Theorem 2. Weak atomic equivalence is a congruence. On the Algebraic Structure of Transactions. The equivalence relations and ≈a can be used to prove interesting laws of atomic expressions and processes. We list some of these laws in Table 4. Let M denotes the set of all atomic expressions. The behavioral rules for atomic expressions are particularly interesting since they exhibit a
60
L. Acciai, M. Boreale, and S. Dal Zilio
rich algebraic structure for M . For instance, rules ( COMM ) and ( DIST ) state that action prefix α.M is a commutative operation that distribute over orElse. We also have that (M , orElse, retry) is an idempotent semigroup with left identity retry, rules ( ASS ), ( ABS RT 2) and ( IDEM ), and that end annihilates M , rule ( ABS E ND ). Most of these laws appear in [17] but are not formally proved. Actually, we can show that the structure of M is close to that of a bound joinsemilattice. We assume unary function symbols a( ) and a( ) for every name a (a term a(M) is intended to represent a prefix wt a .M) and use the symbols , 1, 0 instead of orElse, end, retry. With this presentation, the behavioral laws for atomic expression are almost those of a semilattice. By definition of , we have that M M M if and only if M M and for all M, N we have 1 M N M 0. µ(µ (M)) µ (µ(M))
µ(M N) µ(M) µ(N)
0 M M M 0
1 M 1
µ(0) 0
It is possible to prove other behavioral laws to support our interpretation of orElse as a join. However some important properties are missing, most notably, while is associative, it is not commutative. For instance, a(b(1)) 1 1 while 1 1 a(b(1)), rule ( ABS E ND ). This observation could help improve the design of the transaction language: it will be interesting to enrich the language so that we obtain a real lattice. Normal Form for Transactions. Next, we show that it is possible to rearrange an atomic expression (using behavioral laws) to put it into a simple normal form. This procedure can be understood as a kind of compilation that transform an expression M into a simpler form. Informally, an atomic expression M is said to be in normal form if it does not contain nested orElse (all occurrences are at top level) and if there are no redundant branches. A redundant branch is a sequence of actions that will never be executed. For instance, the read actions in rda .rdb in rda .end are included .end, then the second branch in the composition rd a .end orElse rd a .rd b .end is redundant: obviously, if rd a .end fails then rd a .rd b .end cannot succeed. We overload the functions defined on logs and write RD( M) for the (multiset of) names occurring in read actions in M. We define WT ( M) similarly. In what follows, we abbreviate (M1 orElse . . . orElse Mn ) with the expression i∈1..n Mi . We say that an expression M is in normal form if it is of the form i∈1..n Ki where for all indexes i, j ∈ 1..n we have: (1) Ki is a sequence of action prefixes α j1 . . . . .α jni .end; and (2) RD ( Ki ) RD ( K j ) for all i < j. Condition (1) requires the absence of nested orElse and condition (2) prohibits redundant branches (it also means that all branches, but the last one, has a read action). Proposition 2. For every expression M there is a normal form M such that M M . Proof. Laws ( COMM ), ( DIST ) and ( ASS ) in Table 4 can be applied for eliminating nested orElse. Next, we use the fact that if K is a redundant branch of M then M K. Our choice of using bisimulation for reasoning about atomic transactions may appear arbitrary. In the long version [1], we study a testing equivalence for AT CCS, more particularly an asynchronous may testing semantics [15].
A Concurrent Calculus with Atomic Transactions
61
5 Future and Related Works There is a long history of works that try to formalize the notions of transactions and atomicity, and a variety of approaches to tackle this problem. We review some of these works that are the most related to ours. We can list several works that combine ACID transactions with process calculi. Gorrieri et al [16] have modeled concurrent systems with atomic behaviors using an extension of CCS. They use a two-level transition systems (a high and a low level) where high actions are decomposed into atomic sequences of low actions. To enforce isolation, atomic sequences must go into a special invisible state during all their execution. Contrary to our model, this work does not follow an optimistic approach: sequences are executed sequentially, without interleaving with other actions, as though in a critical section. Another related calculus is RCCS, a reversible version of CCS [13,14] based on an earlier notion of process calculus with backtracking [4]. In RCCS, each process has access to a log of its synchronization’s history and may always wind back to a previous state. This calculus guarantees the ACD properties of transactions (isolation is meaningless since RCCS do not use a shared memory model). Finally, a framework for specifying the semantics of transactions in an object calculus is given in [23]. The framework is parametrized by the definition of a transactional mechanism and allows the study of multiple models, such as the usual lock-based approach. In this work, STM is close to a model called versioning semantics. Like in our approach, this model is based on the use of logs and is characterized by an optimistic approach where log consistency is checked at commit time. Fewer works consider behavioral equivalences for transactions. A foundational work is [6], that gives a theory of transactions specifying atomicity, isolation and durability in the form of an equivalence relation on processes, but it provides no formal proof system. Linked to the upsurge of works on Web Services (and on long running Web transactions), a larger body of works is concerned with formalizing compensating transactions. In this context, each transactive block of actions is associated with a compensation (code) that has to be run if a failure is detected. The purpose of compensation is to undo most of the visible actions that have been performed and, in this case, atomicity, isolation and durability are obviously violated. We give a brief survey of works that formalize compensable processes using process calculi. These works are of two types: (1) interaction based compensation [7,8,19], which are extensions of process calculi (like π or joincalculus) for describing transactional choreographies where composition take place dynamically and where each service describes its possible interactions and compensations; (2) compensable flow composition [9,11], where ad hoc process algebras are designed from scratch to describe the possible flow of control among services. These calculi are oriented towards the orchestration of services and service failures. This second approach is also followed in [3,5] where two frameworks for composing transactional services are presented. The study of AT CCS is motivated by our objective to better understand the semantics of the STM model. Obtaining a suitable behavioral equivalence for atomic expression is a progress for the verification of concurrent applications that use STM. However, we can imagine using our calculus for other purposes. An interesting problem is to develop
62
L. Acciai, M. Boreale, and S. Dal Zilio
an approach merging atomic and compensating transactions. A first step in this direction is to enrich our language and allow the parallel composition of atomic expressions and the nesting of transactions. We are currently working on this problem. Another area for research stems from our observation (see Section 4) that the algebraic structure of atomic expressions is lacking interesting property. Indeed, it will be interesting to enrich the language of expressions in order to obtain a real lattice. The addition of a symmetric choice operator for atomic expressions may be a solution, but it could introduce unwanted nondeterminism in the evaluation of transactions.
References 1. L. Acciai, M. Boreale and S. Dal Zilio. A Concurrent Calculus with Atomic Transactions (long version). http://arxiv.org/abs/cs.LO/0610137. 2. R. Amadio, I. Castellani and D. Sangiorgi. On Bisimulations for the Asynchronous πCalculus. Th. Comp. Sci., 195(2):291–324, 1998. 3. D. Berardi, D. Calvanese, G. De Giacomo, R. Hull and M. Mecella. Automatic Composition of Transition-Based Web Services with Messaging. In Proc. of VLDB, 2005. 4. J.A. Bergstra, A. Ponse and J.J. van Wamel. Process Algebra with Backtracking. In Proc. of REX Workshop, LNCS 803, 1994. 5. S. Bhiri, O. Perrin and C. Godart. Ensuring Required Failure Atomicity of Composite Web Services. In Proc. of WWW, ACM Press, 2005. 6. A.P. Black, V. Cremet, R. Guerraoui and M. Odersky. An Equational Theory for Transactions. In Proc. of FSTTCS, LNCS 2914, 2003. 7. L. Bocchi, C. Laneve and G. Zavattaro. A Calculus for Long Running Transactions. In Proc. of FMOODS, LNCS 2884, 2003. 8. R. Bruni, H.C. Melgratti and U. Montanari. Nested Commits for Mobile Calculi: extending Join. In Proc. of IFIP TCS, 563–576, 2004. 9. R. Bruni, H.C. Melgratti and U. Montanari. Theoretical Foundations for Compensations in Flow Composition Languages. In Proc. of POPL, ACM Press, 209–220, 2005. 10. N. Busi, R. Gorrieri, G. Zavattaro. A Process Algebraic View of Linda Coordination Primitives. Th. Comp. Sci., 192(2):167–199, 1998. 11. M.J. Butler, C. Ferreira and M.Y. Ng. Precise Modeling of Compensating Business Transactions and its Application to BPEL. In J. UCS, 11:712–743, 2005. 12. T. Chothia and D. Duggan. Abstractions for Fault-Tolerant Global Computing. Th. Comp. Sci., 322(3):567–613, 2004. 13. V. Danos and J. Krivine. Reversible Communicating System. In Proc. of CONCUR, LNCS 3170, 2004. 14. V. Danos and J. Krivine. Transactions in RCCS. In Proc. of CONCUR, LNCS 3653, 2005. 15. R. De Nicola and M.C.B. Hennessy. Testing Equivalence for Processes. Th. Comp. Sci., 34:83–133, 1984. 16. R. Gorrieri, S. Marchetti and U. Montanari. A2 CCS: Atomic Actions for CCS. Th. Comp. Sci., 72(2-3):203–223, 1990. 17. T. Harris, S. Marlow, S.P. Jones and M. Herlihy. Composable Memory Transactions. In Proc. of PPOPP, ACM Press, 48–60, 2005. 18. M. Herlihy, J.E. Moss. Transactional Memory: Architectural Support for Lock-Free Data Structures In Proc. of International Symposium on Computer Architecture, 1993.
A Concurrent Calculus with Atomic Transactions
63
19. C. Laneve and G. Zavattaro. Foundations of Web Transactions. In Proc. of FoSSaCS, LNCS 3441, 2005. 20. R. Milner. Calculi for Synchrony and Asynchrony. Th. Comp. Sci., 25:267–310, 1983. 21. C. Palamidessi. Comparing the Expressive Power of the Synchronous and the Asynchronous pi-calculus. Math. Struct. in Comp. Sci., 13(5), 2003. 22. N. Shavit and D. Touitou. Software Transactional Memory. In Proc. of Principles of Distributed Computing, ACM Press, 1995. 23. J. Vitek, S. Jagannathan, A. Welc and A.L. Hosking. A semantic Framework for Designer Transactions. In Proc. of ESOP, LNCS 2986, 2004.
Modal I/O Automata for Interface and Product Line Theories Kim G. Larsen1 , Ulrik Nyman1 , and Andrzej Wąsowski1,2 1
2
Department of Computer Science, Aalborg University Computational Logic and Algorithms Group, IT University of Copenhagen {kgl,ulrik,wasowski}@cs.aau.dk
Abstract. Alfaro and Henzinger use alternating simulation in a two player game as a refinement for interface automata [1]. We show that interface automata correspond to a subset of modal transition systems of Larsen and Thomsen [2], on which alternating simulation coincides with modal refinement. As a consequence a more expressive interface theory may be built, by a simple generalization from interface automata to modal automata. We define modal I/O automata, an extension of interface automata with modality. Our interface theory that follows can express liveness properties, disallowing trivial implementations of interfaces, a problem that exists for theories build around simulation preorders. In order to further exemplify the usefulness of modal I/O automata, we construct a behavioral variability theory for product line development.
1
Introduction
An interface theory [1,3,4,5,6,7] is a type-system-like theory for component languages, where types (interfaces) describe components (implementations) with composition being the only operator available. A type error proves that either a component does not conform to its interface, or that two composed components are incompatible. Since the overall structure of these type systems is so simple, it is often accepted not to give typing rules explicitly when describing interface theories (for example [1,3,4,5,6]), focusing instead on the essential ingredients of conformance, compatibility and composition. Regular, non-component types are only applied to existing objects in program code. In contrast for interface theories it makes sense to discuss interfaces as specifications of application’s architecture in isolation from actual source code. An interface abstracts the component in terms of the assumptions made by the component and the guarantees that it provides. One reasons about possible connections between component implementations (compositions) by using properties of composition of interfaces; most importantly independent implementability (that any implementations conforming to compatible interfaces are compatible) and generality properties (that the composition of interfaces produces an interface with the weakest assumptions and strongest guarantees). R. De Nicola (Ed.): ESOP 2007, LNCS 4421, pp. 64–79, 2007. © Springer-Verlag Berlin Heidelberg 2007
Modal I/O Automata for Interface and Product Line Theories
65
We consider behavioral interface theories suitable for specification of communication protocols between components (web services or embedded systems). Such theories typically require a contravariant treatment of inputs and outputs to ensure deadlock-free implementations: inputs guaranteed by the specification are always offered by the implementation and that the implementation never produces more outputs than the specification. This observation led de Alfaro, Henzinger and colleagues [1,3,4] to a conclusion that game theoretical models of interaction are most suitable as building blocks for behavioral interface theories. While we do appreciate the values of the game theoretical formulations, we disagree with some claims in the above cited work and argue that game formulations are insufficient in themselves: there is a genuine value in combining the game theoretical approach with more traditional formulations based on transition systems, or more precisely on modal transition systems. The two worlds of game models and modal transition systems convey largely orthogonal information about the moves of a system. Game models specify who has control over transitions, while modal transition systems focus on requirements, modality: which moves are allowed and which are required. In this paper we try to relate the two worlds, explain their weaknesses and their qualities. Eventually we combine them into a unified interface theory. Game theoretical notions of conformance are often based on alternating simulation [8]. We show that alternating simulation in a two player setting, as used in interface automata [1,9], is just a special case of modal transition systems refinement developed by Larsen and Thomsen [2] in the late eighties. This suggests that the real value of the game theoretic approach to component theories does not lie in the use of alternating simulation, but in the use of control information in the composition synthesis algorithms. Not surprisingly then, modal transition systems themselves cannot be used to build an interface theory, without adding control information. We build a new interface theory around modal I/O automata, which combine features of both game theoretic models and modal transition systems. Thanks to this new combination, our interfaces are now able to express liveness properties, which was impossible in existing interface theories (after this work has been completed we have learned about [10], which achieves a similar effect in a different setting). In order to further demonstrate the usefulness of our modal I/O automata, we construct a product line [11,12,13] theory. In simple words a product line is a set of similar products built by combining assets from a common platform available in the development process. The differences between the products are referred to as variability. Our theory is a behavioral formalism for describing the variability of components. The theory supports deciding whether given requirements can be satisfied by choosing concrete instances from the set of available assets. This theory, though very small, is to the best of our knowledge one of the very few attempts at describing software product lines in a behavioral fashion, and unlike the previous work [14], which takes a top-down approach to describing product families, it facilitates a bottom up construction of products, which is how product line development is more typically understood in the software engineering
66
K.G. Larsen, U. Nyman, and A. Wąsowski
community. This contribution is not meant to be comprehensive, highly developed and well set in the tradition of the product line development. It should be understood as a simple example that emphasizes the semantic difference between modeling components in component based development and modeling assets for product family development. We do hope to extend this theory soon and report about it separately in detail. The paper proceeds as follows. In the next section we shall explain the main results of the paper in nontechnical terms. Our main results concentrate in sections 3, 5 and 6. In Section 3 we draw a correspondence between the alternating simulation and observational modal refinement. In Section 4 modal I/O automata are defined, which are then used to construct an interface theory in Section 5 and a product line theory in Section 6. Sections 5 and 6 are largely independent, though they share a lot of intuitions. We conclude in Section 7.
2
Interface Automata vs Modal Automata: An Example
Consider an example interface automaton for a Client component (Fig. 1 (left), originally presented in [1]). This simple model describes a component that occasionally may want to send a package, and once it has made the request it is ready to receive an acknowledgment. The signature of the interface also mentions a fail input, but the component is never able to receive it. This means that Client is only capable of interacting with network links that never fail. In interface automata, due to a game theoretic semantics, all outputs are controlled by the component itself (called the Output player), while all inputs to such components are controlled by the environment player (called the Input player). An implementation conforms to the interface iff whenever some input is offered by the interface, then it is also offered by the implementation, and whenever an implementation produces any output, this output is also present in the interface (conformance formalized as alternating simulation [8]). Such a notion of conformance implies that compatibility can be passed from interfaces to components: if there is no winning strategy for the input player that leads to a deadlock in the interface automaton, then there won’t be such a strategy for the same player that interacts directly with any implementation. Similarly if there is no strategy for the output player that leads to an output that cannot be accepted by the environment, then there is also no such strategy for any of the implementations.
send!
3
3
2
4
ok?
2
send!
ok?
fail?
send!
ok?
fail?
Fig. 1. The Client interface (left) and a trivial implementation of it (right)
Modal I/O Automata for Interface and Product Line Theories
67
Unfortunately this notion of conformance, though very much safety oriented, does not enforce that the implementations take on any useful activities at all. Consider for example the diagram on the right side of Fig. 1. It presents a model of an implementation that does not perform any actions ever. In other words this is a network application that does not use the network at all. Still this new model conforms to its interface on the left, as in its initial state it does not add any illegal outputs and it offers all the inputs that were offered by the interface. If we turn this into the terminology used in modal transition systems it means that all the inputs are required, which is indicated by the 2 (must) modality on the corresponding transition, and the outputs are allowed, which is indicated by the 3 (may) modality on the transitions. In a modal transition systems perspective, conformance is based on modal refinement [2]. This refinement requires that whenever an implementation makes a step, then it must be possible to mimic it by an allowed transition of the specification; whenever the specification makes a required step it must be possible to match it with some required step of the corresponding state in the implementation. With the assignment of may to output transitions and must to input transitions this sounds nearly like the alternating simulation described above. In Section 3 we prove that indeed the two relations coincide if we require that the may transition relation is input-enabled. Consequently modality gives strictly more modeling power than alternating refinement. Various modalities can be assigned to actions regardless of whom controls them. Instead of allowing all possible extensions on inputs, as in interface automata, the designer is able to control what extensions are allowed. For example we can change the Client model of Fig. 1 to have a must modality (2) on the send! transition, which will have the effect that now all the implementations must be able to proceed producing an output. This would rule out trivial implementations as the one presented on the right side of Fig. 1. The game theoretic formulation of conformance gives a certain interpretation to inputs and outputs. Namely that inputs are incoming requests for service (for example remote procedure calls), while outputs are outgoing requests for service (also remote procedure calls, albeit in the other direction). With such an interpretation it becomes clear that removing services from the promised list should be illegal, while removing calls to external services is perfectly fine. This is exactly what alternating simulation achieves. What it misses is a more complex structure of communication. In asynchronous systems some messages indeed convey calls for service, however many other return feedback from the services (return a value). When a given output models returning a value from a component, then clearly it should never be removed, as then the whole component becomes useless. Fig. 2 illustrates another interface modeling a data link layer, which exploits the interplay between control and modality. The must modality is placed on transmt! transitions, as the data link layer would be useless if the implementation was permitted not to forward packets down the stack. Similarly the transition sending back the error message cannot legally be removed. At the same time the call for linkStatus! is a may transition as some implementations are allowed not to consult the hardware
68
K.G. Larsen, U. Nyman, and A. Wąsowski
send?
ok!
19
ok!
ok;
ack?
2
2
2
send? 14
2
trnsmt! 15
2
ack? nack? 16 2
linkStatus!
2
fail! 22
fail!
log!
trnsmt!
linkStatus!
2
18
14
3
trnsmt! 15
2
nack?
log!
ack? nack? 16 2
linkStatus! log!
up?
20
2
send;
trnsmt! 17
ack?
2
2
2 3
3
down? 21
3
19
2
22
ack? nack?
up?
down?
3
down? 21
3
20
2
2
18
2 3
nack? up?
log!
linkStatus!
trnsmt!
trnsmt! 17
ack? nack?
up?
down?
Fig. 2. DataLink layer with nontrivial modalities (left). Composition DataLink ⊗ Client (right). State 22 is an error state, where DataLink can produce the fail action, not accepted by Client.
ok;
19
ok;
ack?
2
2
2
send; 14
3
trnsmt! 15
2
ack? nack? 16
2
linkStatus! 3
20
trnsmt!
linkStatus!
log!
19
send;
trnsmt! 17
2
18
ack?
2
2
2
14
3
trnsmt! 15
2
ack? nack? 16
2
linkStatus!
2 3
nack?
ack? nack?
3
down?
up?
21
up?
down?
trnsmt!
2
linkStatus!
20
log!
trnsmt! 17
2
18
2 3
nack? up?
ack? nack?
up?
down?
Fig. 3. Composed interfaces LinkLayer | Client and variability models LinkLayer · Client
link explicitly to detect errors. Finally not all implementations are forced to be able to work with links that fail twice in a row, which is modeled by the second nack! transition being a may transition. Now consider how the two interfaces of Fig. 1 (left) and Fig. 2 (left) should be composed. The composition resembles a product computation (taken separately for the may transition relation and the must transition relation). As a result we obtain the interface presented on the right side of Fig. 2. Because the client component was so weak, the ultimate interface shows a system that possibly may never do anything. However if Client will send some packets, these packets will certainly be processed by the composition, unless the hardware link is broken. In such a case it might be that the implementation will produce a fail! message which will cause a deadlock with the current version of the Client (this can happen when the composition is in state 22). Since we cannot modify the composed system we instead synthesize a new interface which restricts the use of the composition in order to guarantee error freeness. States of the composition that can experience deadlocks are called error states. We follow Alfaro and Henzinger in removing error states, and transitively all states from which error states can be reached by following internally controllable transitions of the component (outputs and internal actions). This leads to the interface on Fig. 3
Modal I/O Automata for Interface and Product Line Theories
69
(left), expressing the fact that this component works well as long as the physical link never goes down. The pruning mechanism described above would not be possible without the information describing which transitions are internally controllable being explicitly present in the model. It does not seem possible to compute the safe fragment of the product automaton, by just investigating the modalities of transitions. While we have said that modal refinement is strictly more expressive than alternating simulation, the control information of interface automata has its unique qualities too: it enables valuable synthesis algorithms not otherwise possible. Let us now revisit the model of Fig. 2 (left) giving it a different interpretation than previously. Instead of perceiving it as an abstraction of a component, we should now see it as a description of a set of components. A modal automaton describes in fact a whole, often infinite, set of possible implementation automata1 . One can think of them as all possible configurations of the model. This feature of modal automata suggests the possibility of using them as a behavioral formalism in describing variability in product lines. A product line is a collection of products that are similar in that they offer overlapping functionality, and in that they are built from assets selected from a common platform. In here we want to describe both assets and the whole product line by modal I/O automata. If each of the assets is modeled as a modal I/O automaton we can model the capabilities of the family by composing these descriptions. However this time we would not be interested in a composition that guarantees compatible behavior of any selection of assets. It is normally expected that not all the assets in a product line platform are mutually compatible. Some of them will deadlock (for example a failing link layer and our Client component). The requirement for composing the variability descriptions is not to synthesize an interface that guarantees correctness of composition of all possible combination of assets, but to precisely describes what the correct combinations are: i.e. what are the deadlock free behaviors respecting the modalities that can be constructed with the available automata. It turns out that a composition like that exists and it resembles the pruning of the product automaton for interface automata. The only difference is that now error states are the states where the error must be possible to realize (so one party must be required to produce an output that the other party must not be allowed to receive) and that we prune all the states from which reaching an error state is unavoidable (in our interface theory we have pruned states from which reaching errors might be possible). The result of composing Client and LinkLayer using the variability model semantics is presented on the right side of Figure 3. This result contains a slightly bigger model than the interface automaton composition on the left. It states that there exists a pair of assets (implementations of Client and LinkLayer ) such that it is able to accept a link down message without an error message. The transition 1
This is also true for interface automata, though to a much lesser extent. Due to the lack of modality the set of implementations for an interface automaton is much simpler than it can be for a modal automaton.
70
K.G. Larsen, U. Nyman, and A. Wąsowski
with the down message was removed in the interface compositions as, for some pairs of implementations, it would lead to a deadlock. Can a given specification be implemented by choosing components from available assets? Is the result of the composition the most general possible, containing all possible legal products? Can we find what the configuration of these elements should be? We address some of these questions in section 6, with an intention of elaborating more in upcoming work.
3
Alternating Simulation vs Modal Refinement
Let us begin with defining modal automata, a version of modal transition systems [2] extended with signatures. A modal automaton has two transition relations indicating respectively allowed (may) and required (must ) behavior. Definition 1 (Modal Automaton). A modal automaton S is a six tuple: S = (statesS , startS , extS , intS , −→3 , −→2 ) where statesS is a finite set of states, startS ∈ statesS is the initial state, extS and intS are disjoint sets of external and internal actions and actS = extS ∪ intS , −→3 S ⊆ statesS × actS × statesS is the may transition relation describing allowed behavior, and −→2 S ⊆ statesS × actS × statesS is the must transition relation describing required behavior. Throughout the paper we sometimes use the symbols “!”, “?” and “;” after an action. This is done in order to increase the readers intuition of whether the action is respectively an output, input or internal action. No symbol is used when the action can be of more than one type. These symbols could be left out completely as it is the identity of the action that is significant. τ ∗ s meaning that there exists a sequence of inIn the following we write s− − →2 ternal must actions leading from s to s . The same is defined for may transitions. A modal automaton is syntactically consistent if everything that is required is also allowed, such that −→2 ⊆ −→3 . In the following we only consider syntactically consistent modal automata. A modal automaton is an implementation if the two transition relations coincide. A modal automaton describes a set of possible implementations. Simplistically when refining a modal automaton specification into an implementation one can remove a may transition, that does not have a corresponding must transitions or strengthen it into a must transition. In general this refinement is not syntactic, but behavioral, so it is not the syntactic transitions that are refined but the actual steps taken by the transition system. The same transition can be refined differently each time it is taken. Definition 2 (Modal Refinement). For a pair of modal automata S and T with the same signature, a binary relation R ⊆ statesS × statesT is a modal refinement if whenever sRt and a ∈ actS it holds that if t−−a→2 t then ∃s .s−−a→2 s and (s , t ) ∈ R. if s−−a→3 s then ∃t .t−−a→3 t and (s , t ) ∈ R.
Modal I/O Automata for Interface and Product Line Theories
71
Modal refinement ≤m is defined as the largest such relation. We say that a modal automaton S modally refines a modal automaton T , written S ≤m T , iff there exists a modal refinement containing (startS , startT ). Observational modal refinement is a weaker refinement in which the two modal automata can take internal transitions, that cannot be directly observed by the other automaton. In absence of internal actions the observational refinement coincides with the non-observational one. Definition 3 (Observational Modal Refinement). For a pair of modal automata S and T with the same signature, a binary relation R ⊆ statesS × statesT is an observational modal refinement if whenever sRt and a ∈ actS it holds that if t−−a→2 t and a ∈ extT then ∃s. s−−a→2 s ∧ (s , t ) ∈ R. τ ∗ t .∃t. t a if s−−a→3 s and a ∈ extS then ∃t .t−− →3 −−→3 t ∧ (s , t ) ∈ R. ∗ a τ if s−−→3 s and a ∈ intS then ∃t .t− − →3 t .(s , t ) ∈ R Observational modal refinement ≤∗m is defined as the largest such relation. We say that a modal automaton S observationally refines a modal automaton T if there exists an observational modal refinement containing (startS , startT ). Interface Automata [1] can be considered a subset of modal automata in which the external actions extS are partitioned into inputs inS and outputs outS . Definition 4 (Interface Automaton). An interface automaton P is a tuple P = (statesP , startP , inP , intP , outP , − →P ) where statesP is a finite set of states, startP ∈ statesP is the initial state, inP , outP and intP are three pairwise disjoint sets of input, output and hidden (internal) actions respectively, and − →P ⊆ statesP × actP × statesP is the set of transitions where actP = inP ∪ outP ∪ intP . We require that the transition relation is input-deterministic such that for all a? s and s a? s then s, s , s ∈ statesP and all input actions a ∈ inP if s−− → −−→ s =s . τ ∗ s for Interface Automata to Similarly as for Modal Automata we define s−− → mean that there exists a sequence of internal transitions leading from s to s . We define alternating simulation for interface automata as commonly used in software specification [9], which is slightly less general than the original [1]:
Definition 5 (Alternating Simulation). For a pair of interface automata S and T with the same signature, a binary relation R ⊆ statesS × statesT is an alternating simulation if whenever sRt and a ∈ actS it holds that: a? t and a ∈ in then ∃s .s a? s and (s , t ) ∈ R if t−− → −−→ T a! s and a ∈ out then ∃t .t τ ∗ t .∃t .t a t and (s, t ) ∈ R if s−− → − − → −→ S a; s and a ∈ int then ∃t .t τ ∗ t and (s , t ) ∈ R if s−− → −− → S
Alternating simulation ≤a is defined as the largest such relation. We say that S simulates T , written S ≤a T , if there exists an alternating simulation containing (startS , startT ).
72
K.G. Larsen, U. Nyman, and A. Wąsowski
In order to compare interface automata with modal automata, we construct a translation function T mapping from the former to the latter. The result of the translation always fulfills the conditions listed below. It is easy to see that for modal automata that fulfill these conditions a reversed mapping can be constructed, too. 1. The may transition relation is input enabled, meaning that for each state s ∈ statesS and each input action a ∈ inS there exists a state s and a may transition s−−a? −→3 s 2. The constructed modal automaton is syntactically consistent: −→2 ⊆ −→3 3. Must transitions are only labeled by inputs: −→2 S ⊆ statesS × inS × statesS Let smayall be a fresh state that allows all behavior but does not require any behavior. If U denotes the universe of all inputs, such that for all interface automata P , inP ∈ U , then we define the translation function as follows: T (statesP , startP , inP , outP , intP , − →P ) = (statesS , startS , extS , intS , −→3 , −→2 ) where statesS = statesP ∪{smayall }, startS = startP , extS = U ∪outP , intS = intP and s1 −−a→S3 s2 if s1 −a→Ps2 and a ∈ outP ∪ intP and s3 −−a→S2 s4 and s3 −−a→S3 s4 if s3 −a→Ps4 and a ∈ inP and s3 −−a→S3 smayall if ∀s ∈ statesP (s3 , a, s ) ∈ /− →P and a ∈ U , and smayall is a fresh state such that ∀a ∈ actS .smayall −−a→S3 smayall . Theorem 6. Alternating simulation and observational modal refinement coincide for interface automata in the following sense: for any two interface automata S, T : S ≤a T iff T (S) ≤∗m T (T )
(1)
Theorem 6 suggests that the usefulness of game theoretical models for component theories does not lie in its conformance relation. The crux is the use of control information in synthesis algorithms, when paths to error states are pruned. If this is the case we can construct an interface theory based on modal refinement and modal automata augmented with control information. Since modal refinement is richer and we can use a generalization of the synthesis algorithm used for interface automata, we will obtain a more expressive interface theory. The fact that alternating simulation coincides with the observational version of modal refinement is expected, because Definition 5 embeds a closure on internal transitions. In fact in the absence of internal actions alternating simulation coincides with the regular modal refinement, as described in Definition 2, which is easy to prove. In order to simplify the developments we use the regular modal refinement (≤m ) from now on, even though most of our theorems can reasonably be considered for the observational refinement (≤∗m ), too.
4
Modal I/O Automata
Let us now define modal I/O automata, an extension of modal automata with control information, that will be the main ingredients of our interface theory and the product line theory coming in the next sections.
Modal I/O Automata for Interface and Product Line Theories
73
Definition 7. A modal I/O automaton S is a tuple S = (statesS , startS , inS , outS , intS , −→3 , −→2 ), where statesS is a set of states, startS ∈ statesS is an initial state, inS , outS and intS are pairwise disjoint sets of inputs, outputs and internal actions respectively (actS = inS ∪ outS ∪ intS ), −→3 S ⊆ statesS × actS × statesS is a may-transition relation, and −→2 S ⊆ statesS × actS × statesS is a must-transition relation. Like previously we only consider syntactically consistent modal I/O automata here, so −→2 ⊆ −→3 . The composition for modal I/O automata combines both the modal aspects and the communications aspects. Two modal I/O automata S1 ,S2 are composeable iff their actions only overlap on complementary types: (inS1 ∪ intS1 ) ∩ (inS2 ∪ intS2 ) = ∅ and (outS1 ∪ intS1 ) ∩ (outS2 ∪ intS2 ) = ∅. The composition S1 ⊗ S2 gives rise to a modal I/O automaton S such that statesS = statesS1 × statesS2 , startS = (startS1 , startS2 ), inS = (inS1 \ outS2 ) ∪ (inS2 \ outS1 ), outS = (outS1 \ inS2 ) ∪ (outS2 \ inS1 ), intS = intS1 ∪ intS2 ∪ (inS1 ∩ outS2 ) ∪ (outS1 ∩ inS2 ). The transition relations are given by the following rules (see Fig. 2 for an example): a! a? s1 −− s2 −− →γ s1 →γ s2 a s1 ⊗ s2 − − →γ s1 ⊗ s2 a a∈ / actS2 s1 − −→γ s1 a s1 ⊗ s2 − − →γ s1 ⊗ s2
γ ∈ {2, 3} γ ∈ {2, 3}
a? a! s1 −− s2 −− →γ s1 →γ s2 γ ∈ {2, 3} a s1 ⊗ s2 − − →γ s1 ⊗ s2 a s2 − a∈ / actS1 − →γ s2 γ ∈ {2, 3} a s1 ⊗ s2 − − →γ s1 ⊗ s2
For technical reasons (efficiency and simplicity) we always assume that unreachable states are removed after computing a composition (both here and in later sections). The following theorem is a simple corollary from the general fact that the modal refinement is a precongruence [15,16]: Theorem 8. Modal refinement is a precongruence with respect to the above composition operator: for any four modal I/O automata T1 , T2 , S1 , S2 such that T1 ≤m S1 and T2 ≤m S2 it holds that T1 ⊗ T2 ≤m S1 ⊗ S2 . The composition operator (⊗) defined above corresponds to a usual composition of software (hardware) components. Whenever we use it below we mean an unrestricted connection of components, which does not preclude deadlocks or other kinds of errors. We shall soon introduce two seemingly similar composition operators, (|) and (·) having a very different use. In fact they are algorithms synthesizing specifications of how a result of simple composition (⊗) should be used in order to guarantee the absence of certain errors.
5
A Modal Interface Theory
Interface theories support component based development. The aim is to specify component interfaces and from these interfaces to derive the interfaces of composite components. The novel aspect of the interface theory presented here is that the components can specify both required and allowed behavior, consequently it is suitable for expressing liveness properties.
74
K.G. Larsen, U. Nyman, and A. Wąsowski
In our specific interface theory an interface is given by a modal I/O automaton. A given interface specifies a set of potential implementations (concrete implementations have identical transition relations −→3 = −→2 ). The goal of our interface theory is to be able to use interface descriptions to describe legal implementations of components in a component based system. The implementation relation, the relation that specifies which implementations conform to a given interface description is modal refinement ≤m . From the interface descriptions of two components it should be possible to derive the interface of the combined component. This is done without knowing more about the implementations, than the fact that they conform to their individual interface specification. The result of composing two interfaces is a subset of the result of composing two modal I/O automata, in which all possible internally controllable paths leading to error states are removed. An error state is a state in which one component can output something that the other component might be unable to receive: errSi 1 ,S2 = {(s1 , s2 ) ∈ statesS1 ⊗S2 | there exists a ∈ intS1 ⊗S2 and states s1 , s2 a! S1 s and s a? S2 ) or (s a! S2 such that (s1 −− →3 1 −−→2 −a? −→S21 )} 2 − 2 −−→3 s2 and s1 −
(2)
State 22 on Fig. 2 is an error state, witnessed by the fail action. We are now ready to define the set of states of the composition: statesS1 |S2 =
∞
pruneni (statesS1 ⊗S2 \errSi 1 ,S2 ) ,
(3)
n=0
where prunei (S) = {s ∈ S | ∀s ∀a ∈ intS1 ⊗S2 . s−−a→3 s implies s ∈ S}, which is a monotonic function that removes, from the set of states S, all those states that in one internally controllable step may reach a state that is not in S. See Figure 3 (left) for an example of how pruning works. State 22 has been removed as an error state, then state 21 was pruned as an error state can be reached from it by the internally controllable transition log!. Then all transitions involving states 21 and 22 were removed. State 20 remains in the result as the must transition labeled down is externally controllable. Definition 9 (Composition). The composition of two interfaces S1 and S2 is defined if S1 and S2 are composable modal I/O automata and startS1 ⊗S2 ∈ statesS1 |S2 (see above). The composition results in a modal I/O automaton S1 |S2 such that S1 |S2 = (statesS1 |S2 , startS1 ⊗S2 , inS1 ⊗S2 , outS1 ⊗S2 , intS1 ⊗S2 , −→S31 ⊗S2 ∩ (statesS1 |S2 × actS1 ⊗S2 × statesS1 |S2 ), −→S21 ⊗S2 ∩ (statesS1 |S2 × actS1 ⊗S2 × statesS1 |S2 )). Two interfaces are compatible if the set of states resulting from composition, statesS1 |S2 , contains the initial state (startS1 , startS2 ). A desirable property of an interface theory is that components can be implemented independently of each other once the specifications are known. The following theorem formally states that this theory satisfies the property.
Modal I/O Automata for Interface and Product Line Theories
75
Theorem 10 (Independent Implementability). For any two compatible interfaces S1 , S2 and for any two implementations I1 , I2 , I1 ≤m S1 and I2 ≤m S2 , it holds that I1 ⊗ I2 ≤m S1 |S2 . This has three implications. First, I1 ⊗ I2 would deliver all the required behavior promised by S1 |S2 as long as it interacts with an environment obeying S1 |S2 . Second, I1 ⊗ I2 will not do anything that S1 |S2 would not allow in such an environment. Third, since S1 |S2 does not contain error states then I1 ⊗ I2 will not deadlock. Theorem 11 (Deadlock Freeness Preservation). For any two compatible interfaces S1 , S2 , any two implementations I1 , I2 , so I1 ≤m S1 and I2 ≤m S2 , and any interface T compatible with S1 |S2 , if T ⊗ (S1 |S2 ) has no reachable error states then T ⊗ (I1 ⊗ I2 ) has no reachable error states. Finally the composition operator (|) is commutative and associative up to graph isomorphism.
6
A Product Line Theory
In product line development one typically maintains a family of existing assets that are composed in a bottom-up fashion in order to build a product. Here we assume that existing assets are sufficient to build the product and no genuinely new programming is required. Assets are organized in small subfamilies, that can be thought of as configurable components. Choosing an asset from a subfamily is a configuration process. We model subfamilies as modal I/O automata, and call them variability models, to distinguish them from interfaces. The configuration process amounts to finding a suitable modal refinement of a variability model. There is a need for a mechanism for composing variability models, to enable reasoning about the products that can be constructed using available assets. As in the interface theory we are interested in computing the legal uses for the composition of two models, without reaching error states. However we weaken the requirement this time: we do not require that all possible pairs of implementations give an error free composition, but only that there exists a pair of implementations that can avoid errors under a suitable use. Two variability models are composable if their input, output and hidden actions do not overlap (the general rule for modal I/O automata). Two composable families can be composed, resulting in a description of a higher level component family. The signature of this variability model is found in the same way as for modal I/O automata. The requirement for the description of this more abstract family is that a specification that refines its description can be realized by choosing some concrete implementations from both lower level families involved. So that in effect one can configure the final product by configuring the abstract composed variability model, being sure that the selected configuration can be refined to configurations of each of the smaller components, available in the collection of assets. We give a sufficient condition for a refinement of a variability model to be decomposable.
76
K.G. Larsen, U. Nyman, and A. Wąsowski
The ultimate composition closely resembles the composition (|) for interface automata: it uses the regular modal I/O automata composition (⊗) first and then removes error states. However now only internally controllable required transitions are pruned, while in the interface theory we had also removed states reachable by allowed executions of the same kind. The very existence of allowed internally controlled execution to an error state was considered dangerous in the interface theory—it is not in the product line theory. This is because we are not interested in eliminating errors by all means, but only in making sure that there exist error-free realizations of the specification. For two syntactically composable variability models we define the set of error states, errSv1 ,S2 , to be: errSv1 ,S2 = {(s1 , s2 ) ∈ statesS1 ⊗S2 | there exists a ∈ intS1 ⊗S2 and states s1 , s2 a! a! such that (s1 −− →2 s1 and s2 −−a? −→3 ) or (s1 −−a? −→3 and s2 −− →2 s2 )}
(4)
In Figure 2 (right) state 22 is still an error state, though for a different reason than previously: in state 22 the LinkLayer must be able to produce fail, but the Client is not allowed to receive it. If a product of two variability models contains an error state it means that there exist configurations of composed assets that cannot safely work together. However, in the same spirit as in the interface theory, we can compute the set of legal uses that guarantee that there exist pairs of compatible configurations to interact with them. We remove from the product S1 ⊗ S2 all the states that according to the variability specification must be able to reach an error state. If there is no states left then the two variability models are incompatible. Otherwise we arrive at a specification of states and transitions among the compatible states that constraint possible legal implementations obtained from these two families. Formally: ∞
statesS1 · S2 =
prunenv (statesS1 ⊗S2 \errSv1 ,S2 ) ,
(5)
n=0
where prunev (S) = {s ∈ S | ∀s . ∀a ∈ intS1 ⊗S2 ∪ outS1 ⊗S2 . s−−a→2 s and s ∈ S}. We compute the two transition relations for the composition, by projecting the transition relations of the parallel composition S1 ⊗S2 onto the new set of states: S1 ⊗S2 ∩ (statesS1 ·S2 × actS1 ⊗S2 × statesS1 ·S2 ) −→3S1 ·S2 = −→3
(6)
−→2S1 ·S2
(7)
=
−→2S1 ⊗S2
∩ (statesS1 ·S2 × actS1 ⊗S2 × statesS1 ·S2 ) .
Finally we can state the complete result of the composition: a modal I/O automaton S1 · S2 such that S1 · S2 = (statesS1 ·S2 , (startS1 , startS2 ), inS1 ⊗S2 , outS1 ⊗S2 , S1 ·S2 intS1 ⊗S2 , −→3 , −→2S1 ·S2 ) and all the components are defined above. Definition 12. Two variability models are compatible if they are composable and their composition is nonempty. It turns out that observationally consistent refinements of compositions of variability models are realizable with existing assets. We define observational consistency for states of a single automaton. Let t−−A→2 ∗ t mean that t is reachable
Modal I/O Automata for Interface and Product Line Theories
77
from t via a possible empty sequence of required transitions labeled by possibly different actions from a set A. Definition 13. Let T be a modal automaton and let A ⊆ actT be a set of actions. A relation C ⊆ statesT ×statesT is an observational consistency relation with respect to A if for any pair of states (t1 , t2 ) ∈ C the following two properties hold: 1. ∀t1 . if t1 −−A→2∗ t1 then ∀a ∈ / A. ∀t1 . t1 −−a→2 t1 implies ∃t2 . t2 −−a→3 t2 ∧ (t1 , t2 ) ∈ C. / A. ∀t2 . t2 −−a→2 t2 implies ∃t1 . t1 −−a→3 t1 ∧ (t1 , t2 ) ∈ C. 2. ∀t2 . if t2 −−A→2∗ t2 then ∀a ∈
Two states are observationally consistent if there exists an observational consistency relation relating them. A set of states is said to be observationally consistent with respect to A if all possible pairs of states from the set are observationally consistent with respect to A. An automaton T is observationally consistent with respect to A iff the set {startT } is an observationally consistent set. The following theorem states the existence of decomposition formally: Theorem 14 (Decomposability). Let T1 , T2 be deterministic composable variability models, and S be a configuration (a deterministic variability model itself ) such that S ≤m T1 · T2 , and T1 , S are observationally consistent with respect to actT1 \ actT2 and T2 , S are observationally consistent with respect to actT2 \ actT1 . Then there exist S1 and S2 such that S1 ≤m T1 and S2 ≤m T2 and S1 ⊗ S2 ≤m S. A version of the theorem, not requiring observational consistency, does not hold, which can be demonstrated with a counter-example, not included here. An important corollary is that the decomposition can be carried over down to precise configurations: if a concrete configuration of a product is required, then there exist concrete configurations of assets to realize it. The question whether a specification is realizable with given assets is reduced to establishing observational consistency and a modal refinement between the postulated requirement and the variability model. Consequently the abstract variability model can be communicated to configuration engineers and used to configure final products. Let us close our discussion with a statement that the (·) operator is general enough to describe all implementations safely realizable with existing assets. Theorem 15 (Completeness). For any two compatible variability models T1 , T2 and any two compatible concrete implementation specifications I1 , I2 , where I1 ≤m T1 and I2 ≤m T2 it holds that I1 · I2 ≤m T1 · T2 .
7
Conclusion and Future Work
We have investigated the relation between alternating simulation as used in interface automata and observational modal refinement, concluding that former is a case of the latter. We have argued that the strength of the game theoretic
78
K.G. Larsen, U. Nyman, and A. Wąsowski
approach to interface theories does not lie in alternating refinement itself, but in the labeling of transitions with control information; in partitioning the actions into internally and externally controllable. We have extended modal transition systems with this information and demonstrated that in this way interface theories tracking liveness properties, can be built. Finally we have presented a product line theory describing variability in behavior of component families. In the future we would like to extend the product line theory of Section 6 to a full featured theory based on observational modal refinement and study its properties in depth. Also it appears interesting to investigate the relation between the general notion of alternating refinement [8] and (modal) transition systems, lifting the restrictions accepted in Section 3 after the interface automata model.
References 1. Alfaro, L., Henzinger, T.A.: Interface automata. In: Proceedings of the Ninth Annual Symposium on Foundations of Software Engineering (FSE), Vienna, Austria, ACM Press (2001) 109–120 2. Larsen, K.G., Thomsen, B.: A modal process logic. In: LICS, IEEE Computer Society (1988) 3. Chakabarti, A., de Alfaro, L., Henzinger, T.A., Stoelinga, M.I.A.: Resource interfaces. In Alur, R., Lee, I., eds.: EMSOFT 03: 3rd Intl. Workshop on Embedded Software. LNCS, Springer (2003) 4. Alfaro, L., Henzinger, T., Stoelinga, M.I.A.: Timed interfaces. In SangiovanniVincentelli, A., Sifakis, J., eds.: EMSOFT 02: 2nd Intl. Workshop on Embedded Software. LNCS, Springer (2002) 5. Larsen, K.G., Nyman, U., Wąsowski, A.: Interface input/output automata. In Misra, J., Nipkow, T., Sekerinski, E., eds.: 14th International Symposium on Formal Methods (FM) Hamilton, Canada, August 21–27, 2006 Proceedings. Volume 4085 of LNCS., Springer (2006) 82–97 6. Černá, I., Vařeková, P., Zimmerová, B.: Component substitutability via equivalencies of component-interaction automata. In: FACS’06. (2006) 115–130 To be published in ENTCS. 7. Hermanns, H., Rehof, J., Stoelinga, M.I.A., eds.: Workshop Procedings FIT 2005: Foundations of Interface Technologies. ENTCS, Elsevier Science Publishers (2005) 8. Alur, R., Henzinger, T.A., Kupferman, O., Vardi, M.: Alternating refinement relations. In Sangiorgi, D., de Simone, R., eds.: Proceedings of the Ninth International Conference on Concurrency Theory (CONCUR’98). Volume 1466 of LNCS., Springer (1998) 163–178 9. Alfaro, L., Henzinger, T.A.: Interface-based design. In: In Engineering Theories of Software Intensive Systems, Marktoberdorf Summer School, Kluwer Academic Publishers (2004) 10. Carrez, C., Fantechi, A., Najm, E.: Assembling components with behavioral contracts. Annales del Télécommunications 60 (2005) 11. Parnas, D.L.: On the design and development of program families. IEEE Transactions on Software Engineering Vol. SE-2 (1976) 1–9 12. Czarnecki, K., Eisenecker, U.W.: Generative Programming: Methods, Tools, and Applications. Addison-Wesley (2000)
Modal I/O Automata for Interface and Product Line Theories
79
13. Pohl, K., Böckle, G., van der Linden, F.: Software Product Line Engineering— Foundations, Principles, and Techniques. Springer (2005) 14. Larsen, K.G., Larsen, U., Wąsowski, A.: Color-blind specifications for transformations of reactive synchronous programs. In Cerioli, M., ed.: FASE, Edinburgh, April 2005. LNCS, Springer (2005) 15. Boudol, G., Larsen, K.G.: Graphical versus logical specifications. In Arnold, A., ed.: CAAP. Volume 431 of Lecture Notes in Computer Science., Springer (1990) 57–71 16. Larsen, K.G.: Modal specifications. In Sifakis, J., ed.: Automatic Verification Methods for Finite State Systems. Volume 407 of Lecture Notes in Computer Science., Springer (1989) 232–246
Using History Invariants to Verify Observers K. Rustan M. Leino and Wolfram Schulte Microsoft Research, Redmond, WA, USA {leino,schulte}@microsoft.com Abstract. This paper contributes a technique that expands the set of object invariants that one can reason about in modular verification. The technique uses history invariants, two-state invariants that describe the evolution of data values. The technique enables a flexible new way to specify and verify variations of the observer pattern, including iterators. The paper details history invariants and the new kind of object invariants, and proves a soundness theorem.
1 Introduction The observer pattern is an important and common programming idiom [13]. For example, it is a foundation of the model-view-controller paradigm on which all modern graphical user interfaces rely. The observer pattern consists of a subject object, which contains some data that may change over time, and a number of observer objects. An observer depends on the data of the subject in some way. For example, an observer may display the current data values of the subject in a graphical user interface. For efficiency, such an observer may keep a local copy of the data to be displayed, so that it can redraw the display without needing to consult the subject. A variation of the observer pattern is the iterator pattern [13], where the subject is a collection and the observers are iterators. An observer may iterate through the items of the collection, providing clients with one data item at a time. These two patterns are different mainly in that the collection does not have references to its iterators. In this paper, we focus on the one-to-many dependency between the subject and observers, which the two patterns have in common, so we will simply refer to both of them as the observer pattern. To verify the correctness of a program that uses the observer pattern, it is necessary to be able to write specifications for both subject and observers. We are interested in modular verification of programs, which allows a program’s modules (or classes) to be verified separately. In order for the verification process to be sound, the separately verified correctness of each module should imply the correctness of the whole program. For the observer pattern, this means we want to be able to specify and verify the subject separately from the observers. Verifying the observer pattern is a challenge. The difficulty is that the data consistency of an observer, which is expressed as an object invariant, depends on the data of the subject. Updates of the subject and the maintenance of these invariants must therefore be coordinated. The situation is further complicated by the fact that the subject may not be able to reach (through object references in the heap) all the observers, and the observer invariants, let alone the observer classes, may not be available in the separateverification context of the subject. A partial solution, which works when the observers are known by the subject, has been given by Barnett and Naumann [5]. R. De Nicola (Ed.): ESOP 2007, LNCS 4421, pp. 80–94, 2007. c Springer-Verlag Berlin Heidelberg 2007
Using History Invariants to Verify Observers
81
In this paper, we introduce a specification and verification methodology that is wellsuited for supporting the kinds of object invariants one wants to write in observer classes. In a nutshell, the subject advertises how its data values evolve over time, and this allows observers to declare object invariants that depend on the subject’s data, provided the object invariants are insensitive to the evolution of the subject. In more detail, our solution consists of the following ingredients: 1. We use history invariants to specify how an object may evolve. A history invariant is a reflexive and transitive two-state predicate that relates any earlier state to any later state in a program’s execution. In our solution, subjects have history invariants. 2. We allow an object invariant of an observer to access the fields of the subject, provided the dereference goes via a field annotated with a new field modifier, subject . If an object invariant dereferences a subject field, we call it an observer invariant. 3. We explicitly keep track of whether an object invariant is known to hold, in which case we say that the object is consistent. 4. An observer invariant can be assumed if the observer and its subject are both in the consistent state. 5. For the soundness of modular verification, each observer invariant gives rise to an additional proof obligation, which is that it be maintained under the history invariant of the subject. Our main contributions in this paper are 2, 4, and 5, which together give a methodology to specify and verify observer patterns, including its iterator variation. Ingredient 3 comes from the Boogie methodology, which we explain in Section 2. For ingredient 1, history invariants were introduced by Liskov and Wing [22] under the name of constraints, and are supported by the Java Modeling Language (JML) [18]; our paper contributes a formalization of history invariants in the presence of reentrancy and representation objects. Example. Figure 1 shows our solution to specifying a verifiable observer pattern. An observer’s cache depends on the state of the subject. When a subject’s state is updated, it notifies all of its observers, so that they can synchronize their caches. We use a field vers (for “version”) in both the subject and observers, so that an observer can detect whether it is currently synchronized with the subject. We have found this specification idiom useful for all of our observer-pattern examples, though our methodology does not depend on it. (The vers field is in fact used in the implementation of the iterator pattern in both .NET [1] and Java [14], where it is used to detect modifications of the underlying collection when there is still an active iterator.) Note that between the update of state and vers in method Update , the observer’s invariant is broken. Our methodology handles this on account of ingredient 4. At the end of the expose block, the observer’s invariant holds again, on account of the specification idiom used in the observer invariant. The program is correct and satisfies the proof obligations of our methodology: the history invariants are admissible, because they are reflexive and transitive; the updates performed by the Subject methods are allowed, because they maintain the history invariants; and the observer invariants are admissible, because they are maintained under the subject’s history invariants.
82
K.R.M. Leino and W. Schulte
interface IObserver { void Notify(); }
class MyObserver : IObserver { readonly subject Subject subj ; int cache; int vers;
class Subject { rep Setpeer IObserver obs; int state; int vers;
invariant vers subj .vers; invariant subj = null ∧ subj .vers = vers ⇒ cache = subj .state;
history invariant old(vers) vers; history invariant vers = old(vers) ⇒ state = old(state);
MyObserver (Subject s) requires s = null; ensures owner = s.owner ; { initialize (this) { cache = s.Get(); vers = s.vers; sub = s; owner = s.owner ; } }
Subject() { initialize (this) { state = 0; vers = 0; obs = new Setpeer IObserver (); } }
void Notify() { expose (this) { cache = s.Get(); vers = s.vers; } }
void Register (IObserver o) requires o = null ∧ o.owner = owner ; { expose (this) { obs.Add (o); } o.Notify(); } void Update(int y) { expose (this) { state = y; vers = vers + 1; } foreach (IObserver o in obs) { o.Notify(); } }
}
int Get() ensures result = state; { return state; }
}
void DisplayData() { ... }
class Program { void Main() { Subject s = new Subject(); MyObserver o = new MyObserver (s); s.Register (o); s.Update(57); } }
Fig. 1. An example of the observer pattern, where class Subject uses objects of type IObserver as its observers. Each of the two columns in this figure is a separately verifiable module. The details of the constructs used in this example are explained in the paper. As details that make the verification go through, we have assumed that each object has a reference valued owner and a boolean inv field. Further, we assumed that the condition PeerConsistent(x ) ∧ ¬x .owner .inv is implicitly added as a postcondition to all constructors (with this for x ), as a precondition to all methods (with this for x ), and as a precondition to all constructors and methods (for each reference parameter x ). On entry to a constructor body, we also assume that the new object starts off with some arbitrary, unshared, and exposed owner. Finally, we assume that all methods are implicitly allowed to modify the fields of this and of any parameter x , and also the fields of the peers of this and x .
Using History Invariants to Verify Observers
83
Outline. In the next section, we describe the foundations of our work, as well as a body of previous work that tackles the problem of specifying and verifying the observer pattern. In Section 3, we define history invariants and their associated proof obligations. In Section 4, we define the additional machinery needed to support observer invariants, culminating in a soundness theorem about them. The paper wraps up with additional examples (Section 5), more related work (Section 6), future work (Section 7), and conclusions (Section 8).
2 Methodologies for Object Invariants In this section, we review how a modular-verification system deals with objects invariants. We also look at how previous work has tackled the problem of specifying and verifying the observer pattern. In this section and throughout most of the paper, we ignore the issue of subclassing. Visible-state semantics. The first question to address when designing a methodology for object invariants is: when does the invariant of an object hold? A simple answer is: whenever no constructor or method of the object is active. This simple methodology is called visible-state semantics [25,18], because an object’s invariant holds in all states visible to public clients of the object. Because of the possibility of reentrancy in object-oriented programs, we need to be concerned about the situation where an object a breaks its invariant, calls a method on an object b , and then b calls back into some method of a that assumes the invariant to hold. Visible-state semantics prevents this situation by using alias control, as with the universe type system [25,26]: a can be used only as a read-only object while the method on b is invoked, restricting b ’s use of a to read-only methods, and visible-state semantics does not allow read-only methods to rely on the invariant. Boogie methodology. A richer methodology is the Boogie methodology supported by Spec# [4]. The basic Boogie methodology [2] adds a bit inv to every object. If inv = true , the object is said to be consistent, its invariant holds, and its fields are not allowed to be updated. If inv = false , the object is said to be mutable, its invariant may be violated, and the fields are allowed to be updated. This guarantees the following program invariant (a condition that holds in all reachable states of the program): ( ∀ o • o.inv ⇒ Inv (o) )
(1)
where, here and throughout, the quantification ranges over non-null, allocated objects and Inv (o) denotes the declared object invariant of o . For the moment, we assume Inv (o) to be an intra-object invariant, that is, that it depends only on the fields declared in the class of o . By mentioning inv explicitly in preconditions, methods can indicate whether or not they expect the object invariant to hold on entry. The Boogie methodology controls changes to the inv field by introducing two special program statements. The statement unpack o changes o.inv from true to false , and the statement pack o changes o.inv from false to true , after first checking that Inv (o) holds. (This check can be done either by static verification or by run-time checking. In this paper, we focus on static verification.)
84
K.R.M. Leino and W. Schulte
Use of unpack and pack is typically stylized, so in this paper we instead use a block statement initialize (o) {S } , which abbreviates: S ; pack o and a block statement expose (o) {S } , which abbreviates: unpack o; S ; pack o The former typically wraps the body of a constructor and the latter wraps the bodies of other methods, as we have seen in Fig. 1. Owners and representation objects. Going beyond intra-object invariants, we now consider invariants that span several objects. To meet preconditions involving inv , it becomes necessary for an object o to know the state of its representation objects (or rep objects), that is, the objects that o uses in its implementation. The Boogie methodology lets a class declare a field with the rep modifier to say that the field