• No results found

Compositional and sound seasoning about active objects with shared futures

N/A
N/A
Protected

Academic year: 2022

Share "Compositional and sound seasoning about active objects with shared futures"

Copied!
28
0
0

Laster.... (Se fulltekst nå)

Fulltekst

(1)

UNIVERSITY OF OSLO Department of Informatics

Compositional and Sound Reasoning

about Active Objects with Shared Futures Research Report 437 Crystal Chang Din Olaf Owe

ISBN 978-82-7368-402-8 ISSN 0806-3036

February 2014

(2)

Contents

1 Introduction 2

2 A Core Language with Shared Futures 3

2.1 An Example . . . 4

3 Observable Behaviour 7 3.1 Communication Events . . . 7

3.2 Communication Histories . . . 8

4 Operational Semantics 9 4.1 Operational Rules . . . 9

4.2 Semantic Properties . . . 12

5 Program Verification 13 5.1 Local Reasoning . . . 14

5.2 Soundness . . . 15

5.3 Compositional Reasoning . . . 20

5.4 Soundness Proof of Compositional Reasoning . . . 21

5.5 Example . . . 22

6 Related Work and Conclusion 23

(3)

Compositional and Sound Reasoning about Active Objects with Shared Futures

Crystal Chang Din, Olaf Owe

Dept. of Informatics, University of Oslo, P.O. Box 1080 Blindern, N-0316 Oslo, Norway.

E-mails: {crystald,olaf}@ifi.uio.no

Abstract

Distributed and concurrent object-oriented systems are difficult to analyze due to the complexity of their concurrency, communication, and synchronization mech- anisms. Thefuture mechanismextends the traditional method call communication model by facilitating sharing of references to futures. By assigning method call result values to futures, third party objects may pick up these values. This may reduce the time spent waiting for replies in a distributed environment. However, futures add a level of complexity to program analysis, as the program semantics becomes more involved.

This paper presents a model for asynchronously communicating objects, where return values from method calls are handled by futures. The model facilitates in- variant specifications over the locally visible communication history of each object.

Compositional reasoning is supported and proved sound, as each object may be specified and verified independently of its environment. A kernel object-oriented language with futures inspired by the ABS modeling language is considered. A compositional proof system for this language is presented, formulated within dy- namic logic.

1 Introduction

Distributed systems play an essential role in society today. However, quality assurance of distributed systems is non-trivial since they depend on unpredictable factors, such as different processing speeds of independent components. Therefore, it is highly challeng- ing to test such distributed systems after deployment under different relevant conditions.

These challenges motivates frameworks combining precise modeling and analysis with suitable tool support. In particular,compositional verification systems allow the differ- ent components to be analyzed independently from their surrounding components.

Object orientation is the leading framework for concurrent and distributed systems, recommended by the RM-ODP [26]. However, method-based communication between concurrent units may cause busy-waiting, as in the case of remote and synchronous method invocation, e.g., Java RMI [3]. Concurrent objects communicating by asyn- chronous method callshave been proposed as a promising framework to combine object- orientation and distribution in a natural manner. Each concurrent object encapsulates its own state and processor, and internal interference is avoided as at most one process

This work was done in the context of the EU project FP7-231620 HATS: Highly Adaptable and Trustworthy Software using Formal Models(http://www.hats-project.eu) and supported by the Short Term Scientific Mission, COST Action IC0701.

(4)

is executing on an object at a time. Asynchronous method calls allow the caller to con- tinue with its own activity without blocking while waiting for the reply, and a method call leads to a new process on the called object. The notion of futures [6, 23, 30, 35]

improves this setting by providing a decoupling of the process invoking a method and the process reading the returned value. By sharingfuture identities, the caller enables other objects to wait for method results. However, futures complicate program analysis since programs become more involved compared to semantics with traditional method calls, and in particular local reasoning is a challenge.

The execution of a distributed system can be represented by itscommunication history ortrace; i.e., the sequence of observable communication events between system compo- nents [8, 25]. At any point in time the communication history abstractly captures the system state [11, 12]. In fact, traces are used in semantics for full abstraction results (e.g., [1, 27]). Thelocal history of an object reflects the communication visible to that object, i.e., between the object and its surroundings. A system may be specified by the finite initial segments of its communication histories, and a history invariant is a predicate which holds for all finite sequences in the set of possible histories, expressing safety properties [5].

In this work we consider a kernel object-oriented language, where futures are used to manage return values of method calls. Objects are concurrent and communicate asyn- chronously. We formalize object communication by a four event operational semantics, capturing shared futures, where each event is visible to only one object. Consequently, the local histories of two different objects share no common events, and history invariants can be established independently for each object. We present adynamic logicproof sys- tem for class verification, facilitating independent reasoning about each class. A verified class invariantcan be instantiated to each object of that class, resulting in an invariant over the local history of the object. Modularity is achieved as the independently derived history invariants can be composed to formglobal system specifications. Global history consistency is captured by a notion of historywellformedness. The formalization of ob- ject communication extends previous work [18] which considered concurrent objects and asynchronous communication, but without futures.

Paper overview. Sect. 2 presents a core language with shared futures. The commu- nication model is presented in Sect. 3, and Sect. 4 defines the operational semantics.

Sect. 5 presents the compositional reasoning system, and Sect. 6 contains related work and concludes the paper.

2 A Core Language with Shared Futures

Afutureis a placeholder for the return value of a method call. Each future has a unique identity which is generated when a method is invoked. The future is resolved upon method termination, by placing the return value of the method in the future. Thus, unlike the traditional method call mechanism, the callee does not send the return value directly back to the caller. However, the caller may keep a reference to the future, allowing the caller tofetch the future value once resolved. References to futures may be shared between objects, e.g., by passing them as parameters. After achieving a future reference, this means that third party objects may fetch the future value. Thus, the future value may be fetched several times, possibly by different objects. In this manner, shared futures provide an efficient way to distribute method call results to a number of objects.

For the purposes of this paper, we consider a core object-oriented language with futures, presented in Fig 1. It includes basic statements for first order futures, inspired byABS [24]. Class instances are concurrent, encapsulating their own state and processor. Each method invoked on the object leads to a new process, and at most one process is executing

(5)

Cl :: classCprT cpsq trT wr:es?s s Mu class definition M :: T mprT xsq trvarrT xss?s; returneu method definition T :: C|Int|Bool|String|Void|Fut T¡ types

v :: x|w variables (local or field)

e :: null|this |v|cp|fpeq pure expressions s :: v:e|fr:v!mpeq |v:e? statements

|skip|ifethensrelsess? fi|s;s

|whileedosod|v:newCpeq

Figure 1: Core language syntax, with C class name, cp formal class parameter, m method name,w fields,xmethod parameter or local variable, and wherefr is a future variable. We letr s andr s?denote repeated and optional parts, respectively, andeis a (possibly empty) expression list. Expressionseand functionsf are side-effect free.

on an object at a time. Object communication isasynchronous, as there is no explicit transfer of control between the caller and the callee. Methods are organized in classes in a standard manner. A classC takes a list of formal parameterscp, defines fields w, initialization blocksand methodsM. There is read-only access to the parameterscp. A method definition has the formmpxqtvar y; s; returneu, ignoring type information, where x is the list of parameters, y an optional list of method-local variables, s is a sequence of statements, and the value ofeis returned upon termination.

A future variablefr is declared by Fut T¡fr, indicating thatfr may refer to futures which will eventually contain values of typeT. The call statementfr:x!mpeqinvokes the method m on object xwith input values e. The identity of the generated future is assigned tofr, and the calling process continues execution without waiting forfr to become resolved. The query statementv :fr? is used to fetch the value of a future.

The statement blocks untilfr is resolved, and then assigns the value contained infr to v. The language contains additional statements for assignment,skip, conditionals, and sequential composition.

We assume that call and query statements are well-typed. Ifxrefers to an object where m is defined with no input values and return type Int, the following is a well-typed blocking method call: Fut Int¡fr; Intv; fr:x!mpq; v:fr?.

To avoid blocking,ABS provides statements for process control, including a statement await fr?, which releases the current process as long as fr is not yet resolved. This gives rise to more efficient computing with futures. It is possible to add a treatment of process release statements as a straight forward extension of the present work, following the approach of [18]. We here focus on a core language for futures, with a simple seman- tics, avoiding specialized features such as process control. The core language ignores ABS features that are orthogonal to shared futures, including interface encapsulation, inheritance, local synchronous calls, and internal scheduling of processes by means of cooperative multitasking. We refer to the report version of this paper for a treatment of these issues [19].

2.1 An Example

In order to illustrate the usage of futures, we consider the problem of counting the number of occurrences of each word in a large collection of documents. We consider the computing model MapReduce in Fig. 2. MapReduce is invented and used heavily by Google for efficient distributed computing over large data sets [17]. It has three major steps: Map, Shuffle and Reduce. The Map phase runs over input data, which might be

(6)

data 1

data 2

output worker

worker

key1 key2 key1 key2

key2

key3

Map Shuffle

worker

worker Reduce

key1 worker

key3

key3

Figure 2: MapReduce model.

a database or some files, and output key-value pairs. The input data is split in parts so they can be processed by workers in parallel. The second step is the Shuffle phase, which collates values with the same key together. At last, the Reduce function is called by workers in parallel on the shuffled data distinguished by keys.

We assume two interfaces, WorkerI and MapReduceI. The interfaceWorkerI is imple- mented by a classWorker shown in Listing. 1, in which the methodinvokeMap takes a file and emits a list of pairs. Such that each word in the file is associated with a counting number: ‘1’ in this example. For instance, if the content of the file is ‘I am fine’, the output ofinvokeMapis ‘(I,1),(am,1),(fine,1)’. The methodinvokeReducein classWorker sums together all counts emitted for a particular word. For instance,invokeReducetakes

‘(am, (1,1))’ and outputs 2.

The interfaceMapReduceI is implemented by classMapReduce, shown in Listing. 2. We here assume generic data types for sets, lists, and pairs, the latter withfst andsnd to extract the first and second element, respectively.

The input to the methodmapReduce is a list of files each starts with a filename and con- tains a list of words, i.e. the content of the file. Each file are handled by a worker in par- allel. To achieve concurrency, for each file the object ofMapReducecalls asynchronously the method invokeMap on the assigned worker w. This is realized by the statement fMap := w!invokeMap(filename, content). The functioninsertElementcollects all the futures into a setfMapResults. Next is the Shuffle phase. The functiontakerandomly

class Worker () implements WorkerI { List<Pair<String, Int>>

invokeMap(String filename, List<String> content) {...}

Int invokeReduce(String key, List<Int> value) {...}

...

}

class WorkerPool() implements WorkerPoolI { WorkerI getWorker() {// provides idle workers,

// or generates new workers if needed.}

}

Listing 1: Sketch of the classes Worker and WorkerPool.

(7)

class MapReduce(WorkerPoolI wp) implements MapReduceI { List<Pair<String, Int>> mapReduce(

List<Pair<String, List<String>>> files) {

Set<Fut<List<Pair<String, Int>>>> fMapResults := EmptySet;

Set<Pair<String, Fut<Int>>> fReduceResults := EmptySet;

List<Pair<String, Int>> result := Nil;

// Map phase //

while (~isEmpty(files)) do ...

WorkerI w := wp.getWorker();

...

Fut<List<Pair<String, Int>>>

fMap := w!invokeMap(filename, content);

fMapResults := insertElement(fMapResults, fMap) od;

// Shuffle phase //

while(~emptySet(fMapResults)) do Fut<List<Pair<String, Int>>>

fMapResult := take(fMapResults);

...

List<Pair<String, Int>> mapResult := fMapResult?;

... // collates values with the same key together od;

// Reduce phase //

while(~emptySet(keys)) do ...

WorkerI w := wp.getWorker();

Fut<Int> fReduce := w!invokeReduce(key, values);

fReduceResults := insertElement(

fReduceResults, Pair(key, fReduce)) od;

while (~emptySet(fReduceResults)) do

Pair<String, Fut<Int>> reduceResult := take(fReduceResults);

...

String key := fst(reduceResult);

Fut<Int> fValue := snd(reduceResult);

Int value := fValue?;

result := Cons(Pair(key, value), result) od;

return result;

} }

Listing 2: The MapReduce class. Here the notationx:o.mpeqabbreviates u: o!mpeq;x:u?(for some fresh futureu) to de-emphasize trivial usage of futures.

(8)

o' o

u

<o o', u, m, e >

< o', u, m, e>

<o , u, e>

o''

<o o', u, m, e >

<o'' , u, e>

<o'' , u, e>

Figure 3: A method call cycle: object o calls a methodm on objecto1 with future u.

The events on the left-hand side are visible too, those in the middle are visible too1, and the ones on the right-hand side are visible too2. There is an arbitrary delay between message receiving and reaction.

extracts an element from a set. The methodmapReduce waits upon each future, gets the results from each future: mapResult := fMapResult?, and collates all the values with the same key, i.e. word, together. For instance, ‘(I,1),(am,1),(who,1),(I,1),(am,1)’

is shuffled to ‘(I,(1,1)),(am,(1,1)),(who,(1))’. In the Reduce phase, each ‘key’ and the corresponding values are handled by a worker in parallel. In the same way as the Map phase for achieving concurrency, the first part of the reduce phase calls asynchronously the methodinvokeReduce on the assigned worker w. This is realized by the statement fReduce := w!invokeReduce(key, values). The function insertElement collects all the futures into a setfReduceResults. At the very last, the methodmapReduce waits upon each future, gets the results from each future: value := fValue?, and return the number of occurrences of each word in a large collection of files.

Here the future mechanism is exploited to make an efficient implementation, avoiding blocking calls on the workers: The Map phase is not waiting for the workers to do invokeMap, storing future identities only, thereby allowing many workers to start and work concurrently. Likewise in the loop callinginvokeReduce, only futures identities are recorded. Blocking is delayed to phases where the future value information is actually needed.

3 Observable Behaviour

In this section we describe a communication model for concurrent objects communicating by means of asynchronous message passing and futures. The model is defined in terms of theobservable communication between objects in the system. We consider how the execution of an object may be described by differentcommunication events which reflect the observable interaction between the object and its environment. The observable behavior of a system is described by communication histories over observable events [8, 25].

3.1 Communication Events

Since message passing is asynchronous, we consider separate events for method invoca- tion, reacting upon a method call, resolving a future, and for fetching the value of a future. Each event is observable to only one object, which is the one thatgenerates the

(9)

event. The events generated by a method call cycle is depicted in Fig. 3. The object o calls a method m on object o1 with input values e and where u denotes the future identity. An invocation message is sent fromotoo1when the method is invoked. This is reflected by theinvocation event xoÑo1,u, m, eygenerated byo. Aninvocation reaction event xoo1,u, m, ey is generated byo1 once the method starts execution. When the method terminates, the objecto1 generates thefuture event xÐo1,u, m, ey. This event reflects thatu is resolved with return valuee. The fetching event xo,u, ey is gener- ated byo when o fetches the value of the resolved future. Since future identities may be passed to other objects, e.g,o2, this object may also fetch the future value, reflected by the eventxo2,u, ey, generated byo2. The creation of an objecto1 by an object o is reflected by the event xo ÝÑnew o1, C, ey, where o1 is the instance of classC and eare the actual values for the class parameters. Let typeMidinclude all method names, and letDatabe the supertype of all values occurring as actual parameters, including future identitiesFidand object identitiesOid.

Definition 1 (Events) Let caller,callee,receiver : Oid, future : Fid, method : Mid, class:Cls, args:ListrDatas, and result:Data. Communication eventsEvinclude:

• Invocation eventsxcallerÑcallee,future,method,argsy, generated by caller.

• Invocation reaction eventsxcallercallee,future,method,argsy, generated by callee.

• Future eventsxÐcallee,future,method,resulty, generated by callee.

• Fetching eventsxreceiver,future,resulty, generated by receiver

• Creation eventsxcallerÝÑnewcallee,class,argsy, generated by caller

Events may be decomposed by functions. For instance, _.result : Ev Ñ Data is well- defined for future and fetching events, e.g.,xÐo1,u, m, ey.resulte.

For a method invocation with futureu, the ordering of events depicted in Fig. 3 is de- scribed by the following regular expression (usingfor sequential composition of events)

xoÑo1,u, m, ey xoo1,u, m, ey xÐo1,u, m, eyrx_,u, eys

for some fixedo,o1,m,e,e, and where _ denotes an arbitrary value. This implies that the result value may be read several times, each time with the same value, namely that given in the preceding future event.

3.2 Communication Histories

The execution of a system up to present time may be described by its history of observ- able events, defined as a sequence. A sequence over some typeT is constructed by the empty sequenceεand the right append function __:SeqrTs T ÑSeqrTs(where “_”

indicates an argument position). The choice of constructors gives rise to generate induc- tive function definitions, in the style of [12]. Projection, _{_:SeqrTsSetrTs ÑSeqrTs is defined inductively byε{s εandpaxq{s ifxPsthenpa{sqxelsea{sfi, for a:SeqrTs,x:T, ands:SetrTs, restrictingato the elements ins. We use dot notation to extract components from record-like structures, for instancexoÑo1, f, m, ey.calleeis o1, and also lift the dot notation to sequences. For a sequencehof events,h{ Ðis the subsequence of invocation events, andph{ Ðq.callee is the sequence of callee elements from these invocation events.

Acommunication history for a setS of objects is defined as a sequence of events gener- ated by the objects inS. We say that a history isglobal ifS includes all objects in the system.

(10)

Definition 2 (Communication histories)The communication historyhof a system of objectsS is a sequence of typeSeqrEvs, such that each event in his generated by an object inS.

We observe that thelocal history of a single objectois achieved by restricting Sto the single object, i.e., the history contains only elements generated byo. For a historyh, we leth{o abbreviate the projection ofhto the events generated byo. Since each event is generated by only one object, it follows that the local histories of two different objects are disjoint.

Definition 3 (Local histories)For a global historyhand an objecto, the projection h{ois the local history ofo.

4 Operational Semantics

Rewriting logic [31] is a logical and semantic framework in which concurrent and dis- tributed systems can be specified in an object-oriented style. Unbounded data structures and user-defined data types are defined in this framework by means of equational spec- ifications. Rewriting logic extends membership equational logic with rewrite rules, so that in arewrite theory, the dynamicbehavior of a system is specified as a set of rules on top of itsstatic part, defined by a set of equations. Informally, alabeled conditional rewrite ruleis a transitionl: tÝÑt1 if cond,wherelis alabel,tandt1are terms over typed variables and function symbols of given arities, andcond is a condition that must hold for the transition to take place. Rewrite rules are used to specify local transitions in a system, from a state fragment that matches the patternt, to another state fragment that is an instance of the pattern t1. Rules are selected nondeterministic if there are at least two rule instantiations with left-hand sides matching overlapping fragments of a term. Concurrent rewriting is possible if the fragments are non-overlapping. Fur- thermore, matching is made modulo the properties of the function symbols that appear in the rewrite rule, like associativity, commutativity, identity (ACI), which introduces further nondeterminism. The Maude tools [9] allow simulation, state exploration, reach- ability analysis, and LTL model checking of rewriting logic specifications. The state of a concurrent object system is captured by aconfiguration, which is an ACI multiset of units such as objects and messages, and other relevant system parts, which in our case includes futures. Concurrency is then supported in the framework by allowing con- current application of rules when there are non-overlapping matches of left-hand sides.

The following context rule, which is implicit in rewriting logic, describes interleaving semantics (lettingG,G1,G2denote subconfigurations):

context rule G1ÑG2

G G1ÝÑG G2

4.1 Operational Rules

For our purpose, aconfiguration is a multiset of (concurrent) objects, classes, messages, futures, as well as a representation of the global history. We use blank-space as the multiset constructor, allowing ACI pattern matching. Objects have the formobject(Id : o,A) whereois the unique identity of the object andAis a set of semantic attributes, including

(11)

Cl: c the classc of the object,

Pr : s the remaining codes of the active process, Lvar : l the local statel of the active process, including

method parameters and the implicit future identity destiny, Flds : a the state aof the fields, including class parameters,

Cnt : n a countern used to generate future identities, Mtd: m the namem of the current method.

Similarly, classes have the form

classpId:c,Par:z,Flds:a,Init:s,Mtds:q,Cnt:nq

wherec is the class name, z the class parameters,a the fields, ands the initialization code. The variableq is a multiset of method definitions of the form

pm, p,l,sq

wherem is the method name,pis the list of parameters,l contains the local variables (including default values), and s is the code. The counter n in the class is used to generate object identities.

Messages have the form of invocation events as described above. And, a future unit is of the formfutpId:u,Val:vqwhereu is the future identity andv is its value. The global history is represented by a unithistphq where h is finite sequence of events (initially empty). Remark that a system configuration contains exactly one history. The history is included to define the interleaving semantics upon which we derive our history-based reasoning formalism.

The initial state of an objectoof classCwith actual class parameter valuesvis denoted inito:Cpvqand is defined by

inito:CpvqobjectpId:o,Cl:C,Pr:initC,Lvar:H,Flds:a,Cnt: 0,Mtd:initq wherea is the initial state of the object fields given byrthis ÞÑo,ParC ÞÑ v,FldsC ÞÑ ds. Here ParC, FldsC, and initC, represent the class parameters, the fields, and the initialization code ofC, respectively. The class parametersParC are initialized by the actual parametersv, the fieldsFldsCare initialized by default valuesd(of the appropriate types), and the initial code is ready to be executed with an empty local state.

A system is given by a set of self-contained classes Cl, including a class Main, with- out class parameters, used to generate the initial object initmain:M ainpεq. The initial configuration of a system is defined by

initClCl initmain:M ainpεq histpεq

The operational rules are summarized in Fig. 4. The rules for skip, assignment, initialized variable declarations, if- and while-statements are standard. Note thatpa;lqrepresents the total object state, composed by a, the state of the fields/class parameters, andl, the state of the local variables/parameters of the method. Lookup of a variable if left to right, i.e.,l is tried before a. Expressionse without side-effects are evaluated by a semantic function depending on the total state, i.e.,evalpe,pa;lqq.

Method invocation is captured by the rule call. The generated future identityftpo, nq is globally unique (assuming thenextfunction is producing locally unique values). The future unit itself is not generated yet; it will be generated by return from the called method.

If there is no active process in an object, denotedPr : empty, a method call is selected for execution by rule method. The invocation message is consumed by this rule, and the future identity of the call is assigned to the implicit parameter destiny. Method

(12)

skip: objectpId:o,Pr: pskip;sqq ÝÑobjectpId:o,Pr:sq assign: objectpId:o,Pr:pv:e;sq,Lvar:l,Flds:aq

ÝÑ

if vin LvarthenobjectpId:o,Pr:s,Lvar:lrvÞÑevalpe,pa;lqqs,Flds:aq elseobjectpId:o,Pr:s,Lvar:l,Flds:arvÞÑevalpe,pa;lqqsq

init: objectpId:o,Pr:pT v:e;sq,Lvar:l,Flds:aq ÝÑ

objectpId:o,Pr:pT v;v:e;sq,Lvar:l,Flds:aq

if-else: objectpId:o,Pr:pif e then s1else s2f i;sq,Lvar:l,Flds:aq ÝÑ

if evalpe,pa;lqqthenobjectpId:o,Pr:ps1;sq,Lvar:l,Flds:aq elseobjectpId:o,Pr:ps2;sq,Lvar:l,Flds:aq

while: objectpId:o,Pr:pwhile e do s1od;sq,Lvar:l,Flds:aq ÝÑ

objectpId:o,Pr:pif e then s1;while e do s1od f i;sq,Lvar:l,Flds:aq

new: histphqclasspId:C,Cnt:nq

objectpId:o,Pr:pv:new Cpeq;sq,Lvar:l,Flds:aq ÝÑ

histph xonewÝÑobpC, nq, C,evalpe,pa;lqqyqclasspId:C,Cnt:nextpnqq objectpId:o,Pr:pv:obpC, nq;sq,Lvar:l,Flds:aq

initobpC,nq:Cpevalpe,pa;lqqq

call: histphqobjectpId:o,Pr:pfr:v!mpeq;sq,Lvar:l,Flds:a,Cnt:nq ÝÑ

msghistphmsgq

objectpId:o,Pr:pfr:ftpo, nq;sq,Lvar:l,Flds:a,Cnt:nextpnqq

method: xo1Ño,u, m, vyhistphqclasspId:c,Mtds:pqpm, p, l, sqqq objectpId:o,Cl:c,Pr:empty,Flds:aq

ÝÑ

histph xo1o,u, m, vyqclasspId:c,Mtds:pqpm, p, l, sqqq

objectpId:o,Cl:c,Pr:s,Lvar:lrpÞÑvsrdestinyÞÑus,Flds:a,Mtd:mq return: histphqobjectpId:o,Pr:returne,Lvar:l,Flds:a,Mtd:mq

ÝÑ

histpho,evalpdestiny, lq, m,evalpe,pa;lqqyq futpId:eval(destiny,l),Val:eval(e,(a;l))q objectpId:o,Pr:empty,Flds:aq

query: histphqfutpId:u,Val:dqobjectpId:o,Pr:pv:e?;sq,Lvar:l,Flds:aq ÝÑ

histph xo,u,dyqfutpId:u,Val:dq objectpId:o,Pr:pv:d;sq,Lvar:l,Flds:aq ifevalpe,pa;lqq u

Figure 4: Operational rules, using the standard rewriting logic convention that irrele- vant attributes may be omitted in a rule. Variables are denoted by single characters (the uniform naming convention is left implicit),pa;lqrepresents the total object state, and arv ÞÑ ds is the state a updated by binding the variable v to the data value d.

Theevalfunction evaluates an expression in a given state, andinis used for testing do- main membership. In rulecall,msgdenotesxoÑevalpv,pa;lqq,ftpo, nq, m,evalpe,pa;lqqy where ftpo, nq is the generated future identity. In rule new, obpC, nq is the generated object identity.

execution is completed by rule return, and a future value is fetched by rule query. A query can only succeed if the appropriate future unit is generated. A future unit appears in the configuration when resolved by rulereturn, which means that a query statement blocks until the future is resolved. Remark that rulequerydoes not remove the future unit from the configuration, which allows several processes to fetch the value of the same future.

In the rule new, the new object gets a unique identity obpC, nq, given by that of the generating object and a counter, the actual class parameters are evaluated, and the ini-

(13)

tialization is performed. The given language fragment may be extended with constructs for inter object process control and suspension, e.g., by using theABS approach of [18].

4.2 Semantic Properties

Semantic properties are stated by means of notions of validity. We defineglobal validity (denoted|ù) andlocal validity with respect to a classC(denoted|ùC). A global object system initiated by a configurationinitCl is said to satisfy a global invariant property Iphq, if the global historyhof any reachable configurationGsatisfiesIphq:

Cl|ùIphq @G . initClÝÑG^G.histhñIphq

whereÝÑdenotes the transitive and reflexive extension of the transition relation, lifted to configurations, and whereG.histextracts the history of the configurationG.

Similarly, an object system initiated by a configurationinitCl is said to satisfy aC-local invariant property Iphq if every object o of class C in any reachable configuration G satisfiesIph{oq, i.e., the projection from global history to the objecto:

Cl|ùCIphq @G, o . initClÝÑG^G.histh^oPG.obj^Gros.classCñIph{oq whereG.objextracts the object identities from the objects in the configuration G.

We next provide notions of global and local wellformedness for global histories. We first introduce some notation and functions used in defining wellformed histories. For sequencesaandb, letaew xdenote thatxis the last element ofa,agreepaqdenote that all elements (if any) are equal, anda¤bdenote thatais a prefix ofb. Letrx1, x2, . . . , xis denote the sequence ofx1, x2, . . . , xifori¡0(allowing repeated partsr...s). Functions for event decomposition are lifted to sequences in the standard way, ignoring events for which the decomposition is not defined, e.g., _.result:SeqrEvs ÑSeqrDatas.

Functions may extract information from the history. In particular, we define oid : SeqrEvs ÑSetrObjsextracting all object identities occurring in a history, as follows:

oidpεq tmainu oidphγq oidphq Yoidpγq

oidpxoÑo1,u, m,peqyq to, o1u Yoidpeq oidpxo1o,u, m, eyq to, o1u Yoidpeq oidpxÐo,u, m, eyq tou Yoidpeq oidpxo,u, eyq tou Yoidpeq

oidpxoÝÑnew o1, C, eyq to, o1u Yoidpeq

whereγ:Ev, andoidpeqreturns the set of object identifiers occurring in the expression liste. The functionfid:SeqrEvs ÑSetrFidsextracts future identities from a history:

fidpεq H fidphγq fidphq Yfidpγq

fidpxoÑo1,u, m, eyq tuu fidpxo1o,u, m, eyq tuu Yfidpeq fidpxÐo,u, m, eyq H fidpxo,u, eyq fidpeq

fidpxoÝÑnewo1, C, eyq fidpeq

whereγ :Ev, andfidpeq returns the set of future identities occurring in the expression list e. For a global history h, the function fidphq returns all future identities on h, and for a local historyh{o, the function fidph{oqreturns the futures generated by o or received as parameters. At last, h{uabbreviates the projection of history hto the set tγ|γ.futureuu, i.e., all events with futureu.

Definition 4 (Wellformed histories) Let h: SeqrEvs be a history of a global object

(14)

systemS. The wellformedness predicate wf:SeqrEvs ÑBool is defined by:

wfpεq true

wfph xoÑo1,u, m, eyq wfphq ^onull^uRfidphq Yfidpeq wfph xo1 o,u, m, eyq wfphq ^onull^h{u rxo1 Ño,u, m, eys wfph xÐo,u, m, eyq wfphq ^h{u ew x_o,u, m,_y

wfph xo,u, eyq wfphq ^uPfidph{oq ^agreeppph{uq.resultq eq wfph xoÝÑnewo1, C, eyq wfphq ^onull^o1null^o1Roidphq Yoidpeq

It follows directly that a wellformed global history satisfies the communication order pictured in Fig. 3, i.e.,

@u.Do, o1, m, e, e .

h{u¤ rxo1 Ño,u, m, ey,xo1o,u, m, ey,xÐo,u, m, ey,rx_,u, eyss Also, it ensures the uniqueness of object identifiers and future identities. We can prove that the operational semantics guarantees wellformedness:

Lemma 1 The global historyhof a global object systemS obtained by the given oper- ational semantics, is wellformed, i.e., |ù wfphq where wfphq is strengthened by the two conditions fidphq „ ph{ Ñq.f utureand oidphq null„ ph{ÝÑqnew .callee.

The two conditions ensure that a history may not refer to object and future identities before generated by creation and invocation events, respectively. This lemma follows by induction over the number of rule applications.

Wellformedness of a local history for an objecto, denotedwfophq, is defined as in Def. 4, except that the last conjunct of the casexo1 o,u, m, ey only holds for self calls, i.e., whereo ando1 are equal. For local wellformedness, the conjunct is therefore weakened to o o1 ñ h{u rxo1 Ñ o,u, m, eys. If h is a wellformed global history, it follows immediately that each projectionh{ois locally wellformed, i.e.,

wfphq ñwfoph{oq

5 Program Verification

The communication history abstractly captures the system state at any point in time [11, 12]. Partial correctness properties of a system may thereby be specified by finite initial segments of its communication histories. Ahistory invariant is a predicate over the communication history, which holds for all finite sequences in the (prefix-closed) set of possible histories, expressing safety properties [5]. In this section we present a framework for compositional reasoning about object systems, establishing an invariant over the global history from invariants over the local histories of each object. Since the local object histories are disjoint with our four event semantics, it is possible to reason locally about each object. In particular, the history updates of the operational semantics affect the local history of the active object only, and can be treated simply as an assignment to the local history. The local history is not effected by the environment, and interference- free reasoning is then possible. Correspondingly, the reasoning framework consists of two parts: A proof system for local (class-based) reasoning, and a rule for composition of object specifications.

(15)

invoc $ @u.tH:H xthisÑv,u, m, ey||fr:uu rssφ

$ rfr:v!mpeq; ssφ

fetch $ @v1.tH:H xthis, e, v1y||v:v1u prssφ^ Dw . Ipw,Hqq

$ rv:e?; ssφ

new $ @v1.tH:H xthisÝÑnewv1, C, ey||v:v1u rssφ

$ rv :newCpeq; ssφ

Figure 5: Dynamic logic rules for method invocation, future query and object creation.

Ipw,Hqis the class invariant.

5.1 Local Reasoning

Pre- and postconditions to method definitions are in our setting used to establish aclass invariant. The class invariant must hold after initialization of all class instances and must be maintained by all methods, serving as a contract for the different methods:

A method implements its part of the contract by ensuring that the invariant holds upon termination, assuming that it holds when the method starts execution. A class invariant establishes arelationship between the internal state and the observable behavior of class instances. The internal state reflects the values of the fields, and the observable behavior is expressed as potential communication histories. A user-provided invariant Ipw,Hqfor a class C is a predicate over the fields w, the read-only parameterscpand this, in addition to the local historyHwhich is a sequence of events generated by this.

The proof system for class-based verification is formulated withindynamic logicas used by the KeY framework [7], facilitating class invariant verification by considering each method independently. The dynamic logic formulation suggests that the proof system is suitable for an implementation in the KeY framework.

Dynamic logic provides a structured way to describe program behavior by an integration of programs and assertions within a single language. The formula ψ ñ rssφ express partial correctness properties: if statements is executed in a state whereψ holds and the execution terminates, thenφ holds in the final state. The formula is verified by a symbolic execution ofs, where state modifications are handled by theupdatemechanism [7]. A dynamic formula rs1;ssφ is equal to rs1srssφ, where rssφis the precondition of s. A dynamic formula rv :e;ssφ, i.e., where an assignment is the first statement, reduces totv:eurssφ, wheretv:euis an update. We assume that expressionsecan be evaluated within the assertion language. Updates can only be applied on formulas without programs, which means that updates on a formularssφ are accumulated and delayed until the symbolic execution of s is complete. Update application tv : tue, on an expression e, evaluates to the substitution evt, replacing all free occurrences of v in eby t. The parallel updatetv1 :e1||...||vn :enu, for disjoint variablesv1, ..., vn, represents an accumulated update, and the application of a parallel update leads to a simultaneous substitution. For an update U, we have Upφ12q Uφ1^Uφ2. A sequent ψ1, ..., ψn1, ..., φm contains assumptionsψ1, ..., ψn, and formulas φ1, ..., φm

to be proved. The sequent isvalidif at least one formulaφifollows from the assumptions, and it can be interpreted asψ1^...^ψnñφ1_..._φm.

In order to verify a class invariantIpw,Hq, we must prove that the invariant is established by the initialization code and maintained by all method definitions in C, assuming wellformedness of the local history. For a method definitionmpxqts; returneuinC,

(16)

skip rskip; ssφ rssφ

assign rv:e; ssφ tv:eu rssφ

declInit rT ve; ssφ rv1:e; svv1sφ decINoInit rT v; ssφ rv1:defaultT; svv1

ifElse rifbthens1 elses2 fi; ssφ ifbthenrs1;ssφelsers2;ssφ while rwhileb dos1 od; ssφ ifbthenpDw . Ipw,Hqq^

prs1; whilebdos1 od; ssφqelserssφ

Figure 6: Semantical definitions for standardABS statements. Hereφis the postcondi- tion,sis the remaining program yet to be executed, primes denote fresh variables,svv1is swith all (free) occurrences ofvreplaced byv1, anddefaultT is the default value defined for typeT.

this amounts to a proof of the sequent:

$ pwfthispHq ^Ipw,Hq ñ rH:H xcallerthis,destiny, m, xy; s; H:H xÐthis,destiny, m, eyspwfthispHq ñIpw,Hqq

Here, the method body is extended with a statement for extending the history with the invocation reaction event, and thereturnstatement is treated as a history extension.

Dynamic logic rules for method invocation, future query, and object creation, can be found in Fig. 5. When invoking a method, the update in the premise of rule invoc captures the history extension and the generation of a fresh future identityu. Similarly, the update in rulefetch captures the history extension and the assignment of a fresh value tov, where the wellformedness assumptions ensure that all values received from the same future are equal. The update in the premise of rulenewcaptures the history extension and the generation of a fresh object identityv1, and the universal quantifier reflects non-determinism. The prime is needed here sincev may occur ine. The query rule insists that the class invariant holds for local history, ignoring the field values of the current state, as discussed in the soundness proof. Assignments are analyzed as explained above, and rules forskipand conditionals are standard. We refer to Din et al. for further details [19].

The rules for the rest of theABS statements can be defined as substitution rules in- troduced in Fig. 6. For instance,rskip; ssφcan be rewritten torssφ. In ruledeclInit anddeclNoInitv1is needed since the postcondition may talk about a field with the same namev. If-statements without an else-branch are as usual.

5.2 Soundness

The reasoning system for statements in dynamic logic is sound if any provable property is valid, i.e.,

$ψñ rssφñ |ùψñ rssφ

Validity of a dynamic logic formula, denoted|ù ψ ñ rssφ, is defined by means of the operational semantics. We base the semantics on the operational semantics above, as given by unlabeled transitions of the formG1ÑG2.

Note that each rule is local to one object, and we write G1

ÝÝÑo:s G2 to indicate an execution involving only object o such that exactly the statement (list) s has been executed byo. And we writeG1

o:sÑG2 ifoexecutesswhile other objects may execute.

(17)

Definition 5 (Explicit execution step) G1

o:sÑG2 G1ÝÑG2^G1ros.Prs;G2ros.Pr G1ÝÝÑo:s G2 G1o:sÑG2^ @o1. o1oñG1ro1s G2ro1s

expressing one or more transitions from the configurationG1toG2such thatoexecutes s, with or without, respectively, interleaved execution by other objects. The notation Grosdenotes the objectoof the configurationG.

We consider pre- and postconditions over local states and the local history. Such an assertion can be evaluated in a state defining values for attributes (of the appropriate class), parameters and local variables (of the method) and the local history. We let rrψÝÝÑo:s φssG,oexpress that if the conditionψholds for objectobefore execution ofsby the object in configurationG, thenφholds for oafter the execution. As above, we let ÝÝÑo:s express local execution byo, ando:sÑexecution byointerleaved with other objects:

Definition 6 (Validity of pre/post-conditions over execution steps) rrψÝÝÑo:s φssG,o @G1, z .wfpG1.histq ^GÝÝÑo:s G1^locpG, oqrψs ñlocpG1, oqrφs

rrψo:sÑφssG,o @G1, z .wfpG1.histq ^Go:sÑG1^locpG, oqrψs ñlocpG1, oqrφs wherez is the list of auxiliary variables inψ and/or φ, not bound byGnor G1. Here locpG, oq denotes the local state of object o, as derived from the global state G. The functionloc:ConfigOidÑStateis defined by

locpG, oq pGros.Flds;Gros.Lvarq rHÞÑ pG.histq{os

where the resultingHranges over local histories (i.e., in the alphabet ofo), and where thisis bound tooin Gas explained earlier. Thus the extraction is made by taking the state of objecto and adding the history localized to o. We let locpG, oqrψs denote the value ofψin statelocpG, oq.

It follows that local reasoning suffices for local pre/post-conditions, in the sense that when reasoning about one object in our system, one may ignore the activity of other objects.

Lemma 2 rrψÝÝÑo:s φssG,o is the same asrrψo:sÑφssG,o

The lemma follows by induction on the length of executions, and the fact thatlocpG, oq for anyGis not affected by execution steps by other objects thano, since remote access to fields is not allowed in our language and sinceh{oonly contains events generated by o.

In our setting, we may understand a sequent by means of the ÝÝÑo:s relation, letting a dynamic logic subformula depend on a given pre-configurationGand objecto.

Definition 7 (Validity of dynamic logic sequents)

|ùψ1, ..., ψn1, ..., φm @G, o .wfpG.histq ñ rrψ1^...^ψnñφ1_..._φmssG,o

rrrssφssG,o rrtrueÝÝÑo:s φssG,o

rressG,o locpG, oqres rrUrssφssG,o rrrU1;ssφssG,o

rrψ^φssG,o rrψssG,o^ rrφssG,o, rrψ_φssG,o rrψssG,o_ rrφssG,o

rrψñφssG,o rrψssG,oñ rrφssG,o

(18)

whereeis a formula without the dynamic logic operators, and the equations for updates are as given earlier. U1is the sequentialized version of the parallel update U introducing temporary variables if needed. For instance the sequentialized version ofx:y||y :x isx0:x;x:y;y:x0. It follows from the definition that

rrψñ rssφssG,o rrψÝÝÑo:s φssG,o

Hereois the executing object and the object on whichψandφare interpreted. Thus the formula is valid if for any objectoexecutings, the postcondition holds in the poststate, provided the precondition holds in the prestate. In dynamic logic the prestate given byGando is fixed for the whole sequent, and therefore the meaning of the individual operators is given in the context ofGando.

We verify an invariantIpw,Hqfor a classC by showing thatIpw,Hqis established by the initialization ofC, i.e. initC, and is maintained by all methods inC, assuming local wellfomedness. The rule is:

class

$ Dw . Ipw,Hγq ñ Dw . Ipw,Hq

$ Hεñ rinitCspwfthispHq ñIpw,Hqq

$ pwfthispHq ^Ipw,Hqq ñ rbodyC,mspwfthispHq ñIpw,Hqq,for all methodsm inC

$CDw . Ipw,Hq

where bodyC,m denotes the body s of method m of C augmented with effects on the local history reflecting the start and end of the method, namely

H:H xcallerthis,destiny, m, xy;s; H:H xÐthis,destiny, m, ey

Lemma 3 Reasoning about statements is sound:

$ψñ rssφñ |ùψñ rssφ

Theorem 1 The proof system for reasoning about classes is sound:

$CIpHq ñ|ùC IpHq

Proof of lemma 3. We focus on the rules for statements involving futures and object generation, and consider therefore the rules invoc, fetch and new, as given in figure 5.

The axioms given in figure 6 represent standard statements not involving futures, and we omit the soundness proof of these.

Asynchronous method call statement

We prove that the invoc rule preserves validity. The validity of the conclusion is |ù rfr:v!mpeq; ssφ. Consider now a givenGando, and letφ1 denoterssφ. According to Definition. 7, the validity can be written as

wfpG.histq ñ rrtrueÝÝÝÝÝÝÝÝÑo:fr:v!mpeq φ1ssG,o

which by Definition. 6 is

@G1, z .wfpG.histq ^wfpG1.histq ^GÝÝÝÝÝÝÝÝÑo:fr:v!mpeq G1 ñlocpG1, oqrφ1s

By the operational semantics of call and assign, we have that G1 is G with msg and G1.hist G.histmsg, where msgdenotes xo Ñ locpG, oqrvs,ftpo, nq, m, locpG, oqresy,

(19)

and such that the object stateG1ros.lispGros.lqrfrÞÑftpo, nqsiffrPGros.l, and otherwise G1ros.aispGros.aqrfrÞÑftpo, nqs. Herenis the counter value ofGros(same as inG1ros).

Other parts of the object state are unchanged.

ThuslocpG1, oqrφ1scan be reduced tolocpG, oqrφ1 fr,Hftpo,nq,HxthisÑv,ftpo,nq,m,eys sincelocpG, oqrxthisÑv,ftpo, nq, m, eys msg, and it suffices to prove

@z .wfpG.histq ñlocpG, oqrφ1 fr,Hftpo,nq,HxthisÑv,ftpo,nq,m,eys The validity of the premise is

|ù @u.tH:H xthisÑv,u, m, ey||fr:uuφ1 which by Definition 7 is

@z,u.wfpG.histq ñlocpG, oqrφ1 fr,Hu,HxthisÑv,u,m,eys

Clearly this is sufficient to ensure validity of the conclusion, since the universal quantifier onucovers the value given byftpo, nq.

Query statement

We prove that the fetch rule preserves validity. The validity of the conclusion is |ù rv : e?; ssφ. Consider now a given G and o, and let φ1 denote rssφ. According to Definition. 7, the validity can be written as

wfpG.histq ñ rrtrueÝÝÝÝÝÑo:v:e? φ1ssG,o

which by Definition. 6 is

@G1, z .wfpG.histq ^wfpG1.histq ^GÝÝÝÝÝÑo:v:e? G1ñlocpG1, oqrφ1s

By the operational semantics of query and assign, we have thatG1 isG withmsgand G1.histG.histmsg, wheremsgdenotesxo, locpG, oqres,dyand such that the object stateG1ros.l is pGros.lqrv ÞÑds ifv P Gros.l, and otherwise G1ros.a is pGros.aqrv ÞÑds. Other parts of the object state are unchanged.

ThuslocpG1, oqrφ1scan be reduced tolocpG, oqrφ1 v,Hd,Hxthis,e,dys sincelocpG, oqrxthis, e,dys msg, and it suffices to prove

@z .wfpG.histq ñlocpG, oqrφ1 v,Hd,Hxthis,e,dys The validity of the premise is

|ù @v1.tH:H xthis, e, v1y||v:v1u pφ1^ Dw . Ipw,Hqq which by Definition 7 is

@z, v1.wfpG.histq ñlocpG, oqrpφ1^ Dw . Ipw,Hqqv,Hv1,Hxthis,e,v1ys

Clearly this is sufficient to ensure validity of the conclusion, since the universal quantifier onv1 covers the value given byd. Note that the invariant is not required here. But it will be needed later to prove soundness of theclassrule.

(20)

Object creation statement

We prove that thenewrule preserves validity. The validity of the conclusion is|ù rv: new Cpeq; ssφ. Consider now a given G and o, and let φ1 denote rssφ. According to Definition. 7, the validity can be written as

wfpG.histq ñ rrtrueÝÝÝÝÝÝÝÝÝÑo:v:new Cpeq φ1ssG,o

which by Definition. 6 is

@G1, z .wfpG.histq ^wfpG1.histq ^GÝÝÝÝÝÝÝÝÝÑo:v:new Cpeq G1ñlocpG1, oqrφ1s

By the operational semantics of new and assign, we have thatG1 is G with msgand G1.hist G.histmsg, where msg denotes xo ÝÑnew obpC, nq, C, locpG, oqresy and such that the object stateG1ros.lispGros.lqrvÞÑobpC, nqsifvPGros.l, and otherwiseG1ros.a ispGros.aqrvÞÑobpC, nqs. Herenis the counter value ofGrCs(same as inG1rCs). Other parts of the object state are unchanged.

ThuslocpG1, oqrφ1scan be reduced tolocpG, oqrφ1 v,H

obpC,nq,HxthisnewÝÑobpC,nq,C,eys sincelocpG, oqrxthisÝÑnewobpC, nq, C, eys msg, and it suffices to prove

@z .wfpG.histq ñlocpG, oqrφ1 v,HobpC,nq,Hxthisnew

ÝÑobpC,nq,C,eys The validity of the premise is

|ù @v1.tH:H xthisÝÑnewv1, C, ey||v:v11 which by Definition 7 is

@z, v1.wfpG.histq ñlocpG, oqrφ1 v,Hv1,Hxthisnew

ÝÑv1,C,eys

Clearly this is sufficient to ensure validity of the conclusion, since the universal quantifier onv1 covers the value given byobpC, nq.

Proof of Theorem 1. The theorem follows by lemma 3 above and by proving that if one can prove$C I1pHqby the classrule, then|ùC I1pHq, letting I1pHqdenote Dw . Ipw,Hq.

Consider the rule class. We may assume that the premises of the rule are valid. By definition, the validity ofI1pHqis

@G, o . initClÝÑG^G.histH^oPG.obj^Gros.classCñI1pH{oq We first prove that this holds for allCobjectsoin statesGsuch thatGros.Prempty.

With the given operational semantics,Pr isemptyfor an objecto whenohas finished a method, orinitC, and it can only start a new method whenPris empty. By lemma 1 we only need to consider states with a wellformed history. We need to show that the invariantIpw,Hq holds after the initialization and is maintained by every methods of classC, considering any interleaved execution according to the operational semantics.

The validity of the second premise gives

@G, o .wfpG.histq ñ rrHεÝÝÝÝÑ po:initC wfthispHq ñIpw,HqqssG,o

which by lemma 2 is the same as

@G, o .wfpG.histq ñ rrHεo:initÑ pC wfthispHq ñIpw,HqqssG,o

Referanser

RELATERTE DOKUMENTER

In contrast to previous work on Creol reasoning [14], we here consider dynamic systems, and present a more general framework where class semantics and reasoning are

Cooperation: TVEPS - Center for Interprofessional Collaborative Learning in Primary Care, coordinated by Professor Anders Brheim and represented by the Department of Global

In addition to the previously mentioned partners, Oslo and Akershus University College, Centre for the Study of Professions for TF3, the Institute of Educational Research for TF2

Centre for child and adolescent mental health, Eastern and Southern Norway (RBUP) hereby confirms its willingness to participate as a partner in the Center of Excellence in

• utilizing the clinical practice arenas in the programmes of professional study to strengthen the faculty’s collaboration with the public health service and profile the

These may change over time, but initially they are likely to be (i) The Academic Development Unit at the Faculty of Engineering at Lund University, Sweden (confirmed), (ii)

19. “A Density Distributing Locally Orthotropic 2-D Femur Remodeling Algorithm.” International Society of Bioengineers. “Integrating Engineering and Science Analysis and Design

A forerunner to the joint R&amp;D unit is a long lasting collaboration process between HSH and the local health services regarding quality of clinical practice and development of